diff options
521 files changed, 37235 insertions, 34829 deletions
diff --git a/JavaLibrary.mk b/JavaLibrary.mk index 64fdb7e..f9468a8 100644 --- a/JavaLibrary.mk +++ b/JavaLibrary.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"); @@ -20,26 +21,37 @@ # Common definitions for host and target. # -# The core library is divided into modules. Each module has a separate -# Java source directory, and some (hopefully eventually all) also have -# a directory for tests. +# dalvik/libcore is divided into modules. +# +# The structure of each module is: +# +# src/ +# main/ # To be shipped on every device. +# java/ # Java source for library code. +# native/ # C++ source for library code. +# resources/ # Support files. +# test/ # Built only on demand, for testing. +# java/ # Java source for tests. +# native/ # C++ source for tests (rare). +# resources/ # Support files. +# +# All subdirectories are optional (hence the "2> /dev/null"s below). -define all-core-java-files -$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) && find */src/$(1)/java -name "*.java")) +define all-main-java-files-under +$(foreach dir,$(1),$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) && find $(dir)/src/main/java -name "*.java" 2> /dev/null))) +endef + +define all-test-java-files-under +$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) && find $(1)/src/test/java -name "*.java" 2> /dev/null)) endef -# Redirect ls stderr to /dev/null because the corresponding resources -# directories don't always exist. define all-core-resource-dirs $(shell cd $(LOCAL_PATH) && ls -d */src/$(1)/{java,resources} 2> /dev/null) endef -# The core Java files and associated resources. -core_src_files := $(call all-core-java-files,main) +# The Java files and their associated resources. +core_src_files := $(call all-main-java-files-under,annotation archive auth awt-kernel concurrent crypto dalvik dom icu json junit logging luni luni-kernel math nio nio_char openssl prefs regex security security-kernel sql suncompat support text x-net xml) core_resource_dirs := $(call all-core-resource-dirs,main) - -# The test Java files and associated resources. -test_src_files := $(call all-core-java-files,test) test_resource_dirs := $(call all-core-resource-dirs,test) @@ -67,24 +79,274 @@ include $(BUILD_JAVA_LIBRARY) core-intermediates := ${intermediates} -# Definitions to make the core-tests library. + +# Definitions to make the sqlite JDBC driver. + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-main-java-files-under,sqlite-jdbc) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core +LOCAL_MODULE := sqlite-jdbc +include $(BUILD_JAVA_LIBRARY) + + +# Definitions to make the core-tests libraries. +# +# We make a library per module, because otherwise the .jar files get too +# large, to the point that dx(1) can't cope (and the build is +# ridiculously slow). +# +# TODO: DalvikRunner will make this nonsense obsolete. + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,annotation) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-annotation +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,archive) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-archive +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,concurrent) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-concurrent +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,crypto) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-crypto +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,dom) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-dom +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,icu) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-icu +include $(BUILD_JAVA_LIBRARY) include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,json) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-json +include $(BUILD_JAVA_LIBRARY) -LOCAL_SRC_FILES := $(test_src_files) +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,logging) LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-logging +include $(BUILD_JAVA_LIBRARY) +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,luni-kernel) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-luni-kernel +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,luni) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +# This module contains the top-level "tests.AllTests" that ties everything +# together, so it has compile-time dependencies on all the other test +# libraries. +# TODO: we should have a bogus module that just contains tests.AllTests for speed. +LOCAL_JAVA_LIBRARIES := \ + core \ + core-tests-support \ + core-tests-annotation \ + core-tests-archive \ + core-tests-concurrent \ + core-tests-crypto \ + core-tests-dom \ + core-tests-icu \ + core-tests-json \ + core-tests-logging \ + core-tests-luni-kernel \ + core-tests-math \ + core-tests-nio \ + core-tests-nio_char \ + core-tests-prefs \ + core-tests-regex \ + core-tests-security \ + core-tests-sql \ + core-tests-suncompat \ + core-tests-text \ + core-tests-x-net \ + core-tests-xml +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-luni +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,math) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-math +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,nio) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-nio +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,nio_char) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-nio_char +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,prefs) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-prefs +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,regex) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-regex +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,security) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-security +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,sql) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support sqlite-jdbc +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-sql +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,suncompat) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-suncompat +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,support) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) LOCAL_NO_STANDARD_LIBRARIES := true LOCAL_JAVA_LIBRARIES := core LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-support +include $(BUILD_JAVA_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,text) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-text +include $(BUILD_JAVA_LIBRARY) +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,x-net) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library LOCAL_MODULE_TAGS := tests -LOCAL_MODULE := core-tests +LOCAL_MODULE := core-tests-x-net +include $(BUILD_JAVA_LIBRARY) +include $(CLEAR_VARS) +LOCAL_SRC_FILES := $(call all-test-java-files-under,xml) +LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) +LOCAL_NO_STANDARD_LIBRARIES := true +LOCAL_JAVA_LIBRARIES := core core-tests-support +LOCAL_DX_FLAGS := --core-library +LOCAL_MODULE_TAGS := tests +LOCAL_MODULE := core-tests-xml include $(BUILD_JAVA_LIBRARY) + # This one's tricky. One of our tests needs to have a # resource with a "#" in its name, but Perforce doesn't # allow us to submit such a file. So we create it here @@ -164,21 +426,4 @@ ifeq ($(WITH_HOST_DALVIK),true) include $(BUILD_HOST_JAVA_LIBRARY) - - # Definitions to make the core-tests library. - - include $(CLEAR_VARS) - - LOCAL_SRC_FILES := $(test_src_files) - LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs) - - LOCAL_NO_STANDARD_LIBRARIES := true - LOCAL_JAVA_LIBRARIES := core - LOCAL_DX_FLAGS := --core-library - - LOCAL_MODULE_TAGS := tests - LOCAL_MODULE := core-tests - - include $(BUILD_HOST_JAVA_LIBRARY) - endif @@ -59,7 +59,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. == NOTICE file for the ICU License. == ========================================================================= -Copyright (c) 1995-2006 International Business Machines Corporation and others +Copyright (c) 1995-2009 International Business Machines Corporation and others All rights reserved. diff --git a/NativeCode.mk b/NativeCode.mk index 57c4903..38ff709 100644 --- a/NativeCode.mk +++ b/NativeCode.mk @@ -85,6 +85,11 @@ core_static_libraries := $(sort $(LOCAL_STATIC_LIBRARIES)) include $(CLEAR_VARS) +ifeq ($(TARGET_ARCH),arm) +# Ignore "note: the mangling of 'va_list' has changed in GCC 4.4" +LOCAL_CFLAGS += -Wno-psabi +endif + # Define the rules. LOCAL_SRC_FILES := $(core_src_files) LOCAL_C_INCLUDES := $(core_c_includes) diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java index e306435..c2b179e 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java @@ -25,7 +25,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.annotation"); + TestSuite suite = new TestSuite("Test for java.lang.annotation"); // $JUnit-BEGIN$ suite.addTestSuite(AnnotationTest.class); diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java index c2a32b8..b80f3a9 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java @@ -17,29 +17,17 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.lang.annotation.AnnotationFormatError; import junit.framework.TestCase; -import java.lang.annotation.AnnotationFormatError; - /** * Test case of java.lang.annotation.AnnotationFormatError */ -@TestTargetClass(AnnotationFormatError.class) public class AnnotationFormatErrorTest extends TestCase { /** * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AnnotationFormatError", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_constructorLjava_lang_String() { AnnotationFormatError e = new AnnotationFormatError("some message"); @@ -49,12 +37,6 @@ public class AnnotationFormatErrorTest extends TestCase { /** * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AnnotationFormatError", - args = {java.lang.Throwable.class} - ) public void test_constructorLjava_lang_Throwable() { IllegalArgumentException iae = new IllegalArgumentException(); AnnotationFormatError e = new AnnotationFormatError(iae); @@ -64,12 +46,6 @@ public class AnnotationFormatErrorTest extends TestCase { /** * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String,Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AnnotationFormatError", - args = {java.lang.String.class, java.lang.Throwable.class} - ) @SuppressWarnings("nls") public void test_constructorLjava_lang_StringLjava_lang_Throwable() { IllegalArgumentException iae = new IllegalArgumentException(); diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTest.java index c50c0e8..e9657de 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - import junit.framework.TestCase; import java.lang.annotation.Annotation; @@ -35,23 +30,8 @@ import java.util.Map; /** * Test case of java.lang.annotation.Annotation */ -@TestTargetClass(value = Annotation.class, - untestedMethods = { - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "the spec does not require any specific output (although @something is probable)", - method = "toString", - args = {} - )} -) public class AnnotationTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "annotationType", - args = {} - ) public void test_annotationType() { Annotation [] annotations = AnnotatedClass.class.getDeclaredAnnotations(); assertEquals(1, annotations.length); @@ -59,20 +39,6 @@ public class AnnotationTest extends TestCase { assertEquals(TestAnnotation1.class, anno.annotationType()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = { Object.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) - }) public void test_equals() throws Exception { // test type Method m1 = AnnotatedClass2.class @@ -133,12 +99,6 @@ public class AnnotationTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() throws SecurityException, NoSuchMethodException { Annotation a1 = AnnotatedClass.class.getDeclaredAnnotations()[0]; assertEquals(a1.hashCode(), (127 * "value".hashCode() ^ "foobar".hashCode())); diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java index 5430286..37ee8c1 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java @@ -17,20 +17,14 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.lang.annotation.AnnotationTypeMismatchException; import java.lang.reflect.Method; +import junit.framework.TestCase; + /** * Test case of java.lang.annotation.AnnotationTypeMismatchException */ -@TestTargetClass(AnnotationTypeMismatchException.class) public class AnnotationTypeMismatchExceptionTest extends TestCase { /** @@ -39,26 +33,6 @@ public class AnnotationTypeMismatchExceptionTest extends TestCase { * @tests java.lang.annotation.AnnotationTypeMismatchException#AnnotationTypeMismatchException(Method, * String) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AnnotationTypeMismatchException", - args = {java.lang.reflect.Method.class, java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "element", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "foundType", - args = {} - ) - }) @SuppressWarnings("nls") public void test_constructorLjava_lang_reflect_MethodLjava_lang_String() throws SecurityException, ClassNotFoundException { Method[] methods = Class.forName("java.lang.String").getMethods(); diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java index dec9bf7..d81cabd 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java @@ -17,32 +17,20 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.lang.annotation.ElementType; import java.util.Arrays; +import junit.framework.TestCase; + /** * Test case of java.lang.annotation.ElementType */ -@TestTargetClass(ElementType.class) public class ElementTypeTest extends TestCase { /** * @throws Exception * @tests java.lang.annotation.ElementType#valueOf(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_valueOfLjava_lang_String() throws Exception { assertSame(ElementType.ANNOTATION_TYPE, ElementType @@ -67,12 +55,6 @@ public class ElementTypeTest extends TestCase { * @throws Exception * @tests java.lang.annotation.ElementType#values() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "values", - args = {} - ) @SuppressWarnings("nls") public void test_values() throws Exception { ElementType[] values = ElementType.values(); diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java index 5c718ed..d44b90a 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java @@ -17,28 +17,19 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.lang.annotation.IncompleteAnnotationException; import junit.framework.TestCase; -import java.lang.annotation.IncompleteAnnotationException; - -@TestTargetClass(IncompleteAnnotationException.class) +/** + * + */ public class IncompleteAnnotationExceptionTest extends TestCase { /* * Class under test for void IncompleteAnnotationException(String) * Regression for HARMONY-2477 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies NullPointerException.", - method = "IncompleteAnnotationException", - args = {java.lang.Class.class, java.lang.String.class} - ) public void testNullType() { try { new IncompleteAnnotationException(null, "str"); @@ -53,26 +44,6 @@ public class IncompleteAnnotationExceptionTest extends TestCase { * @tests java.lang.annotation.IncompleteAnnotationException#IncompleteAnnotationException(Class, * String) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IncompleteAnnotationException", - args = {java.lang.Class.class, java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "annotationType", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "elementName", - args = {} - ) - }) @SuppressWarnings("nls") public void test_constructorLjava_lang_Class_Ljava_lang_String() throws Exception { diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java index 1827b7d..c4f7c03 100644 --- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java +++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java @@ -17,31 +17,19 @@ package org.apache.harmony.annotation.tests.java.lang.annotation; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.lang.annotation.RetentionPolicy; import java.util.Arrays; +import junit.framework.TestCase; + /** * Test case of java.lang.annotation.RetentionPolicy */ -@TestTargetClass(RetentionPolicy.class) public class RetentionPolicyTest extends TestCase { /** * @throws Exception * @tests java.lang.annotation.RetentionPolicy#valueOf(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_valueOfLjava_lang_String() throws Exception { assertSame(RetentionPolicy.CLASS, RetentionPolicy @@ -62,12 +50,6 @@ public class RetentionPolicyTest extends TestCase { * @throws Exception * @tests java.lang.annotation.RetentionPolicy#values() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "values", - args = {} - ) @SuppressWarnings("nls") public void test_values() throws Exception { RetentionPolicy[] values = RetentionPolicy.values(); diff --git a/annotation/src/test/java/tests/annotation/AllTests.java b/annotation/src/test/java/tests/annotation/AllTests.java index 172cc10..c95fe26 100644 --- a/annotation/src/test/java/tests/annotation/AllTests.java +++ b/annotation/src/test/java/tests/annotation/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the NIO_Char project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Annotation test suites"); + TestSuite suite = new TestSuite("All Annotation test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.annotation.tests.java.lang.annotation.AllTests.suite()); // $JUnit-END$ diff --git a/archive/src/main/java/java/util/zip/ZipConstants.java b/archive/src/main/java/java/util/zip/ZipConstants.java index 9fbce06..4ce65bc 100644 --- a/archive/src/main/java/java/util/zip/ZipConstants.java +++ b/archive/src/main/java/java/util/zip/ZipConstants.java @@ -17,6 +17,11 @@ package java.util.zip; +/** + * Do not add constants to this interface! It's implemented by the classes + * in this package whose names start "Zip", and the constants are thereby + * public API. + */ interface ZipConstants { public static final long LOCSIG = 0x4034b50, EXTSIG = 0x8074b50, diff --git a/archive/src/main/java/java/util/zip/ZipEntry.java b/archive/src/main/java/java/util/zip/ZipEntry.java index 75466ce..d68aa2f 100644 --- a/archive/src/main/java/java/util/zip/ZipEntry.java +++ b/archive/src/main/java/java/util/zip/ZipEntry.java @@ -400,20 +400,16 @@ public class ZipEntry implements ZipConstants, Cloneable { } try { - /* - * The actual character set is "IBM Code Page 437". As of - * Sep 2006, the Zip spec (APPNOTE.TXT) supports UTF-8. When - * bit 11 of the GP flags field is set, the file name and - * comment fields are UTF-8. - * - * TODO: add correct UTF-8 support. - */ - name = new String(nameBytes, "ISO-8859-1"); + // BEGIN android-changed + // The RI has always assumed UTF-8. (If GPBF_UTF8_FLAG isn't set, the encoding is + // actually IBM-437.) + name = new String(nameBytes, "UTF-8"); if (commentBytes != null) { - comment = new String(commentBytes, "ISO-8859-1"); + comment = new String(commentBytes, "UTF-8"); } else { comment = null; } + // END android-changed } catch (UnsupportedEncodingException uee) { throw new InternalError(uee.getMessage()); } diff --git a/archive/src/main/java/java/util/zip/ZipFile.java b/archive/src/main/java/java/util/zip/ZipFile.java index 48541e1..6513622 100644 --- a/archive/src/main/java/java/util/zip/ZipFile.java +++ b/archive/src/main/java/java/util/zip/ZipFile.java @@ -43,6 +43,26 @@ import java.util.Iterator; * @see ZipOutputStream */ public class ZipFile implements ZipConstants { + /** + * General Purpose Bit Flags, Bit 3. + * If this bit is set, the fields crc-32, compressed + * size and uncompressed size are set to zero in the + * local header. The correct values are put in the + * data descriptor immediately following the compressed + * data. (Note: PKZIP version 2.04g for DOS only + * recognizes this bit for method 8 compression, newer + * versions of PKZIP recognize this bit for any + * compression method.) + */ + static final int GPBF_DATA_DESCRIPTOR_FLAG = 1 << 3; // android-added + + /** + * General Purpose Bit Flags, Bit 11. + * Language encoding flag (EFS). If this bit is set, + * the filename and comment fields for this file + * must be encoded using UTF-8. + */ + static final int GPBF_UTF8_FLAG = 1 << 11; // android-added /** * Open ZIP file for read. diff --git a/archive/src/main/java/java/util/zip/ZipInputStream.java b/archive/src/main/java/java/util/zip/ZipInputStream.java index 554f5d5..c2af30c 100644 --- a/archive/src/main/java/java/util/zip/ZipInputStream.java +++ b/archive/src/main/java/java/util/zip/ZipInputStream.java @@ -49,8 +49,6 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants static final int STORED = 0; - static final int ZIPDataDescriptorFlag = 8; - static final int ZIPLocalHeaderVersionNeeded = 20; private boolean entriesEnd = false; @@ -236,7 +234,7 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants throw new ZipException(Messages.getString("archive.22")); //$NON-NLS-1$ } int flags = getShort(hdrBuf, LOCFLG - LOCVER); - hasDD = ((flags & ZIPDataDescriptorFlag) == ZIPDataDescriptorFlag); + hasDD = ((flags & ZipFile.GPBF_DATA_DESCRIPTOR_FLAG) != 0); int cetime = getShort(hdrBuf, LOCTIM - LOCVER); int cemodDate = getShort(hdrBuf, LOCTIM - LOCVER + 2); int cecompressionMethod = getShort(hdrBuf, LOCHOW - LOCVER); diff --git a/archive/src/main/java/java/util/zip/ZipOutputStream.java b/archive/src/main/java/java/util/zip/ZipOutputStream.java index 21b4221..e53061a 100644 --- a/archive/src/main/java/java/util/zip/ZipOutputStream.java +++ b/archive/src/main/java/java/util/zip/ZipOutputStream.java @@ -54,8 +54,6 @@ public class ZipOutputStream extends DeflaterOutputStream implements */ public static final int STORED = 0; - static final int ZIPDataDescriptorFlag = 8; - static final int ZIPLocalHeaderVersionNeeded = 20; private String comment; @@ -141,11 +139,12 @@ public class ZipOutputStream extends DeflaterOutputStream implements writeLong(out, currentEntry.size = def.getTotalIn()); } // Update the CentralDirectory + // http://www.pkware.com/documents/casestudies/APPNOTE.TXT + int flags = currentEntry.getMethod() == STORED ? 0 : ZipFile.GPBF_DATA_DESCRIPTOR_FLAG; writeLong(cDir, CENSIG); writeShort(cDir, ZIPLocalHeaderVersionNeeded); // Version created writeShort(cDir, ZIPLocalHeaderVersionNeeded); // Version to extract - writeShort(cDir, currentEntry.getMethod() == STORED ? 0 - : ZIPDataDescriptorFlag); + writeShort(cDir, flags); writeShort(cDir, currentEntry.getMethod()); writeShort(cDir, currentEntry.time); writeShort(cDir, currentEntry.modDate); @@ -283,16 +282,23 @@ public class ZipOutputStream extends DeflaterOutputStream implements 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; + // Java always outputs UTF-8 filenames. (Before Java 7, the RI didn't set this flag and used + // modified UTF-8. From Java 7, it sets this flag and uses normal UTF-8.) + flags |= ZipFile.GPBF_UTF8_FLAG; writeLong(out, LOCSIG); // Entry header writeShort(out, ZIPLocalHeaderVersionNeeded); // Extraction version - writeShort(out, currentEntry.getMethod() == STORED ? 0 - : ZIPDataDescriptorFlag); + writeShort(out, flags); writeShort(out, currentEntry.getMethod()); if (currentEntry.getTime() == -1) { currentEntry.setTime(System.currentTimeMillis()); } writeShort(out, currentEntry.time); writeShort(out, currentEntry.modDate); + // END android-changed if (currentEntry.getMethod() == STORED) { if (currentEntry.size == -1) { diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java index 13fe019..7b39de6 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * Test suite for java.util.jar package. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( + TestSuite suite = new TestSuite( "Suite org.apache.harmony.archive.tests.java.util.jar"); suite.addTestSuite(AttributesNameTest.class); suite.addTestSuite(AttributesTest.class); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java index 067bf49..efeb128 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java @@ -17,26 +17,14 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.util.jar.Attributes; import junit.framework.TestCase; -@TestTargetClass(Attributes.Name.class) public class AttributesNameTest extends TestCase { /** * @tests java.util.jar.Attributes.Name#Name(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Name", - args = {java.lang.String.class} - ) public void test_AttributesName_Constructor() { // Regression for HARMONY-85 try { @@ -57,12 +45,6 @@ public class AttributesNameTest extends TestCase { assertNotNull(new Attributes.Name("Attr")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { Attributes.Name attr1 = new Attributes.Name("Attr"); Attributes.Name attr2 = new Attributes.Name("Attr"); @@ -72,12 +54,6 @@ public class AttributesNameTest extends TestCase { assertFalse(attr1.equals(attr2)); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { Attributes.Name attr1 = new Attributes.Name("Attr1"); Attributes.Name attr2 = new Attributes.Name("Attr2"); @@ -85,12 +61,6 @@ public class AttributesNameTest extends TestCase { assertNotSame(attr1.hashCode(), attr2.hashCode()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { String str1 = "Attr1"; String str2 = "Attr2"; diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java index 0b3d2cf..f437d20 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -31,7 +26,6 @@ import java.util.Set; import java.util.jar.Attributes; import junit.framework.TestCase; -@TestTargetClass(Attributes.class) public class AttributesTest extends TestCase { private Attributes a; @@ -47,12 +41,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#Attributes(java.util.jar.Attributes) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Attributes", - args = {java.util.jar.Attributes.class} - ) public void test_ConstructorLjava_util_jar_Attributes() { Attributes a2 = new Attributes(a); assertEquals(a, a2); @@ -63,12 +51,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#clear() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clear", - args = {} - ) public void test_clear() { a.clear(); assertNull("a) All entries should be null after clear", a.get("1")); @@ -81,12 +63,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#containsKey(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "containsKey", - args = {java.lang.Object.class} - ) public void test_containsKeyLjava_lang_Object() { assertTrue("a) Should have returned false", !a.containsKey(new Integer( 1))); @@ -98,12 +74,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#containsValue(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "containsValue", - args = {java.lang.Object.class} - ) public void test_containsValueLjava_lang_Object() { assertTrue("Should have returned false", !a.containsValue("One")); assertTrue("Should have returned true", a.containsValue("one")); @@ -112,12 +82,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#entrySet() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entrySet", - args = {} - ) public void test_entrySet() { Set<Map.Entry<Object, Object>> entrySet = a.entrySet(); Set<Object> keySet = new HashSet<Object>(); @@ -148,12 +112,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#get(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getValue", - args = {java.lang.String.class} - ) public void test_getLjava_lang_Object() { assertEquals("a) Incorrect value returned", "one", a.getValue("1")); assertNull("b) Incorrect value returned", a.getValue("0")); @@ -168,12 +126,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#isEmpty() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isEmpty", - args = {} - ) public void test_isEmpty() { assertTrue("Should not be empty", !a.isEmpty()); a.clear(); @@ -185,12 +137,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#keySet() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "keySet", - args = {} - ) public void test_keySet() { Set<?> s = a.keySet(); assertEquals(4, s.size()); @@ -207,12 +153,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#putAll(java.util.Map) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "putAll", - args = {java.util.Map.class} - ) public void test_putAllLjava_util_Map() { Attributes b = new Attributes(); b.putValue("3", "san"); @@ -245,12 +185,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#putAll(java.util.Map) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test", - method = "putAll", - args = {java.util.Map.class} - ) public void test_putAllLjava_util_Map2() { // Regression for HARMONY-464 try { @@ -275,12 +209,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#remove(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "remove", - args = {java.lang.Object.class} - ) public void test_removeLjava_lang_Object() { a.remove(new Attributes.Name("1")); a.remove(new Attributes.Name("3")); @@ -291,12 +219,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#size() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "size", - args = {} - ) public void test_size() { assertEquals("Incorrect size returned", 4, a.size()); a.clear(); @@ -306,12 +228,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#values() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "values", - args = {} - ) public void test_values() { Collection<?> valueCollection = a.values(); assertTrue("a) Should contain entry", valueCollection.contains("one")); @@ -323,12 +239,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#clone() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clone", - args = {} - ) public void test_clone() { Attributes a2 = (Attributes) a.clone(); assertEquals(a, a2); @@ -339,12 +249,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes#equals(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { Attributes.Name n1 = new Attributes.Name("name"), n2 = new Attributes.Name( "Name"); @@ -361,12 +265,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes.put(java.lang.Object, java.lang.Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Checks ClassCastException", - method = "put", - args = {java.lang.Object.class, java.lang.Object.class} - ) public void test_putLjava_lang_ObjectLjava_lang_Object() { Attributes atts = new Attributes(); assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH, @@ -391,12 +289,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes.put(java.lang.Object, java.lang.Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "ClassCastException checking missed.", - method = "put", - args = {java.lang.Object.class, java.lang.Object.class} - ) public void test_putLjava_lang_ObjectLjava_lang_Object_Null() { Attributes attribute = new Attributes(); @@ -424,12 +316,6 @@ public class AttributesTest extends TestCase { /** * @tests java.util.jar.Attributes.hashCode() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode_consistent_with_map() { MockAttributes mockAttr = new MockAttributes(); mockAttr.putValue("1", "one"); @@ -442,34 +328,16 @@ public class AttributesTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Attributes", - args = {} - ) public void test_Constructor() { Attributes attr = new Attributes(); assertTrue(attr.size() >= 0); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Attributes", - args = {int.class} - ) public void test_ConstructorI() { Attributes attr = new Attributes(10); assertTrue(attr.size() >= 0); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "get", - args = {java.lang.Object.class} - ) public void test_getLjava_lang_Object_true() { assertEquals("a) Incorrect value returned", "one", a .get(new Attributes.Name("1"))); @@ -477,12 +345,6 @@ public class AttributesTest extends TestCase { assertNull("b) Incorrect value returned", a.get("1")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getValue", - args = {java.util.jar.Attributes.Name.class} - ) public void test_getValueLjava_util_jar_Attributes_Name() { assertEquals("a) Incorrect value returned", "one", a .getValue(new Attributes.Name("1"))); @@ -490,12 +352,6 @@ public class AttributesTest extends TestCase { .getValue(new Attributes.Name("0"))); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { Attributes b = (Attributes) a.clone(); b.putValue("33", "Thirty three"); @@ -505,12 +361,6 @@ public class AttributesTest extends TestCase { assertNotSame(a.hashCode(), b.hashCode()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "putValue", - args = {java.lang.String.class, java.lang.String.class} - ) public void test_putValueLjava_lang_StringLjava_lang_String() { Attributes b = new Attributes(); b.put(new Attributes.Name("1"), "one"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java index 601fe42..a8c6148 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java @@ -16,11 +16,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; import junit.framework.TestCase; import static tests.support.Support_Exec.execAndGetOutput; import tests.support.resource.Support_Resources; @@ -37,8 +32,6 @@ import java.util.jar.JarOutputStream; import java.util.jar.Manifest; -@TestTargetClass(JarOutputStream.class) -@AndroidOnly("dalvik vm specific") public class DalvikExecTest extends TestCase { String execDalvik1(String classpath, String mainClass, String arg1) @@ -78,15 +71,7 @@ public class DalvikExecTest extends TestCase { return execDalvik1(classpath, mainClass, null); } - @TestTargets ({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Execute an existing JAR on dalvikvm using -classpath option.", - clazz = Runtime.class, - method = "exec", - args = {java.lang.String[].class} - ) - }) + // Execute an existing JAR on dalvikvm using -classpath option.", public void test_execExistingJar () throws IOException, InterruptedException { String res; File jarFile; @@ -113,26 +98,7 @@ public class DalvikExecTest extends TestCase { } } - - @TestTargets ({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "JarOutputStream", - args = {java.io.OutputStream.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Create a temp file, fill it with contents according to Dalvik JAR format, and execute it on dalvikvm using -classpath option.", - clazz = Runtime.class, - method = "exec", - args = {java.lang.String[].class} - ) - }) + // Create a temp file, fill it with contents according to Dalvik JAR format, and execute it on dalvikvm using -classpath option.", public void test_execCreatedJar () throws IOException, InterruptedException { File jarFile = File.createTempFile("cts_dalvikExecTest_", ".jar"); jarFile.deleteOnExit(); @@ -171,24 +137,6 @@ public class DalvikExecTest extends TestCase { } - @TestTargets ({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "JarOutputStream", - args = {java.io.OutputStream.class, java.util.jar.Manifest.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - clazz = Runtime.class, - method = "exec", - args = {java.lang.String[].class} - ) - }) /** * This test does quite the same as test_execCreatedJar, but includes a manifest. * Note however that the Dalvik JAR format does not require this manifest. diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java index 90144be..e179024 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -35,7 +30,6 @@ import junit.framework.TestCase; import tests.support.resource.Support_Resources; -@TestTargetClass(JarEntry.class) public class JarEntryTest extends TestCase { private ZipEntry zipEntry; @@ -75,12 +69,6 @@ public class JarEntryTest extends TestCase { * @throws IOException * @tests java.util.jar.JarEntry#JarEntry(java.util.jar.JarEntry) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "JarEntry", - args = {java.util.jar.JarEntry.class} - ) public void test_ConstructorLjava_util_jar_JarEntry_on_null() throws IOException { JarEntry newJarEntry = new JarEntry(jarFile.getJarEntry(entryName)); assertNotNull(newJarEntry); @@ -97,12 +85,6 @@ public class JarEntryTest extends TestCase { /** * @tests java.util.jar.JarEntry#JarEntry(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarEntry", - args = {java.util.zip.ZipEntry.class} - ) public void test_ConstructorLjava_util_zip_ZipEntry() { assertNotNull("Jar file is null", jarFile); zipEntry = jarFile.getEntry(entryName); @@ -118,12 +100,6 @@ public class JarEntryTest extends TestCase { /** * @tests java.util.jar.JarEntry#getAttributes() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAttributes", - args = {} - ) public void test_getAttributes() { JarFile attrJar = null; File file = null; @@ -165,12 +141,6 @@ public class JarEntryTest extends TestCase { /** * @tests java.util.jar.JarEntry#getCertificates() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCertificates", - args = {} - ) public void test_getCertificates() throws Exception { zipEntry = jarFile.getEntry(entryName2); jarEntry = new JarEntry(zipEntry); @@ -206,12 +176,6 @@ public class JarEntryTest extends TestCase { /** * @tests java.util.jar.JarEntry#getCodeSigners() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCodeSigners", - args = {} - ) public void test_getCodeSigners() throws IOException { String jarFileName = "TestCodeSigners.jar"; Support_Resources.copyFile(resources, null, jarFileName); @@ -247,12 +211,6 @@ public class JarEntryTest extends TestCase { new JarEntry("aaa").getCodeSigners()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarEntry", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { assertNotNull("Jar file is null", jarFile); zipEntry = jarFile.getEntry(entryName); @@ -279,12 +237,6 @@ public class JarEntryTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "JarEntry", - args = {java.util.jar.JarEntry.class} - ) public void test_ConstructorLjava_util_jar_JarEntry() { assertNotNull("Jar file is null", jarFile); JarEntry je = jarFile.getJarEntry(entryName); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java index 7f48342..9a0caf4 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java @@ -17,28 +17,16 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.jar.Manifest; import junit.framework.TestCase; import java.util.jar.JarException; -@TestTargetClass(JarException.class) public class JarExceptionTest extends TestCase { /** * @tests java.util.jar.JarException#JarException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarException", - args = {} - ) public void test_Constructor() throws Exception { JarException ex = new JarException(); JarException ex1 = new JarException("Test string"); @@ -49,12 +37,6 @@ public class JarExceptionTest extends TestCase { assertSame(ex.getMessage(), ex2.getMessage()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() throws Exception { JarException ex1 = new JarException("Test string"); JarException ex2 = new JarException(null); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java index 01f5a8c..e2a11c7 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java @@ -17,10 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; import static tests.support.Support_Exec.execAndGetOutput; import static tests.support.Support_Exec.javaProcessBuilder; import tests.support.resource.Support_Resources; @@ -40,19 +36,11 @@ import java.util.jar.Manifest; * */ -@TestTargetClass(JarOutputStream.class) public class JarExecTest extends junit.framework.TestCase { /** * regression test for HARMONY-1562 issue * */ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Regression functional test. Exception checking missed.", - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_1562() throws Exception { // create the manifest Manifest man = new Manifest(); @@ -87,13 +75,6 @@ public class JarExecTest extends junit.framework.TestCase { * * @throws Exception in case of troubles */ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "JarOutputStream", - args = {java.io.OutputStream.class, java.util.jar.Manifest.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_jar_class_path() throws Exception { File fooJar = File.createTempFile("hyts_", ".jar"); File barJar = File.createTempFile("hyts_", ".jar"); @@ -159,13 +140,6 @@ public class JarExecTest extends junit.framework.TestCase { * * @throws Exception in case of troubles */ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "JarOutputStream", - args = {java.io.OutputStream.class, java.util.jar.Manifest.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_main_class_in_another_jar() throws Exception { File fooJar = File.createTempFile("hyts_", ".jar"); File barJar = File.createTempFile("hyts_", ".jar"); @@ -201,13 +175,6 @@ public class JarExecTest extends junit.framework.TestCase { execAndGetOutput(builder).startsWith("FOOBAR")); } - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "JarOutputStream", - args = {java.io.OutputStream.class, java.util.jar.Manifest.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_classpath() throws Exception { File resources = Support_Resources.createTempFolder(); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java index d2a5110..67debfc 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import tests.support.Support_PlatformFile; @@ -47,7 +42,6 @@ import java.util.zip.ZipException; import java.util.zip.ZipFile; -@TestTargetClass(JarFile.class) public class JarFileTest extends TestCase { // BEGIN android-added @@ -112,12 +106,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#JarFile(java.io.File) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "JarFile", - args = {java.io.File.class} - ) public void test_ConstructorLjava_io_File() { try { JarFile jarFile = new JarFile(new File("Wrong.file")); @@ -149,12 +137,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#JarFile(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarFile", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { try { JarFile jarFile = new JarFile("Wrong.file"); @@ -187,12 +169,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#JarFile(java.lang.String, boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarFile", - args = {java.lang.String.class, boolean.class} - ) public void test_ConstructorLjava_lang_StringZ() { try { JarFile jarFile = new JarFile("Wrong.file", false); @@ -225,12 +201,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarFile", - args = {java.io.File.class, boolean.class} - ) public void test_ConstructorLjava_io_FileZ() { try { JarFile jarFile = new JarFile(new File("Wrong.file"), true); @@ -262,12 +232,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarFile", - args = {java.io.File.class, boolean.class, int.class} - ) public void test_ConstructorLjava_io_FileZI() { try { JarFile jarFile = new JarFile(new File("Wrong.file"), true, @@ -316,12 +280,6 @@ public class JarFileTest extends TestCase { * @tests java.util.jar.JarFile#JarFile(java.io.File) * @tests java.util.jar.JarFile#JarFile(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "JarFile", - args = {java.io.File.class} - ) public void testConstructor_file() throws IOException { File f = new File(resources, jarName); Support_Resources.copyFile(resources, null, jarName); @@ -334,12 +292,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#entries() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_entries() throws Exception { /* * Note only (and all of) the following should be contained in the file @@ -357,12 +309,6 @@ public class JarFileTest extends TestCase { assertEquals(6, i); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_entries2() throws Exception { Support_Resources.copyFile(resources, null, jarName); JarFile jarFile = new JarFile(new File(resources, jarName)); @@ -388,12 +334,6 @@ public class JarFileTest extends TestCase { * @throws IOException * @tests java.util.jar.JarFile#getJarEntry(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getEntry", - args = {java.lang.String.class} - ) public void test_getEntryLjava_lang_String() throws IOException { try { Support_Resources.copyFile(resources, null, jarName); @@ -431,12 +371,6 @@ public class JarFileTest extends TestCase { * @throws IOException * @tests java.util.jar.JarFile#getJarEntry(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getJarEntry", - args = {java.lang.String.class} - ) public void test_getJarEntryLjava_lang_String() throws IOException { try { Support_Resources.copyFile(resources, null, jarName); @@ -474,12 +408,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#getJarEntry(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getEntry", - args = {java.lang.String.class} - ) public void testGetJarEntry() throws Exception { Support_Resources.copyFile(resources, null, jarName); JarFile jarFile = new JarFile(new File(resources, jarName)); @@ -559,12 +487,6 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#getManifest() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getManifest", - args = {} - ) public void test_getManifest() { // Test for method java.util.jar.Manifest // java.util.jar.JarFile.getManifest() @@ -656,16 +578,9 @@ public class JarFileTest extends TestCase { /** * @tests java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "SecurityException and functionality checked.", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) - @AndroidOnly("This test doesn't pass on RI. If entry size is set up " + - "incorrectly, SecurityException is thrown. " + - "But SecurityException is thrown on RI only " + - "if jar file is signed incorreclty.") + // This test doesn't pass on RI. If entry size is set up incorrectly, + // SecurityException is thrown. But SecurityException is thrown on RI only + // if jar file is signed incorrectly. public void test_getInputStreamLjava_util_jar_JarEntry_subtest0() { File signedFile = null; try { @@ -734,12 +649,6 @@ public class JarFileTest extends TestCase { * The jar created by 1.4 which does not provide a * algorithm-Digest-Manifest-Main-Attributes entry in .SF file. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_Jar_created_before_java_5() throws IOException { String modifiedJarName = "Created_by_1_4.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -753,12 +662,6 @@ public class JarFileTest extends TestCase { } /* The jar is intact, then everything is all right. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_JarFile_Integrate_Jar() throws IOException { String modifiedJarName = "Integrate.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -774,12 +677,6 @@ public class JarFileTest extends TestCase { /** * The jar is intact, but the entry object is modified. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getInputStream", - args = {ZipEntry.class} - ) public void testJarVerificationModifiedEntry() throws IOException { Support_Resources.copyFile(resources, null, integrateJar); File f = new File(resources, integrateJar); @@ -805,12 +702,6 @@ public class JarFileTest extends TestCase { * If another entry is inserted into Manifest, no security exception will be * thrown out. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_JarFile_InsertEntry_in_Manifest_Jar() throws IOException { String modifiedJarName = "Inserted_Entry_Manifest.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -831,12 +722,6 @@ public class JarFileTest extends TestCase { * If another entry is inserted into Manifest, no security exception will be * thrown out. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_Inserted_Entry_Manifest_with_DigestCode() throws IOException { String modifiedJarName = "Inserted_Entry_Manifest_with_DigestCode.jar"; @@ -858,12 +743,6 @@ public class JarFileTest extends TestCase { * throw security Exception, but it will anytime before the inputStream got * from getInputStream method has been read to end. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "SecurityException and functionality checked.", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_JarFile_Modified_Class() throws IOException { String modifiedJarName = "Modified_Class.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -893,12 +772,6 @@ public class JarFileTest extends TestCase { * tampered manually. Hence the RI 5.0 JarFile.getInputStream of any * JarEntry will throw security exception. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "SecurityException and functionality checked.", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_JarFile_Modified_Manifest_MainAttributes() throws IOException { String modifiedJarName = "Modified_Manifest_MainAttributes.jar"; @@ -922,12 +795,6 @@ public class JarFileTest extends TestCase { * example Test.class in our jar, the jarFile.getInputStream will throw * Security Exception. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "SecurityException and functionality checked.", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_JarFile_Modified_Manifest_EntryAttributes() throws IOException { String modifiedJarName = "Modified_Manifest_EntryAttributes.jar"; @@ -950,12 +817,6 @@ public class JarFileTest extends TestCase { * If the content of the .SA file is modified, no matter what it resides, * JarFile.getInputStream of any JarEntry will throw Security Exception. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "SecurityException and functionality checked.", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_JarFile_Modified_SF_EntryAttributes() throws IOException { String modifiedJarName = "Modified_SF_EntryAttributes.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -973,12 +834,6 @@ public class JarFileTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "close", - args = {} - ) public void test_close() throws IOException { String modifiedJarName = "Modified_SF_EntryAttributes.jar"; Support_Resources.copyFile(resources, null, modifiedJarName); @@ -996,12 +851,6 @@ public class JarFileTest extends TestCase { * @throws IOException * @tests java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException { File localFile = null; try { @@ -1074,13 +923,7 @@ public class JarFileTest extends TestCase { /** * The jar is intact, but the entry object is modified. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test for issue introduced by HAROMNY-4569. " - + "signed archives containing files with size 0 could not get verified", - method = "getInputStream", - args = {ZipEntry.class} - ) + // Regression test for issue introduced by HARMONY-4569: signed archives containing files with size 0 could not get verified. public void testJarVerificationEmptyEntry() throws IOException { Support_Resources.copyFile(resources, null, emptyEntryJar); File f = new File(resources, emptyEntryJar); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java index 5befa77..06853e7 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java @@ -17,10 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; import tests.support.resource.Support_Resources; import java.io.File; @@ -36,7 +32,6 @@ import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipException; -@TestTargetClass(JarInputStream.class) public class JarInputStreamTest extends junit.framework.TestCase { // a 'normal' jar file private String jarName; @@ -61,12 +56,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { /** * @tests java.util.jar.JarInputStream#JarInputStream(java.io.InputStream) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarInputStream", - args = {java.io.InputStream.class} - ) public void test_ConstructorLjava_io_InputStream() { // Test for method java.util.jar.JarInputStream(java.io.InputStream) InputStream is = null; @@ -103,12 +92,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { /** * @tests java.util.jar.JarInputStream#getManifest() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getManifest", - args = {} - ) public void test_getManifest() { // Test for method java.util.jar.Manifest // java.util.jar.JarInputStream.getManifest() @@ -134,11 +117,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { /** * @tests java.util.jar.JarInputStream#getNextJarEntry() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getNextJarEntry", - args = {} - ) public void test_getNextJarEntry() throws Exception { final Set<String> desired = new HashSet<String>(Arrays .asList(new String[] { @@ -174,11 +152,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getNextJarEntry", - args = {} - ) public void test_getNextJarEntry_Ex() throws Exception { final Set<String> desired = new HashSet<String>(Arrays .asList("foo/", "foo/bar/", "foo/bar/A.class", "Blah.txt")); @@ -213,12 +186,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Exceptions checking missed. Case2", - method = "getNextJarEntry", - args = {} - ) public void test_JarInputStream_Integrate_Jar_getNextEntry() throws IOException { String intJarName = Support_Resources.getURL("Integrate.jar"); @@ -234,12 +201,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "getNextEntry", - args = {} - ) public void test_JarInputStream_Modified_Class_getNextEntry() throws IOException { String modJarName = Support_Resources.getURL("Modified_Class.jar"); @@ -266,12 +227,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "getNextEntry", - args = {} - ) public void test_JarInputStream_Modified_Manifest_MainAttributes_getNextEntry() throws IOException { String modJarName = Support_Resources.getURL("Modified_Manifest_MainAttributes.jar"); @@ -292,12 +247,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "getNextEntry", - args = {} - ) public void test_JarInputStream_Modified_Manifest_EntryAttributes_getNextEntry() throws IOException { String modJarName = Support_Resources @@ -324,12 +273,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "getNextEntry", - args = {} - ) public void test_JarInputStream_Modified_SF_EntryAttributes_getNextEntry() throws IOException { String modJarName = Support_Resources @@ -356,12 +299,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "read", - args = {byte[].class} - ) public void test_JarInputStream_Modified_Class_read() throws IOException { String modJarName = Support_Resources.getURL("Modified_Class.jar"); InputStream is = new URL(modJarName).openConnection().getInputStream(); @@ -390,12 +327,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "read", - args = {byte[].class} - ) public void test_Integrate_Jar_read() throws IOException { String intJarName = Support_Resources.getURL("Integrate.jar"); InputStream is = new URL(intJarName).openConnection().getInputStream(); @@ -416,12 +347,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "read", - args = {byte[].class} - ) public void test_JarInputStream_Modified_Manifest_MainAttributes_read() throws IOException { String modJarName = Support_Resources @@ -452,12 +377,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed.", - method = "read", - args = {byte[].class} - ) public void test_JarInputStream_Modified_SF_EntryAttributes_read() throws IOException { String modJarName = Support_Resources @@ -488,12 +407,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { jin.close(); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "JarInputStream", - args = {java.io.InputStream.class, boolean.class} - ) public void test_ConstructorLjava_io_InputStreamZ() { // Test for method java.util.jar.JarInputStream(java.io.InputStream) InputStream is = null; @@ -527,11 +440,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "close", - args = {} - ) public void test_closeAfterException() throws Exception { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_entry.jar"); @@ -553,11 +461,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "getNextEntry", - args = {} - ) public void test_getNextEntry() throws Exception { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_entry.jar"); @@ -591,12 +494,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "createZipEntry", - args = {java.lang.String.class} - ) public void test_createZipEntryLjava_lang_String() throws Exception { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_entry.jar"); @@ -605,11 +502,6 @@ public class JarInputStreamTest extends junit.framework.TestCase { assertNotNull(mjis.createZipEntry("New entry")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "read", - args = {byte[].class, int.class, int.class} - ) public void test_read$ZII() throws Exception { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_entry_data.jar"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java index b2ecdec..72dfcab 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -36,17 +31,11 @@ import java.util.zip.ZipEntry; import tests.support.resource.Support_Resources; -@TestTargetClass(JarOutputStream.class) public class JarOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.jar.JarOutputStream#putNextEntry(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ) public void test_putNextEntryLjava_util_zip_ZipEntry() throws Exception { // testClass file`s actual extension is .class, since having .class // extension files in source dir causes @@ -133,12 +122,6 @@ public class JarOutputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks IOException", - method = "JarOutputStream", - args = {java.io.OutputStream.class, java.util.jar.Manifest.class} - ) public void test_JarOutputStreamLjava_io_OutputStreamLjava_util_jar_Manifest() throws IOException { File fooJar = File.createTempFile("hyts_", ".jar"); @@ -161,12 +144,6 @@ public class JarOutputStreamTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Can not check IOException", - method = "JarOutputStream", - args = {java.io.OutputStream.class} - ) public void test_JarOutputStreamLjava_io_OutputStream() throws IOException { File fooJar = File.createTempFile("hyts_", ".jar"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java index 42b2543..0834fb1 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java @@ -16,11 +16,6 @@ */ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -38,7 +33,6 @@ import junit.framework.TestCase; import tests.support.resource.Support_Resources; -@TestTargetClass(Manifest.class) public class ManifestTest extends TestCase { private final String jarName = "hyts_patch.jar"; @@ -88,12 +82,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#Manifest() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Manifest", - args = {} - ) public void test_Constructor() { // Test for method java.util.jar.Manifest() Manifest emptyManifest = new Manifest(); @@ -106,12 +94,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#Manifest(java.util.jar.Manifest) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Manifest", - args = {java.util.jar.Manifest.class} - ) public void testCopyingConstructor() throws IOException { Manifest firstManifest = new Manifest(new URL(Support_Resources .getURL(MANIFEST_NAME)).openStream()); @@ -122,12 +104,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#Manifest(Manifest) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Manifest", - args = {java.util.jar.Manifest.class} - ) public void test_ConstructorLjava_util_jar_Manifest() { // Test for method java.util.jar.Manifest() Manifest emptyManifest = new Manifest(); @@ -173,12 +149,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#Manifest(java.io.InputStream) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IOException checking missed.", - method = "Manifest", - args = {java.io.InputStream.class} - ) public void test_ConstructorLjava_io_InputStream() throws IOException { Manifest m = getManifest(attJarName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -214,12 +184,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#clear() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clear", - args = {} - ) public void test_clear() { m2.clear(); assertTrue("Should have no entries", m2.getEntries().isEmpty()); @@ -227,12 +191,6 @@ public class ManifestTest extends TestCase { .isEmpty()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clone", - args = {} - ) public void test_clone() throws IOException { Manifest emptyManifest = new Manifest(); Manifest emptyClone = (Manifest) emptyManifest.clone(); @@ -250,12 +208,6 @@ public class ManifestTest extends TestCase { checkManifest(manifestClone); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equals() throws IOException { Manifest manifest1 = new Manifest(new URL(Support_Resources.getURL( "manifest/hyts_MANIFEST.MF")).openStream()); @@ -269,12 +221,6 @@ public class ManifestTest extends TestCase { assertFalse(manifest1.equals(this)); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() throws IOException { Manifest manifest1 = new Manifest(new URL(Support_Resources .getURL("manifest/hyts_MANIFEST.MF")).openStream()); @@ -286,12 +232,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#getAttributes(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAttributes", - args = {String.class} - ) public void test_getAttributesLjava_lang_String() { assertNull("Should not exist", m2.getAttributes("Doesn't Exist")); @@ -302,12 +242,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#getEntries() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getEntries", - args = {} - ) public void test_getEntries() { Map<String, Attributes> myMap = m2.getEntries(); assertNull("Shouldn't exist", myMap.get("Doesn't exist")); @@ -319,12 +253,6 @@ public class ManifestTest extends TestCase { /** * @tests java.util.jar.Manifest#getMainAttributes() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMainAttributes", - args = {} - ) public void test_getMainAttributes() { // Test for method java.util.jar.Attributes // java.util.jar.Manifest.getMainAttributes() @@ -333,12 +261,6 @@ public class ManifestTest extends TestCase { Attributes.Name.MANIFEST_VERSION)); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {java.io.OutputStream.class} - ) public void test_writeLjava_io_OutputStream() throws IOException { byte b[] = null; Manifest manifest1 = null; @@ -385,12 +307,6 @@ public class ManifestTest extends TestCase { * @see <a * href="http://issues.apache.org/jira/browse/HARMONY-5662">HARMONY-5662</a> */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Manifest", - args = {InputStream.class} - ) public void testNul() throws IOException { String manifestContent = "Manifest-Version: 1.0\nCreated-By: nasty gcc tool\n\n\0"; @@ -413,12 +329,6 @@ public class ManifestTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "Manifest", - args = {InputStream.class} - ) - @KnownFailure("CharsetDecoder fails with an IllegalStateException") public void testDecoding() throws IOException { Manifest m = getManifest(attJarName); final byte[] bVendor = new byte[] { (byte) 0xd0, (byte) 0x9C, @@ -565,12 +475,6 @@ public class ManifestTest extends TestCase { /** * @tests {@link java.util.jar.Manifest#read(java.io.InputStream) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "read", - args = {InputStream.class} - ) public void testRead() { // Regression for HARMONY-89 InputStream is = new InputStreamImpl(); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200PackerTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200PackerTest.java index 0d72108..5e4b668 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200PackerTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200PackerTest.java @@ -16,11 +16,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import tests.support.resource.Support_Resources; @@ -37,29 +32,14 @@ import java.util.jar.JarInputStream; import java.util.jar.Pack200; import java.util.jar.Pack200.Packer; -@TestTargetClass(Pack200.Packer.class) public class Pack200PackerTest extends TestCase { Packer packer; Map properties; - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "properties", - args = {} - ) - @KnownFailure("No Implementation in Android!") public void testProperties() { assertTrue(properties.size()>0); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "pack", - args = {java.util.jar.JarFile.class, java.io.OutputStream.class} - ) - @KnownFailure("No Implementation in Android!") public void testPackJarFileOutputStream() throws IOException { File resources = Support_Resources.createTempFolder(); //Use junit4.jar file for testing pack200 compressing rate. @@ -93,13 +73,6 @@ public class Pack200PackerTest extends TestCase { assertTrue(packFile2.length()>packFile3.length()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "pack", - args = {java.util.jar.JarInputStream.class, java.io.OutputStream.class} - ) - @KnownFailure("No Implementation in Android!") public void testPackJarInputStreamOutputStream() throws IOException { File resources = Support_Resources.createTempFolder(); //Use junit4.jar file for testing pack200 compressing rate. @@ -142,13 +115,6 @@ public class Pack200PackerTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "addPropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - @KnownFailure("No Implementation in Android!") public void testAddPropertyChangeListener() { MyPCL pcl = new MyPCL(); packer.addPropertyChangeListener(pcl); @@ -157,13 +123,6 @@ public class Pack200PackerTest extends TestCase { assertTrue(pcl.isCalled()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removePropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - @KnownFailure("No Implementation in Android!") public void testRemovePropertyChangeListener() { MyPCL pcl = new MyPCL(); packer.addPropertyChangeListener(pcl); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200Test.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200Test.java index 9fb3cf9..0e2b688 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200Test.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200Test.java @@ -16,27 +16,14 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.jar.Pack200; -@TestTargetClass(Pack200.class) public class Pack200Test extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "newPacker", - args = {} - ) - @KnownFailure("No Implementation in Android!") public void testNewPacker() { Method[] methodsInt = Pack200.Packer.class.getDeclaredMethods(); Method[] methodsImpl = Pack200.newPacker().getClass() @@ -68,13 +55,6 @@ public class Pack200Test extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "newUnpacker", - args = {} - ) - @KnownFailure("No Implementation in Android!") public void testNewUnpacker() { assertNotNull(Pack200.newUnpacker().getClass()); Method[] methodsInt = Pack200.Unpacker.class.getDeclaredMethods(); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200UnpackerTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200UnpackerTest.java index c1f9813..249a7cf 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200UnpackerTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/Pack200UnpackerTest.java @@ -16,11 +16,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import tests.support.resource.Support_Resources; @@ -38,29 +33,14 @@ import java.util.jar.Pack200; import java.util.jar.Pack200.Packer; import java.util.jar.Pack200.Unpacker; -@TestTargetClass(Pack200.Unpacker.class) public class Pack200UnpackerTest extends TestCase { Unpacker unpacker; Map properties; - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "properties", - args = {} - ) - @KnownFailure("No Implementation in Android!") public void testProperties() { assertTrue(properties.size()>0); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "unpack", - args = {java.io.File.class, java.util.jar.JarOutputStream.class} - ) - @KnownFailure("No Implementation in Android!") public void testUnpackInputStreamJarOutputStream() throws IOException { File resources = Support_Resources.createTempFolder(); //Use junit4.jar file for testing pack200 compressing rate. @@ -115,13 +95,6 @@ public class Pack200UnpackerTest extends TestCase { assertEquals(jarEntries, new JarFile(jarFile3).size()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "unpack", - args = {java.io.InputStream.class, java.util.jar.JarOutputStream.class} - ) - @KnownFailure("No Implementation in Android!") public void testUnpackFileJarOutputStream() throws IOException { File resources = Support_Resources.createTempFolder(); //Use junit4.jar file for testing pack200 compressing rate. @@ -191,13 +164,6 @@ public class Pack200UnpackerTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "addPropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - @KnownFailure("No Implementation in Android!") public void testAddPropertyChangeListener() { MyPCL pcl = new MyPCL(); unpacker.addPropertyChangeListener(pcl); @@ -206,13 +172,6 @@ public class Pack200UnpackerTest extends TestCase { assertTrue(pcl.isCalled()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removePropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - @KnownFailure("No Implementation in Android!") public void testRemovePropertyChangeListener() { MyPCL pcl = new MyPCL(); unpacker.addPropertyChangeListener(pcl); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java index 013974c..5ce657b 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java @@ -17,10 +17,6 @@ package org.apache.harmony.archive.tests.java.util.jar; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; import static tests.support.Support_Exec.javaProcessBuilder; import static tests.support.Support_Exec.execAndGetOutput; import tests.support.resource.Support_Resources; @@ -42,15 +38,7 @@ import java.util.zip.ZipOutputStream; * some tests are just copy of JarExecTest ones */ -@TestTargetClass(ZipOutputStream.class) public class ZipExecTest extends junit.framework.TestCase { - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Regression functional test. Exception checking missed.", - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_1562() throws Exception { Manifest man = new Manifest(); Attributes att = man.getMainAttributes(); @@ -86,13 +74,6 @@ public class ZipExecTest extends junit.framework.TestCase { * * @throws Exception in case of troubles */ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "ZipOutputStream", - args = {java.io.OutputStream.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_zip_class_path() throws Exception { File fooZip = File.createTempFile("hyts_", ".zip"); File barZip = File.createTempFile("hyts_", ".zip"); @@ -160,13 +141,6 @@ public class ZipExecTest extends junit.framework.TestCase { } - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "ZipOutputStream", - args = {java.io.OutputStream.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_zip_jar_mix() throws Exception { File fooJar = File.createTempFile("hyts_", ".jar"); File barZip = File.createTempFile("hyts_", ".zip"); @@ -201,13 +175,6 @@ public class ZipExecTest extends junit.framework.TestCase { execAndGetOutput(builder).startsWith("FOOBAR")); } - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "ZipOutputStream", - args = {java.io.OutputStream.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_zip_jar_mix_1() throws Exception { File fooZip = File.createTempFile("hyts_", ".zip"); File barJar = File.createTempFile("hyts_", ".jar"); @@ -251,13 +218,6 @@ public class ZipExecTest extends junit.framework.TestCase { * * @throws Exception in case of troubles */ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - notes = "Functional test.", - method = "ZipOutputStream", - args = {java.io.OutputStream.class} - ) - @KnownFailure("Maybe not a failure, but dalvikvm -jar is not supported (, as yet).") public void test_main_class_in_another_zip() throws Exception { File fooZip = File.createTempFile("hyts_", ".zip"); File barZip = File.createTempFile("hyts_", ".zip"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java index 532a3a6..7290ac2 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java @@ -14,211 +14,156 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.util.zip.Adler32; -@TestTargetClass(Adler32.class) public class Adler32Test extends junit.framework.TestCase { - /** - * @tests java.util.zip.Adler32#Adler32() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Adler32", - args = {} - ) - public void test_Constructor() { - // test method of java.util.zip.Adler32() - Adler32 adl = new Adler32(); - assertEquals("Constructor of adl32 failed", 1, adl.getValue()); - } - - /** - * @tests java.util.zip.Adler32#getValue() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getValue", - args = {} - ) - public void test_getValue() { - // test methods of java.util.zip.getValue() - Adler32 adl = new Adler32(); - assertEquals( - "GetValue should return a zero as a result of construction an object of Adler32", - 1, adl.getValue()); - - adl.reset(); - adl.update(1); - // System.out.print("value of adl"+adl.getValue()); - // The value of the adl should be 131074 - assertEquals( - "update(int) failed to update the checksum to the correct value ", - 131074, adl.getValue()); - adl.reset(); - assertEquals("reset failed to reset the checksum value to zero", 1, adl - .getValue()); - - adl.reset(); - adl.update(Integer.MIN_VALUE); - // System.out.print("value of adl " + adl.getValue()); - // The value of the adl should be 65537 - assertEquals( - "update(min) failed to update the checksum to the correct value ", - 65537L, adl.getValue()); - } - - /** - * @tests java.util.zip.Adler32#reset() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reset", - args = {} - ) - public void test_reset() { - // test methods of java.util.zip.reset() - Adler32 adl = new Adler32(); - adl.update(1); - // System.out.print("value of adl"+adl.getValue()); - // The value of the adl should be 131074 - assertEquals( - "update(int) failed to update the checksum to the correct value ", - 131074, adl.getValue()); - adl.reset(); - assertEquals("reset failed to reset the checksum value to zero", 1, adl - .getValue()); - } - - /** - * @tests java.util.zip.Adler32#update(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {int.class} - ) - public void test_updateI() { - // test methods of java.util.zip.update(int) - Adler32 adl = new Adler32(); - adl.update(1); - // The value of the adl should be 131074 - assertEquals( - "update(int) failed to update the checksum to the correct value ", - 131074, adl.getValue()); - - adl.reset(); - adl.update(Integer.MAX_VALUE); - // System.out.print("value of adl " + adl.getValue()); - // The value of the adl should be 16777472 - assertEquals( - "update(max) failed to update the checksum to the correct value ", - 16777472L, adl.getValue()); - - adl.reset(); - adl.update(Integer.MIN_VALUE); - // System.out.print("value of adl " + adl.getValue()); - // The value of the adl should be 65537 - assertEquals( - "update(min) failed to update the checksum to the correct value ", - 65537L, adl.getValue()); - - } - - /** - * @tests java.util.zip.Adler32#update(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {byte[].class} - ) - public void test_update$B() { - // test method of java.util.zip.update(byte[]) - byte byteArray[] = {1, 2}; - Adler32 adl = new Adler32(); - adl.update(byteArray); - // System.out.print("value of adl"+adl.getValue()); - // The value of the adl should be 393220 - assertEquals( - "update(byte[]) failed to update the checksum to the correct value ", - 393220, adl.getValue()); - - adl.reset(); - byte byteEmpty[] = new byte[10000]; - adl.update(byteEmpty); - // System.out.print("value of adl"+adl.getValue()); - // The value of the adl should be 655360001 - assertEquals( - "update(byte[]) failed to update the checksum to the correct value ", - 655360001L, adl.getValue()); - - } - - /** - * @tests java.util.zip.Adler32#update(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {byte[].class, int.class, int.class} - ) - public void test_update$BII() { - // test methods of java.util.zip.update(byte[],int,int) - byte[] byteArray = {1, 2, 3}; - Adler32 adl = new Adler32(); - int off = 2;// accessing the 2nd element of byteArray - int len = 1; - int lenError = 3; - int offError = 4; - adl.update(byteArray, off, len); - // System.out.print("value of adl"+adl.getValue()); - // The value of the adl should be 262148 - assertEquals( - "update(byte[],int,int) failed to update the checksum to the correct value ", - 262148, adl.getValue()); - int r = 0; - - try { - adl.update(byteArray, off, lenError); - } catch (ArrayIndexOutOfBoundsException e) { - r = 1; - } - assertEquals( - "update(byte[],int,int) failed b/c lenError>byte[].length-off", - 1, r); - - try { - adl.update(byteArray, offError, len); - } catch (ArrayIndexOutOfBoundsException e) { - r = 2; - } - assertEquals( - "update(byte[],int,int) failed b/c offError>byte[].length", 2, - r); - - } - - @Override + /** + * @tests java.util.zip.Adler32#Adler32() + */ + public void test_Constructor() { + // test method of java.util.zip.Adler32() + Adler32 adl = new Adler32(); + assertEquals("Constructor of adl32 failed", 1, adl.getValue()); + } + + /** + * @tests java.util.zip.Adler32#getValue() + */ + public void test_getValue() { + // test methods of java.util.zip.getValue() + Adler32 adl = new Adler32(); + assertEquals("GetValue should return a zero as a result of construction an object of Adler32", + 1, adl.getValue()); + + adl.reset(); + adl.update(1); + // System.out.print("value of adl"+adl.getValue()); + // The value of the adl should be 131074 + assertEquals("update(int) failed to update the checksum to the correct value ", + 131074, adl.getValue()); + adl.reset(); + assertEquals("reset failed to reset the checksum value to zero", 1, adl + .getValue()); + + adl.reset(); + adl.update(Integer.MIN_VALUE); + // System.out.print("value of adl " + adl.getValue()); + // The value of the adl should be 65537 + assertEquals("update(min) failed to update the checksum to the correct value ", + 65537L, adl.getValue()); + } + + /** + * @tests java.util.zip.Adler32#reset() + */ + public void test_reset() { + // test methods of java.util.zip.reset() + Adler32 adl = new Adler32(); + adl.update(1); + // System.out.print("value of adl"+adl.getValue()); + // The value of the adl should be 131074 + assertEquals("update(int) failed to update the checksum to the correct value ", + 131074, adl.getValue()); + adl.reset(); + assertEquals("reset failed to reset the checksum value to zero", 1, adl + .getValue()); + } + + /** + * @tests java.util.zip.Adler32#update(int) + */ + public void test_updateI() { + // test methods of java.util.zip.update(int) + Adler32 adl = new Adler32(); + adl.update(1); + // The value of the adl should be 131074 + assertEquals("update(int) failed to update the checksum to the correct value ", + 131074, adl.getValue()); + + adl.reset(); + adl.update(Integer.MAX_VALUE); + // System.out.print("value of adl " + adl.getValue()); + // The value of the adl should be 16777472 + assertEquals("update(max) failed to update the checksum to the correct value ", + 16777472L, adl.getValue()); + + adl.reset(); + adl.update(Integer.MIN_VALUE); + // System.out.print("value of adl " + adl.getValue()); + // The value of the adl should be 65537 + assertEquals("update(min) failed to update the checksum to the correct value ", + 65537L, adl.getValue()); + + } + + /** + * @tests java.util.zip.Adler32#update(byte[]) + */ + public void test_update$B() { + // test method of java.util.zip.update(byte[]) + byte byteArray[] = { 1, 2 }; + Adler32 adl = new Adler32(); + adl.update(byteArray); + // System.out.print("value of adl"+adl.getValue()); + // The value of the adl should be 393220 + assertEquals("update(byte[]) failed to update the checksum to the correct value ", + 393220, adl.getValue()); + + adl.reset(); + byte byteEmpty[] = new byte[10000]; + adl.update(byteEmpty); + // System.out.print("value of adl"+adl.getValue()); + // The value of the adl should be 655360001 + assertEquals("update(byte[]) failed to update the checksum to the correct value ", + 655360001L, adl.getValue()); + + } + + /** + * @tests java.util.zip.Adler32#update(byte[], int, int) + */ + public void test_update$BII() { + // test methods of java.util.zip.update(byte[],int,int) + byte[] byteArray = { 1, 2, 3 }; + Adler32 adl = new Adler32(); + int off = 2;// accessing the 2nd element of byteArray + int len = 1; + int lenError = 3; + int offError = 4; + adl.update(byteArray, off, len); + // System.out.print("value of adl"+adl.getValue()); + // The value of the adl should be 262148 + assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ", + 262148, adl.getValue()); + int r = 0; + + try { + adl.update(byteArray, off, lenError); + } catch (ArrayIndexOutOfBoundsException e) { + r = 1; + } + assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off", + 1, r); + + try { + adl.update(byteArray, offError, len); + } catch (ArrayIndexOutOfBoundsException e) { + r = 2; + } + assertEquals("update(byte[],int,int) failed b/c offError>byte[].length", + 2, r); + + } + + @Override protected void setUp() { - } + } - @Override + @Override protected void tearDown() { - } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java index acde889..562b396 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * Test suite for java.util.zip package. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( + TestSuite suite = new TestSuite( "Suite org.apache.harmony.archive.tests.java.util.zip"); // $JUnit-BEGIN$ suite.addTestSuite(Adler32Test.class); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java index 805cab3..7eb0566 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java @@ -14,229 +14,173 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.util.zip.CRC32; -@TestTargetClass(CRC32.class) public class CRC32Test extends junit.framework.TestCase { - /** - * @tests java.util.zip.CRC32#CRC32() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "CRC32", - args = {} - ) - public void test_Constructor() { - // test methods of java.util.zip.CRC32() - CRC32 crc = new CRC32(); - assertEquals("Constructor of CRC32 failed", 0, crc.getValue()); - } - - /** - * @tests java.util.zip.CRC32#getValue() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getValue", - args = {} - ) - public void test_getValue() { - // test methods of java.util.zip.crc32.getValue() - CRC32 crc = new CRC32(); - assertEquals( - "getValue() should return a zero as a result of constructing a CRC32 instance", - 0, crc.getValue()); - - crc.reset(); - crc.update(Integer.MAX_VALUE); - // System.out.print("value of crc " + crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 4278190080 - assertEquals( - "update(max) failed to update the checksum to the correct value ", - 4278190080L, crc.getValue()); - - crc.reset(); - byte byteEmpty[] = new byte[10000]; - crc.update(byteEmpty); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 1295764014 - assertEquals( - "update(byte[]) failed to update the checksum to the correct value ", - 1295764014L, crc.getValue()); - - crc.reset(); - crc.update(1); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 2768625435 - // assertEquals("update(int) failed to update the checksum to the - // correct - // value ",2768625435L, crc.getValue()); - crc.reset(); - assertEquals("reset failed to reset the checksum value to zero", 0, crc - .getValue()); - } - - /** - * @tests java.util.zip.CRC32#reset() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reset", - args = {} - ) - public void test_reset() { - // test methods of java.util.zip.crc32.reset() - CRC32 crc = new CRC32(); - crc.update(1); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 2768625435 - assertEquals( - "update(int) failed to update the checksum to the correct value ", - 2768625435L, crc.getValue()); - crc.reset(); - assertEquals("reset failed to reset the checksum value to zero", 0, crc - .getValue()); - - } - - /** - * @tests java.util.zip.CRC32#update(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {int.class} - ) - public void test_updateI() { - // test methods of java.util.zip.crc32.update(int) - CRC32 crc = new CRC32(); - crc.update(1); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 2768625435 - assertEquals( - "update(1) failed to update the checksum to the correct value ", - 2768625435L, crc.getValue()); - - crc.reset(); - crc.update(Integer.MAX_VALUE); - // System.out.print("value of crc " + crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 4278190080 - assertEquals( - "update(max) failed to update the checksum to the correct value ", - 4278190080L, crc.getValue()); - - crc.reset(); - crc.update(Integer.MIN_VALUE); - // System.out.print("value of crc " + crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 3523407757 - assertEquals( - "update(min) failed to update the checksum to the correct value ", - 3523407757L, crc.getValue()); - } - - /** - * @tests java.util.zip.CRC32#update(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {byte[].class} - ) - public void test_update$B() { - // test methods of java.util.zip.crc32.update(byte[]) - byte byteArray[] = {1, 2}; - CRC32 crc = new CRC32(); - crc.update(byteArray); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 3066839698 - assertEquals( - "update(byte[]) failed to update the checksum to the correct value ", - 3066839698L, crc.getValue()); - - crc.reset(); - byte byteEmpty[] = new byte[10000]; - crc.update(byteEmpty); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 1295764014 - assertEquals( - "update(byte[]) failed to update the checksum to the correct value ", - 1295764014L, crc.getValue()); - } - - /** - * @tests java.util.zip.CRC32#update(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "update", - args = {byte[].class, int.class, int.class} - ) - public void test_update$BII() { - // test methods of java.util.zip.update(byte[],int,int) - byte[] byteArray = {1, 2, 3}; - CRC32 crc = new CRC32(); - int off = 2;// accessing the 2nd element of byteArray - int len = 1; - int lenError = 3; - int offError = 4; - crc.update(byteArray, off, len); - // System.out.print("value of crc"+crc.getValue()); - // Ran JDK and discovered that the value of the CRC should be - // 1259060791 - assertEquals( - "update(byte[],int,int) failed to update the checksum to the correct value ", - 1259060791L, crc.getValue()); - int r = 0; - try { - crc.update(byteArray, off, lenError); - } catch (ArrayIndexOutOfBoundsException e) { - r = 1; - } - assertEquals( - "update(byte[],int,int) failed b/c lenError>byte[].length-off", - 1, r); - - try { - crc.update(byteArray, offError, len); - } catch (ArrayIndexOutOfBoundsException e) { - r = 2; - } - assertEquals( - "update(byte[],int,int) failed b/c offError>byte[].length", 2, - r); - } - - @Override + /** + * @tests java.util.zip.CRC32#CRC32() + */ + public void test_Constructor() { + // test methods of java.util.zip.CRC32() + CRC32 crc = new CRC32(); + assertEquals("Constructor of CRC32 failed", 0, crc.getValue()); + } + + /** + * @tests java.util.zip.CRC32#getValue() + */ + public void test_getValue() { + // test methods of java.util.zip.crc32.getValue() + CRC32 crc = new CRC32(); + assertEquals("getValue() should return a zero as a result of constructing a CRC32 instance", + 0, crc.getValue()); + + crc.reset(); + crc.update(Integer.MAX_VALUE); + // System.out.print("value of crc " + crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 4278190080 + assertEquals("update(max) failed to update the checksum to the correct value ", + 4278190080L, crc.getValue()); + + crc.reset(); + byte byteEmpty[] = new byte[10000]; + crc.update(byteEmpty); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 1295764014 + assertEquals("update(byte[]) failed to update the checksum to the correct value ", + 1295764014L, crc.getValue()); + + crc.reset(); + crc.update(1); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 2768625435 + // assertEquals("update(int) failed to update the checksum to the correct + // value ",2768625435L, crc.getValue()); + crc.reset(); + assertEquals("reset failed to reset the checksum value to zero", 0, crc + .getValue()); + } + + /** + * @tests java.util.zip.CRC32#reset() + */ + public void test_reset() { + // test methods of java.util.zip.crc32.reset() + CRC32 crc = new CRC32(); + crc.update(1); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 2768625435 + assertEquals("update(int) failed to update the checksum to the correct value ", + 2768625435L, crc.getValue()); + crc.reset(); + assertEquals("reset failed to reset the checksum value to zero", 0, crc + .getValue()); + + } + + /** + * @tests java.util.zip.CRC32#update(int) + */ + public void test_updateI() { + // test methods of java.util.zip.crc32.update(int) + CRC32 crc = new CRC32(); + crc.update(1); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 2768625435 + assertEquals("update(1) failed to update the checksum to the correct value ", + 2768625435L, crc.getValue()); + + crc.reset(); + crc.update(Integer.MAX_VALUE); + // System.out.print("value of crc " + crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 4278190080 + assertEquals("update(max) failed to update the checksum to the correct value ", + 4278190080L, crc.getValue()); + + crc.reset(); + crc.update(Integer.MIN_VALUE); + // System.out.print("value of crc " + crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 3523407757 + assertEquals("update(min) failed to update the checksum to the correct value ", + 3523407757L, crc.getValue()); + } + + /** + * @tests java.util.zip.CRC32#update(byte[]) + */ + public void test_update$B() { + // test methods of java.util.zip.crc32.update(byte[]) + byte byteArray[] = { 1, 2 }; + CRC32 crc = new CRC32(); + crc.update(byteArray); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 3066839698 + assertEquals("update(byte[]) failed to update the checksum to the correct value ", + 3066839698L, crc.getValue()); + + crc.reset(); + byte byteEmpty[] = new byte[10000]; + crc.update(byteEmpty); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 1295764014 + assertEquals("update(byte[]) failed to update the checksum to the correct value ", + 1295764014L, crc.getValue()); + } + + /** + * @tests java.util.zip.CRC32#update(byte[], int, int) + */ + public void test_update$BII() { + // test methods of java.util.zip.update(byte[],int,int) + byte[] byteArray = { 1, 2, 3 }; + CRC32 crc = new CRC32(); + int off = 2;// accessing the 2nd element of byteArray + int len = 1; + int lenError = 3; + int offError = 4; + crc.update(byteArray, off, len); + // System.out.print("value of crc"+crc.getValue()); + // Ran JDK and discovered that the value of the CRC should be + // 1259060791 + assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ", + 1259060791L, crc.getValue()); + int r = 0; + try { + crc.update(byteArray, off, lenError); + } catch (ArrayIndexOutOfBoundsException e) { + r = 1; + } + assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off", + 1, r); + + try { + crc.update(byteArray, offError, len); + } catch (ArrayIndexOutOfBoundsException e) { + r = 2; + } + assertEquals("update(byte[],int,int) failed b/c offError>byte[].length", + 2, r); + } + + @Override protected void setUp() { - } + } - @Override + @Override protected void tearDown() { - } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java index 4450bdf..393923d 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java @@ -14,139 +14,99 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; import java.io.InputStream; +import java.io.IOException; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; + import junit.framework.TestCase; import tests.support.resource.Support_Resources; - -@TestTargetClass(CheckedInputStream.class) public class CheckedInputStreamTest extends TestCase { + + @Override + protected void tearDown() { + try { + File deletedFile = new File("empty.txt"); + deletedFile.delete(); + } catch (SecurityException e) { + fail("Cannot delete file for security reasons"); + } - /** - * @tests java.util.zip.CheckedInputStream#CheckedInputStream(java.io.InputStream, - * java.util.zip.Checksum) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "CheckedInputStream", - args = {java.io.InputStream.class, java.util.zip.Checksum.class} - ) - public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Checksum() - throws Exception { - InputStream checkInput = Support_Resources - .getStream("hyts_checkInput.txt"); - CheckedInputStream checkIn = new CheckedInputStream(checkInput, - new CRC32()); - assertEquals("constructor of checkedInputStream has failed", 0, checkIn - .getChecksum().getValue()); + } + + /** + * @tests java.util.zip.CheckedInputStream#CheckedInputStream(java.io.InputStream, + * java.util.zip.Checksum) + */ + public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Checksum() throws Exception { + InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt"); + CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32()); + assertEquals("constructor of checkedInputStream has failed", 0, checkIn.getChecksum() + .getValue()); checkInput.close(); } - /** - * @tests java.util.zip.CheckedInputStream#getChecksum() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getChecksum", - args = {} - ) - public void test_getChecksum() throws Exception { + /** + * @tests java.util.zip.CheckedInputStream#getChecksum() + */ + public void test_getChecksum() throws Exception { byte outBuf[] = new byte[100]; // testing getChecksum for an empty file - File empty = File.createTempFile("empty", ".txt"); - empty.deleteOnExit(); - FileOutputStream outEmp = new FileOutputStream(empty); + FileOutputStream outEmp = new FileOutputStream("empty.txt"); outEmp.close(); - InputStream inEmp = new FileInputStream(empty); - CheckedInputStream checkEmpty = new CheckedInputStream(inEmp, - new CRC32()); + InputStream inEmp = new FileInputStream("empty.txt"); + CheckedInputStream checkEmpty = new CheckedInputStream(inEmp, new CRC32()); while (checkEmpty.read() >= 0) { } - assertEquals("the checkSum value of an empty file is not zero", 0, - checkEmpty.getChecksum().getValue()); + assertEquals("the checkSum value of an empty file is not zero", 0, checkEmpty + .getChecksum().getValue()); inEmp.close(); // testing getChecksum for the file checkInput - InputStream checkInput = Support_Resources - .getStream("hyts_checkInput.txt"); - CheckedInputStream checkIn = new CheckedInputStream(checkInput, - new CRC32()); + InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt"); + CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32()); while (checkIn.read() >= 0) { } // ran JDK and found that the checkSum value of this is 2036203193 // System.out.print(" " + checkIn.getChecksum().getValue()); - assertEquals("the checksum value is incorrect", 2036203193, checkIn - .getChecksum().getValue()); + assertEquals("the checksum value is incorrect", 2036203193, checkIn.getChecksum() + .getValue()); checkInput.close(); // testing getChecksum for file checkInput checkInput = Support_Resources.getStream("hyts_checkInput.txt"); - CheckedInputStream checkIn2 = new CheckedInputStream(checkInput, - new CRC32()); + CheckedInputStream checkIn2 = new CheckedInputStream(checkInput, new CRC32()); checkIn2.read(outBuf, 0, 10); // ran JDK and found that the checkSum value of this is 2235765342 // System.out.print(" " + checkIn2.getChecksum().getValue()); - assertEquals("the checksum value is incorrect", 2235765342L, checkIn2 - .getChecksum().getValue()); + assertEquals("the checksum value is incorrect", 2235765342L, checkIn2.getChecksum() + .getValue()); checkInput.close(); } - /** - * @tests java.util.zip.CheckedInputStream#skip(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "skip", - args = {long.class} - ) - public void test_skipJ() throws Exception { + /** + * @tests java.util.zip.CheckedInputStream#skip(long) + */ + public void test_skipJ() throws Exception { // testing that the return by skip is valid - InputStream checkInput = Support_Resources - .getStream("hyts_checkInput.txt"); - CheckedInputStream checkIn = new CheckedInputStream(checkInput, - new CRC32()); + InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt"); + CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32()); long skipValue = 5; - assertEquals( - "the value returned by skip(n) is not the same as its parameter", + assertEquals("the value returned by skip(n) is not the same as its parameter", skipValue, checkIn.skip(skipValue)); checkIn.skip(skipValue); // ran JDK and found the checkSum value is 2235765342 // System.out.print(checkIn.getChecksum().getValue()); - assertEquals("checkSum value is not correct", 2235765342L, checkIn - .getChecksum().getValue()); + assertEquals("checkSum value is not correct", 2235765342L, checkIn.getChecksum() + .getValue()); checkInput.close(); - try { - checkInput.skip(33); - fail("IOException expected"); - } catch (IOException ee) { - // expected - } } - /** - * @tests java.util.zip.CheckedInputStream#read() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "read", - args = {} - ) public void test_read() throws Exception { // testing that the return by skip is valid InputStream checkInput = Support_Resources @@ -161,16 +121,9 @@ public class CheckedInputStreamTest extends TestCase { } catch (IOException ee) { // expected } - long skipValue = 5; checkInput.close(); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "read", - args = {byte[].class, int.class, int.class} - ) public void test_read$byteII() throws Exception { // testing that the return by skip is valid InputStream checkInput = Support_Resources @@ -186,7 +139,6 @@ public class CheckedInputStreamTest extends TestCase { } catch (IOException ee) { // expected } - long skipValue = 5; checkInput.close(); } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java index 31974d1..9a56226 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -29,19 +24,12 @@ import java.util.zip.Adler32; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; -@TestTargetClass(CheckedOutputStream.class) public class CheckedOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.CheckedOutputStream#CheckedOutputStream(java.io.OutputStream, * java.util.zip.Checksum) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "CheckedOutputStream", - args = {java.io.OutputStream.class, java.util.zip.Checksum.class} - ) public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Checksum() { // test method java.util.zip.checkedOutputStream.constructor try { @@ -62,12 +50,6 @@ public class CheckedOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.CheckedOutputStream#getChecksum() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getChecksum", - args = {} - ) public void test_getChecksum() { // test method java.util.zip.checkedOutputStream.getChecksum() byte byteArray[] = {1, 2, 3, 'e', 'r', 't', 'g', 3, 6}; @@ -100,12 +82,6 @@ public class CheckedOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.CheckedOutputStream#write(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {int.class} - ) public void test_writeI() { // test method java.util.zip.checkedOutputStream.writeI() CheckedOutputStream chkOut = null; @@ -137,12 +113,6 @@ public class CheckedOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.CheckedOutputStream#write(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {byte[].class, int.class, int.class} - ) public void test_write$BII() { // test method java.util.zip.checkOutputStream.writeBII() CheckedOutputStream chkOut = null; diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java index 6561bbd..929227d 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java @@ -16,35 +16,17 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import java.util.zip.DataFormatException; -@TestTargetClass(DataFormatException.class) public class DataFormatExceptionTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DataFormatException", - args = {} - ) public void testDataFormatException() { DataFormatException dfe = new DataFormatException(); assertEquals(dfe.getMessage(), null); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DataFormatException", - args = {java.lang.String.class} - ) public void testDataFormatExceptionString() { DataFormatException dfe = new DataFormatException("Test"); assertEquals(dfe.getMessage(), "Test"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java index 738f610..be28774 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.EOFException; import java.io.File; import java.io.FileInputStream; @@ -34,7 +29,6 @@ import java.util.zip.InflaterInputStream; import junit.framework.TestCase; -@TestTargetClass(DeflaterOutputStream.class) public class DeflaterOutputStreamTest extends TestCase { private class MyDeflaterOutputStream extends DeflaterOutputStream { @@ -64,10 +58,6 @@ public class DeflaterOutputStreamTest extends TestCase { boolean getDaflateFlag() { return deflateFlag; } - - void cleanDaflateFlag() { - deflateFlag = false; - } } private byte outPutBuf[] = new byte[500]; @@ -75,7 +65,7 @@ public class DeflaterOutputStreamTest extends TestCase { @Override protected void setUp() { // setting up a deflater to be used - byte byteArray[] = {1, 3, 4, 7, 8}; + byte byteArray[] = { 1, 3, 4, 7, 8 }; int x = 0; Deflater deflate = new Deflater(1); deflate.setInput(byteArray); @@ -93,16 +83,9 @@ public class DeflaterOutputStreamTest extends TestCase { * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream, * java.util.zip.Deflater) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DeflaterOutputStream", - args = {java.io.OutputStream.class, java.util.zip.Deflater.class} - ) - public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater() - throws Exception { - byte byteArray[] = {1, 3, 4, 7, 8}; - File f1 = File.createTempFile("hyts_Constru_OD", ".tst"); + public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater() throws Exception { + byte byteArray[] = { 1, 3, 4, 7, 8 }; + File f1 = new File("hyts_Constru(OD).tst"); FileOutputStream fos = new FileOutputStream(f1); Deflater defl = null; MyDeflaterOutputStream dos; @@ -127,14 +110,8 @@ public class DeflaterOutputStreamTest extends TestCase { /** * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DeflaterOutputStream", - args = {java.io.OutputStream.class} - ) public void test_ConstructorLjava_io_OutputStream() throws Exception { - File f1 = File.createTempFile("hyts_Constru_O", ".tst"); + File f1 = new File("hyts_Constru(O).tst"); FileOutputStream fos = new FileOutputStream(f1); MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos); @@ -151,19 +128,13 @@ public class DeflaterOutputStreamTest extends TestCase { * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream, * java.util.zip.Deflater, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DeflaterOutputStream", - args = {java.io.OutputStream.class, java.util.zip.Deflater.class, int.class} - ) public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_DeflaterI() throws Exception { int buf = 5; int negBuf = -5; int zeroBuf = 0; - byte byteArray[] = {1, 3, 4, 7, 8, 3, 6}; - File f1 = File.createTempFile("hyts_Constru_ODI", ".tst"); + byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 }; + File f1 = new File("hyts_Constru(ODI).tst"); FileOutputStream fos = new FileOutputStream(f1); Deflater defl = null; MyDeflaterOutputStream dos; @@ -203,12 +174,6 @@ public class DeflaterOutputStreamTest extends TestCase { /** * @tests java.util.zip.DeflaterOutputStream#close() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IOException can not be checked.", - method = "close", - args = {} - ) public void test_close() throws Exception { File f1 = File.createTempFile("close", ".tst"); @@ -268,20 +233,14 @@ public class DeflaterOutputStreamTest extends TestCase { /** * @tests java.util.zip.DeflaterOutputStream#finish() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finish", - args = {} - ) public void test_finish() throws Exception { // Need test to see if method finish() actually finishes // Only testing possible errors, not if it actually works - File f1 = File.createTempFile("finish", ".tst"); + File f1 = new File("finish.tst"); FileOutputStream fos1 = new FileOutputStream(f1); DeflaterOutputStream dos = new DeflaterOutputStream(fos1); - byte byteArray[] = {1, 3, 4, 6}; + byte byteArray[] = { 1, 3, 4, 6 }; dos.write(byteArray); dos.finish(); @@ -325,14 +284,8 @@ public class DeflaterOutputStreamTest extends TestCase { /** * @tests java.util.zip.DeflaterOutputStream#write(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {int.class} - ) public void test_writeI() throws Exception { - File f1 = File.createTempFile("writeI1", ".tst"); + File f1 = new File("writeI1.tst"); FileOutputStream fos = new FileOutputStream(f1); DeflaterOutputStream dos = new DeflaterOutputStream(fos); for (int i = 0; i < 3; i++) { @@ -367,17 +320,11 @@ public class DeflaterOutputStreamTest extends TestCase { /** * @tests java.util.zip.DeflaterOutputStream#write(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {byte[].class, int.class, int.class} - ) public void test_write$BII() throws Exception { - byte byteArray[] = {1, 3, 4, 7, 8, 3, 6}; + byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 }; // Test to see if the correct bytes are saved. - File f1 = File.createTempFile("writeBII", ".tst"); + File f1 = new File("writeBII.tst"); FileOutputStream fos1 = new FileOutputStream(f1); DeflaterOutputStream dos1 = new DeflaterOutputStream(fos1); dos1.write(byteArray, 2, 3); @@ -393,7 +340,7 @@ public class DeflaterOutputStreamTest extends TestCase { f1.delete(); // Test for trying to write more bytes than available from the array - File f2 = File.createTempFile("writeBII", ".tst"); + File f2 = new File("writeBII2.tst"); FileOutputStream fos2 = new FileOutputStream(f2); DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2); try { @@ -441,13 +388,6 @@ public class DeflaterOutputStreamTest extends TestCase { f2.delete(); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "deflate", - args = {} - ) public void test_deflate() throws Exception { File f1 = File.createTempFile("writeI1", ".tst"); FileOutputStream fos = new FileOutputStream(f1); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java index ae77450..93fe710 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java @@ -17,15 +17,9 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.zip.Adler32; - import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; @@ -33,447 +27,376 @@ import java.util.zip.Inflater; import junit.framework.TestCase; import tests.support.resource.Support_Resources; -@TestTargetClass(Deflater.class) public class DeflaterTest extends TestCase { - class MyDeflater extends Deflater { - MyDeflater() { - super(); - } - - MyDeflater(int lvl) { - super(lvl); - } - - MyDeflater(int lvl, boolean noHeader) { - super(lvl, noHeader); - } - - void myFinalize() { - finalize(); - } - - int getDefCompression() { - return DEFAULT_COMPRESSION; - } - - int getDefStrategy() { - return DEFAULT_STRATEGY; - } - - int getHuffman() { - return HUFFMAN_ONLY; - } - - int getFiltered() { - return FILTERED; - } - } - - /** - * @tests java.util.zip.Deflater#deflate(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "deflate", - args = {byte[].class} - ) - public void test_deflate$B() { - byte outPutBuf[] = new byte[50]; - byte byteArray[] = {1, 3, 4, 7, 8}; - byte outPutInf[] = new byte[50]; - int x = 0; - - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + class MyDeflater extends Deflater { + MyDeflater() { + super(); + } + + MyDeflater(int lvl) { + super(lvl); + } + + MyDeflater(int lvl, boolean noHeader) { + super(lvl, noHeader); + } + + void myFinalize() { + finalize(); + } + + int getDefCompression() { + return DEFAULT_COMPRESSION; + } + + int getDefStrategy() { + return DEFAULT_STRATEGY; + } + + int getHuffman() { + return HUFFMAN_ONLY; + } + + int getFiltered() { + return FILTERED; + } + } + + /** + * @tests java.util.zip.Deflater#deflate(byte[]) + */ + public void test_deflate$B() { + byte outPutBuf[] = new byte[50]; + byte byteArray[] = { 1, 3, 4, 7, 8 }; + byte outPutInf[] = new byte[50]; + int x = 0; + + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { x += defl.deflate(outPutBuf); } - assertEquals("Deflater at end of stream, should return 0", 0, defl - .deflate(outPutBuf)); + assertEquals("Deflater at end of stream, should return 0", 0, defl + .deflate(outPutBuf)); int totalOut = defl.getTotalOut(); int totalIn = defl.getTotalIn(); assertEquals(x, totalOut); assertEquals(byteArray.length, totalIn); - defl.end(); + defl.end(); - Inflater infl = new Inflater(); - try { - infl.setInput(outPutBuf); - while (!infl.finished()) { + Inflater infl = new Inflater(); + try { + infl.setInput(outPutBuf); + while (!infl.finished()) { infl.inflate(outPutInf); } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } assertEquals(totalIn, infl.getTotalOut()); assertEquals(totalOut, infl.getTotalIn()); - for (int i = 0; i < byteArray.length; i++) { + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], outPutInf[i]); } - assertEquals( - "Final decompressed data contained more bytes than original", - 0, outPutInf[byteArray.length]); - infl.end(); - } - - /** - * @tests java.util.zip.Deflater#deflate(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "deflate", - args = {byte[].class, int.class, int.class} - ) - public void test_deflate$BII() { - byte outPutBuf[] = new byte[50]; - byte byteArray[] = {5, 2, 3, 7, 8}; - byte outPutInf[] = new byte[50]; - int offSet = 1; - int length = outPutBuf.length - 1; - int x = 0; - - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + assertEquals("Final decompressed data contained more bytes than original", + 0, outPutInf[byteArray.length]); + infl.end(); + } + + /** + * @tests java.util.zip.Deflater#deflate(byte[], int, int) + */ + public void test_deflate$BII() { + byte outPutBuf[] = new byte[50]; + byte byteArray[] = { 5, 2, 3, 7, 8 }; + byte outPutInf[] = new byte[50]; + int offSet = 1; + int length = outPutBuf.length - 1; + int x = 0; + + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { x += defl.deflate(outPutBuf, offSet, length); } - assertEquals("Deflater at end of stream, should return 0", 0, defl - .deflate(outPutBuf, offSet, length)); - int totalOut = defl.getTotalOut(); - int totalIn = defl.getTotalIn(); + assertEquals("Deflater at end of stream, should return 0", 0, defl.deflate( + outPutBuf, offSet, length)); + int totalOut = defl.getTotalOut(); + int totalIn = defl.getTotalIn(); assertEquals(x, totalOut); assertEquals(byteArray.length, totalIn); - defl.end(); + defl.end(); - Inflater infl = new Inflater(); - try { - infl.setInput(outPutBuf, offSet, length); - while (!infl.finished()) { + Inflater infl = new Inflater(); + try { + infl.setInput(outPutBuf, offSet, length); + while (!infl.finished()) { infl.inflate(outPutInf); } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } assertEquals(totalIn, infl.getTotalOut()); assertEquals(totalOut, infl.getTotalIn()); - for (int i = 0; i < byteArray.length; i++) { + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], outPutInf[i]); } - assertEquals( - "Final decompressed data contained more bytes than original", - 0, outPutInf[byteArray.length]); - infl.end(); - - // Set of tests testing the boundaries of the offSet/length - defl = new Deflater(); - outPutBuf = new byte[100]; - defl.setInput(byteArray); - for (int i = 0; i < 2; i++) { - if (i == 0) { - offSet = outPutBuf.length + 1; - length = outPutBuf.length; - } else { - offSet = 0; - length = outPutBuf.length + 1; - } - try { - defl.deflate(outPutBuf, offSet, length); - fail("Test " + i - + ": ArrayIndexOutOfBoundsException not thrown"); - } catch (ArrayIndexOutOfBoundsException e) { - } - } - defl.end(); - } - - /** - * @tests java.util.zip.Deflater#end() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "end", - args = {} - ) - public void test_end() { - byte byteArray[] = {5, 2, 3, 7, 8}; - byte outPutBuf[] = new byte[100]; - - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + assertEquals("Final decompressed data contained more bytes than original", + 0, outPutInf[byteArray.length]); + infl.end(); + + // Set of tests testing the boundaries of the offSet/length + defl = new Deflater(); + outPutBuf = new byte[100]; + defl.setInput(byteArray); + for (int i = 0; i < 2; i++) { + if (i == 0) { + offSet = outPutBuf.length + 1; + length = outPutBuf.length; + } else { + offSet = 0; + length = outPutBuf.length + 1; + } + try { + defl.deflate(outPutBuf, offSet, length); + fail("Test " + i + + ": ArrayIndexOutOfBoundsException not thrown"); + } catch (ArrayIndexOutOfBoundsException e) { + } + } + defl.end(); + } + + /** + * @tests java.util.zip.Deflater#end() + */ + public void test_end() { + byte byteArray[] = { 5, 2, 3, 7, 8 }; + byte outPutBuf[] = new byte[100]; + + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - defl.end(); - helper_end_test(defl, "end"); - } - - /** - * @tests java.util.zip.Deflater#finalize() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finalize", - args = {} - ) - public void test_finalize() { - MyDeflater mdefl = new MyDeflater(); - mdefl.myFinalize(); - System.gc(); - helper_end_test(mdefl, "finalize"); - } - - /** - * @tests java.util.zip.Deflater#finish() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finish", - args = {} - ) - public void test_finish() throws Exception { - // This test already here, its the same as test_deflate() - byte byteArray[] = {5, 2, 3, 7, 8}; - byte outPutBuf[] = new byte[100]; - byte outPutInf[] = new byte[100]; - int x = 0; - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - - // needsInput should never return true after finish() is called - if (System.getProperty("java.vendor").startsWith("IBM")) { - assertFalse( - "needsInput() should return false after finish() is called", - defl.needsInput()); - } - - while (!defl.finished()) { + defl.end(); + helper_end_test(defl, "end"); + } + + /** + * @tests java.util.zip.Deflater#finalize() + */ + public void test_finalize() { + MyDeflater mdefl = new MyDeflater(); + mdefl.myFinalize(); + System.gc(); + helper_end_test(mdefl, "finalize"); + } + + /** + * @tests java.util.zip.Deflater#finish() + */ + public void test_finish() throws Exception { + // This test already here, its the same as test_deflate() + byte byteArray[] = { 5, 2, 3, 7, 8 }; + byte outPutBuf[] = new byte[100]; + byte outPutInf[] = new byte[100]; + int x = 0; + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + + // needsInput should never return true after finish() is called + if (System.getProperty("java.vendor").startsWith("IBM")) { + assertFalse("needsInput() should return false after finish() is called", defl + .needsInput()); + } + + while (!defl.finished()) { x += defl.deflate(outPutBuf); } - int totalOut = defl.getTotalOut(); - int totalIn = defl.getTotalIn(); + int totalOut = defl.getTotalOut(); + int totalIn = defl.getTotalIn(); assertEquals(x, totalOut); assertEquals(byteArray.length, totalIn); - defl.end(); + defl.end(); - Inflater infl = new Inflater(); - infl.setInput(outPutBuf); - while (!infl.finished()) { - infl.inflate(outPutInf); - } + Inflater infl = new Inflater(); + infl.setInput(outPutBuf); + while (!infl.finished()) { + infl.inflate(outPutInf); + } assertEquals(totalIn, infl.getTotalOut()); assertEquals(totalOut, infl.getTotalIn()); - for (int i = 0; i < byteArray.length; i++) { + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], outPutInf[i]); } - assertEquals( - "Final decompressed data contained more bytes than original", - 0, outPutInf[byteArray.length]); - infl.end(); - } - - /** - * @tests java.util.zip.Deflater#finished() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finished", - args = {} - ) - public void test_finished() { - byte byteArray[] = {5, 2, 3, 7, 8}; - byte outPutBuf[] = new byte[100]; - Deflater defl = new Deflater(); - assertTrue("Test 1: Deflater should not be finished.", !defl.finished()); - defl.setInput(byteArray); - assertTrue("Test 2: Deflater should not be finished.", !defl.finished()); - defl.finish(); - assertTrue("Test 3: Deflater should not be finished.", !defl.finished()); - while (!defl.finished()) { + assertEquals("Final decompressed data contained more bytes than original", + 0, outPutInf[byteArray.length]); + infl.end(); + } + + /** + * @tests java.util.zip.Deflater#finished() + */ + public void test_finished() { + byte byteArray[] = { 5, 2, 3, 7, 8 }; + byte outPutBuf[] = new byte[100]; + Deflater defl = new Deflater(); + assertTrue("Test 1: Deflater should not be finished.", !defl.finished()); + defl.setInput(byteArray); + assertTrue("Test 2: Deflater should not be finished.", !defl.finished()); + defl.finish(); + assertTrue("Test 3: Deflater should not be finished.", !defl.finished()); + while (!defl.finished()) { defl.deflate(outPutBuf); } - assertTrue("Test 4: Deflater should be finished.", defl.finished()); - defl.end(); - assertTrue("Test 5: Deflater should be finished.", defl.finished()); - } - - /** - * @tests java.util.zip.Deflater#getAdler() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAdler", - args = {} - ) - public void test_getAdler() { - byte byteArray[] = {'a', 'b', 'c', 1, 2, 3}; - byte outPutBuf[] = new byte[100]; - Deflater defl = new Deflater(); - - // getting the checkSum value using the Adler - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + assertTrue("Test 4: Deflater should be finished.", defl.finished()); + defl.end(); + assertTrue("Test 5: Deflater should be finished.", defl.finished()); + } + + /** + * @tests java.util.zip.Deflater#getAdler() + */ + public void test_getAdler() { + byte byteArray[] = { 'a', 'b', 'c', 1, 2, 3 }; + byte outPutBuf[] = new byte[100]; + Deflater defl = new Deflater(); + + // getting the checkSum value using the Adler + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - long checkSumD = defl.getAdler(); - defl.end(); - - // getting the checkSum value through the Adler32 class - Adler32 adl = new Adler32(); - adl.update(byteArray); - long checkSumR = adl.getValue(); - assertEquals( + long checkSumD = defl.getAdler(); + defl.end(); + + // getting the checkSum value through the Adler32 class + Adler32 adl = new Adler32(); + adl.update(byteArray); + long checkSumR = adl.getValue(); + assertEquals( "The checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance", checkSumD, checkSumR); - } - - /** - * @tests java.util.zip.Deflater#getTotalIn() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTotalIn", - args = {} - ) - public void test_getTotalIn() { - byte outPutBuf[] = new byte[5]; - byte byteArray[] = {1, 3, 4, 7, 8}; - - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + } + + /** + * @tests java.util.zip.Deflater#getTotalIn() + */ + public void test_getTotalIn() { + byte outPutBuf[] = new byte[5]; + byte byteArray[] = { 1, 3, 4, 7, 8 }; + + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } assertEquals(byteArray.length, defl.getTotalIn()); - defl.end(); - - defl = new Deflater(); - int offSet = 2; - int length = 3; - outPutBuf = new byte[5]; - defl.setInput(byteArray, offSet, length); - defl.finish(); - while (!defl.finished()) { + defl.end(); + + defl = new Deflater(); + int offSet = 2; + int length = 3; + outPutBuf = new byte[5]; + defl.setInput(byteArray, offSet, length); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } assertEquals(length, defl.getTotalIn()); - defl.end(); - } - - /** - * @tests java.util.zip.Deflater#getTotalOut() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTotalOut", - args = {} - ) - public void test_getTotalOut() { - // the getTotalOut should equal the sum of value returned by deflate() - byte outPutBuf[] = new byte[5]; - byte byteArray[] = {5, 2, 3, 7, 8}; - int x = 0; - Deflater defl = new Deflater(); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + defl.end(); + } + + /** + * @tests java.util.zip.Deflater#getTotalOut() + */ + public void test_getTotalOut() { + // the getTotalOut should equal the sum of value returned by deflate() + byte outPutBuf[] = new byte[5]; + byte byteArray[] = { 5, 2, 3, 7, 8 }; + int x = 0; + Deflater defl = new Deflater(); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { x += defl.deflate(outPutBuf); } assertEquals(x, defl.getTotalOut()); - defl.end(); - - x = 0; - int offSet = 2; - int length = 3; - defl = new Deflater(); - outPutBuf = new byte[5]; - defl.setInput(byteArray, offSet, length); - defl.finish(); - while (!defl.finished()) { + defl.end(); + + x = 0; + int offSet = 2; + int length = 3; + defl = new Deflater(); + outPutBuf = new byte[5]; + defl.setInput(byteArray, offSet, length); + defl.finish(); + while (!defl.finished()) { x += defl.deflate(outPutBuf); } assertEquals(x, defl.getTotalOut()); - } - - /** - * @tests java.util.zip.Deflater#needsInput() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "needsInput", - args = {} - ) - public void test_needsInput() { - Deflater defl = new Deflater(); - assertTrue( - "needsInput give the wrong boolean value as a result of no input buffer", - defl.needsInput()); - byte byteArray[] = {1, 2, 3}; - defl.setInput(byteArray); - assertFalse( - "needsInput give wrong boolean value as a result of a full input buffer", - defl.needsInput()); - byte[] outPutBuf = new byte[50]; - while (!defl.needsInput()) { + } + + /** + * @tests java.util.zip.Deflater#needsInput() + */ + public void test_needsInput() { + Deflater defl = new Deflater(); + assertTrue( + "needsInput give the wrong boolean value as a result of no input buffer", + defl.needsInput()); + byte byteArray[] = { 1, 2, 3 }; + defl.setInput(byteArray); + assertFalse( + "needsInput give wrong boolean value as a result of a full input buffer", + defl.needsInput()); + byte[] outPutBuf = new byte[50]; + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - byte emptyByteArray[] = new byte[0]; - defl.setInput(emptyByteArray); - assertTrue( - "needsInput give wrong boolean value as a result of an empty input buffer", - defl.needsInput()); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + byte emptyByteArray[] = new byte[0]; + defl.setInput(emptyByteArray); + assertTrue( + "needsInput give wrong boolean value as a result of an empty input buffer", + defl.needsInput()); + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - // needsInput should NOT return true after finish() has been - // called. - if (System.getProperty("java.vendor").startsWith("IBM")) { + // needsInput should NOT return true after finish() has been + // called. + if (System.getProperty("java.vendor").startsWith("IBM")) { assertFalse( - "needsInput gave wrong boolean value as a result of finish() being called", - defl.needsInput()); - } - defl.end(); - } - - /** - * @tests java.util.zip.Deflater#reset() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reset", - args = {} - ) - public void test_reset() { - byte outPutBuf[] = new byte[100]; - byte outPutInf[] = new byte[100]; - byte curArray[] = new byte[5]; - byte byteArray[] = {1, 3, 4, 7, 8}; - byte byteArray2[] = {8, 7, 4, 3, 1}; - int x = 0; - int orgValue = 0; - Deflater defl = new Deflater(); - - for (int i = 0; i < 3; i++) { - if (i == 0) { + "needsInput gave wrong boolean value as a result of finish() being called", + defl.needsInput()); + } + defl.end(); + } + + /** + * @tests java.util.zip.Deflater#reset() + */ + public void test_reset() { + byte outPutBuf[] = new byte[100]; + byte outPutInf[] = new byte[100]; + byte curArray[] = new byte[5]; + byte byteArray[] = { 1, 3, 4, 7, 8 }; + byte byteArray2[] = { 8, 7, 4, 3, 1 }; + int x = 0; + int orgValue = 0; + Deflater defl = new Deflater(); + + for (int i = 0; i < 3; i++) { + if (i == 0) { curArray = byteArray; } else if (i == 1) { curArray = byteArray2; @@ -481,13 +404,13 @@ public class DeflaterTest extends TestCase { defl.reset(); } - defl.setInput(curArray); - defl.finish(); - while (!defl.finished()) { + defl.setInput(curArray); + defl.finish(); + while (!defl.finished()) { x += defl.deflate(outPutBuf); } - if (i == 0) { + if (i == 0) { assertEquals(x, defl.getTotalOut()); } else if (i == 1) { assertEquals(x, orgValue); @@ -495,333 +418,296 @@ public class DeflaterTest extends TestCase { assertEquals(x, orgValue * 2); } - if (i == 0) { + if (i == 0) { orgValue = x; } - try { - Inflater infl = new Inflater(); - infl.setInput(outPutBuf); - while (!infl.finished()) { + try { + Inflater infl = new Inflater(); + infl.setInput(outPutBuf); + while (!infl.finished()) { infl.inflate(outPutInf); } - infl.end(); - } catch (DataFormatException e) { - fail("Test " + i + ": Invalid input to be decompressed"); - } + infl.end(); + } catch (DataFormatException e) { + fail("Test " + i + ": Invalid input to be decompressed"); + } - if (i == 1) { + if (i == 1) { curArray = byteArray; } - for (int j = 0; j < curArray.length; j++) { + for (int j = 0; j < curArray.length; j++) { assertEquals(curArray[j], outPutInf[j]); } assertEquals(0, outPutInf[curArray.length]); - } - } - - /** - * @tests java.util.zip.Deflater#setDictionary(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setDictionary", - args = {byte[].class} - ) - public void test_setDictionary$B() { - // This test is very close to getAdler() - byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3}; - byte byteArray[] = { - 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r'}; - byte outPutBuf[] = new byte[100]; - - Deflater defl = new Deflater(); - long deflAdler = defl.getAdler(); - assertEquals( - "No dictionary set, no data deflated, getAdler should return 1", - 1, deflAdler); - defl.setDictionary(dictionaryArray); - deflAdler = defl.getAdler(); - - // getting the checkSum value through the Adler32 class - Adler32 adl = new Adler32(); - adl.update(dictionaryArray); - long realAdler = adl.getValue(); + } + } + + /** + * @tests java.util.zip.Deflater#setDictionary(byte[]) + */ + public void test_setDictionary$B() { + // This test is very close to getAdler() + byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 }; + byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', + 'w', 'r' }; + byte outPutBuf[] = new byte[100]; + + Deflater defl = new Deflater(); + long deflAdler = defl.getAdler(); + assertEquals("No dictionary set, no data deflated, getAdler should return 1", + 1, deflAdler); + defl.setDictionary(dictionaryArray); + deflAdler = defl.getAdler(); + + // getting the checkSum value through the Adler32 class + Adler32 adl = new Adler32(); + adl.update(dictionaryArray); + long realAdler = adl.getValue(); assertEquals(deflAdler, realAdler); - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - deflAdler = defl.getAdler(); - adl = new Adler32(); - adl.update(byteArray); - realAdler = adl.getValue(); - // Deflate is finished and there were bytes deflated that did not occur - // in the dictionaryArray, therefore a new dictionary was automatically - // set. + deflAdler = defl.getAdler(); + adl = new Adler32(); + adl.update(byteArray); + realAdler = adl.getValue(); + // Deflate is finished and there were bytes deflated that did not occur + // in the dictionaryArray, therefore a new dictionary was automatically + // set. assertEquals(realAdler, deflAdler); - defl.end(); - } - - /** - * @tests java.util.zip.Deflater#setDictionary(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setDictionary", - args = {byte[].class, int.class, int.class} - ) - public void test_setDictionary$BII() { - // This test is very close to getAdler() - byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't'}; - byte byteArray[] = { - 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r', 't', - 'u', 'i', 'o', 4, 5, 6, 7}; - byte outPutBuf[] = new byte[500]; - - int offSet = 4; - int length = 5; - - Deflater defl = new Deflater(); - long deflAdler = defl.getAdler(); - assertEquals( - "No dictionary set, no data deflated, getAdler should return 1", - 1, deflAdler); - defl.setDictionary(dictionaryArray, offSet, length); - deflAdler = defl.getAdler(); - - // getting the checkSum value through the Adler32 class - Adler32 adl = new Adler32(); - adl.update(dictionaryArray, offSet, length); - long realAdler = adl.getValue(); + defl.end(); + } + + /** + * @tests java.util.zip.Deflater#setDictionary(byte[], int, int) + */ + public void test_setDictionary$BII() { + // This test is very close to getAdler() + byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't' }; + byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', + 'w', 'r', 't', 'u', 'i', 'o', 4, 5, 6, 7 }; + byte outPutBuf[] = new byte[500]; + + int offSet = 4; + int length = 5; + + Deflater defl = new Deflater(); + long deflAdler = defl.getAdler(); + assertEquals("No dictionary set, no data deflated, getAdler should return 1", + 1, deflAdler); + defl.setDictionary(dictionaryArray, offSet, length); + deflAdler = defl.getAdler(); + + // getting the checkSum value through the Adler32 class + Adler32 adl = new Adler32(); + adl.update(dictionaryArray, offSet, length); + long realAdler = adl.getValue(); assertEquals(deflAdler, realAdler); - defl.setInput(byteArray); - while (!defl.needsInput()) { + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - deflAdler = defl.getAdler(); - adl = new Adler32(); - adl.update(byteArray); - realAdler = adl.getValue(); - // Deflate is finished and there were bytes deflated that did not occur - // in the dictionaryArray, therefore a new dictionary was automatically - // set. + deflAdler = defl.getAdler(); + adl = new Adler32(); + adl.update(byteArray); + realAdler = adl.getValue(); + // Deflate is finished and there were bytes deflated that did not occur + // in the dictionaryArray, therefore a new dictionary was automatically + // set. assertEquals(realAdler, deflAdler); - defl.end(); - - // boundary check - defl = new Deflater(); - for (int i = 0; i < 2; i++) { - if (i == 0) { - offSet = 0; - length = dictionaryArray.length + 1; - } else { - offSet = dictionaryArray.length + 1; - length = 1; - } - try { - defl.setDictionary(dictionaryArray, offSet, length); - fail("Test " - + i - + ": boundary check for setDictionary failed for offset " - + offSet + " and length " + length); - } catch (ArrayIndexOutOfBoundsException e) { - } - } - } - - /** - * @tests java.util.zip.Deflater#setInput(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setInput", - args = {byte[].class} - ) - public void test_setInput$B() { - byte[] byteArray = {1, 2, 3}; - byte[] outPutBuf = new byte[50]; - byte[] outPutInf = new byte[50]; - - Deflater defl = new Deflater(); - defl.setInput(byteArray); - assertTrue("the array buffer in setInput() is empty", !defl - .needsInput()); - // The second setInput() should be ignored since needsInput() return - // false - defl.setInput(byteArray); - defl.finish(); - while (!defl.finished()) { + defl.end(); + + // boundary check + defl = new Deflater(); + for (int i = 0; i < 2; i++) { + if (i == 0) { + offSet = 0; + length = dictionaryArray.length + 1; + } else { + offSet = dictionaryArray.length + 1; + length = 1; + } + try { + defl.setDictionary(dictionaryArray, offSet, length); + fail( + "Test " + + i + + ": boundary check for setDictionary failed for offset " + + offSet + " and length " + length); + } catch (ArrayIndexOutOfBoundsException e) { + } + } + } + + /** + * @tests java.util.zip.Deflater#setInput(byte[]) + */ + public void test_setInput$B() { + byte[] byteArray = { 1, 2, 3 }; + byte[] outPutBuf = new byte[50]; + byte[] outPutInf = new byte[50]; + + Deflater defl = new Deflater(); + defl.setInput(byteArray); + assertTrue("the array buffer in setInput() is empty", !defl + .needsInput()); + // The second setInput() should be ignored since needsInput() return + // false + defl.setInput(byteArray); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - defl.end(); + defl.end(); - Inflater infl = new Inflater(); - try { - infl.setInput(outPutBuf); - while (!infl.finished()) { + Inflater infl = new Inflater(); + try { + infl.setInput(outPutBuf); + while (!infl.finished()) { infl.inflate(outPutInf); } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], outPutInf[i]); } - assertEquals(byteArray.length, infl.getTotalOut()); - infl.end(); - } - - /** - * @tests java.util.zip.Deflater#setInput(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setInput", - args = {byte[].class, int.class, int.class} - ) - public void test_setInput$BII() throws Exception { - byte[] byteArray = {1, 2, 3, 4, 5}; - byte[] outPutBuf = new byte[50]; - byte[] outPutInf = new byte[50]; - int offSet = 1; - int length = 3; - - Deflater defl = new Deflater(); - defl.setInput(byteArray, offSet, length); - assertFalse("the array buffer in setInput() is empty", defl - .needsInput()); - // The second setInput() should be ignored since needsInput() return - // false - defl.setInput(byteArray, offSet, length); - defl.finish(); - while (!defl.finished()) { + assertEquals(byteArray.length, infl.getTotalOut()); + infl.end(); + } + + /** + * @tests java.util.zip.Deflater#setInput(byte[], int, int) + */ + public void test_setInput$BII() throws Exception { + byte[] byteArray = { 1, 2, 3, 4, 5 }; + byte[] outPutBuf = new byte[50]; + byte[] outPutInf = new byte[50]; + int offSet = 1; + int length = 3; + + Deflater defl = new Deflater(); + defl.setInput(byteArray, offSet, length); + assertFalse("the array buffer in setInput() is empty", defl.needsInput()); + // The second setInput() should be ignored since needsInput() return + // false + defl.setInput(byteArray, offSet, length); + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - defl.end(); + defl.end(); - Inflater infl = new Inflater(); - infl.setInput(outPutBuf); - while (!infl.finished()) { - infl.inflate(outPutInf); - } - for (int i = 0; i < length; i++) { + Inflater infl = new Inflater(); + infl.setInput(outPutBuf); + while (!infl.finished()) { + infl.inflate(outPutInf); + } + for (int i = 0; i < length; i++) { assertEquals(byteArray[i + offSet], outPutInf[i]); } - assertEquals(length, infl.getTotalOut()); - infl.end(); - - // boundary check - defl = new Deflater(); - for (int i = 0; i < 2; i++) { - if (i == 0) { - offSet = 0; - length = byteArray.length + 1; - } else { - offSet = byteArray.length + 1; - length = 1; - } - try { - defl.setInput(byteArray, offSet, length); - fail("Test " + i - + ": boundary check for setInput failed for offset " - + offSet + " and length " + length); - } catch (ArrayIndexOutOfBoundsException e) { - } - } - } - - /** - * @tests java.util.zip.Deflater#setLevel(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {int.class} - ) - public void test_setLevelI() throws Exception { - // Very similar to test_Constructor(int) - byte[] byteArray = new byte[100]; - InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); - inFile.read(byteArray); - inFile.close(); - - byte[] outPutBuf; - int totalOut; - for (int i = 0; i < 10; i++) { - Deflater defl = new Deflater(); - defl.setLevel(i); - outPutBuf = new byte[500]; - defl.setInput(byteArray); - while (!defl.needsInput()) { + assertEquals(length, infl.getTotalOut()); + infl.end(); + + // boundary check + defl = new Deflater(); + for (int i = 0; i < 2; i++) { + if (i == 0) { + offSet = 0; + length = byteArray.length + 1; + } else { + offSet = byteArray.length + 1; + length = 1; + } + try { + defl.setInput(byteArray, offSet, length); + fail("Test " + i + + ": boundary check for setInput failed for offset " + + offSet + " and length " + length); + } catch (ArrayIndexOutOfBoundsException e) { + } + } + } + + /** + * @tests java.util.zip.Deflater#setLevel(int) + */ + public void test_setLevelI() throws Exception { + // Very similar to test_Constructor(int) + byte[] byteArray = new byte[100]; + InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); + inFile.read(byteArray); + inFile.close(); + + byte[] outPutBuf; + int totalOut; + for (int i = 0; i < 10; i++) { + Deflater defl = new Deflater(); + defl.setLevel(i); + outPutBuf = new byte[500]; + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - totalOut = defl.getTotalOut(); - defl.end(); + totalOut = defl.getTotalOut(); + defl.end(); - outPutBuf = new byte[500]; - defl = new Deflater(i); - defl.setInput(byteArray); - while (!defl.needsInput()) { + outPutBuf = new byte[500]; + defl = new Deflater(i); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - assertEquals(totalOut, defl.getTotalOut()); - defl.end(); - } - - // testing boundaries - try { - Deflater boundDefl = new Deflater(); - // Level must be between 0-9 - boundDefl.setLevel(-2); - fail("IllegalArgumentException not thrown when setting level to a number < 0."); - } catch (IllegalArgumentException e) { - } - try { - Deflater boundDefl = new Deflater(); - boundDefl.setLevel(10); - fail("IllegalArgumentException not thrown when setting level to a number > 9."); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.Deflater#setStrategy(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setStrategy", - args = {int.class} - ) - public void test_setStrategyI() throws Exception { - byte[] byteArray = new byte[100]; - InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); - inFile.read(byteArray); - inFile.close(); - - for (int i = 0; i < 3; i++) { - byte outPutBuf[] = new byte[500]; - MyDeflater mdefl = new MyDeflater(); - - if (i == 0) { + assertEquals(totalOut, defl.getTotalOut()); + defl.end(); + } + + // testing boundaries + try { + Deflater boundDefl = new Deflater(); + // Level must be between 0-9 + boundDefl.setLevel(-2); + fail( + "IllegalArgumentException not thrown when setting level to a number < 0."); + } catch (IllegalArgumentException e) { + } + try { + Deflater boundDefl = new Deflater(); + boundDefl.setLevel(10); + fail( + "IllegalArgumentException not thrown when setting level to a number > 9."); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.Deflater#setStrategy(int) + */ + public void test_setStrategyI() throws Exception { + byte[] byteArray = new byte[100]; + InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); + inFile.read(byteArray); + inFile.close(); + + for (int i = 0; i < 3; i++) { + byte outPutBuf[] = new byte[500]; + MyDeflater mdefl = new MyDeflater(); + + if (i == 0) { mdefl.setStrategy(mdefl.getDefStrategy()); } else if (i == 1) { mdefl.setStrategy(mdefl.getHuffman()); @@ -829,335 +715,325 @@ public class DeflaterTest extends TestCase { mdefl.setStrategy(mdefl.getFiltered()); } - mdefl.setInput(byteArray); - while (!mdefl.needsInput()) { + mdefl.setInput(byteArray); + while (!mdefl.needsInput()) { mdefl.deflate(outPutBuf); } - mdefl.finish(); - while (!mdefl.finished()) { + mdefl.finish(); + while (!mdefl.finished()) { mdefl.deflate(outPutBuf); } - if (i == 0) { - // System.out.println(mdefl.getTotalOut()); - // ran JDK and found that getTotalOut() = 86 for this particular - // file - assertEquals( - "getTotalOut() for the default strategy did not correspond with JDK", - 86, mdefl.getTotalOut()); - } else if (i == 1) { - // System.out.println(mdefl.getTotalOut()); - // ran JDK and found that getTotalOut() = 100 for this - // particular file - assertEquals( - "getTotalOut() for the Huffman strategy did not correspond with JDK", - 100, mdefl.getTotalOut()); - } else { - // System.out.println(mdefl.getTotalOut()); - // ran JDK and found that totalOut = 93 for this particular file - assertEquals( - "Total Out for the Filtered strategy did not correspond with JDK", - 93, mdefl.getTotalOut()); - } - mdefl.end(); - } - - // Attempting to setStrategy to an invalid value - try { - Deflater defl = new Deflater(); - defl.setStrategy(-412); - fail("IllegalArgumentException not thrown when setting strategy to an invalid value."); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.Deflater#Deflater() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Deflater", - args = {} - ) - public void test_Constructor() throws Exception { - byte[] byteArray = new byte[100]; - InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); - inFile.read(byteArray); - inFile.close(); - - Deflater defl = new Deflater(); - byte[] outPutBuf = new byte[500]; - defl.setInput(byteArray); - while (!defl.needsInput()) { + if (i == 0) { + // System.out.println(mdefl.getTotalOut()); + // ran JDK and found that getTotalOut() = 86 for this particular + // file + assertEquals("getTotalOut() for the default strategy did not correspond with JDK", + 86, mdefl.getTotalOut()); + } else if (i == 1) { + // System.out.println(mdefl.getTotalOut()); + // ran JDK and found that getTotalOut() = 100 for this + // particular file + assertEquals("getTotalOut() for the Huffman strategy did not correspond with JDK", + 100, mdefl.getTotalOut()); + } else { + // System.out.println(mdefl.getTotalOut()); + // ran JDK and found that totalOut = 93 for this particular file + assertEquals("Total Out for the Filtered strategy did not correspond with JDK", + 93, mdefl.getTotalOut()); + } + mdefl.end(); + } + + // Attempting to setStrategy to an invalid value + try { + Deflater defl = new Deflater(); + defl.setStrategy(-412); + fail( + "IllegalArgumentException not thrown when setting strategy to an invalid value."); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.Deflater#Deflater() + */ + public void test_Constructor() throws Exception { + byte[] byteArray = new byte[100]; + InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); + inFile.read(byteArray); + inFile.close(); + + Deflater defl = new Deflater(); + byte[] outPutBuf = new byte[500]; + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - int totalOut = defl.getTotalOut(); - defl.end(); - - // creating a Deflater using the DEFAULT_COMPRESSION as the int - MyDeflater mdefl = new MyDeflater(); - mdefl = new MyDeflater(mdefl.getDefCompression()); - outPutBuf = new byte[500]; - mdefl.setInput(byteArray); - while (!mdefl.needsInput()) { + int totalOut = defl.getTotalOut(); + defl.end(); + + // creating a Deflater using the DEFAULT_COMPRESSION as the int + MyDeflater mdefl = new MyDeflater(); + mdefl = new MyDeflater(mdefl.getDefCompression()); + outPutBuf = new byte[500]; + mdefl.setInput(byteArray); + while (!mdefl.needsInput()) { mdefl.deflate(outPutBuf); } - mdefl.finish(); - while (!mdefl.finished()) { + mdefl.finish(); + while (!mdefl.finished()) { mdefl.deflate(outPutBuf); } - assertEquals(totalOut, mdefl.getTotalOut()); - mdefl.end(); - } - - /** - * @tests java.util.zip.Deflater#Deflater(int, boolean) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Deflater", - args = {int.class, boolean.class} - ) - public void test_ConstructorIZ() throws Exception { - byte byteArray[] = { - 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r'}; - - Deflater defl = new Deflater(); - byte outPutBuf[] = new byte[500]; - defl.setLevel(2); - defl.setInput(byteArray); - while (!defl.needsInput()) { + assertEquals(totalOut, mdefl.getTotalOut()); + mdefl.end(); + } + + /** + * @tests java.util.zip.Deflater#Deflater(int, boolean) + */ + public void test_ConstructorIZ() throws Exception { + byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', + 'w', 'r' }; + + Deflater defl = new Deflater(); + byte outPutBuf[] = new byte[500]; + defl.setLevel(2); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - int totalOut = defl.getTotalOut(); - defl.end(); + int totalOut = defl.getTotalOut(); + defl.end(); - outPutBuf = new byte[500]; - defl = new Deflater(2, false); - defl.setInput(byteArray); - while (!defl.needsInput()) { + outPutBuf = new byte[500]; + defl = new Deflater(2, false); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - assertEquals(totalOut, defl.getTotalOut()); - defl.end(); + assertEquals(totalOut, defl.getTotalOut()); + defl.end(); - outPutBuf = new byte[500]; - defl = new Deflater(2, true); - defl.setInput(byteArray); - while (!defl.needsInput()) { + outPutBuf = new byte[500]; + defl = new Deflater(2, true); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - assertTrue( - "getTotalOut() should not be equal comparing two Deflaters with different header options.", - defl.getTotalOut() != totalOut); - defl.end(); - - byte outPutInf[] = new byte[500]; - Inflater infl = new Inflater(true); - while (!infl.finished()) { - if (infl.needsInput()) { - infl.setInput(outPutBuf); - } - infl.inflate(outPutInf); - } - for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "getTotalOut() should not be equal comparing two Deflaters with different header options.", + defl.getTotalOut() != totalOut); + defl.end(); + + byte outPutInf[] = new byte[500]; + Inflater infl = new Inflater(true); + while (!infl.finished()) { + if (infl.needsInput()) { + infl.setInput(outPutBuf); + } + infl.inflate(outPutInf); + } + for (int i = 0; i < byteArray.length; i++) { assertEquals(byteArray[i], outPutInf[i]); } - assertEquals( - "final decompressed data contained more bytes than original - constructorIZ", - 0, outPutInf[byteArray.length]); - infl.end(); - - infl = new Inflater(false); - outPutInf = new byte[500]; - int r = 0; - try { - while (!infl.finished()) { - if (infl.needsInput()) { + assertEquals("final decompressed data contained more bytes than original - constructorIZ", + 0, outPutInf[byteArray.length]); + infl.end(); + + infl = new Inflater(false); + outPutInf = new byte[500]; + int r = 0; + try { + while (!infl.finished()) { + if (infl.needsInput()) { infl.setInput(outPutBuf); } - infl.inflate(outPutInf); - } - } catch (DataFormatException e) { - r = 1; - } - assertEquals("header option did not correspond", 1, r); - - // testing boundaries - try { - Deflater boundDefl = new Deflater(); - // Level must be between 0-9 - boundDefl.setLevel(-2); - fail("IllegalArgumentException not thrown when setting level to a number < 0."); - } catch (IllegalArgumentException e) { - } - try { - Deflater boundDefl = new Deflater(); - boundDefl.setLevel(10); - fail("IllegalArgumentException not thrown when setting level to a number > 9."); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.Deflater#Deflater(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Deflater", - args = {int.class} - ) - public void test_ConstructorI() throws Exception { - byte[] byteArray = new byte[100]; + infl.inflate(outPutInf); + } + } catch (DataFormatException e) { + r = 1; + } + assertEquals("header option did not correspond", 1, r); + + // testing boundaries + try { + Deflater boundDefl = new Deflater(); + // Level must be between 0-9 + boundDefl.setLevel(-2); + fail("IllegalArgumentException not thrown when setting level to a number < 0."); + } catch (IllegalArgumentException e) { + } + try { + Deflater boundDefl = new Deflater(); + boundDefl.setLevel(10); + fail("IllegalArgumentException not thrown when setting level to a number > 9."); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.Deflater#Deflater(int) + */ + public void test_ConstructorI() throws Exception { + byte[] byteArray = new byte[100]; InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt"); inFile.read(byteArray); inFile.close(); - byte outPutBuf[] = new byte[500]; - Deflater defl = new Deflater(3); - defl.setInput(byteArray); - while (!defl.needsInput()) { + byte outPutBuf[] = new byte[500]; + Deflater defl = new Deflater(3); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - int totalOut = defl.getTotalOut(); - defl.end(); - - // test to see if the compression ratio is the same as setting the level - // on a deflater - outPutBuf = new byte[500]; - defl = new Deflater(); - defl.setLevel(3); - defl.setInput(byteArray); - while (!defl.needsInput()) { + int totalOut = defl.getTotalOut(); + defl.end(); + + // test to see if the compression ratio is the same as setting the level + // on a deflater + outPutBuf = new byte[500]; + defl = new Deflater(); + defl.setLevel(3); + defl.setInput(byteArray); + while (!defl.needsInput()) { defl.deflate(outPutBuf); } - defl.finish(); - while (!defl.finished()) { + defl.finish(); + while (!defl.finished()) { defl.deflate(outPutBuf); } - assertEquals(totalOut, defl.getTotalOut()); - defl.end(); + assertEquals(totalOut, defl.getTotalOut()); + defl.end(); - // testing boundaries - try { + // testing boundaries + try { Deflater boundDefl = new Deflater(); // Level must be between 0-9 boundDefl.setLevel(-2); fail("IllegalArgumentException not thrown when setting level to a number < 0."); } catch (IllegalArgumentException e) { - } - try { + } + try { Deflater boundDefl = new Deflater(); boundDefl.setLevel(10); fail("IllegalArgumentException not thrown when setting level to a number > 9."); } catch (IllegalArgumentException e) { } - } + } + + private void helper_end_test(Deflater defl, String desc) { + // Help tests for test_end() and test_reset(). + byte byteArray[] = { 5, 2, 3, 7, 8 }; + + // Methods where we expect IllegalStateException or NullPointerException + // to be thrown + try { + defl.getTotalOut(); + fail("defl.getTotalOut() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + defl.getTotalIn(); + fail("defl.getTotalIn() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + defl.getAdler(); + fail("defl.getAdler() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + byte[] dict = { 'a', 'b', 'c' }; + defl.setDictionary(dict); + fail("defl.setDictionary() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + defl.getTotalIn(); + fail("defl.getTotalIn() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + defl.getTotalIn(); + fail("defl.getTotalIn() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + try { + defl.deflate(byteArray); + fail("defl.deflate() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } catch (NullPointerException e) { + } + + // Methods where we expect NullPointerException to be thrown + try { + defl.reset(); + fail("defl.reset() can still be used after " + desc + + " is called in test_" + desc); + } catch (NullPointerException e) { + } + + // Methods that should be allowed to be called after end() is called + defl.needsInput(); + defl.setStrategy(1); + defl.setLevel(1); + defl.end(); + + // Methods where exceptions should be thrown + String vendor = System.getProperty("java.vendor"); + if (vendor.indexOf("IBM") != -1) { + try { + defl.setInput(byteArray); + fail("defl.setInput() can still be used after " + desc + + " is called in test_" + desc); + } catch (IllegalStateException e) { + } + } + } - private void helper_end_test(Deflater defl, String desc) { - // Help tests for test_end() and test_reset(). - byte byteArray[] = {5, 2, 3, 7, 8}; - - // Methods where we expect IllegalStateException or NullPointerException - // to be thrown - try { - defl.getTotalOut(); - fail("defl.getTotalOut() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - defl.getTotalIn(); - fail("defl.getTotalIn() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - defl.getAdler(); - fail("defl.getAdler() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - byte[] dict = {'a', 'b', 'c'}; - defl.setDictionary(dict); - fail("defl.setDictionary() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - defl.getTotalIn(); - fail("defl.getTotalIn() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - defl.getTotalIn(); - fail("defl.getTotalIn() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - try { - defl.deflate(byteArray); - fail("defl.deflate() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } catch (NullPointerException e) { - } - - // Methods where we expect NullPointerException to be thrown - try { - defl.reset(); - fail("defl.reset() can still be used after " + desc - + " is called in test_" + desc); - } catch (NullPointerException e) { - } - - // Methods that should be allowed to be called after end() is called - defl.needsInput(); - defl.setStrategy(1); - defl.setLevel(1); - defl.end(); - - // Methods where exceptions should be thrown - String vendor = System.getProperty("java.vendor"); - if (vendor.indexOf("IBM") != -1) { - try { - defl.setInput(byteArray); - fail("defl.setInput() can still be used after " + desc - + " is called in test_" + desc); - } catch (IllegalStateException e) { - } - } + /** + * @tests java.util.zip.Deflater() + */ + public void test_needsDictionary() { + Deflater inf = new Deflater(); + assertEquals(0, inf.getTotalIn()); + assertEquals(0, inf.getTotalOut()); + assertEquals(0, inf.getBytesRead()); + assertEquals(0, inf.getBytesWritten()); } /** @@ -1165,12 +1041,6 @@ public class DeflaterTest extends TestCase { * @throws UnsupportedEncodingException * @tests java.util.zip.Deflater#getBytesRead() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getBytesRead", - args = {} - ) public void test_getBytesRead() throws DataFormatException, UnsupportedEncodingException { // Regression test for HARMONY-158 @@ -1197,12 +1067,6 @@ public class DeflaterTest extends TestCase { * @throws UnsupportedEncodingException * @tests java.util.zip.Deflater#getBytesRead() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getBytesWritten", - args = {} - ) public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException { // Regression test for HARMONY-158 @@ -1223,21 +1087,16 @@ public class DeflaterTest extends TestCase { assertEquals(compressedDataLength, def.getTotalOut()); assertEquals(compressedDataLength, def.getBytesWritten()); } - - // BEGIN android-removed - // We use different default settings for deflating, so our output won't be - // the - // same. - // //Regression Test for HARMONY-2481 - // public void test_deflate_beforeSetInput() throws Exception { - // Deflater deflater = new Deflater(); - // deflater.finish(); - // byte[] buffer = new byte[1024]; - // assertEquals(8, deflater.deflate(buffer)); - // byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 }; - // for (int i = 0; i < expectedBytes.length; i++) { - // assertEquals(expectedBytes[i], buffer[i]); - // } - // } - // END android-removed + + //Regression Test for HARMONY-2481 + public void test_deflate_beforeSetInput() throws Exception { + Deflater deflater = new Deflater(); + deflater.finish(); + byte[] buffer = new byte[1024]; + assertEquals(8, deflater.deflate(buffer)); + byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 }; + for (int i = 0; i < expectedBytes.length; i++) { + assertEquals(expectedBytes[i], buffer[i]); + } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java index 1e8ddb4..3431510 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java @@ -14,14 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -31,127 +25,85 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.zip.Checksum; - import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import tests.support.resource.Support_Resources; -@TestTargetClass(GZIPInputStream.class) public class GZIPInputStreamTest extends junit.framework.TestCase { - File resources; + File resources; - class TestGZIPInputStream extends GZIPInputStream { - TestGZIPInputStream(InputStream in) throws IOException { - super(in); - } + class TestGZIPInputStream extends GZIPInputStream { + TestGZIPInputStream(InputStream in) throws IOException { + super(in); + } - TestGZIPInputStream(InputStream in, int size) throws IOException { - super(in, size); - } + TestGZIPInputStream(InputStream in, int size) throws IOException { + super(in, size); + } - Checksum getChecksum() { - return crc; - } + Checksum getChecksum() { + return crc; + } - boolean endofInput() { - return eos; - } - } + boolean endofInput() { + return eos; + } + } - /** - * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "GZIPInputStream", - args = {java.io.InputStream.class} - ) - public void test_ConstructorLjava_io_InputStream() { - // test method java.util.zip.GZIPInputStream.constructor - try { - Support_Resources.copyFile(resources, "GZIPInputStream", - "hyts_gInput.txt.gz"); - final URL gInput = new File(resources.toString() - + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); - TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput - .openConnection().getInputStream()); - assertNotNull("the constructor for GZIPInputStream is null", inGZIP); - assertEquals("the CRC value of the inputStream is not zero", 0, - inGZIP.getChecksum().getValue()); - inGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to open the input file"); - } - } + /** + * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream) + */ + public void test_ConstructorLjava_io_InputStream() { + // test method java.util.zip.GZIPInputStream.constructor + try { + Support_Resources.copyFile(resources, "GZIPInputStream", + "hyts_gInput.txt.gz"); + final URL gInput = new File(resources.toString() + + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); + TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput + .openConnection().getInputStream()); + assertNotNull("the constructor for GZIPInputStream is null", + inGZIP); + assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP + .getChecksum().getValue()); + inGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to open the input file"); + } + } - /** - * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream, - * int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "GZIPInputStream", - args = {java.io.InputStream.class, int.class} - ) - public void test_ConstructorLjava_io_InputStreamI() { - // test method java.util.zip.GZIPInputStream.constructorI - try { - Support_Resources.copyFile(resources, "GZIPInputStream", - "hyts_gInput.txt.gz"); - final URL gInput = new File(resources.toString() - + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); - TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput - .openConnection().getInputStream(), 200); - assertNotNull("the constructor for GZIPInputStream is null", inGZIP); - assertEquals("the CRC value of the inputStream is not zero", 0, - inGZIP.getChecksum().getValue()); - inGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to open the input file"); - } - try { - Support_Resources.copyFile(resources, "GZIPInputStream", - "hyts_gInput.txt.gz"); - final URL gInput = new File(resources.toString() - + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); - TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput - .openConnection().getInputStream(), 0); - fail("Expected IllegalArgumentException"); - } catch (IOException e) { - fail("an IO error occured while trying to open the input file"); - } catch (IllegalArgumentException ee) { - // expected - } - try { - Support_Resources.copyFile(resources, "GZIPInputStream", - "hyts_gInput.txt.gz"); - final URL gInput = new File(resources.toString() - + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); - TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput - .openConnection().getInputStream(), -1); - fail("Expected IllegalArgumentException"); - } catch (IOException e) { - fail("an IO error occured while trying to open the input file"); - } catch (IllegalArgumentException ee) { - // expected - } - } + /** + * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream, + * int) + */ + public void test_ConstructorLjava_io_InputStreamI() { + // test method java.util.zip.GZIPInputStream.constructorI + try { + Support_Resources.copyFile(resources, "GZIPInputStream", + "hyts_gInput.txt.gz"); + final URL gInput = new File(resources.toString() + + "/GZIPInputStream/hyts_gInput.txt.gz").toURL(); + TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput + .openConnection().getInputStream(), 200); + assertNotNull("the constructor for GZIPInputStream is null", + inGZIP); + assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP + .getChecksum().getValue()); + inGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to open the input file"); + } + } - /** - * @tests java.util.zip.GZIPInputStream#read(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "read", - args = {byte[].class, int.class, int.class} - ) - public void test_read$BII() throws IOException { - // test method java.util.zip.GZIPInputStream.readBII - byte orgBuf[] = {'3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w'}; + /** + * @tests java.util.zip.GZIPInputStream#read(byte[], int, int) + */ + public void test_read$BII() throws IOException { + // test method java.util.zip.GZIPInputStream.readBII + byte orgBuf[] = { '3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w' }; byte outBuf[] = new byte[100]; int result = 0; Support_Resources.copyFile(resources, "GZIPInputStream", @@ -240,14 +192,13 @@ public class GZIPInputStreamTest extends junit.framework.TestCase { exception = true; } assertTrue("Exception expected", exception); - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream zipout = new GZIPOutputStream(baos); zipout.write(test); zipout.close(); outBuf = new byte[530]; - GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(baos - .toByteArray())); + GZIPInputStream in= new GZIPInputStream(new ByteArrayInputStream(baos.toByteArray())); try { in.read(outBuf, 530, 1); fail("Test failed IOOBE was not thrown"); @@ -256,7 +207,7 @@ public class GZIPInputStreamTest extends junit.framework.TestCase { while (true) { result = in.read(outBuf, 0, 5); if (result == -1) { - // "EOF was reached"; + //"EOF was reached"; break; } } @@ -264,64 +215,50 @@ public class GZIPInputStreamTest extends junit.framework.TestCase { result = in.read(null, 100, 1); result = in.read(outBuf, -100, 1); result = in.read(outBuf, -1, 1);// 100, 1); - } + } - /** - * @tests java.util.zip.GZIPInputStream#close() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "close", - args = {} - ) - public void test_close() { - // test method java.util.zip.GZIPInputStream.close - byte outBuf[] = new byte[100]; - try { - int result = 0; - Support_Resources.copyFile(resources, "GZIPInputStream", - "hyts_gInput.txt.gz"); - String resPath = resources.toString(); - if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') { + /** + * @tests java.util.zip.GZIPInputStream#close() + */ + public void test_close() { + // test method java.util.zip.GZIPInputStream.close + byte outBuf[] = new byte[100]; + try { + int result = 0; + Support_Resources.copyFile(resources, "GZIPInputStream", + "hyts_gInput.txt.gz"); + String resPath = resources.toString(); + if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') { resPath = resPath.substring(1); } - final URL gInput = new URL("file:/" + resPath - + "/GZIPInputStream/hyts_gInput.txt.gz"); - TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput - .openConnection().getInputStream()); - while (!(inGZIP.endofInput())) { - result += inGZIP.read(outBuf, result, outBuf.length - result); - } - assertEquals( - "the checkSum value of the compressed and decompressed data does not equal", - 2074883667L, inGZIP.getChecksum().getValue()); - inGZIP.close(); - int r = 0; - try { - inGZIP.read(outBuf, 0, 1); - } catch (IOException e) { - r = 1; - } - assertEquals( - "GZIPInputStream can still be used after close is called", - 1, r); - } catch (IOException e) { - e.printStackTrace(); - fail("unexpected: " + e); - } - } + final URL gInput = new URL("file:/" + resPath + + "/GZIPInputStream/hyts_gInput.txt.gz"); + TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput + .openConnection().getInputStream()); + while (!(inGZIP.endofInput())) { + result += inGZIP.read(outBuf, result, outBuf.length - result); + } + assertEquals("the checkSum value of the compressed and decompressed data does not equal", + 2074883667L, inGZIP.getChecksum().getValue()); + inGZIP.close(); + int r = 0; + try { + inGZIP.read(outBuf, 0, 1); + } catch (IOException e) { + r = 1; + } + assertEquals("GZIPInputStream can still be used after close is called", + 1, r); + } catch (IOException e) { + e.printStackTrace(); + fail("unexpected: " + e); + } + } /** * Regression test for HARMONY-3703. * @tests java.util.zip.GZIPInputStream#read() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "read", - args = {byte[].class} - ) public void test_read() throws IOException { GZIPInputStream gis = null; int result = 0; @@ -350,11 +287,11 @@ public class GZIPInputStreamTest extends junit.framework.TestCase { @Override protected void setUp() { - resources = Support_Resources.createTempFolder(); - } + resources = Support_Resources.createTempFolder(); + } - @Override + @Override protected void tearDown() { - } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java index b71ce63..fdcc3fa 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java @@ -14,14 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -29,213 +23,160 @@ import java.io.OutputStream; import java.util.zip.Checksum; import java.util.zip.GZIPOutputStream; -@TestTargetClass(GZIPOutputStream.class) public class GZIPOutputStreamTest extends junit.framework.TestCase { - class TestGZIPOutputStream extends GZIPOutputStream { - TestGZIPOutputStream(OutputStream out) throws IOException { - super(out); - } - - TestGZIPOutputStream(OutputStream out, int size) throws IOException { - super(out, size); - } - - Checksum getChecksum() { - return crc; - } - } - - /** - * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "GZIPOutputStream", - args = {java.io.OutputStream.class} - ) - public void test_ConstructorLjava_io_OutputStream() { - try { - FileOutputStream outFile = new FileOutputStream( - File.createTempFile("GZIPOutCon", ".txt")); - TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); - assertNotNull("the constructor for GZIPOutputStream is null", - outGZIP); - assertEquals("the CRC value of the outputStream is not zero", 0, - outGZIP.getChecksum().getValue()); - outGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to find the output file or creating GZIP constructor"); - } - } - - /** - * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream, - * int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "GZIPOutputStream", - args = {java.io.OutputStream.class, int.class} - ) - public void test_ConstructorLjava_io_OutputStreamI() { - try { - FileOutputStream outFile = new FileOutputStream( - File.createTempFile("GZIPOutCon", ".txt")); - TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile, - 100); - assertNotNull("the constructor for GZIPOutputStream is null", - outGZIP); - assertEquals("the CRC value of the outputStream is not zero", 0, - outGZIP.getChecksum().getValue()); - outGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to find the output file or creating GZIP constructor"); - } - } - - /** - * @tests java.util.zip.GZIPOutputStream#finish() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finish", - args = {} - ) - public void test_finish() { - // test method java.util.zip.GZIPOutputStream.finish() - byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'}; - TestGZIPOutputStream outGZIP = null; - FileOutputStream outFile = null; - try { - outFile = new FileOutputStream( - File.createTempFile("GZIPOutCon", ".txt")); - outGZIP = new TestGZIPOutputStream(outFile); - - outGZIP.finish(); - int r = 0; - try { - outGZIP.write(byteArray, 0, 1); - } catch (IOException e) { - r = 1; - } - - assertEquals( - "GZIP instance can still be used after finish is called", - 1, r); - outGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to find the output file or creating GZIP constructor"); - } - try { - outFile = new FileOutputStream("GZIPOutFinish.txt"); - outGZIP = new TestGZIPOutputStream(outFile); - outFile.close(); - - outGZIP.finish(); - fail("Expected IOException"); - } catch (IOException e) { - // expected - } - } - - /** - * @tests java.util.zip.GZIPOutputStream#close() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking missed.", - method = "close", - args = {} - ) - public void test_close() { - // test method java.util.zip.GZIPOutputStream.close() - byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'}; - try { - FileOutputStream outFile = new FileOutputStream( - File.createTempFile("GZIPOutCon", ".txt")); - TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); - outGZIP.close(); - int r = 0; - try { - outGZIP.write(byteArray, 0, 1); - } catch (IOException e) { - r = 1; - } - assertEquals( - "GZIP instance can still be used after close is called", 1, - r); - } catch (IOException e) { - fail("an IO error occured while trying to find the output file or creating GZIP constructor"); - } - } - - /** - * @tests java.util.zip.GZIPOutputStream#write(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {byte[].class, int.class, int.class} - ) - public void test_write$BII() { - // test method java.util.zip.GZIPOutputStream.writeBII - byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'}; - TestGZIPOutputStream outGZIP = null; - try { - FileOutputStream outFile = new FileOutputStream( - File.createTempFile("GZIPOutCon", ".txt")); - outGZIP = new TestGZIPOutputStream(outFile); - outGZIP.write(byteArray, 0, 10); - // ran JDK and found this CRC32 value is 3097700292 - // System.out.print(outGZIP.getChecksum().getValue()); - assertEquals( - "the checksum value was incorrect result of write from GZIP", - 3097700292L, outGZIP.getChecksum().getValue()); - - // test for boundary check - int r = 0; - try { - outGZIP.write(byteArray, 0, 11); - } catch (IndexOutOfBoundsException ee) { - r = 1; - } - assertEquals("out of bounds exception is not present", 1, r); - outGZIP.close(); - } catch (IOException e) { - fail("an IO error occured while trying to find the output file or creating GZIP constructor"); - } - try { - outGZIP.write(byteArray, 0, 10); - fail("Expected IOException"); - } catch (IOException e) { - // expected - } - } - - @Override + class TestGZIPOutputStream extends GZIPOutputStream { + TestGZIPOutputStream(OutputStream out) throws IOException { + super(out); + } + + TestGZIPOutputStream(OutputStream out, int size) throws IOException { + super(out, size); + } + + Checksum getChecksum() { + return crc; + } + } + + /** + * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream) + */ + public void test_ConstructorLjava_io_OutputStream() { + try { + FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt"); + TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); + assertNotNull("the constructor for GZIPOutputStream is null", + outGZIP); + assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP + .getChecksum().getValue()); + outGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to find the output file or creating GZIP constructor"); + } + } + + /** + * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream, + * int) + */ + public void test_ConstructorLjava_io_OutputStreamI() { + try { + FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt"); + TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile, + 100); + assertNotNull("the constructor for GZIPOutputStream is null", + outGZIP); + assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP + .getChecksum().getValue()); + outGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to find the output file or creating GZIP constructor"); + } + } + + /** + * @tests java.util.zip.GZIPOutputStream#finish() + */ + public void test_finish() { + // test method java.util.zip.GZIPOutputStream.finish() + byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' }; + try { + FileOutputStream outFile = new FileOutputStream("GZIPOutFinish.txt"); + TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); + + outGZIP.finish(); + int r = 0; + try { + outGZIP.write(byteArray, 0, 1); + } catch (IOException e) { + r = 1; + } + + assertEquals("GZIP instance can still be used after finish is called", + 1, r); + outGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to find the output file or creating GZIP constructor"); + } + } + + /** + * @tests java.util.zip.GZIPOutputStream#close() + */ + public void test_close() { + // test method java.util.zip.GZIPOutputStream.close() + byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' }; + try { + FileOutputStream outFile = new FileOutputStream("GZIPOutClose2.txt"); + TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); + outGZIP.close(); + int r = 0; + try { + outGZIP.write(byteArray, 0, 1); + } catch (IOException e) { + r = 1; + } + assertEquals("GZIP instance can still be used after close is called", + 1, r); + } catch (IOException e) { + fail( + "an IO error occured while trying to find the output file or creating GZIP constructor"); + } + } + + /** + * @tests java.util.zip.GZIPOutputStream#write(byte[], int, int) + */ + public void test_write$BII() { + // test method java.util.zip.GZIPOutputStream.writeBII + byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' }; + try { + FileOutputStream outFile = new FileOutputStream("GZIPOutWrite.txt"); + TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile); + outGZIP.write(byteArray, 0, 10); + // ran JDK and found this CRC32 value is 3097700292 + // System.out.print(outGZIP.getChecksum().getValue()); + assertEquals("the checksum value was incorrect result of write from GZIP", + 3097700292L, outGZIP.getChecksum().getValue()); + + // test for boundary check + int r = 0; + try { + outGZIP.write(byteArray, 0, 11); + } catch (IndexOutOfBoundsException e) { + r = 1; + } + assertEquals("out of bounds exception is not present", 1, r); + outGZIP.close(); + } catch (IOException e) { + fail( + "an IO error occured while trying to find the output file or creating GZIP constructor"); + } + } + + @Override protected void setUp() { - } + } - @Override + @Override protected void tearDown() { - try { - File dFile = new File("GZIPOutCon.txt"); - dFile.delete(); - File dFile2 = new File("GZIPOutFinish.txt"); + try { + File dFile = new File("GZIPOutCon.txt"); + dFile.delete(); + File dFile2 = new File("GZIPOutFinish.txt"); dFile2.delete(); - File dFile3 = new File("GZIPOutWrite.txt"); + File dFile3 = new File("GZIPOutWrite.txt"); dFile3.delete(); - File dFile4 = new File("GZIPOutClose2.txt"); - dFile4.delete(); - } catch (SecurityException e) { - fail("Cannot delete file for security reasons"); - } - } + File dFile4 = new File("GZIPOutClose2.txt"); + dFile4.delete(); + } catch (SecurityException e) { + fail("Cannot delete file for security reasons"); + } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java index 707f13b..3ab7a64 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java @@ -14,139 +14,107 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import tests.support.resource.Support_Resources; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; -import java.io.FileOutputStream; -import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; -@TestTargetClass(InflaterInputStream.class) -public class InflaterInputStreamTest extends TestCase { - - // files hyts_constru(O),hyts_constru(OD),hyts_constru(ODI) needs to be - // included as resources - byte outPutBuf[] = new byte[500]; - - class MyInflaterInputStream extends InflaterInputStream { - MyInflaterInputStream(InputStream in) { - super(in); - } - - MyInflaterInputStream(InputStream in, Inflater infl) { - super(in, infl); - } - - MyInflaterInputStream(InputStream in, Inflater infl, int size) { - super(in, infl, size); - } - - void myFill() throws IOException { - fill(); - } - } - - /** - * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InflaterInputStream", - args = {java.io.InputStream.class} - ) - public void test_ConstructorLjava_io_InputStream() throws IOException { - byte byteArray[] = new byte[100]; - InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); - InflaterInputStream inflatIP = new InflaterInputStream(infile); - - inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes - inflatIP.close(); - } - - /** - * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream, - * java.util.zip.Inflater) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InflaterInputStream", - args = {java.io.InputStream.class, java.util.zip.Inflater.class} - ) - public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater() - throws IOException { - byte byteArray[] = new byte[100]; - InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); - Inflater inflate = new Inflater(); - InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate); - - inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes - inflatIP.close(); - } - - /** - * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream, - * java.util.zip.Inflater, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IllegalArgumentException checking missed.", - method = "InflaterInputStream", - args = {java.io.InputStream.class, java.util.zip.Inflater.class, int.class} - ) - public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI() - throws IOException { - int result = 0; - int buffer[] = new int[500]; - InputStream infile = Support_Resources - .getStream("hyts_constru_ODI.txt"); - Inflater inflate = new Inflater(); - InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate, - 1); - - int i = 0; - while ((result = inflatIP.read()) != -1) { - buffer[i] = result; - i++; - } - inflatIP.close(); +import junit.framework.TestCase; +import tests.support.resource.Support_Resources; - try { - inflatIP = new InflaterInputStream(infile, inflate, -1); - fail("IllegalArgumentException expected."); - } catch (IllegalArgumentException ee) { - // expected - } +public class InflaterInputStreamTest extends TestCase { - } + // files hyts_constru(O),hyts_constru(OD),hyts_constru(ODI) needs to be + // included as resources + // android-changed: we removed the parentheses for the benefit of our broken build system. + byte outPutBuf[] = new byte[500]; + + class MyInflaterInputStream extends InflaterInputStream { + MyInflaterInputStream(InputStream in) { + super(in); + } + + MyInflaterInputStream(InputStream in, Inflater infl) { + super(in, infl); + } + + MyInflaterInputStream(InputStream in, Inflater infl, int size) { + super(in, infl, size); + } + + void myFill() throws IOException { + fill(); + } + } + + /** + * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream) + */ + public void test_ConstructorLjava_io_InputStream() throws IOException { + //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI + /* + int result = 0; + int buffer[] = new int[500]; + InputStream infile = Support_Resources + .getStream("hyts_constru_O.txt"); // android-changed + + InflaterInputStream inflatIP = new InflaterInputStream(infile); + + int i = 0; + while ((result = inflatIP.read()) != -1) { + buffer[i] = result; + i++; + } + inflatIP.close(); + */ + } + + /** + * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream, + * java.util.zip.Inflater) + */ + public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater() throws IOException { + byte byteArray[] = new byte[100]; + InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); // android-changed + Inflater inflate = new Inflater(); + InflaterInputStream inflatIP = new InflaterInputStream(infile, + inflate); + + inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes + inflatIP.close(); + } + + /** + * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream, + * java.util.zip.Inflater, int) + */ + public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI() throws IOException { + int result = 0; + int buffer[] = new int[500]; + InputStream infile = Support_Resources.getStream("hyts_constru_ODI.txt"); // android-changed + Inflater inflate = new Inflater(); + InflaterInputStream inflatIP = new InflaterInputStream(infile, + inflate, 1); + + int i = 0; + while ((result = inflatIP.read()) != -1) { + buffer[i] = result; + i++; + } + inflatIP.close(); + } /** * @tests java.util.zip.InflaterInputStream#mark(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "mark", - args = {int.class} - ) public void test_markI() { InputStream is = new ByteArrayInputStream(new byte[10]); InflaterInputStream iis = new InflaterInputStream(is); @@ -159,12 +127,6 @@ public class InflaterInputStreamTest extends TestCase { /** * @tests java.util.zip.InflaterInputStream#markSupported() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "markSupported", - args = {} - ) public void test_markSupported() { InputStream is = new ByteArrayInputStream(new byte[10]); InflaterInputStream iis = new InflaterInputStream(is); @@ -172,43 +134,32 @@ public class InflaterInputStreamTest extends TestCase { assertTrue(is.markSupported()); } - /** + /** * @tests java.util.zip.InflaterInputStream#read() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "read", - args = {} - ) - public void test_read() throws IOException { - int result = 0; - int buffer[] = new int[500]; - byte orgBuffer[] = {1, 3, 4, 7, 8}; - InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); - Inflater inflate = new Inflater(); - InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate); - - int i = 0; - while ((result = inflatIP.read()) != -1) { - buffer[i] = result; - i++; - } - inflatIP.close(); - - for (int j = 0; j < orgBuffer.length; j++) { - assertTrue( - "original compressed data did not equal decompressed data", - buffer[j] == orgBuffer[j]); - } - inflatIP.close(); - try { - inflatIP.read(); - fail("IOException expected"); - } catch (IOException ee) { - // expected. - } - } + public void test_read() throws IOException { + int result = 0; + int buffer[] = new int[500]; + byte orgBuffer[] = { 1, 3, 4, 7, 8 }; + InputStream infile = Support_Resources + .getStream("hyts_constru_OD.txt"); // android-changed + Inflater inflate = new Inflater(); + InflaterInputStream inflatIP = new InflaterInputStream(infile, + inflate); + + int i = 0; + while ((result = inflatIP.read()) != -1) { + buffer[i] = result; + i++; + } + inflatIP.close(); + + for (int j = 0; j < orgBuffer.length; j++) { + assertTrue( + "original compressed data did not equal decompressed data", + buffer[j] == orgBuffer[j]); + } + } public void testAvailableNonEmptySource() throws Exception { // this byte[] is a deflation of these bytes: { 1, 3, 4, 6 } @@ -246,24 +197,10 @@ public class InflaterInputStreamTest extends TestCase { assertEquals(0, in.available()); } - /** - * @tests java.util.zip.InflaterInputStream#read(byte[], int, int) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed. Additional tests for fill method is not needed.", - method = "read", - args = {byte[].class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException & ZipException checking missed. Additional tests for fill method is not needed.", - method = "fill", - args = {} - ) - }) - public void test_read$BII() throws IOException { + /** + * @tests java.util.zip.InflaterInputStream#read(byte[], int, int) + */ + public void test_read$BII() throws IOException{ byte[] test = new byte[507]; for (int i = 0; i < 256; i++) { test[i] = (byte) i; @@ -282,7 +219,7 @@ public class InflaterInputStreamTest extends TestCase { while (true) { result = iis.read(outBuf, 0, 5); if (result == -1) { - // "EOF was reached"; + //"EOF was reached"; break; } } @@ -292,26 +229,8 @@ public class InflaterInputStreamTest extends TestCase { } catch (IndexOutOfBoundsException e) { // expected; } - iis.close(); - } + } - /** - * @tests java.util.zip.InflaterInputStream#read(byte[], int, int) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking.", - method = "read", - args = {byte[].class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking.", - method = "fill", - args = {} - ) - }) public void test_read$BII2() throws IOException { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_manifest.jar"); @@ -329,20 +248,6 @@ public class InflaterInputStreamTest extends TestCase { } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking.", - method = "read", - args = {byte[].class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking.", - method = "fill", - args = {} - ) - }) public void test_read$BII3() throws IOException { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_manifest.jar"); @@ -362,12 +267,6 @@ public class InflaterInputStreamTest extends TestCase { /** * @tests java.util.zip.InflaterInputStream#reset() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reset", - args = {} - ) public void test_reset() { InputStream is = new ByteArrayInputStream(new byte[10]); InflaterInputStream iis = new InflaterInputStream(is); @@ -378,135 +277,110 @@ public class InflaterInputStreamTest extends TestCase { // correct } } - - /** - * @tests java.util.zip.InflaterInputStream#skip(long) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IOException checking missed.", - method = "skip", - args = {long.class} - ) - public void test_skipJ() throws IOException { - InputStream is = Support_Resources.getStream("hyts_available.tst"); - InflaterInputStream iis = new InflaterInputStream(is); - - // Tests for skipping a negative number of bytes. - try { - iis.skip(-3); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { + + /** + * @tests java.util.zip.InflaterInputStream#skip(long) + */ + public void test_skipJ() throws IOException { + InputStream is = Support_Resources.getStream("hyts_available.tst"); + InflaterInputStream iis = new InflaterInputStream(is); + + // Tests for skipping a negative number of bytes. + try { + iis.skip(-3); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { // Expected - } - assertEquals("Incorrect Byte Returned.", 5, iis.read()); + } + assertEquals("Incorrect Byte Returned.", 5, iis.read()); - try { - iis.skip(Integer.MIN_VALUE); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { + try { + iis.skip(Integer.MIN_VALUE); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { // Expected - } - assertEquals("Incorrect Byte Returned.", 4, iis.read()); + } + assertEquals("Incorrect Byte Returned.", 4, iis.read()); - // Test to make sure the correct number of bytes were skipped - assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3)); + // Test to make sure the correct number of bytes were skipped + assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3)); - // Test to see if the number of bytes skipped returned is true. - assertEquals("Incorrect Byte Returned.", 7, iis.read()); + // Test to see if the number of bytes skipped returned is true. + assertEquals("Incorrect Byte Returned.", 7, iis.read()); - assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0)); - assertEquals("Incorrect Byte Returned.", 0, iis.read()); + assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0)); + assertEquals("Incorrect Byte Returned.", 0, iis.read()); - // Test for skipping more bytes than available in the stream - assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4)); - assertEquals("Incorrect Byte Returned.", -1, iis.read()); - iis.close(); - } + // Test for skipping more bytes than available in the stream + assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4)); + assertEquals("Incorrect Byte Returned.", -1, iis.read()); + iis.close(); + } - /** - * @tests java.util.zip.InflaterInputStream#skip(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IOException checking missed.", - method = "skip", - args = {long.class} - ) - public void test_skipJ2() throws IOException { - int result = 0; - int buffer[] = new int[100]; - byte orgBuffer[] = {1, 3, 4, 7, 8}; + /** + * @tests java.util.zip.InflaterInputStream#skip(long) + */ + public void test_skipJ2() throws IOException { + int result = 0; + int buffer[] = new int[100]; + byte orgBuffer[] = { 1, 3, 4, 7, 8 }; // testing for negative input to skip - InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); - Inflater inflate = new Inflater(); - InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate, - 10); - long skip; - try { - skip = inflatIP.skip(Integer.MIN_VALUE); - fail("Expected IllegalArgumentException when skip() is called with negative parameter"); - } catch (IllegalArgumentException e) { + InputStream infile = Support_Resources + .getStream("hyts_constru_OD.txt"); // android-changed + Inflater inflate = new Inflater(); + InflaterInputStream inflatIP = new InflaterInputStream(infile, + inflate, 10); + long skip; + try { + skip = inflatIP.skip(Integer.MIN_VALUE); + fail("Expected IllegalArgumentException when skip() is called with negative parameter"); + } catch (IllegalArgumentException e) { // Expected - } - inflatIP.close(); - - // testing for number of bytes greater than input. - InputStream infile2 = Support_Resources - .getStream("hyts_constru_OD.txt"); - InflaterInputStream inflatIP2 = new InflaterInputStream(infile2); - - // looked at how many bytes the skip skipped. It is - // 5 and its supposed to be the entire input stream. - - skip = inflatIP2.skip(Integer.MAX_VALUE); - // System.out.println(skip); - assertEquals("method skip() returned wrong number of bytes skipped", 5, - skip); - - // test for skipping of 2 bytes - InputStream infile3 = Support_Resources - .getStream("hyts_constru_OD.txt"); - InflaterInputStream inflatIP3 = new InflaterInputStream(infile3); - skip = inflatIP3.skip(2); - assertEquals( - "the number of bytes returned by skip did not correspond with its input parameters", - 2, skip); - int i = 0; - result = 0; - while ((result = inflatIP3.read()) != -1) { - buffer[i] = result; - i++; - } - inflatIP2.close(); - - for (int j = 2; j < orgBuffer.length; j++) { - assertTrue( - "original compressed data did not equal decompressed data", - buffer[j - 2] == orgBuffer[j]); - } - - try { - inflatIP2.skip(4); - fail("IOException expected."); - } catch (IOException ee) { - // expected - } - } - - /** - * @tests java.util.zip.InflaterInputStream#available() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "available", - args = {} - ) - public void test_available() throws IOException { - InputStream is = Support_Resources.getStream("hyts_available.tst"); - InflaterInputStream iis = new InflaterInputStream(is); + } + inflatIP.close(); + + // testing for number of bytes greater than input. + InputStream infile2 = Support_Resources + .getStream("hyts_constru_OD.txt"); // android-changed + InflaterInputStream inflatIP2 = new InflaterInputStream(infile2); + + // looked at how many bytes the skip skipped. It is + // 5 and its supposed to be the entire input stream. + + skip = inflatIP2.skip(Integer.MAX_VALUE); + // System.out.println(skip); + assertEquals("method skip() returned wrong number of bytes skipped", + 5, skip); + + // test for skipping of 2 bytes + InputStream infile3 = Support_Resources + .getStream("hyts_constru_OD.txt"); // android-changed + InflaterInputStream inflatIP3 = new InflaterInputStream(infile3); + skip = inflatIP3.skip(2); + assertEquals("the number of bytes returned by skip did not correspond with its input parameters", + 2, skip); + int i = 0; + result = 0; + while ((result = inflatIP3.read()) != -1) { + buffer[i] = result; + i++; + } + inflatIP2.close(); + + for (int j = 2; j < orgBuffer.length; j++) { + assertTrue( + "original compressed data did not equal decompressed data", + buffer[j - 2] == orgBuffer[j]); + } + } + + /** + * @tests java.util.zip.InflaterInputStream#available() + */ + public void test_available() throws IOException { + InputStream is = Support_Resources.getStream("hyts_available.tst"); + InflaterInputStream iis = new InflaterInputStream(is); int available; for (int i = 0; i < 11; i++) { @@ -519,31 +393,24 @@ public class InflaterInputStreamTest extends TestCase { } } - iis.close(); - try { - iis.available(); - fail("available after close should throw IOException."); - } catch (IOException e) { + iis.close(); + try { + iis.available(); + fail("available after close should throw IOException."); + } catch (IOException e) { // Expected - } - } + } + } - /** - * @tests java.util.zip.InflaterInputStream#close() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IOException can not be tested.", - method = "close", - args = {} - ) - public void test_close() throws IOException { - InflaterInputStream iin = new InflaterInputStream( - new ByteArrayInputStream(new byte[0])); - iin.close(); + /** + * @tests java.util.zip.InflaterInputStream#close() + */ + public void test_close() throws IOException { + InflaterInputStream iin = new InflaterInputStream( + new ByteArrayInputStream(new byte[0])); + iin.close(); // test for exception - iin.close(); - - } + iin.close(); + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java index cd5d538..49be8d0 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java @@ -14,17 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.util.Arrays; import java.util.zip.Adler32; import java.io.UnsupportedEncodingException; import java.util.zip.DataFormatException; @@ -34,345 +29,292 @@ import java.util.zip.ZipException; import tests.support.resource.Support_Resources; -@TestTargetClass(Inflater.class) public class InflaterTest extends junit.framework.TestCase { - byte outPutBuff1[] = new byte[500]; - - byte outPutDiction[] = new byte[500]; - - /** - * @tests java.util.zip.Inflater#end() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "end", - args = {} - ) - public void test_end() { - // test method of java.util.zip.inflater.end() - byte byteArray[] = {5, 2, 3, 7, 8}; - - int r = 0; - Inflater inflate = new Inflater(); - inflate.setInput(byteArray); - inflate.end(); - try { - inflate.reset(); - inflate.setInput(byteArray); - } catch (NullPointerException e) { - r = 1; - } - assertEquals("inflate can still be used after end is called", 1, r); - - Inflater i = new Inflater(); - i.end(); - // check for exception - i.end(); - } - - /** - * @tests java.util.zip.Inflater#finished() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finished", - args = {} - ) - public void test_finished() { - // test method of java.util.zip.inflater.finished() - byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'}; - Inflater inflate = new Inflater(false); - byte outPutInf[] = new byte[500]; - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - - inflate.inflate(outPutInf); - } - assertTrue( - "the method finished() returned false when no more data needs to be decompressed", - inflate.finished()); - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - byteArray[i] == outPutInf[i]); - } - assertEquals( - "final decompressed data contained more bytes than original - finished()", - 0, outPutInf[byteArray.length]); - } - - /** - * @tests java.util.zip.Inflater#getAdler() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAdler", - args = {} - ) - public void test_getAdler() { - // test method of java.util.zip.inflater.getAdler() - byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3}; - - Inflater inflateDiction = new Inflater(); - inflateDiction.setInput(outPutDiction); - if (inflateDiction.needsDictionary() == true) { - // getting the checkSum value through the Adler32 class - Adler32 adl = new Adler32(); - adl.update(dictionaryArray); - long checkSumR = adl.getValue(); - assertTrue( - "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance", - checkSumR == inflateDiction.getAdler()); - } - } + byte outPutBuff1[] = new byte[500]; + + byte outPutDiction[] = new byte[500]; + + /** + * @tests java.util.zip.Inflater#end() + */ + public void test_end() { + // test method of java.util.zip.inflater.end() + byte byteArray[] = { 5, 2, 3, 7, 8 }; + + int r = 0; + Inflater inflate = new Inflater(); + inflate.setInput(byteArray); + inflate.end(); + try { + inflate.reset(); + inflate.setInput(byteArray); + } catch (NullPointerException e) { + r = 1; + } + assertEquals("inflate can still be used after end is called", 1, r); + + Inflater i = new Inflater(); + i.end(); + // check for exception + i.end(); + } + + /** + * @tests java.util.zip.Inflater#finished() + */ + public void test_finished() { + // test method of java.util.zip.inflater.finished() + byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' }; + Inflater inflate = new Inflater(false); + byte outPutInf[] = new byte[500]; + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + + inflate.inflate(outPutInf); + } + assertTrue( + "the method finished() returned false when no more data needs to be decompressed", + inflate.finished()); + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - finished()", + 0, outPutInf[byteArray.length]); + } + + /** + * @tests java.util.zip.Inflater#getAdler() + */ + public void test_getAdler() { + // test method of java.util.zip.inflater.getAdler() + byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 }; + + Inflater inflateDiction = new Inflater(); + inflateDiction.setInput(outPutDiction); + if (inflateDiction.needsDictionary() == true) { + // getting the checkSum value through the Adler32 class + Adler32 adl = new Adler32(); + adl.update(dictionaryArray); + long checkSumR = adl.getValue(); + assertTrue( + "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance", + checkSumR == inflateDiction.getAdler()); + } + } + + /** + * @tests java.util.zip.Inflater#getRemaining() + */ + public void test_getRemaining() { + // test method of java.util.zip.inflater.getRemaining() + byte byteArray[] = { 1, 3, 5, 6, 7 }; + Inflater inflate = new Inflater(); + assertEquals("upon creating an instance of inflate, getRemaining returned a non zero value", + 0, inflate.getRemaining()); + inflate.setInput(byteArray); + assertTrue( + "getRemaining returned zero when there is input in the input buffer", + inflate.getRemaining() != 0); + } + + /** + * @tests java.util.zip.Inflater#getTotalIn() + */ + public void test_getTotalIn() { + // test method of java.util.zip.inflater.getTotalIn() + // creating the decompressed data + byte outPutBuf[] = new byte[500]; + byte byteArray[] = { 1, 3, 4, 7, 8 }; + byte outPutInf[] = new byte[500]; + int x = 0; + Deflater deflate = new Deflater(1); + deflate.setInput(byteArray); + while (!(deflate.needsInput())) { + x += deflate.deflate(outPutBuf, x, outPutBuf.length - x); + } + deflate.finish(); + while (!(deflate.finished())) { + x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x); + } + + Inflater inflate = new Inflater(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuf); + } + + inflate.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Input to inflate is invalid or corrupted - getTotalIn"); + } + // System.out.print(deflate.getTotalOut() + " " + inflate.getTotalIn()); + assertTrue( + "the total byte in outPutBuf did not equal the byte returned in getTotalIn", + inflate.getTotalIn() == deflate.getTotalOut()); + + Inflater inflate2 = new Inflater(); + int offSet = 0;// seems only can start as 0 + int length = 4; + try { + // seems no while loops allowed + if (inflate2.needsInput()) { + inflate2.setInput(outPutBuff1, offSet, length); + } + + inflate2.inflate(outPutInf); + + } catch (DataFormatException e) { + fail("Input to inflate is invalid or corrupted - getTotalIn"); + } + // System.out.print(inflate2.getTotalIn() + " " + length); + assertTrue( + "total byte dictated by length did not equal byte returned in getTotalIn", + inflate2.getTotalIn() == length); + } + + /** + * @tests java.util.zip.Inflater#getTotalOut() + */ + public void test_getTotalOut() { + // test method of java.util.zip.inflater.Inflater() + // creating the decompressed data + byte outPutBuf[] = new byte[500]; + byte byteArray[] = { 1, 3, 4, 7, 8 }; + int y = 0; + int x = 0; + Deflater deflate = new Deflater(1); + deflate.setInput(byteArray); + while (!(deflate.needsInput())) { + x += deflate.deflate(outPutBuf, x, outPutBuf.length - x); + } + deflate.finish(); + while (!(deflate.finished())) { + x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x); + } + + Inflater inflate = new Inflater(); + byte outPutInf[] = new byte[500]; + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuf); + } + + y += inflate.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Input to inflate is invalid or corrupted - getTotalIn"); + } + + assertTrue( + "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()", + y == inflate.getTotalOut()); + assertTrue( + "the total number of bytes to be compressed does not equal the total bytes decompressed", + inflate.getTotalOut() == deflate.getTotalIn()); + + // testing inflate(byte,int,int) + inflate.reset(); + y = 0; + int offSet = 0;// seems only can start as 0 + int length = 4; + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuf); + } + + y += inflate.inflate(outPutInf, offSet, length); + } + } catch (DataFormatException e) { + System.out + .println("Input to inflate is invalid or corrupted - getTotalIn"); + } + assertTrue( + "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()", + y == inflate.getTotalOut()); + assertTrue( + "the total number of bytes to be compressed does not equal the total bytes decompressed", + inflate.getTotalOut() == deflate.getTotalIn()); + } + + /** + * @tests java.util.zip.Inflater#inflate(byte[]) + */ + public void test_inflate$B() { + // test method of java.util.zip.inflater.inflate(byte) + + byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' }; + byte outPutInf[] = new byte[500]; + Inflater inflate = new Inflater(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + inflate.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - inflateB", + 0, outPutInf[byteArray.length]); + // testing for an empty input array + byte outPutBuf[] = new byte[500]; + byte emptyArray[] = new byte[11]; + int x = 0; + Deflater defEmpty = new Deflater(3); + defEmpty.setInput(emptyArray); + while (!(defEmpty.needsInput())) { + x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x); + } + defEmpty.finish(); + while (!(defEmpty.finished())) { + x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x); + } + assertTrue( + "the total number of byte from deflate did not equal getTotalOut - inflate(byte)", + x == defEmpty.getTotalOut()); + assertTrue( + "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)", + defEmpty.getTotalIn() == emptyArray.length); + Inflater infEmpty = new Inflater(); + try { + while (!(infEmpty.finished())) { + if (infEmpty.needsInput()) { + infEmpty.setInput(outPutBuf); + } + infEmpty.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < emptyArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + emptyArray[i] == outPutInf[i]); + assertEquals("Final decompressed data does not equal zero", + 0, outPutInf[i]); + } + assertEquals("Final decompressed data contains more element than original data", + 0, outPutInf[emptyArray.length]); + } - /** - * @tests java.util.zip.Inflater#getRemaining() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getRemaining", - args = {} - ) - public void test_getRemaining() { - // test method of java.util.zip.inflater.getRemaining() - byte byteArray[] = {1, 3, 5, 6, 7}; - Inflater inflate = new Inflater(); - assertEquals( - "upon creating an instance of inflate, getRemaining returned a non zero value", - 0, inflate.getRemaining()); - inflate.setInput(byteArray); - assertTrue( - "getRemaining returned zero when there is input in the input buffer", - inflate.getRemaining() != 0); - } - - /** - * @tests java.util.zip.Inflater#getTotalIn() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTotalIn", - args = {} - ) - public void test_getTotalIn() { - // test method of java.util.zip.inflater.getTotalIn() - // creating the decompressed data - byte outPutBuf[] = new byte[500]; - byte byteArray[] = {1, 3, 4, 7, 8}; - byte outPutInf[] = new byte[500]; - int x = 0; - Deflater deflate = new Deflater(1); - deflate.setInput(byteArray); - while (!(deflate.needsInput())) { - x += deflate.deflate(outPutBuf, x, outPutBuf.length - x); - } - deflate.finish(); - while (!(deflate.finished())) { - x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x); - } - - Inflater inflate = new Inflater(); - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuf); - } - - inflate.inflate(outPutInf); - } - } catch (DataFormatException e) { - fail("Input to inflate is invalid or corrupted - getTotalIn"); - } - // System.out.print(deflate.getTotalOut() + " " + inflate.getTotalIn()); - assertTrue( - "the total byte in outPutBuf did not equal the byte returned in getTotalIn", - inflate.getTotalIn() == deflate.getTotalOut()); - - Inflater inflate2 = new Inflater(); - int offSet = 0;// seems only can start as 0 - int length = 4; - try { - // seems no while loops allowed - if (inflate2.needsInput()) { - inflate2.setInput(outPutBuff1, offSet, length); - } - - inflate2.inflate(outPutInf); - - } catch (DataFormatException e) { - fail("Input to inflate is invalid or corrupted - getTotalIn"); - } - // System.out.print(inflate2.getTotalIn() + " " + length); - assertTrue( - "total byte dictated by length did not equal byte returned in getTotalIn", - inflate2.getTotalIn() == length); - } - - /** - * @tests java.util.zip.Inflater#getTotalOut() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTotalOut", - args = {} - ) - public void test_getTotalOut() { - // test method of java.util.zip.inflater.Inflater() - // creating the decompressed data - byte outPutBuf[] = new byte[500]; - byte byteArray[] = {1, 3, 4, 7, 8}; - int y = 0; - int x = 0; - Deflater deflate = new Deflater(1); - deflate.setInput(byteArray); - while (!(deflate.needsInput())) { - x += deflate.deflate(outPutBuf, x, outPutBuf.length - x); - } - deflate.finish(); - while (!(deflate.finished())) { - x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x); - } - - Inflater inflate = new Inflater(); - byte outPutInf[] = new byte[500]; - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuf); - } - - y += inflate.inflate(outPutInf); - } - } catch (DataFormatException e) { - fail("Input to inflate is invalid or corrupted - getTotalIn"); - } - - assertTrue( - "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()", - y == inflate.getTotalOut()); - assertTrue( - "the total number of bytes to be compressed does not equal the total bytes decompressed", - inflate.getTotalOut() == deflate.getTotalIn()); - - // testing inflate(byte,int,int) - inflate.reset(); - y = 0; - int offSet = 0;// seems only can start as 0 - int length = 4; - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuf); - } - - y += inflate.inflate(outPutInf, offSet, length); - } - } catch (DataFormatException e) { - System.out - .println("Input to inflate is invalid or corrupted - getTotalIn"); - } - assertTrue( - "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()", - y == inflate.getTotalOut()); - assertTrue( - "the total number of bytes to be compressed does not equal the total bytes decompressed", - inflate.getTotalOut() == deflate.getTotalIn()); - } - - /** - * @tests java.util.zip.Inflater#inflate(byte[]) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "DataFormatException checking missed.", - method = "inflate", - args = {byte[].class} - ) - public void test_inflate$B() { - // test method of java.util.zip.inflater.inflate(byte) - - byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'}; - byte outPutInf[] = new byte[500]; - Inflater inflate = new Inflater(); - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - inflate.inflate(outPutInf); - } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - byteArray[i] == outPutInf[i]); - } - assertEquals( - "final decompressed data contained more bytes than original - inflateB", - 0, outPutInf[byteArray.length]); - // testing for an empty input array - byte outPutBuf[] = new byte[500]; - byte emptyArray[] = new byte[11]; - int x = 0; - Deflater defEmpty = new Deflater(3); - defEmpty.setInput(emptyArray); - while (!(defEmpty.needsInput())) { - x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x); - } - defEmpty.finish(); - while (!(defEmpty.finished())) { - x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x); - } - assertTrue( - "the total number of byte from deflate did not equal getTotalOut - inflate(byte)", - x == defEmpty.getTotalOut()); - assertTrue( - "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)", - defEmpty.getTotalIn() == emptyArray.length); - Inflater infEmpty = new Inflater(); - try { - while (!(infEmpty.finished())) { - if (infEmpty.needsInput()) { - infEmpty.setInput(outPutBuf); - } - infEmpty.inflate(outPutInf); - } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < emptyArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - emptyArray[i] == outPutInf[i]); - assertEquals("Final decompressed data does not equal zero", 0, - outPutInf[i]); - } - assertEquals( - "Final decompressed data contains more element than original data", - 0, outPutInf[emptyArray.length]); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "inflate", - args = {byte[].class} - ) public void test_inflate$B1() { byte codedData[] = { 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87, @@ -408,82 +350,53 @@ public class InflaterTest extends junit.framework.TestCase { infl2.end(); } - /** - * @tests java.util.zip.Inflater#Inflater() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Inflater", - args = {} - ) - public void test_Constructor() { - // test method of java.util.zip.inflater.Inflater() - Inflater inflate = new Inflater(); - assertNotNull("failed to create the instance of inflater", - inflate); - } - - /** - * @tests java.util.zip.Inflater#inflate(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "DataFormatException checking missed.", - method = "inflate", - args = {byte[].class, int.class, int.class} - ) - public void test_inflate$BII() { - // test method of java.util.zip.inflater.inflate(byte,int,int) - - byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'}; - byte outPutInf[] = new byte[100]; - int y = 0; - Inflater inflate = new Inflater(); - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - y += inflate.inflate(outPutInf, y, outPutInf.length - y); - } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - byteArray[i] == outPutInf[i]); - } - assertEquals( - "final decompressed data contained more bytes than original - inflateB", - 0, outPutInf[byteArray.length]); - - // test boundary checks - inflate.reset(); - int r = 0; - int offSet = 0; - int lengthError = 101; - try { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - inflate.inflate(outPutInf, offSet, lengthError); - - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } catch (ArrayIndexOutOfBoundsException e) { - r = 1; - } - assertEquals("out of bounds error did not get caught", 1, r); - } + /** + * @tests java.util.zip.Inflater#inflate(byte[], int, int) + */ + public void test_inflate$BII() { + // test method of java.util.zip.inflater.inflate(byte,int,int) + + byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' }; + byte outPutInf[] = new byte[100]; + int y = 0; + Inflater inflate = new Inflater(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + y += inflate.inflate(outPutInf, y, outPutInf.length - y); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - inflateB", + 0, outPutInf[byteArray.length]); + + // test boundary checks + inflate.reset(); + int r = 0; + int offSet = 0; + int lengthError = 101; + try { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + inflate.inflate(outPutInf, offSet, lengthError); + + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } catch (ArrayIndexOutOfBoundsException e) { + r = 1; + } + assertEquals("out of bounds error did not get caught", 1, r); + } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "inflate", - args = {byte[].class, int.class, int.class} - ) public void test_inflate$BII1() { byte codedData[] = { 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87, @@ -519,271 +432,292 @@ public class InflaterTest extends junit.framework.TestCase { infl2.end(); } - /** - * @tests java.util.zip.Inflater#Inflater(boolean) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Inflater", - args = {boolean.class} - ) - public void test_ConstructorZ() { - // test method of java.util.zip.inflater.Inflater(boolean) - // note does not throw exception if deflater has a header, but inflater - // doesn't or vice versa. - byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'}; - Inflater inflate = new Inflater(true); - assertNotNull("failed to create the instance of inflater", inflate); - byte outPutInf[] = new byte[500]; - int r = 0; - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - - inflate.inflate(outPutInf); - } - for (int i = 0; i < byteArray.length; i++) { - assertEquals( - "the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed", - 0, outPutBuff1[i]); - } - } catch (DataFormatException e) { - r = 1; - } - assertEquals( - "Error: exception should be thrown because of header inconsistency", - 1, r); - - } - - /** - * @tests java.util.zip.Inflater#needsDictionary() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "needsDictionary", - args = {} - ) - public void test_needsDictionary() { - // test method of java.util.zip.inflater.needsDictionary() - // note: this flag is set after inflate is called - byte outPutInf[] = new byte[500]; - - // testing with dictionary set. - Inflater inflateDiction = new Inflater(); - if (inflateDiction.needsInput()) { - inflateDiction.setInput(outPutDiction); - } - try { - assertEquals("should return 0 because needs dictionary", 0, - inflateDiction.inflate(outPutInf)); - } catch (DataFormatException e) { - fail("Should not cause exception"); - } - assertTrue( - "method needsDictionary returned false when dictionary was used in deflater", - inflateDiction.needsDictionary()); - - // testing without dictionary - Inflater inflate = new Inflater(); - try { - inflate.setInput(outPutBuff1); - inflate.inflate(outPutInf); - assertFalse( - "method needsDictionary returned true when dictionary was not used in deflater", - inflate.needsDictionary()); - } catch (DataFormatException e) { - fail("Input to inflate is invalid or corrupted - needsDictionary"); - } + /** + * @tests java.util.zip.Inflater#Inflater() + */ + public void test_Constructor() { + // test method of java.util.zip.inflater.Inflater() + Inflater inflate = new Inflater(); + assertNotNull("failed to create the instance of inflater", + inflate); + } + + /** + * @tests java.util.zip.Inflater#Inflater(boolean) + */ + public void test_ConstructorZ() { + // test method of java.util.zip.inflater.Inflater(boolean) + // note does not throw exception if deflater has a header, but inflater + // doesn't or vice versa. + byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' }; + Inflater inflate = new Inflater(true); + assertNotNull("failed to create the instance of inflater", inflate); + byte outPutInf[] = new byte[500]; + int r = 0; + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + + inflate.inflate(outPutInf); + } + for (int i = 0; i < byteArray.length; i++) { + assertEquals("the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed", + 0, outPutBuff1[i]); + } + } catch (DataFormatException e) { + r = 1; + } + assertEquals("Error: exception should be thrown because of header inconsistency", + 1, r); + + } + + /** + * @tests java.util.zip.Inflater#needsDictionary() + */ + public void test_needsDictionary() { + // test method of java.util.zip.inflater.needsDictionary() + // note: this flag is set after inflate is called + byte outPutInf[] = new byte[500]; + + // testing with dictionary set. + Inflater inflateDiction = new Inflater(); + if (inflateDiction.needsInput()) { + inflateDiction.setInput(outPutDiction); + } + try { + assertEquals("should return 0 because needs dictionary", + 0, inflateDiction.inflate(outPutInf)); + } catch (DataFormatException e) { + fail("Should not cause exception"); + } + assertTrue( + "method needsDictionary returned false when dictionary was used in deflater", + inflateDiction.needsDictionary()); + + // testing without dictionary + Inflater inflate = new Inflater(); + try { + inflate.setInput(outPutBuff1); + inflate.inflate(outPutInf); + assertFalse( + "method needsDictionary returned true when dictionary was not used in deflater", + inflate.needsDictionary()); + } catch (DataFormatException e) { + fail( + "Input to inflate is invalid or corrupted - needsDictionary"); + } // Regression test for HARMONY-86 Inflater inf = new Inflater(); assertFalse(inf.needsDictionary()); - assertEquals(0, inf.getTotalIn()); - assertEquals(0, inf.getTotalOut()); - assertEquals(0, inf.getBytesRead()); - assertEquals(0, inf.getBytesWritten()); - } - - /** - * @tests java.util.zip.Inflater#needsInput() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "needsInput", - args = {} - ) - public void test_needsInput() { - // test method of java.util.zip.inflater.needsInput() - Inflater inflate = new Inflater(); - assertTrue( - "needsInput give the wrong boolean value as a result of no input buffer", - inflate.needsInput()); - - byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9}; - inflate.setInput(byteArray); - assertFalse( - "methodNeedsInput returned true when the input buffer is full", - inflate.needsInput()); - - inflate.reset(); - byte byteArrayEmpty[] = new byte[0]; - inflate.setInput(byteArrayEmpty); - assertTrue( - "needsInput give wrong boolean value as a result of an empty input buffer", - inflate.needsInput()); - } - - /** - * @tests java.util.zip.Inflater#reset() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reset", - args = {} - ) - public void test_reset() { - // test method of java.util.zip.inflater.reset() - byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'}; - byte outPutInf[] = new byte[100]; - int y = 0; - Inflater inflate = new Inflater(); - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - y += inflate.inflate(outPutInf, y, outPutInf.length - y); - } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - byteArray[i] == outPutInf[i]); - } - assertEquals( - "final decompressed data contained more bytes than original - reset", - 0, outPutInf[byteArray.length]); - - // testing that resetting the inflater will also return the correct - // decompressed data - - inflate.reset(); - try { - while (!(inflate.finished())) { - if (inflate.needsInput()) { - inflate.setInput(outPutBuff1); - } - inflate.inflate(outPutInf); - } - } catch (DataFormatException e) { - fail("Invalid input to be decompressed"); - } - for (int i = 0; i < byteArray.length; i++) { - assertTrue( - "Final decompressed data does not equal the original data", - byteArray[i] == outPutInf[i]); - } - assertEquals( - "final decompressed data contained more bytes than original - reset", - 0, outPutInf[byteArray.length]); - - } - - - /** - * @tests java.util.zip.Inflater#setInput(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setInput", - args = {byte[].class} - ) - public void test_setInput$B() { - // test method of java.util.zip.inflater.setInput(byte) - byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9}; - Inflater inflate = new Inflater(); - inflate.setInput(byteArray); - assertTrue("setInputB did not deliver any byte to the input buffer", - inflate.getRemaining() != 0); - } - - /** - * @tests java.util.zip.Inflater#setInput(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setInput", - args = {byte[].class, int.class, int.class} - ) - public void test_setInput$BII() { - // test method of java.util.zip.inflater.setInput(byte,int,int) - byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9}; - int offSet = 6; - int length = 6; - Inflater inflate = new Inflater(); - inflate.setInput(byteArray, offSet, length); - assertTrue( - "setInputBII did not deliver the right number of bytes to the input buffer", - inflate.getRemaining() == length); - // boundary check - inflate.reset(); - int r = 0; - try { - inflate.setInput(byteArray, 100, 100); - } catch (ArrayIndexOutOfBoundsException e) { - r = 1; - } - assertEquals("boundary check is not present for setInput", 1, r); - } - - @Override + assertEquals(0,inf.getTotalIn()); + assertEquals(0,inf.getTotalOut()); + assertEquals(0,inf.getBytesRead()); + assertEquals(0,inf.getBytesWritten()); + } + + /** + * @tests java.util.zip.Inflater#needsInput() + */ + public void test_needsInput() { + // test method of java.util.zip.inflater.needsInput() + Inflater inflate = new Inflater(); + assertTrue( + "needsInput give the wrong boolean value as a result of no input buffer", + inflate.needsInput()); + + byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 }; + inflate.setInput(byteArray); + assertFalse( + "methodNeedsInput returned true when the input buffer is full", + inflate.needsInput()); + + inflate.reset(); + byte byteArrayEmpty[] = new byte[0]; + inflate.setInput(byteArrayEmpty); + assertTrue( + "needsInput give wrong boolean value as a result of an empty input buffer", + inflate.needsInput()); + } + + /** + * @tests java.util.zip.Inflater#reset() + */ + public void test_reset() { + // test method of java.util.zip.inflater.reset() + byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' }; + byte outPutInf[] = new byte[100]; + int y = 0; + Inflater inflate = new Inflater(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + y += inflate.inflate(outPutInf, y, outPutInf.length - y); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - reset", + 0, outPutInf[byteArray.length]); + + // testing that resetting the inflater will also return the correct + // decompressed data + + inflate.reset(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutBuff1); + } + inflate.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - reset", + 0, outPutInf[byteArray.length]); + + } + + /** + * @tests java.util.zip.Inflater#setDictionary(byte[]) + */ + public void test_setDictionary$B() { + //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI + /* + // test method of java.util.zip.inflater.setDictionary(byte) + byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 }; + byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', + 'w', 'r' }; + + byte outPutInf[] = new byte[100]; + + // trying to inflate without setting a dictionary + + Inflater inflateWO = new Inflater(); + byte outPutInf2[] = new byte[100]; + int r = 0; + try { + while (!(inflateWO.finished())) { + if (inflateWO.needsInput()) { + inflateWO.setInput(outPutDiction); + } + inflateWO.inflate(outPutInf2); + } + } catch (DataFormatException e) { + r = 1; + } + assertEquals("invalid input to be decompressed due to dictionary not set", + 1, r); + // now setting the dictionary in inflater + Inflater inflate = new Inflater(); + try { + while (!(inflate.finished())) { + if (inflate.needsInput()) { + inflate.setInput(outPutDiction); + } + if (inflate.needsDictionary()) { + inflate.setDictionary(dictionaryArray); + } + inflate.inflate(outPutInf); + } + } catch (DataFormatException e) { + fail("Invalid input to be decompressed"); + } + for (int i = 0; i < byteArray.length; i++) { + assertTrue( + "Final decompressed data does not equal the original data", + byteArray[i] == outPutInf[i]); + } + assertEquals("final decompressed data contained more bytes than original - deflateB", + 0, outPutInf[byteArray.length]); + */ + } + + /** + * @tests java.util.zip.Inflater#setInput(byte[]) + */ + public void test_setInput$B() { + // test method of java.util.zip.inflater.setInput(byte) + byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 }; + Inflater inflate = new Inflater(); + inflate.setInput(byteArray); + assertTrue("setInputB did not deliver any byte to the input buffer", + inflate.getRemaining() != 0); + } + + /** + * @tests java.util.zip.Inflater#setInput(byte[], int, int) + */ + public void test_setInput$BII() { + // test method of java.util.zip.inflater.setInput(byte,int,int) + byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 }; + int offSet = 6; + int length = 6; + Inflater inflate = new Inflater(); + inflate.setInput(byteArray, offSet, length); + assertTrue( + "setInputBII did not deliver the right number of bytes to the input buffer", + inflate.getRemaining() == length); + // boundary check + inflate.reset(); + int r = 0; + try { + inflate.setInput(byteArray, 100, 100); + } catch (ArrayIndexOutOfBoundsException e) { + r = 1; + } + assertEquals("boundary check is not present for setInput", 1, r); + } + + @Override protected void setUp() { - try { - java.io.InputStream infile = Support_Resources - .getStream("hyts_compressD.txt"); - BufferedInputStream inflatIP = new BufferedInputStream(infile); - inflatIP.read(outPutBuff1, 0, outPutBuff1.length); - inflatIP.close(); - - java.io.InputStream infile2 = Support_Resources - .getStream("hyts_compDiction.txt"); - BufferedInputStream inflatIP2 = new BufferedInputStream(infile2); - inflatIP2.read(outPutDiction, 0, outPutDiction.length); - inflatIP2.close(); - - } catch (FileNotFoundException e) { - fail("input file to test InflaterInputStream constructor is not found"); - } catch (ZipException e) { - fail("read() threw an zip exception while testing constructor"); - } catch (IOException e) { - fail("read() threw an exception while testing constructor"); - } - } - - @Override + try { + java.io.InputStream infile = Support_Resources + .getStream("hyts_compressD.txt"); + BufferedInputStream inflatIP = new BufferedInputStream(infile); + inflatIP.read(outPutBuff1, 0, outPutBuff1.length); + inflatIP.close(); + + java.io.InputStream infile2 = Support_Resources + .getStream("hyts_compDiction.txt"); + BufferedInputStream inflatIP2 = new BufferedInputStream(infile2); + inflatIP2.read(outPutDiction, 0, outPutDiction.length); + inflatIP2.close(); + + } catch (FileNotFoundException e) { + fail( + "input file to test InflaterInputStream constructor is not found"); + } catch (ZipException e) { + fail( + "read() threw an zip exception while testing constructor"); + } catch (IOException e) { + fail("read() threw an exception while testing constructor"); + } + } + + @Override protected void tearDown() { - } - + } + /** * @tests java.util.zip.Deflater#getBytesRead() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getBytesRead", - args = {} - ) public void test_getBytesRead() throws DataFormatException, UnsupportedEncodingException { // Regression test for HARMONY-158 @@ -802,23 +736,16 @@ public class InflaterTest extends junit.framework.TestCase { def.finish(); def.deflate(output); inf.setInput(output); - int compressedDataLength = inf.inflate(input); + int compressedDataLength =inf.inflate(input); assertEquals(16, inf.getTotalIn()); assertEquals(compressedDataLength, inf.getTotalOut()); assertEquals(16, inf.getBytesRead()); } - + /** * @tests java.util.zip.Deflater#getBytesRead() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getBytesWritten", - args = {} - ) - public void test_getBytesWritten() throws DataFormatException, - UnsupportedEncodingException { + public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException { // Regression test for HARMONY-158 Deflater def = new Deflater(); Inflater inf = new Inflater(); @@ -835,7 +762,7 @@ public class InflaterTest extends junit.framework.TestCase { def.finish(); def.deflate(output); inf.setInput(output); - int compressedDataLength = inf.inflate(input); + int compressedDataLength =inf.inflate(input); assertEquals(16, inf.getTotalIn()); assertEquals(compressedDataLength, inf.getTotalOut()); assertEquals(14, inf.getBytesWritten()); @@ -844,14 +771,8 @@ public class InflaterTest extends junit.framework.TestCase { /** * @tests java.util.zip.Deflater#inflate(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test", - method = "inflate", - args = {byte[].class, int.class, int.class} - ) public void testInflate() throws Exception { - // Regression for HARMONY-81 + // Regression for HARMONY-81 Inflater inf = new Inflater(); int res = inf.inflate(new byte[0], 0, 0); @@ -862,30 +783,32 @@ public class InflaterTest extends junit.framework.TestCase { byte[] b = new byte[1024]; assertEquals(0, inflater.inflate(b)); inflater.end(); - } - /** - * @tests java.util.zip.Deflater#inflate(byte[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Can not be checked. Should be tested in DX test package.", - method = "finalize", - args = {} - ) - public void testFinalize() throws Exception { + // Regression for HARMONY-2510 + inflater = new Inflater(); + inflater.setInput(new byte[] { -1 }); + try { + inflater.inflate(b); + + // The RI detects malformed data on the malformed input { -1 }. Both + // this implementation and the native zlib API return "need input" + // on that data. This is an error if the stream is exhausted, but + // not one that results in an exception in the Inflater API. + assertTrue(inflater.needsInput()); + } catch (DataFormatException e) { + // expected + } + + inflater = new Inflater(); + inflater.setInput(new byte[] { -1, -1, -1 }); + try { + inflater.inflate(b); + } catch (DataFormatException e) { + // expected + } } - /** - * @tests java.util.zip.Inflater#setDictionary(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks setDictionary. Can be splitted for 2 separate tests for Deflater & Inflater. Can be used as a base for setDictionary with additional params.", - method = "setDictionary", - args = {byte[].class} - ) - public void testsetDictionary$B() throws Exception { + public void testSetDictionary$B() throws Exception { int i = 0; String inputString = "blah string contains blahblahblahblah and blah"; String dictionary1 = "blah"; @@ -1003,16 +926,7 @@ public class InflaterTest extends junit.framework.TestCase { infl1.end(); } - /** - * @tests java.util.zip.Inflater#setDictionary(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks setDictionary. Can be splitted for 2 separate tests for Deflater & Inflater. Can be used as a base for setDictionary with additional params.", - method = "setDictionary", - args = {byte[].class, int.class, int.class} - ) - public void testsetDictionary$BII() throws Exception { + public void testSetDictionary$BII() throws Exception { int i = 0; String inputString = "blah string contains blahblahblahblah and blah"; String dictionary1 = "blah"; @@ -1113,4 +1027,5 @@ public class InflaterTest extends junit.framework.TestCase { assertEquals(inputString, new String(result, 0, decLen)); } + } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java index ee7aceb..be5d0c6 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java @@ -14,27 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - -import tests.support.resource.Support_Resources; - +import java.util.TimeZone; +import java.util.zip.ZipEntry; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.TimeZone; -import java.util.zip.ZipEntry; -@TestTargetClass(ZipEntry.class) +import tests.support.resource.Support_Resources; + public class ZipEntryTest extends junit.framework.TestCase { - // BEGIN android-added public byte[] getAllBytesFromStream(InputStream is) throws IOException { ByteArrayOutputStream bs = new ByteArrayOutputStream(); byte[] buf = new byte[512]; @@ -47,601 +38,463 @@ public class ZipEntryTest extends junit.framework.TestCase { return bs.toByteArray(); } - // END android-added - - // zip file hyts_ZipFile.zip must be included as a resource - java.util.zip.ZipEntry zentry; - - java.util.zip.ZipFile zfile; - - private static final String platformId = System.getProperty( - "com.ibm.oti.configuration", "JDK") - + System.getProperty("java.vm.version"); - - static final String tempFileName = platformId + "zipentrytest.zip"; - - long orgSize; - - long orgCompressedSize; - - long orgCrc; - - long orgTime; - - String orgComment; - - /** - * @tests java.util.zip.ZipEntry#ZipEntry(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ZipEntry", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.zip.ZipEntry(java.lang.String) - zentry = zfile.getEntry("File3.txt"); - assertNotNull("Failed to create ZipEntry", zentry); - try { - zentry = zfile.getEntry(null); - fail("NullPointerException not thrown"); - } catch (NullPointerException e) { - } - StringBuffer s = new StringBuffer(); - for (int i = 0; i < 65535; i++) { - s.append('a'); - } - try { - zentry = new ZipEntry(s.toString()); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException During Test."); - } - try { - s.append('a'); - zentry = new ZipEntry(s.toString()); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - try { - String n = null; - zentry = new ZipEntry(n); - fail("NullPointerException not thrown"); - } catch (NullPointerException e) { - } - } - - /** - * @tests java.util.zip.ZipEntry#getComment() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getComment", - args = {} - ) - public void test_getComment() { - // Test for method java.lang.String java.util.zip.ZipEntry.getComment() - ZipEntry zipEntry = new ZipEntry("zippy.zip"); - assertNull("Incorrect Comment Returned.", zipEntry.getComment()); - zipEntry.setComment("This Is A Comment"); - assertEquals("Incorrect Comment Returned.", "This Is A Comment", - zipEntry.getComment()); - } + // zip file hyts_ZipFile.zip must be included as a resource + java.util.zip.ZipEntry zentry; - /** - * @tests java.util.zip.ZipEntry#getCompressedSize() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCompressedSize", - args = {} - ) - public void test_getCompressedSize() { - // Test for method long java.util.zip.ZipEntry.getCompressedSize() - assertTrue("Incorrect compressed size returned", zentry - .getCompressedSize() == orgCompressedSize); - } + java.util.zip.ZipFile zfile; - /** - * @tests java.util.zip.ZipEntry#getCrc() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCrc", - args = {} - ) - public void test_getCrc() { - // Test for method long java.util.zip.ZipEntry.getCrc() - assertTrue("Failed to get Crc", zentry.getCrc() == orgCrc); - } + private static final String platformId = System.getProperty( + "com.ibm.oti.configuration", "JDK") + + System.getProperty("java.vm.version"); - /** - * @tests java.util.zip.ZipEntry#getExtra() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getExtra", - args = {} - ) - public void test_getExtra() { - // Test for method byte [] java.util.zip.ZipEntry.getExtra() - assertNull("Incorrect extra information returned", zentry.getExtra()); - byte[] ba = {'T', 'E', 'S', 'T'}; - zentry = new ZipEntry("test.tst"); - zentry.setExtra(ba); - assertTrue("Incorrect Extra Information Returned.", - zentry.getExtra() == ba); - } + static final String tempFileName = platformId + "zfzezi.zip"; - /** - * @tests java.util.zip.ZipEntry#getMethod() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMethod", - args = {} - ) - public void test_getMethod() { - // Test for method int java.util.zip.ZipEntry.getMethod() - zentry = zfile.getEntry("File1.txt"); - assertTrue("Incorrect compression method returned", - zentry.getMethod() == java.util.zip.ZipEntry.STORED); - zentry = zfile.getEntry("File3.txt"); - assertTrue("Incorrect compression method returned", - zentry.getMethod() == java.util.zip.ZipEntry.DEFLATED); - zentry = new ZipEntry("test.tst"); - assertEquals("Incorrect Method Returned.", -1, zentry.getMethod()); - } + long orgSize; - /** - * @tests java.util.zip.ZipEntry#getName() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getName", - args = {} - ) - public void test_getName() { - // Test for method java.lang.String java.util.zip.ZipEntry.getName() - assertEquals( - "Incorrect name returned - Note return result somewhat ambiguous in spec", - "File1.txt", zentry.getName()); - } + long orgCompressedSize; - /** - * @tests java.util.zip.ZipEntry#getSize() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSize", - args = {} - ) - public void test_getSize() { - // Test for method long java.util.zip.ZipEntry.getSize() - assertTrue("Incorrect size returned", zentry.getSize() == orgSize); - } + long orgCrc; - /** - * @tests java.util.zip.ZipEntry#getTime() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTime", - args = {} - ) - public void test_getTime() { - // Test for method long java.util.zip.ZipEntry.getTime() - assertTrue("Failed to get time", zentry.getTime() == orgTime); - } + long orgTime; - /** - * @tests java.util.zip.ZipEntry#isDirectory() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isDirectory", - args = {} - ) - public void test_isDirectory() { - // Test for method boolean java.util.zip.ZipEntry.isDirectory() - assertTrue("Entry should not answer true to isDirectory", !zentry - .isDirectory()); - zentry = new ZipEntry("Directory/"); - assertTrue("Entry should answer true to isDirectory", zentry - .isDirectory()); - } + String orgComment; - /** - * @tests java.util.zip.ZipEntry#setComment(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setComment", - args = {java.lang.String.class} - ) - public void test_setCommentLjava_lang_String() { - // Test for method void - // java.util.zip.ZipEntry.setComment(java.lang.String) - zentry = zfile.getEntry("File1.txt"); - zentry.setComment("Set comment using api"); - assertEquals("Comment not correctly set", "Set comment using api", - zentry.getComment()); - String n = null; - zentry.setComment(n); - assertNull("Comment not correctly set", zentry.getComment()); - StringBuffer s = new StringBuffer(); - for (int i = 0; i < 0xFFFF; i++) { + /** + * @tests java.util.zip.ZipEntry#ZipEntry(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + // Test for method java.util.zip.ZipEntry(java.lang.String) + zentry = zfile.getEntry("File3.txt"); + assertNotNull("Failed to create ZipEntry", zentry); + try { + zentry = zfile.getEntry(null); + fail("NullPointerException not thrown"); + } catch (NullPointerException e) { + } + StringBuffer s = new StringBuffer(); + for (int i = 0; i < 65535; i++) { s.append('a'); } - try { - zentry.setComment(s.toString()); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException During Test."); - } - try { + try { + zentry = new ZipEntry(s.toString()); + } catch (IllegalArgumentException e) { + fail("Unexpected IllegalArgumentException During Test."); + } + try { + s.append('a'); + zentry = new ZipEntry(s.toString()); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + try { + String n = null; + zentry = new ZipEntry(n); + fail("NullPointerException not thrown"); + } catch (NullPointerException e) { + } + } + + /** + * @tests java.util.zip.ZipEntry#getComment() + */ + public void test_getComment() { + // Test for method java.lang.String java.util.zip.ZipEntry.getComment() + ZipEntry zipEntry = new ZipEntry("zippy.zip"); + assertNull("Incorrect Comment Returned.", zipEntry.getComment()); + zipEntry.setComment("This Is A Comment"); + assertEquals("Incorrect Comment Returned.", + "This Is A Comment", zipEntry.getComment()); + } + + /** + * @tests java.util.zip.ZipEntry#getCompressedSize() + */ + public void test_getCompressedSize() { + // Test for method long java.util.zip.ZipEntry.getCompressedSize() + assertTrue("Incorrect compressed size returned", zentry + .getCompressedSize() == orgCompressedSize); + } + + /** + * @tests java.util.zip.ZipEntry#getCrc() + */ + public void test_getCrc() { + // Test for method long java.util.zip.ZipEntry.getCrc() + assertTrue("Failed to get Crc", zentry.getCrc() == orgCrc); + } + + /** + * @tests java.util.zip.ZipEntry#getExtra() + */ + public void test_getExtra() { + // Test for method byte [] java.util.zip.ZipEntry.getExtra() + assertNull("Incorrect extra information returned", + zentry.getExtra()); + byte[] ba = { 'T', 'E', 'S', 'T' }; + zentry = new ZipEntry("test.tst"); + zentry.setExtra(ba); + assertTrue("Incorrect Extra Information Returned.", + zentry.getExtra() == ba); + } + + /** + * @tests java.util.zip.ZipEntry#getMethod() + */ + public void test_getMethod() { + // Test for method int java.util.zip.ZipEntry.getMethod() + zentry = zfile.getEntry("File1.txt"); + assertTrue("Incorrect compression method returned", + zentry.getMethod() == java.util.zip.ZipEntry.STORED); + zentry = zfile.getEntry("File3.txt"); + assertTrue("Incorrect compression method returned", + zentry.getMethod() == java.util.zip.ZipEntry.DEFLATED); + zentry = new ZipEntry("test.tst"); + assertEquals("Incorrect Method Returned.", -1, zentry.getMethod()); + } + + /** + * @tests java.util.zip.ZipEntry#getName() + */ + public void test_getName() { + // Test for method java.lang.String java.util.zip.ZipEntry.getName() + assertEquals("Incorrect name returned - Note return result somewhat ambiguous in spec", + "File1.txt", zentry.getName()); + } + + /** + * @tests java.util.zip.ZipEntry#getSize() + */ + public void test_getSize() { + // Test for method long java.util.zip.ZipEntry.getSize() + assertTrue("Incorrect size returned", zentry.getSize() == orgSize); + } + + /** + * @tests java.util.zip.ZipEntry#getTime() + */ + public void test_getTime() { + // Test for method long java.util.zip.ZipEntry.getTime() + assertTrue("Failed to get time", zentry.getTime() == orgTime); + } + + /** + * @tests java.util.zip.ZipEntry#isDirectory() + */ + public void test_isDirectory() { + // Test for method boolean java.util.zip.ZipEntry.isDirectory() + assertTrue("Entry should not answer true to isDirectory", !zentry + .isDirectory()); + zentry = new ZipEntry("Directory/"); + assertTrue("Entry should answer true to isDirectory", zentry + .isDirectory()); + } + + /** + * @tests java.util.zip.ZipEntry#setComment(java.lang.String) + */ + public void test_setCommentLjava_lang_String() { + // Test for method void + // java.util.zip.ZipEntry.setComment(java.lang.String) + zentry = zfile.getEntry("File1.txt"); + zentry.setComment("Set comment using api"); + assertEquals("Comment not correctly set", + "Set comment using api", zentry.getComment()); + String n = null; + zentry.setComment(n); + assertNull("Comment not correctly set", zentry.getComment()); + StringBuffer s = new StringBuffer(); + for (int i = 0; i < 0xFFFF; i++) { s.append('a'); - zentry.setComment(s.toString()); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.ZipEntry#setCompressedSize(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setCompressedSize", - args = {long.class} - ) - public void test_setCompressedSizeJ() { - // Test for method void java.util.zip.ZipEntry.setCompressedSize(long) - zentry.setCompressedSize(orgCompressedSize + 10); - assertTrue("Set compressed size failed", - zentry.getCompressedSize() == (orgCompressedSize + 10)); - zentry.setCompressedSize(0); - assertEquals("Set compressed size failed", 0, zentry - .getCompressedSize()); - zentry.setCompressedSize(-25); - assertEquals("Set compressed size failed", -25, zentry - .getCompressedSize()); - zentry.setCompressedSize(4294967296l); - assertTrue("Set compressed size failed", - zentry.getCompressedSize() == 4294967296l); - } - - /** - * @tests java.util.zip.ZipEntry#setCrc(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setCrc", - args = {long.class} - ) - public void test_setCrcJ() { - // Test for method void java.util.zip.ZipEntry.setCrc(long) - zentry.setCrc(orgCrc + 100); - assertTrue("Failed to set Crc", zentry.getCrc() == (orgCrc + 100)); - zentry.setCrc(0); - assertEquals("Failed to set Crc", 0, zentry.getCrc()); - try { - zentry.setCrc(-25); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - try { - zentry.setCrc(4294967295l); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException during test"); - } - try { - zentry.setCrc(4294967296l); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.ZipEntry#setExtra(byte[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setExtra", - args = {byte[].class} - ) - public void test_setExtra$B() { - // Test for method void java.util.zip.ZipEntry.setExtra(byte []) - zentry = zfile.getEntry("File1.txt"); - zentry.setExtra("Test setting extra information".getBytes()); - assertEquals("Extra information not written properly", - "Test setting extra information", new String(zentry.getExtra(), - 0, zentry.getExtra().length)); - zentry = new ZipEntry("test.tst"); - byte[] ba = new byte[0xFFFF]; - try { - zentry.setExtra(ba); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException during test"); - } - try { - ba = new byte[0xFFFF + 1]; - zentry.setExtra(ba); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - - // One constructor - ZipEntry zeInput = new ZipEntry("InputZIP"); - byte[] extraB = {'a', 'b', 'd', 'e'}; - zeInput.setExtra(extraB); - assertEquals(extraB, zeInput.getExtra()); - assertEquals(extraB[3], zeInput.getExtra()[3]); - assertEquals(extraB.length, zeInput.getExtra().length); - - // test another constructor - ZipEntry zeOutput = new ZipEntry(zeInput); - assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]); - assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length); - assertEquals(extraB[3], zeOutput.getExtra()[3]); - assertEquals(extraB.length, zeOutput.getExtra().length); - } - - /** - * @tests java.util.zip.ZipEntry#setMethod(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMethod", - args = {int.class} - ) - public void test_setMethodI() { - // Test for method void java.util.zip.ZipEntry.setMethod(int) - zentry = zfile.getEntry("File3.txt"); - zentry.setMethod(ZipEntry.STORED); - assertTrue("Failed to set compression method", - zentry.getMethod() == ZipEntry.STORED); - zentry.setMethod(ZipEntry.DEFLATED); - assertTrue("Failed to set compression method", - zentry.getMethod() == ZipEntry.DEFLATED); - try { - int error = 1; - zentry = new ZipEntry("test.tst"); - zentry.setMethod(error); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.ZipEntry#setSize(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setSize", - args = {long.class} - ) - public void test_setSizeJ() { - // Test for method void java.util.zip.ZipEntry.setSize(long) - zentry.setSize(orgSize + 10); - assertTrue("Set size failed", zentry.getSize() == (orgSize + 10)); - zentry.setSize(0); - assertEquals("Set size failed", 0, zentry.getSize()); - try { - zentry.setSize(-25); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - try { - zentry.setCrc(4294967295l); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException during test"); - } - try { - zentry.setCrc(4294967296l); - fail("IllegalArgumentException not thrown"); - } catch (IllegalArgumentException e) { - } - } - - /** - * @tests java.util.zip.ZipEntry#setTime(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setTime", - args = {long.class} - ) - public void test_setTimeJ() { - // Test for method void java.util.zip.ZipEntry.setTime(long) - zentry.setTime(orgTime + 10000); - assertTrue("Test 1: Failed to set time: " + zentry.getTime(), zentry - .getTime() == (orgTime + 10000)); - zentry.setTime(orgTime - 10000); - assertTrue("Test 2: Failed to set time: " + zentry.getTime(), zentry - .getTime() == (orgTime - 10000)); - TimeZone zone = TimeZone.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("EST")); - zentry.setTime(0); - assertTrue("Test 3: Failed to set time: " + zentry.getTime(), - zentry.getTime() == 315550800000L); - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - assertTrue("Test 3a: Failed to set time: " + zentry.getTime(), - zentry.getTime() == 315532800000L); - zentry.setTime(0); - TimeZone.setDefault(TimeZone.getTimeZone("EST")); - assertTrue("Test 3b: Failed to set time: " + zentry.getTime(), - zentry.getTime() == 315550800000L); - - zentry.setTime(-25); - assertTrue("Test 4: Failed to set time: " + zentry.getTime(), - zentry.getTime() == 315550800000L); - zentry.setTime(4354837200000L); - assertTrue("Test 5: Failed to set time: " + zentry.getTime(), - zentry.getTime() == 315550800000L); - } finally { - TimeZone.setDefault(zone); - } - } - - /** - * @tests java.util.zip.ZipEntry#toString() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - public void test_toString() { - // Test for method java.lang.String java.util.zip.ZipEntry.toString() - assertTrue("Returned incorrect entry name", zentry.toString().indexOf( - "File1.txt") >= 0); - } - - /** - * @tests java.util.zip.ZipEntry#ZipEntry(java.util.zip.ZipEntry) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ZipEntry", - args = {java.util.zip.ZipEntry.class} - ) - public void test_ConstructorLjava_util_zip_ZipEntry() { - // Test for method java.util.zip.ZipEntry(util.zip.ZipEntry) - zentry.setSize(2); - zentry.setCompressedSize(4); - zentry.setComment("Testing"); - ZipEntry zentry2 = new ZipEntry(zentry); - assertEquals("ZipEntry Created With Incorrect Size.", 2, zentry2 - .getSize()); - assertEquals("ZipEntry Created With Incorrect Compressed Size.", 4, - zentry2.getCompressedSize()); - assertEquals("ZipEntry Created With Incorrect Comment.", "Testing", - zentry2.getComment()); - assertTrue("ZipEntry Created With Incorrect Crc.", - zentry2.getCrc() == orgCrc); - assertTrue("ZipEntry Created With Incorrect Time.", - zentry2.getTime() == orgTime); - } - - /** - * @tests java.util.zip.ZipEntry#clone() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clone", - args = {} - ) - public void test_clone() { - // Test for method java.util.zip.ZipEntry.clone() - Object obj = zentry.clone(); - assertTrue("toString()", obj.toString().equals(zentry.toString())); - assertTrue("hashCode()", obj.hashCode() == zentry.hashCode()); - - // One constructor - ZipEntry zeInput = new ZipEntry("InputZIP"); - byte[] extraB = {'a', 'b', 'd', 'e'}; - zeInput.setExtra(extraB); - assertEquals(extraB, zeInput.getExtra()); - assertEquals(extraB[3], zeInput.getExtra()[3]); - assertEquals(extraB.length, zeInput.getExtra().length); - - // test Clone() - ZipEntry zeOutput = (ZipEntry) zeInput.clone(); - assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]); - assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length); - assertEquals(extraB[3], zeOutput.getExtra()[3]); - assertEquals(extraB.length, zeOutput.getExtra().length); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) - public void test_hashCode() { - try { - zentry.hashCode(); - } catch (Exception ee) { - fail("Unexpected exception " + ee); } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - - @Override + try { + zentry.setComment(s.toString()); + } catch (IllegalArgumentException e) { + fail("Unexpected IllegalArgumentException During Test."); + } + try { + s.append('a'); + zentry.setComment(s.toString()); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.ZipEntry#setCompressedSize(long) + */ + public void test_setCompressedSizeJ() { + // Test for method void java.util.zip.ZipEntry.setCompressedSize(long) + zentry.setCompressedSize(orgCompressedSize + 10); + assertTrue("Set compressed size failed", + zentry.getCompressedSize() == (orgCompressedSize + 10)); + zentry.setCompressedSize(0); + assertEquals("Set compressed size failed", + 0, zentry.getCompressedSize()); + zentry.setCompressedSize(-25); + assertEquals("Set compressed size failed", + -25, zentry.getCompressedSize()); + zentry.setCompressedSize(4294967296l); + assertTrue("Set compressed size failed", + zentry.getCompressedSize() == 4294967296l); + } + + /** + * @tests java.util.zip.ZipEntry#setCrc(long) + */ + public void test_setCrcJ() { + // Test for method void java.util.zip.ZipEntry.setCrc(long) + zentry.setCrc(orgCrc + 100); + assertTrue("Failed to set Crc", zentry.getCrc() == (orgCrc + 100)); + zentry.setCrc(0); + assertEquals("Failed to set Crc", 0, zentry.getCrc()); + try { + zentry.setCrc(-25); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + try { + zentry.setCrc(4294967295l); + } catch (IllegalArgumentException e) { + fail("Unexpected IllegalArgumentException during test"); + } + try { + zentry.setCrc(4294967296l); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.ZipEntry#setExtra(byte[]) + */ + public void test_setExtra$B() { + // Test for method void java.util.zip.ZipEntry.setExtra(byte []) + zentry = zfile.getEntry("File1.txt"); + zentry.setExtra("Test setting extra information".getBytes()); + assertEquals("Extra information not written properly", "Test setting extra information", new String(zentry + .getExtra(), 0, zentry.getExtra().length) + ); + zentry = new ZipEntry("test.tst"); + byte[] ba = new byte[0xFFFF]; + try { + zentry.setExtra(ba); + } catch (IllegalArgumentException e) { + fail("Unexpected IllegalArgumentException during test"); + } + try { + ba = new byte[0xFFFF + 1]; + zentry.setExtra(ba); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + + // One constructor + ZipEntry zeInput = new ZipEntry("InputZIP"); + byte[] extraB = { 'a', 'b', 'd', 'e' }; + zeInput.setExtra(extraB); + assertEquals(extraB, zeInput.getExtra()); + assertEquals(extraB[3], zeInput.getExtra()[3]); + assertEquals(extraB.length, zeInput.getExtra().length); + + // test another constructor + ZipEntry zeOutput = new ZipEntry(zeInput); + assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]); + assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length); + assertEquals(extraB[3], zeOutput.getExtra()[3]); + assertEquals(extraB.length, zeOutput.getExtra().length); + } + + /** + * @tests java.util.zip.ZipEntry#setMethod(int) + */ + public void test_setMethodI() { + // Test for method void java.util.zip.ZipEntry.setMethod(int) + zentry = zfile.getEntry("File3.txt"); + zentry.setMethod(ZipEntry.STORED); + assertTrue("Failed to set compression method", + zentry.getMethod() == ZipEntry.STORED); + zentry.setMethod(ZipEntry.DEFLATED); + assertTrue("Failed to set compression method", + zentry.getMethod() == ZipEntry.DEFLATED); + try { + int error = 1; + zentry = new ZipEntry("test.tst"); + zentry.setMethod(error); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.ZipEntry#setSize(long) + */ + public void test_setSizeJ() { + // Test for method void java.util.zip.ZipEntry.setSize(long) + zentry.setSize(orgSize + 10); + assertTrue("Set size failed", zentry.getSize() == (orgSize + 10)); + zentry.setSize(0); + assertEquals("Set size failed", 0, zentry.getSize()); + try { + zentry.setSize(-25); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + try { + zentry.setCrc(4294967295l); + } catch (IllegalArgumentException e) { + fail("Unexpected IllegalArgumentException during test"); + } + try { + zentry.setCrc(4294967296l); + fail("IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.util.zip.ZipEntry#setTime(long) + */ + public void test_setTimeJ() { + // Test for method void java.util.zip.ZipEntry.setTime(long) + zentry.setTime(orgTime + 10000); + assertTrue("Test 1: Failed to set time: " + zentry.getTime(), zentry + .getTime() == (orgTime + 10000)); + zentry.setTime(orgTime - 10000); + assertTrue("Test 2: Failed to set time: " + zentry.getTime(), zentry + .getTime() == (orgTime - 10000)); + TimeZone zone = TimeZone.getDefault(); + try { + TimeZone.setDefault(TimeZone.getTimeZone("EST")); + zentry.setTime(0); + assertTrue("Test 3: Failed to set time: " + zentry.getTime(), + zentry.getTime() == 315550800000L); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); + assertTrue("Test 3a: Failed to set time: " + zentry.getTime(), + zentry.getTime() == 315532800000L); + zentry.setTime(0); + TimeZone.setDefault(TimeZone.getTimeZone("EST")); + assertTrue("Test 3b: Failed to set time: " + zentry.getTime(), + zentry.getTime() == 315550800000L); + + zentry.setTime(-25); + assertTrue("Test 4: Failed to set time: " + zentry.getTime(), + zentry.getTime() == 315550800000L); + zentry.setTime(4354837200000L); + assertTrue("Test 5: Failed to set time: " + zentry.getTime(), + zentry.getTime() == 315550800000L); + } finally { + TimeZone.setDefault(zone); + } + } + + /** + * @tests java.util.zip.ZipEntry#toString() + */ + public void test_toString() { + // Test for method java.lang.String java.util.zip.ZipEntry.toString() + assertTrue("Returned incorrect entry name", zentry.toString().indexOf( + "File1.txt") >= 0); + } + + /** + * @tests java.util.zip.ZipEntry#ZipEntry(java.util.zip.ZipEntry) + */ + public void test_ConstructorLjava_util_zip_ZipEntry() { + // Test for method java.util.zip.ZipEntry(util.zip.ZipEntry) + zentry.setSize(2); + zentry.setCompressedSize(4); + zentry.setComment("Testing"); + ZipEntry zentry2 = new ZipEntry(zentry); + assertEquals("ZipEntry Created With Incorrect Size.", + 2, zentry2.getSize()); + assertEquals("ZipEntry Created With Incorrect Compressed Size.", 4, zentry2 + .getCompressedSize()); + assertEquals("ZipEntry Created With Incorrect Comment.", "Testing", zentry2 + .getComment()); + assertTrue("ZipEntry Created With Incorrect Crc.", + zentry2.getCrc() == orgCrc); + assertTrue("ZipEntry Created With Incorrect Time.", + zentry2.getTime() == orgTime); + } + + /** + * @tests java.util.zip.ZipEntry#clone() + */ + public void test_clone() { + // Test for method java.util.zip.ZipEntry.clone() + Object obj = zentry.clone(); + assertTrue("toString()", obj.toString().equals(zentry.toString())); + assertTrue("hashCode()", obj.hashCode() == zentry.hashCode()); + + // One constructor + ZipEntry zeInput = new ZipEntry("InputZIP"); + byte[] extraB = { 'a', 'b', 'd', 'e' }; + zeInput.setExtra(extraB); + assertEquals(extraB, zeInput.getExtra()); + assertEquals(extraB[3], zeInput.getExtra()[3]); + assertEquals(extraB.length, zeInput.getExtra().length); + + // test Clone() + ZipEntry zeOutput = (ZipEntry) zeInput.clone(); + assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]); + assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length); + assertEquals(extraB[3], zeOutput.getExtra()[3]); + assertEquals(extraB.length, zeOutput.getExtra().length); + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + + @Override protected void setUp() { - java.io.File f = null; - try { - // BEGIN android-changed - // Create a local copy of the file since some tests want to alter - // information. - f = File.createTempFile(tempFileName, ".zip"); - // Create absolute filename as ZipFile does not resolve using - // user.dir - f = new java.io.File(f.getAbsolutePath()); - f.delete(); - java.io.InputStream is = Support_Resources - .getStream("hyts_ZipFile.zip"); - java.io.FileOutputStream fos = new java.io.FileOutputStream(f); + java.io.File f = null; + try { + // Create a local copy of the file since some tests want to alter + // information. + f = new java.io.File(tempFileName); + // Create absolute filename as ZipFile does not resolve using + // user.dir + f = new java.io.File(f.getAbsolutePath()); + f.delete(); + java.io.InputStream is = Support_Resources + .getStream("hyts_ZipFile.zip"); + java.io.FileOutputStream fos = new java.io.FileOutputStream(f); byte[] rbuf = getAllBytesFromStream(is); - // END android-changed - fos.write(rbuf, 0, rbuf.length); - is.close(); - fos.close(); - zfile = new java.util.zip.ZipFile(f); - zentry = zfile.getEntry("File1.txt"); - orgSize = zentry.getSize(); - orgCompressedSize = zentry.getCompressedSize(); - orgCrc = zentry.getCrc(); - orgTime = zentry.getTime(); - orgComment = zentry.getComment(); - } catch (Exception e) { - System.out.println("Exception during ZipFile setup <" - + f.getAbsolutePath() + ">: "); - e.printStackTrace(); - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - - @Override + fos.write(rbuf, 0, rbuf.length); + is.close(); + fos.close(); + zfile = new java.util.zip.ZipFile(f); + zentry = zfile.getEntry("File1.txt"); + orgSize = zentry.getSize(); + orgCompressedSize = zentry.getCompressedSize(); + orgCrc = zentry.getCrc(); + orgTime = zentry.getTime(); + orgComment = zentry.getComment(); + } catch (Exception e) { + System.out.println("Exception during ZipFile setup <" + + f.getAbsolutePath() + ">: "); + e.printStackTrace(); + } + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + + @Override protected void tearDown() { - try { - if (zfile != null) { + try { + if (zfile != null) { zfile.close(); } - java.io.File f = new java.io.File(tempFileName); - f.delete(); - } catch (java.io.IOException e) { - System.out.println("Exception during tearDown"); - } - } + java.io.File f = new java.io.File(tempFileName); + f.delete(); + } catch (java.io.IOException e) { + System.out.println("Exception during tearDown"); + } + } } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java index eb04777..9f3be8d 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java @@ -16,35 +16,17 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import java.util.zip.ZipException; -@TestTargetClass(ZipException.class) public class ZipExceptionTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ZipException", - args = {} - ) public void testZipException() { ZipException zz = new ZipException(); assertEquals(zz.getMessage(), null); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ZipException", - args = {java.lang.String.class} - ) public void testZipExceptionLjava_lang_String() { ZipException zz = new ZipException("Test"); assertEquals(zz.getMessage(), "Test"); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java index fb326a6..7ff4f98 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java @@ -17,10 +17,6 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; import tests.support.Support_PlatformFile; import tests.support.resource.Support_Resources; import tests.util.TestEnvironment; @@ -38,7 +34,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; -@TestTargetClass(ZipFile.class) public class ZipFileTest extends junit.framework.TestCase { public byte[] getAllBytesFromStream(InputStream is) throws IOException { @@ -77,12 +72,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#ZipFile(java.io.File) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "setUp procedure checks this type of constructor.", - method = "ZipFile", - args = {java.io.File.class} - ) public void test_ConstructorLjava_io_File() { // Test for method java.util.zip.ZipFile(java.io.File) assertTrue("Used to test", true); @@ -91,11 +80,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#ZipFile(java.io.File, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "ZipFile", - args = {java.io.File.class, int.class} - ) public void test_ConstructorLjava_io_FileI() throws IOException { zfile.close(); // about to reopen the same temp file File file = new File(tempFileName); @@ -136,12 +120,6 @@ public class ZipFileTest extends junit.framework.TestCase { * @throws IOException * @tests java.util.zip.ZipFile#ZipFile(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Test contains empty brackets.", - method = "ZipFile", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() throws IOException { System.setProperty("user.dir", System.getProperty("java.io.tmpdir")); @@ -181,12 +159,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#finalize() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "finalize", - args = {} - ) public void test_finalize() throws IOException { InputStream in = Support_Resources.getStream("hyts_ZipFile.zip"); File file = Support_Resources.createTempFile(".jar"); @@ -217,11 +189,6 @@ public class ZipFileTest extends junit.framework.TestCase { * @throws IOException * @tests java.util.zip.ZipFile#close() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "close", - args = {} - ) public void test_close() throws IOException { // Test for method void java.util.zip.ZipFile.close() File fl = new File(tempFileName); @@ -252,12 +219,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#entries() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entries", - args = {} - ) public void test_entries() throws Exception { // Test for method java.util.Enumeration java.util.zip.ZipFile.entries() Enumeration<? extends ZipEntry> enumer = zfile.entries(); @@ -292,11 +253,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#getEntry(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getEntry", - args = {java.lang.String.class} - ) public void test_getEntryLjava_lang_String() throws IOException { // Test for method java.util.zip.ZipEntry // java.util.zip.ZipFile.getEntry(java.lang.String) @@ -325,11 +281,6 @@ public class ZipFileTest extends junit.framework.TestCase { 0, r)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getEntry", - args = {java.lang.String.class} - ) public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException { java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt"); assertNotNull("Could not obtain ZipEntry", zentry); @@ -351,12 +302,6 @@ public class ZipFileTest extends junit.framework.TestCase { assertEquals("Must not be able to read directory data", -1, data); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IllegalStateException checking.", - method = "getEntry", - args = {java.lang.String.class} - ) public void test_getEntryLjava_lang_String_Ex() throws IOException { java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt"); assertNotNull("Could not obtain ZipEntry", zentry); @@ -373,12 +318,6 @@ public class ZipFileTest extends junit.framework.TestCase { * @throws IOException * @tests java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException { // Test for method java.io.InputStream // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry) @@ -417,12 +356,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipFile#getName() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getName", - args = {} - ) public void test_getName() { // Test for method java.lang.String java.util.zip.ZipFile.getName() assertTrue("Returned incorrect name: " + zfile.getName(), zfile @@ -433,11 +366,6 @@ public class ZipFileTest extends junit.framework.TestCase { * @throws IOException * @tests java.util.zip.ZipFile#size() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "size", - args = {} - ) public void test_size() throws IOException { assertEquals(6, zfile.size()); zfile.close(); @@ -451,12 +379,6 @@ public class ZipFileTest extends junit.framework.TestCase { /** * @tests java.io.InputStream#reset() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) - @KnownFailure("ZipEntry.getInputStream().reset() fails with an IOException") public void test_reset() throws IOException { // read an uncompressed entry ZipEntry zentry = zfile.getEntry("File1.txt"); @@ -469,9 +391,11 @@ public class ZipFileTest extends junit.framework.TestCase { r2 = is.read(rbuf2); assertEquals(rbuf2.length, r2); - is.reset(); - r2 = is.read(rbuf2); - assertEquals(rbuf2.length, r2); + try { + is.reset(); + fail(); + } catch (IOException expected) { + } is.close(); // read a compressed entry @@ -480,30 +404,27 @@ public class ZipFileTest extends junit.framework.TestCase { is = zfile.getInputStream(zentry2); r1 = is.read(rbuf3); assertEquals(4183, r1); - is.reset(); - - r1 = is.read(rbuf3); - assertEquals(4183, r1); + try { + is.reset(); + fail(); + } catch (IOException expected) { + } is.close(); is = zfile.getInputStream(zentry2); r1 = is.read(rbuf3, 0, 3000); assertEquals(3000, r1); - is.reset(); - r1 = is.read(rbuf3, 0, 3000); - assertEquals(3000, r1); + try { + is.reset(); + fail(); + } catch (IOException expected) { + } is.close(); } /** * @tests java.io.InputStream#reset() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getInputStream", - args = {java.util.zip.ZipEntry.class} - ) - @KnownFailure("ZipEntry.getInputStream().reset() fails with an IOException") public void test_reset_subtest0() throws IOException { // read an uncompressed entry ZipEntry zentry = zfile.getEntry("File1.txt"); @@ -517,10 +438,12 @@ public class ZipFileTest extends junit.framework.TestCase { assertEquals(8, r); assertEquals(-1, is.read()); - is.reset(); - r = is.read(rbuf2); - assertEquals(8, r); - assertEquals(-1, is.read()); + try { + is.reset(); + fail(); + } catch (IOException expected) { + } + is.close(); // read a compressed entry @@ -534,10 +457,12 @@ public class ZipFileTest extends junit.framework.TestCase { assertEquals(1183, r); assertEquals(-1, is.read()); - is.reset(); - r = is.read(rbuf3); - assertEquals(1183, r); - assertEquals(-1, is.read()); + try { + is.reset(); + fail(); + } catch (IOException expected) { + } + is.close(); } diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java index c5efedc..02ddd08 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java @@ -17,10 +17,6 @@ package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import tests.support.resource.Support_Resources; @@ -37,7 +33,6 @@ import java.util.zip.ZipException; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -@TestTargetClass(ZipInputStream.class) public class ZipInputStreamTest extends TestCase { // the file hyts_zipFile.zip used in setup needs to included as a resource private ZipEntry zentry; @@ -84,12 +79,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#ZipInputStream(java.io.InputStream) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ZipInputStream", - args = {java.io.InputStream.class} - ) public void test_ConstructorLjava_io_InputStream() throws Exception { zentry = zis.getNextEntry(); zis.closeEntry(); @@ -98,12 +87,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#close() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "close", - args = {} - ) public void test_close() { try { zis.close(); @@ -118,12 +101,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#close() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks calling method two times", - method = "close", - args = {} - ) public void test_close2() throws Exception { // Regression for HARMONY-1101 zis.close(); @@ -134,12 +111,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#closeEntry() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "closeEntry", - args = {} - ) public void test_closeEntry() throws Exception { zentry = zis.getNextEntry(); zis.closeEntry(); @@ -169,11 +140,6 @@ public class ZipInputStreamTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "close", - args = {} - ) public void test_closeAfterException() throws Exception { File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "Broken_manifest.jar"); @@ -203,11 +169,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#getNextEntry() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "getNextEntry", - args = {} - ) public void test_getNextEntry() throws Exception { assertNotNull("getNextEntry failed", zis.getNextEntry()); @@ -239,11 +200,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#read(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "read", - args = {byte[].class, int.class, int.class} - ) public void test_read$BII() throws Exception { zentry = zis.getNextEntry(); byte[] rbuf = new byte[(int) zentry.getSize()]; @@ -279,11 +235,6 @@ public class ZipInputStreamTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "read", - args = {byte[].class, int.class, int.class} - ) public void testReadOneByteAtATime() throws IOException { InputStream in = new FilterInputStream(Support_Resources.getStream("hyts_ZipFile.zip")) { @Override @@ -307,11 +258,6 @@ public class ZipInputStreamTest extends TestCase { /** * @tests java.util.zip.ZipInputStream#skip(long) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "skip", - args = {long.class} - ) public void test_skipJ() throws Exception { zentry = zis.getNextEntry(); byte[] rbuf = new byte[(int) zentry.getSize()]; @@ -365,11 +311,6 @@ public class ZipInputStreamTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "available", - args = {} - ) public void test_available() throws Exception { File resources = Support_Resources.createTempFolder(); @@ -422,12 +363,6 @@ public class ZipInputStreamTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "createZipEntry", - args = {java.lang.String.class} - ) public void test_createZipEntryLjava_lang_String() throws Exception { File resources = Support_Resources.createTempFolder(); diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java index 0398f03..7adfeff 100644 --- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java +++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java @@ -14,14 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.archive.tests.java.util.zip; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -33,27 +27,20 @@ import java.util.zip.ZipException; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -@TestTargetClass(ZipOutputStream.class) public class ZipOutputStreamTest extends junit.framework.TestCase { - ZipOutputStream zos; + ZipOutputStream zos; - ByteArrayOutputStream bos; + ByteArrayOutputStream bos; - ZipInputStream zis; + ZipInputStream zis; - static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld"; + static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld"; - /** + /** * @tests java.util.zip.ZipOutputStream#close() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Can not check IOException.", - method = "close", - args = {} - ) - public void test_close() throws Exception { + public void test_close() throws Exception { try { zos.close(); fail("Close on empty stream failed to throw exception"); @@ -76,12 +63,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipOutputStream#closeEntry() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "ZipException can not be checked.", - method = "closeEntry", - args = {} - ) public void test_closeEntry() throws IOException { ZipEntry ze = new ZipEntry("testEntry"); ze.setTime(System.currentTimeMillis()); @@ -90,25 +71,12 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { zos.closeEntry(); assertTrue("closeEntry failed to update required fields", ze.getSize() == 11 && ze.getCompressedSize() == 13); - ze = new ZipEntry("testEntry1"); - zos.close(); - try { - zos.closeEntry(); - fail("IOException expected"); - } catch (IOException ee) { - // expected - } + } /** * @tests java.util.zip.ZipOutputStream#finish() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "ZipException can not be checked.", - method = "finish", - args = {} - ) public void test_finish() throws Exception { ZipEntry ze = new ZipEntry("test"); zos.putNextEntry(ze); @@ -131,12 +99,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipOutputStream#putNextEntry(java.util.zip.ZipEntry) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "ZipException can not be checked.", - method = "putNextEntry", - args = {java.util.zip.ZipEntry.class} - ) public void test_putNextEntryLjava_util_zip_ZipEntry() throws IOException { ZipEntry ze = new ZipEntry("testEntry"); ze.setTime(System.currentTimeMillis()); @@ -161,12 +123,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipOutputStream#setComment(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setComment", - args = {java.lang.String.class} - ) public void test_setCommentLjava_lang_String() { // There is no way to get the comment back, so no way to determine if // the comment is set correct @@ -183,12 +139,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipOutputStream#setLevel(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {int.class} - ) public void test_setLevelI() throws IOException { ZipEntry ze = new ZipEntry("test"); zos.putNextEntry(ze); @@ -200,23 +150,11 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { zos.write(data.getBytes()); zos.closeEntry(); assertTrue("setLevel failed", csize <= ze.getCompressedSize()); - try { - zos.setLevel(-9); // Max Compression - fail("IllegalArgumentException ecpected."); - } catch (IllegalArgumentException ee) { - // expected - } } /** * @tests java.util.zip.ZipOutputStream#setMethod(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMethod", - args = {int.class} - ) public void test_setMethodI() throws IOException { ZipEntry ze = new ZipEntry("test"); zos.setMethod(ZipOutputStream.STORED); @@ -233,23 +171,11 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { zos.write(data.getBytes()); zos.closeEntry(); assertTrue("setLevel failed", csize >= ze.getCompressedSize()); - try { - zos.setMethod(-ZipOutputStream.DEFLATED); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - // expected - } } /** * @tests java.util.zip.ZipOutputStream#write(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "write", - args = {byte[].class, int.class, int.class} - ) public void test_write$BII() throws IOException { ZipEntry ze = new ZipEntry("test"); zos.putNextEntry(ze); @@ -314,12 +240,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { /** * @tests java.util.zip.ZipOutputStream#write(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Regression", - method = "write", - args = {byte[].class, int.class, int.class} - ) public void test_write$BII_2() throws IOException { // Regression for HARMONY-577 File f1 = File.createTempFile("testZip1", "tst"); @@ -331,7 +251,7 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { zip1.setMethod(ZipEntry.STORED); zip1.write(new byte[2]); - + try { zip1.putNextEntry(new ZipEntry("Second")); fail("ZipException expected"); @@ -364,18 +284,7 @@ public class ZipOutputStreamTest extends junit.framework.TestCase { if (zis != null) { zis.close(); } - } catch (Exception e) { - } + } catch (Exception e) {} super.tearDown(); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "See setUp procedure for more info.", - method = "ZipOutputStream", - args = {java.io.OutputStream.class} - ) - public void test_ConstructorLjava_io_OutputStream() { - assertTrue(true); - } } diff --git a/archive/src/test/java/tests/archive/AllTests.java b/archive/src/test/java/tests/archive/AllTests.java index a5c461c..4c1fca2 100644 --- a/archive/src/test/java/tests/archive/AllTests.java +++ b/archive/src/test/java/tests/archive/AllTests.java @@ -21,13 +21,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Archive test suites"); + TestSuite suite = new TestSuite("All Archive test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.archive.tests.java.util.jar.AllTests .suite()); diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java index 99a007a..b80fe64 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java @@ -15,9 +15,6 @@ import java.math.BigInteger; import java.security.*; public class AbstractExecutorServiceTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AbstractExecutorServiceTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java index 0251390..660fec9 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java @@ -15,9 +15,6 @@ import java.util.concurrent.locks.*; import java.io.*; public class AbstractQueueTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AbstractQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java index db89645..e2cfe92 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java @@ -15,9 +15,6 @@ import java.util.concurrent.locks.*; import java.io.*; public class AbstractQueuedSynchronizerTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AbstractQueuedSynchronizerTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java index b650ede..1deea2c 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class ArrayBlockingQueueTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ArrayBlockingQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java index 230357a..c76196b 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java @@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*; import java.io.*; public class AtomicBooleanTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicBooleanTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java index cd13fcf..d8afe4e 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java @@ -14,10 +14,6 @@ import java.io.*; import java.util.*; public class AtomicIntegerArrayTest extends JSR166TestCase { - - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicIntegerArrayTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java index 4c3ecb4..a4ec85e 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java @@ -16,9 +16,6 @@ public class AtomicIntegerFieldUpdaterTest extends JSR166TestCase { volatile int x = 0; int w; long z; - public static void main(String[] args){ - junit.textui.TestRunner.run(suite()); - } public static Test suite() { return new TestSuite(AtomicIntegerFieldUpdaterTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java index d484785..a6b2a17 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java @@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*; import java.io.*; public class AtomicIntegerTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicIntegerTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java index 99ce204..262d273 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java @@ -14,9 +14,6 @@ import java.io.*; import java.util.*; public class AtomicLongArrayTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicLongArrayTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java index 9310795..bac25dc 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java @@ -17,9 +17,6 @@ public class AtomicLongFieldUpdaterTest extends JSR166TestCase { int z; long w; - public static void main(String[] args){ - junit.textui.TestRunner.run(suite()); - } public static Test suite() { return new TestSuite(AtomicLongFieldUpdaterTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java index 143c84a..f4805bf 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java @@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*; import java.io.*; public class AtomicLongTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicLongTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java index 7b3dcb1..7857dde 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java @@ -12,9 +12,6 @@ import junit.framework.*; import java.util.concurrent.atomic.*; public class AtomicMarkableReferenceTest extends JSR166TestCase{ - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicMarkableReferenceTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java index 9330d39..81248cc 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java @@ -15,9 +15,6 @@ import java.util.*; public class AtomicReferenceArrayTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicReferenceArrayTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java index feddce7..7f71781 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java @@ -17,9 +17,6 @@ public class AtomicReferenceFieldUpdaterTest extends JSR166TestCase{ Object z; Integer w; - public static void main(String[] args){ - junit.textui.TestRunner.run(suite()); - } public static Test suite() { return new TestSuite(AtomicReferenceFieldUpdaterTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java index 33da30d..bcb4701 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java @@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*; import java.io.*; public class AtomicReferenceTest extends JSR166TestCase { - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicReferenceTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java index 3ffc0a7..9f4e4f7 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java @@ -12,9 +12,6 @@ import junit.framework.*; import java.util.concurrent.atomic.*; public class AtomicStampedReferenceTest extends JSR166TestCase{ - public static void main (String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(AtomicStampedReferenceTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java index d7f2210..b7549a4 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java @@ -15,9 +15,6 @@ import java.util.Enumeration; import java.io.*; public class ConcurrentHashMapTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ConcurrentHashMapTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java index 8d8e13b..c84dc59 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java @@ -14,11 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class ConcurrentLinkedQueueTest extends JSR166TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(ConcurrentLinkedQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java index d208039..53a1f70 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java @@ -14,11 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class CopyOnWriteArrayListTest extends JSR166TestCase{ - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(CopyOnWriteArrayListTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java index 809fc59..abb33fa 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class CopyOnWriteArraySetTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(CopyOnWriteArraySetTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java index 0d69889..179c81e 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java @@ -13,9 +13,6 @@ import java.util.*; import java.util.concurrent.*; public class CountDownLatchTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(CountDownLatchTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java index ecd6e45..3b99ef8 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java @@ -15,9 +15,6 @@ import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; public class CyclicBarrierTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(CyclicBarrierTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java index 978edb4..3d851e8 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java @@ -13,10 +13,6 @@ import java.util.*; import java.util.concurrent.*; public class DelayQueueTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(DelayQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java index 9811e82..bc0df85 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java @@ -13,10 +13,6 @@ import java.util.*; import java.util.concurrent.*; public class ExchangerTest extends JSR166TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ExchangerTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java index b1988cc..91bedf9 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java @@ -16,9 +16,6 @@ import java.math.BigInteger; import java.security.*; public class ExecutorCompletionServiceTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ExecutorCompletionServiceTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java index e8fc7e5..b0a2ccd 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java @@ -15,9 +15,6 @@ import java.math.BigInteger; import java.security.*; public class ExecutorsTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ExecutorsTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java index 2108986..2635054 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java @@ -13,10 +13,6 @@ import java.util.concurrent.*; import java.util.*; public class FutureTaskTest extends JSR166TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(FutureTaskTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java b/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java index c900616..4e0de95 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java @@ -97,7 +97,7 @@ public class JSR166TestCase extends TestCase { iters = Integer.parseInt(args[0]); Test s = suite(); for (int i = 0; i < iters; ++i) { - junit.textui.TestRunner.run (s); + // junit.textui.TestRunner.run (s); android-changed System.gc(); System.runFinalization(); } @@ -108,8 +108,8 @@ public class JSR166TestCase extends TestCase { * Collects all JSR166 unit tests as one suite */ public static Test suite ( ) { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("JSR166 Unit Tests"); // BEGIN android-changed + TestSuite suite = new TestSuite("JSR166 Unit Tests"); suite.addTest(AbstractExecutorServiceTest.suite()); suite.addTest(AbstractQueueTest.suite()); suite.addTest(AbstractQueuedSynchronizerTest.suite()); diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java index 6648afb..dd6be9a 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java @@ -14,11 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class LinkedBlockingQueueTest extends JSR166TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(LinkedBlockingQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java index 3a20207..3017c52 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java @@ -13,10 +13,6 @@ import java.util.*; import java.util.concurrent.*; public class LinkedListTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(LinkedListTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java index b39db2e..0a74f91 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.util.concurrent.locks.*; public class LockSupportTest extends JSR166TestCase{ - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(LockSupportTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java index 3857e0f..a764866 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class PriorityBlockingQueueTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(PriorityBlockingQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java index 409e1ed..3d3c1be 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class PriorityQueueTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(PriorityQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java index c50482d..8372251 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java @@ -15,9 +15,6 @@ import java.util.*; import java.io.*; public class ReentrantLockTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ReentrantLockTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java index e38165a..4191a13 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java @@ -15,9 +15,6 @@ import java.io.*; import java.util.*; public class ReentrantReadWriteLockTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ReentrantReadWriteLockTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java index da5704e..14e98b4 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class ScheduledExecutorTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ScheduledExecutorTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java index 4019812..3f2ff33 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java @@ -14,9 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class SemaphoreTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(SemaphoreTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java index debce5d..c2ae396 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java @@ -14,11 +14,6 @@ import java.util.concurrent.*; import java.io.*; public class SynchronousQueueTest extends JSR166TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } - public static Test suite() { return new TestSuite(SynchronousQueueTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java index 4433cb1..439039a 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java @@ -11,10 +11,6 @@ package tests.api.java.util.concurrent; import junit.framework.*; public class SystemTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { return new TestSuite(SystemTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java index 0c2256a..b9b7ba5 100644 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java @@ -12,10 +12,6 @@ import junit.framework.*; import java.util.concurrent.Semaphore; public class ThreadLocalTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { return new TestSuite(ThreadLocalTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java index 4f7cc46..ee27e51 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java @@ -14,9 +14,6 @@ import junit.framework.*; import java.util.*; public class ThreadPoolExecutorTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run (suite()); - } public static Test suite() { return new TestSuite(ThreadPoolExecutorTest.class); } diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java index 253d9eb..3885c48 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java @@ -8,17 +8,9 @@ package tests.api.java.util.concurrent; -// BEGIN android-added -import dalvik.annotation.BrokenTest; -// END android-added - import junit.framework.*; public class ThreadTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { return new TestSuite(ThreadTest.class); } @@ -50,9 +42,6 @@ public class ThreadTest extends JSR166TestCase { * getDefaultUncaughtExceptionHandler returns value of last * setDefaultUncaughtExceptionHandler. */ - // BEGIN android-added - @BrokenTest("Different behavior between run-core-tests and CTS") - // END android-added public void testGetAndSetDefaultUncaughtExceptionHandler() { assertEquals(null, Thread.getDefaultUncaughtExceptionHandler()); // failure due to securityException is OK. @@ -74,4 +63,3 @@ public class ThreadTest extends JSR166TestCase { // How to test actually using UEH within junit? } - diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java index 54fdc69..f6504d8 100755 --- a/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java +++ b/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java @@ -13,10 +13,6 @@ import java.util.concurrent.*; import java.io.*; public class TimeUnitTest extends JSR166TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { return new TestSuite(TimeUnitTest.class); } diff --git a/concurrent/src/test/java/tests/concurrent/AllTests.java b/concurrent/src/test/java/tests/concurrent/AllTests.java index d2ebbeb..d599370 100644 --- a/concurrent/src/test/java/tests/concurrent/AllTests.java +++ b/concurrent/src/test/java/tests/concurrent/AllTests.java @@ -23,16 +23,11 @@ import junit.framework.TestSuite; * Test suite for the concurrent module */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - /** * Collects all JSR166 unit tests as one suite */ public static Test suite ( ) { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("JSR166 Unit Tests"); + TestSuite suite = new TestSuite("JSR166 Unit Tests"); suite.addTest(tests.api.java.util.concurrent.JSR166TestCase.suite()); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java index 5050fc8..aa3240f 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto;"); // $JUnit-BEGIN$ suite.addTestSuite(BadPaddingExceptionTest.class); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java index 220c6c6..6f1db9e 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java @@ -922,7 +922,6 @@ public class KeyAgreementTest extends TestCase { method = "engineGenerateSecret", args = {java.lang.String.class} )}) - @KnownFailure("Does not throw expected exception") public void test_generateSecretLjava_lang_String() throws Exception { if (!DEFSupported) { fail(NotSupportMsg); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java index 750342c..5e2414e 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java @@ -1171,11 +1171,6 @@ public class MacTest extends TestCase { public static Test suite() { return new TestSuite(MacTest.class); } - - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - - } } /** * Additional class for Mac constructor verification diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java index 906057b..68b6720 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java @@ -24,11 +24,6 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.func;"); // $JUnit-BEGIN$ diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java index b66a384..b47c23e 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.interfaces;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.interfaces;"); // $JUnit-BEGIN$ suite.addTestSuite(DHPrivateKeyTest.class); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java index 0be596e..02e0bbb 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.serialization;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.serialization;"); // $JUnit-BEGIN$ suite.addTestSuite(BadPaddingExceptionTest.class); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java index 2f632ae..3992d44 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java @@ -42,8 +42,4 @@ public class BadPaddingExceptionTest extends SerializationTest { return new Object[] { new BadPaddingException(), new BadPaddingException(null), new BadPaddingException(msgs[1]) }; } - - public static void main(String[] args) { - junit.textui.TestRunner.run(BadPaddingExceptionTest.class); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java index 7fd8cd0..33665d0 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java @@ -42,8 +42,4 @@ public class ExemptionMechanismExceptionTest extends SerializationTest { return new Object[] { new ExemptionMechanismException(), new ExemptionMechanismException(null), new ExemptionMechanismException(msgs[1]) }; } - - public static void main(String[] args) { - junit.textui.TestRunner.run(ExemptionMechanismExceptionTest.class); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java index 2cc1daa..652c0b0 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java @@ -42,8 +42,4 @@ public class IllegalBlockSizeExceptionTest extends SerializationTest { return new Object[] { new IllegalBlockSizeException(), new IllegalBlockSizeException(null), new IllegalBlockSizeException(msgs[1]) }; } - - public static void main(String[] args) { - junit.textui.TestRunner.run(IllegalBlockSizeExceptionTest.class); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java index 475bd2f..12b98fb 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java @@ -42,8 +42,4 @@ public class NoSuchPaddingExceptionTest extends SerializationTest { return new Object[] { new NoSuchPaddingException(), new NoSuchPaddingException(null), new NoSuchPaddingException(msgs[1]) }; } - - public static void main(String[] args) { - junit.textui.TestRunner.run(NoSuchPaddingExceptionTest.class); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java index ab696e8..c42a5cb 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java @@ -42,8 +42,4 @@ public class ShortBufferExceptionTest extends SerializationTest { return new Object[] { new ShortBufferException(), new ShortBufferException(null), new ShortBufferException(msgs[1]) }; } - - public static void main(String[] args) { - junit.textui.TestRunner.run(ShortBufferExceptionTest.class); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java index d31dc54..cdd3d51 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.spec;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.spec;"); // $JUnit-BEGIN$ suite.addTestSuite(DESKeySpecTest.class); diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java index 9904eed..9106a87 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java @@ -324,9 +324,5 @@ public class DESKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(DESKeySpecTest.class); } - - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java index 5c312a4..3f8ce0a 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java @@ -226,9 +226,5 @@ public class DESedeKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(DESedeKeySpecTest.class); } - - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java index 7b09cb6..aef1286 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java @@ -84,9 +84,5 @@ public class DHGenParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(DHGenParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java index 0c0ac3b..65d1a17 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java @@ -111,9 +111,5 @@ public class DHParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(DHParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java index 7181623..327004a 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java @@ -95,9 +95,5 @@ public class DHPrivateKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(DHPrivateKeySpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java index 064c713..905d8cd 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java @@ -95,9 +95,5 @@ public class DHPublicKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(DHPublicKeySpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java index fda566a..1c27f68 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java @@ -160,9 +160,5 @@ public class IvParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(IvParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java index 6b2c673..3fa2d72 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java @@ -194,9 +194,5 @@ public class OAEPParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(OAEPParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java index 1cb017e..bbce868 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java @@ -356,9 +356,5 @@ public class PBEKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(PBEKeySpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java index b294995..6bca15c 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java @@ -118,9 +118,5 @@ public class PBEParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(PBEParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java index 08e8acd..ac3c5e5 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java @@ -155,8 +155,4 @@ public class PSourceTest extends TestCase { public static Test suite() { return new TestSuite(PSourceTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java index cf72d23..6eb636f 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java @@ -254,9 +254,5 @@ public class RC2ParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(RC2ParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java index 6182615..9b7704d 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java @@ -350,9 +350,5 @@ public class RC5ParameterSpecTest extends TestCase { public static Test suite() { return new TestSuite(RC5ParameterSpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java index 5eeb76f..b39bb1d 100644 --- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java +++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java @@ -315,9 +315,5 @@ public class SecretKeySpecTest extends TestCase { public static Test suite() { return new TestSuite(SecretKeySpecTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/crypto/src/test/java/tests/crypto/AllTests.java b/crypto/src/test/java/tests/crypto/AllTests.java index 795d0a9..0b53942 100644 --- a/crypto/src/test/java/tests/crypto/AllTests.java +++ b/crypto/src/test/java/tests/crypto/AllTests.java @@ -23,14 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the regex project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); -//AllTests.java - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All crypto test suites"); + TestSuite suite = new TestSuite("All crypto test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.crypto.tests.javax.crypto.interfaces.AllTests.suite()); suite.addTest(org.apache.harmony.crypto.tests.javax.crypto.serialization.AllTests.suite()); diff --git a/dalvik/src/main/java/dalvik/bytecode/Opcodes.java b/dalvik/src/main/java/dalvik/bytecode/Opcodes.java index 33795ba..845ace2 100644 --- a/dalvik/src/main/java/dalvik/bytecode/Opcodes.java +++ b/dalvik/src/main/java/dalvik/bytecode/Opcodes.java @@ -273,13 +273,18 @@ public interface Opcodes { int OP_SHR_INT_LIT8 = 0xe1; int OP_USHR_INT_LIT8 = 0xe2; - /* e3-eb unused */ + /* e3-e7 unused */ /* * The rest of these are either generated by dexopt for optimized * code, or inserted by the VM at runtime. They are never generated * by "dx". */ + int OP_IGET_WIDE_VOLATILE = 0xe8; + int OP_IPUT_WIDE_VOLATILE = 0xe9; + int OP_SGET_WIDE_VOLATILE = 0xea; + int OP_SPUT_WIDE_VOLATILE = 0xeb; + int OP_BREAKPOINT = 0xec; int OP_THROW_VERIFICATION_ERROR = 0xed; diff --git a/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java b/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java index 677780a..7214d4f 100644 --- a/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java +++ b/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java @@ -28,7 +28,7 @@ public class AllTests { }*/ public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTest(AllTests_Level1.suite()); suite.addTest(AllTests_Level2.suite()); return suite; diff --git a/dom/src/test/java/tests/dom/AllTests.java b/dom/src/test/java/tests/dom/AllTests.java index 6a5831f..48b362b 100644 --- a/dom/src/test/java/tests/dom/AllTests.java +++ b/dom/src/test/java/tests/dom/AllTests.java @@ -24,7 +24,10 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); + // BEGIN android-changed: this was only referenced from the xml module! + suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); + // END android-changed suite.addTestSuite(JunitTestCases.class); return suite; } diff --git a/icu/src/main/java/com/ibm/icu4jni/text/BreakIterator.java b/icu/src/main/java/com/ibm/icu4jni/text/BreakIterator.java index 5ef1161..aa925aa 100644 --- a/icu/src/main/java/com/ibm/icu4jni/text/BreakIterator.java +++ b/icu/src/main/java/com/ibm/icu4jni/text/BreakIterator.java @@ -16,6 +16,7 @@ package com.ibm.icu4jni.text; +import com.ibm.icu4jni.util.Resources; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Locale; @@ -30,36 +31,7 @@ public abstract class BreakIterator implements Cloneable protected int type = 0; public static Locale[] getAvailableLocales() { - - String[] locales = NativeBreakIterator.getAvailableLocalesImpl(); - - Locale[] result = new Locale[locales.length]; - - String locale; - - int index, index2; - - for(int i = 0; i < locales.length; i++) { - locale = locales[i]; - - index = locale.indexOf('_'); - index2 = locale.lastIndexOf('_'); - - if(index == -1) { - result[i] = new Locale(locales[i]); - } else if(index > 0 && index == index2) { - result[i] = new Locale( - locale.substring(0,index), - locale.substring(index+1)); - } else if(index > 0 && index2 > index) { - result[i] = new Locale( - locale.substring(0,index), - locale.substring(index+1,index2), - locale.substring(index2+1)); - } - } - - return result; + return Resources.localesFromStrings(NativeBreakIterator.getAvailableLocalesImpl()); } public static BreakIterator getCharacterInstance() { diff --git a/icu/src/main/java/com/ibm/icu4jni/text/Collator.java b/icu/src/main/java/com/ibm/icu4jni/text/Collator.java index 4a7e1bf..0963b81 100644 --- a/icu/src/main/java/com/ibm/icu4jni/text/Collator.java +++ b/icu/src/main/java/com/ibm/icu4jni/text/Collator.java @@ -10,8 +10,9 @@ package com.ibm.icu4jni.text; -import java.util.Locale; import com.ibm.icu4jni.text.RuleBasedCollator; +import com.ibm.icu4jni.util.Resources; +import java.util.Locale; /** * Abstract class handling locale specific collation via JNI and ICU. @@ -394,38 +395,7 @@ public abstract class Collator implements Cloneable */ public abstract int hashCode(); - // BEGIN android-added public static Locale[] getAvailableLocales() { - - String[] locales = NativeCollation.getAvailableLocalesImpl(); - - Locale[] result = new Locale[locales.length]; - - String locale; - - int index, index2; - - for(int i = 0; i < locales.length; i++) { - locale = locales[i]; - - index = locale.indexOf('_'); - index2 = locale.lastIndexOf('_'); - - if(index == -1) { - result[i] = new Locale(locales[i]); - } else if(index == 2 && index == index2) { - result[i] = new Locale( - locale.substring(0,2), - locale.substring(3,5)); - } else if(index == 2 && index2 > index) { - result[i] = new Locale( - locale.substring(0,index), - locale.substring(index + 1,index2), - locale.substring(index2 + 1)); - } - } - - return result; + return Resources.localesFromStrings(NativeCollation.getAvailableLocalesImpl()); } - // END android-added } diff --git a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedBreakIterator.java b/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedBreakIterator.java index 4d38f2b..e532ac4 100644 --- a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedBreakIterator.java +++ b/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedBreakIterator.java @@ -58,7 +58,12 @@ public class RuleBasedBreakIterator extends BreakIterator { return result && iter.equals(this.charIter); } - + + @Override + public int hashCode() { + return 42; // No-one uses RuleBasedBreakIterator as a hash key. + } + @Override public int current() { return NativeBreakIterator.currentImpl(this.addr); diff --git a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedNumberFormat.java b/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedNumberFormat.java deleted file mode 100644 index 3c865d8..0000000 --- a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedNumberFormat.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.ibm.icu4jni.text; - -import java.text.FieldPosition; -import java.text.Format; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.Locale; - -public class RuleBasedNumberFormat extends NumberFormat { - - /** - * Enum of predefined RBNF types. - */ - public enum RBNFType { - /** - * This creates a spellout instance of RBNF. - * It formats numbers into textual representation: - * 15 -> 'fifteen' or 15.15 -> 'fifteen point one five' - * and it can parse words into numbers: 'twenty' -> 20 - */ - SPELLOUT(0), - /** - * This creates an ordinal instance of RBNF. - * It formats numbers into an ordinal text representation: - * 15 -> '15th' and by parsing it also works in the other direction. - */ - ORDINAL(1), - /** - * This creates instance of RBNF that allows to format numbers into time - * values: 15 -> '15 sec.' and by parsing it also works in the other - * direction. - */ - DURATION(2); - - int type; - - RBNFType(int t) { - type = t; - } - - int getType() { - return type; - } - } - - @Override - protected void finalize(){ - close(); - } - - private int addr = 0; - - /** - * Open a new rule based number format of selected type for the - * default location - * - * @param type the type of rule based number format - */ - public void open(RBNFType type) { - this.addr = openRBNFImpl(type.getType(), - Locale.getDefault().toString()); - } - - /** - * Open a new rule based number format of selected type for the - * given location - * - * @param type the type of rule based number format - * @param locale the locale to use for this rule based number format - */ - public void open(RBNFType type, Locale locale) { - String loc = locale.toString(); - if (loc == null) { - throw new NullPointerException(); - } - this.addr = openRBNFImpl(type.getType(), loc); - } - - private static native int openRBNFImpl(int type, String loc); - - /** - * Open a new rule based number format for the - * default location. The rule passed to the method has to be of the form - * described in the ibm icu documentation for RuleBasedNumberFormat. - * - * @param rule the rule for the rule based number format - */ - public void open(String rule) { - if (rule == null) { - throw new NullPointerException(); - } - this.addr = openRBNFImpl(rule, Locale.getDefault().toString()); - } - - /** - * Open a new rule based number format for the - * given location. The rule passed to the method has to be of the form - * described in the ibm icu documentation for RuleBasedNumberFormat. - * - * @param rule the rule for the rule based number format - * @param locale the locale to use for this rule based number format - */ - public void open(String rule, Locale locale) { - String loc = locale.toString(); - if (loc == null || rule == null) { - throw new NullPointerException(); - } - this.addr = openRBNFImpl(rule, locale.toString()); - } - - private static native int openRBNFImpl(String rule, String loc); - - /** - * close a RuleBasedNumberFormat - */ - public void close() { - if(this.addr != 0) { - closeRBNFImpl(this.addr); - this.addr = 0; - } - } - - private static native void closeRBNFImpl(int addr); - - @Override - public StringBuffer format(long value, StringBuffer buffer, FieldPosition field) { - - if(buffer == null) { - throw new NullPointerException(); - } - - String fieldType = null; - - if(field != null) { - fieldType = getFieldType(field.getFieldAttribute()); - } - - String result = formatRBNFImpl(this.addr, value, field, - fieldType, null); - - buffer.append(result.toCharArray(), 0, result.length()); - - return buffer; - } - - private static native String formatRBNFImpl(int addr, long value, - FieldPosition field, String fieldType, StringBuffer buffer); - - @Override - public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) { - - if(buffer == null) { - throw new NullPointerException(); - } - - String fieldType = null; - - if(field != null) { - fieldType = getFieldType(field.getFieldAttribute()); - } - - String result = formatRBNFImpl(this.addr, value, field, - fieldType, null); - - buffer.append(result.toCharArray(), 0, result.length()); - - return buffer; - } - - private static native String formatRBNFImpl(int addr, double value, - FieldPosition field, String fieldType, StringBuffer buffer); - - @Override - public Number parse(String string, ParsePosition position) { - if (string == null || position == null) { - throw new NullPointerException(); - } - return parseRBNFImpl(this.addr, string, position, false); - } - - /** - * This method has the same functionality - * as {@link #parse(String, ParsePosition)} - * But it uses lenient parsing. This means it also accepts strings that - * differ from the correct writing (e.g. case or umlaut differences). - * - * @param string the string to parse - * @param position the ParsePosition, updated on return with the index - * following the parsed text, or on error the index is unchanged and - * the error index is set to the index where the error occurred - * @return the Number resulting from the parse, or null if there is an error - */ - public Number parseLenient(String string, ParsePosition position) { - if (string == null || position == null) { - throw new NullPointerException(); - } - return parseRBNFImpl(this.addr, string, position, true); - } - - static native Number parseRBNFImpl(int addr, String string, ParsePosition position, boolean lenient); - - - static private String getFieldType(Format.Field field) { - if(field == null) { - return null; - } - if(field.equals(NumberFormat.Field.SIGN)) { - return "sign"; - } - if(field.equals(NumberFormat.Field.INTEGER)) { - return "integer"; - } - if(field.equals(NumberFormat.Field.FRACTION)) { - return "fraction"; - } - if(field.equals(NumberFormat.Field.EXPONENT)) { - return "exponent"; - } - if(field.equals(NumberFormat.Field.EXPONENT_SIGN)) { - return "exponent_sign"; - } - if(field.equals(NumberFormat.Field.EXPONENT_SYMBOL)) { - return "exponent_symbol"; - } - if(field.equals(NumberFormat.Field.CURRENCY)) { - return "currency"; - } - if(field.equals(NumberFormat.Field.GROUPING_SEPARATOR)) { - return "grouping_separator"; - } - if(field.equals(NumberFormat.Field.DECIMAL_SEPARATOR)) { - return "decimal_separator"; - } - if(field.equals(NumberFormat.Field.PERCENT)) { - return "percent"; - } - if(field.equals(NumberFormat.Field.PERMILLE)) { - return "permille"; - } - return null; - } -} diff --git a/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java b/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java index 24d3323..87f9bc2 100644 --- a/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java +++ b/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java @@ -17,6 +17,7 @@ package com.ibm.icu4jni.util; import java.text.DateFormat; +import java.util.Arrays; /** * Passes locale-specific from ICU native code to Java. @@ -66,12 +67,12 @@ public class LocaleData { return "LocaleData[" + "firstDayOfWeek=" + firstDayOfWeek + "," + "minimalDaysInFirstWeek=" + minimalDaysInFirstWeek + "," + - "amPm=" + amPm + "," + - "eras=" + eras + "," + - "longMonthNames=" + longMonthNames + "," + - "shortMonthNames=" + shortMonthNames + "," + - "longWeekdayNames=" + longWeekdayNames + "," + - "shortWeekdayNames=" + shortWeekdayNames + "," + + "amPm=" + Arrays.toString(amPm) + "," + + "eras=" + Arrays.toString(eras) + "," + + "longMonthNames=" + Arrays.toString(longMonthNames) + "," + + "shortMonthNames=" + Arrays.toString(shortMonthNames) + "," + + "longWeekdayNames=" + Arrays.toString(longWeekdayNames) + "," + + "shortWeekdayNames=" + Arrays.toString(shortWeekdayNames) + "," + "fullTimeFormat=" + fullTimeFormat + "," + "longTimeFormat=" + longTimeFormat + "," + "mediumTimeFormat=" + mediumTimeFormat + "," + diff --git a/icu/src/main/java/com/ibm/icu4jni/util/Resources.java b/icu/src/main/java/com/ibm/icu4jni/util/Resources.java index cbad9a5..4a91d62 100644 --- a/icu/src/main/java/com/ibm/icu4jni/util/Resources.java +++ b/icu/src/main/java/com/ibm/icu4jni/util/Resources.java @@ -18,12 +18,12 @@ package com.ibm.icu4jni.util; import java.util.Arrays; import java.util.Enumeration; +import java.util.HashMap; import java.util.ListResourceBundle; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; /** @@ -33,8 +33,8 @@ import java.util.logging.Logger; */ public class Resources { // A cache for the locale-specific data. - private static final ConcurrentHashMap<String, LocaleData> localeDataCache = - new ConcurrentHashMap<String, LocaleData>(); + private static final HashMap<String, LocaleData> localeDataCache = + new HashMap<String, LocaleData>(); /** * Cache for ISO language names. @@ -64,13 +64,21 @@ public class Resources { locale = Locale.getDefault(); } String localeName = locale.toString(); - LocaleData localeData = localeDataCache.get(localeName); - if (localeData != null) { - return localeData; + synchronized (localeDataCache) { + LocaleData localeData = localeDataCache.get(localeName); + if (localeData != null) { + return localeData; + } + } + LocaleData newLocaleData = makeLocaleData(locale); + synchronized (localeDataCache) { + LocaleData localeData = localeDataCache.get(localeName); + if (localeData != null) { + return localeData; + } + localeDataCache.put(localeName, newLocaleData); + return newLocaleData; } - localeData = makeLocaleData(locale); - boolean absent = (localeDataCache.putIfAbsent(localeName, localeData) == null); - return absent ? localeData : localeDataCache.get(localeName); } private static LocaleData makeLocaleData(Locale locale) { @@ -84,7 +92,7 @@ public class Resources { } else if (country.length() > 0) { result.overrideWithDataFrom(getLocaleData(new Locale(language, "", ""))); } else if (language.length() > 0) { - result.overrideWithDataFrom(getLocaleData(new Locale("", "", ""))); + result.overrideWithDataFrom(getLocaleData(Locale.ROOT)); } // Override with data from this locale. result.overrideWithDataFrom(initLocaleData(locale)); @@ -285,6 +293,35 @@ public class Resources { return result; } + /** + * Returns the appropriate {@code Locale} given a {@code String} of the form returned + * by {@code toString}. This is very lenient, and doesn't care what's between the underscores: + * this method can parse strings that {@code Locale.toString} won't produce. + * Used to remove duplication. + */ + public static Locale localeFromString(String localeName) { + int first = localeName.indexOf('_'); + int second = localeName.indexOf('_', first + 1); + if (first == -1) { + // Language only ("ja"). + return new Locale(localeName); + } else if (second == -1) { + // Language and country ("ja_JP"). + return new Locale(localeName.substring(0, first), localeName.substring(first + 1)); + } else { + // Language and country and variant ("ja_JP_TRADITIONAL"). + return new Locale(localeName.substring(0, first), localeName.substring(first + 1, second), localeName.substring(second + 1)); + } + } + + public static Locale[] localesFromStrings(String[] localeNames) { + Locale[] result = new Locale[localeNames.length]; + for (int i = 0; i < result.length; ++i) { + result[i] = localeFromString(localeNames[i]); + } + return result; + } + // --- Native methods accessing ICU's database ---------------------------- public static native String getDisplayCountryNative(String countryCode, String locale); diff --git a/icu/src/main/native/RuleBasedNumberFormat.cpp b/icu/src/main/native/RuleBasedNumberFormat.cpp deleted file mode 100644 index c7486e1..0000000 --- a/icu/src/main/native/RuleBasedNumberFormat.cpp +++ /dev/null @@ -1,336 +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. - */ - -#include "JNIHelp.h" -#include "AndroidSystemNatives.h" -#include "unicode/numfmt.h" -#include "unicode/rbnf.h" -#include "unicode/fmtable.h" -#include "unicode/ustring.h" -#include "unicode/locid.h" -#include "ErrorCode.h" -#include <stdlib.h> -#include <string.h> - -static jint openRBNFImpl1(JNIEnv* env, jclass clazz, - jint type, jstring locale) { - - // LOGI("ENTER openRBNFImpl1"); - - // the errorcode returned by unum_open - UErrorCode status = U_ZERO_ERROR; - - // prepare the locale string for the call to unum_open - const char *localeChars = env->GetStringUTFChars(locale, NULL); - - URBNFRuleSetTag style; - if(type == 0) { - style = URBNF_SPELLOUT; - } else if(type == 1) { - style = URBNF_ORDINAL; - } else if(type == 2) { - style = URBNF_DURATION; - } else if(type == 3) { - style = URBNF_COUNT; - } else { - icu4jni_error(env, U_ILLEGAL_ARGUMENT_ERROR); - } - - Locale loc = Locale::createFromName(localeChars); - - // open a default type number format - RuleBasedNumberFormat *fmt = new RuleBasedNumberFormat(style, loc, status); - - // release the allocated strings - env->ReleaseStringUTFChars(locale, localeChars); - - // check for an error - if (icu4jni_error(env, status) != FALSE) { - return 0; - } - - // return the handle to the number format - return (long) fmt; - -} - -static jint openRBNFImpl2(JNIEnv* env, jclass clazz, - jstring rule, jstring locale) { - - // LOGI("ENTER openRBNFImpl2"); - - // the errorcode returned by unum_open - UErrorCode status = U_ZERO_ERROR; - - // prepare the pattern string for the call to unum_open - const UChar *ruleChars = env->GetStringChars(rule, NULL); - int ruleLen = env->GetStringLength(rule); - - // prepare the locale string for the call to unum_open - const char *localeChars = env->GetStringUTFChars(locale, NULL); - - // open a rule based number format - UNumberFormat *fmt = unum_open(UNUM_PATTERN_RULEBASED, ruleChars, ruleLen, - localeChars, NULL, &status); - - // release the allocated strings - env->ReleaseStringChars(rule, ruleChars); - env->ReleaseStringUTFChars(locale, localeChars); - - // check for an error - if (icu4jni_error(env, status) != FALSE) { - return 0; - } - - // return the handle to the number format - return (long) fmt; - -} - -static void closeRBNFImpl(JNIEnv *env, jclass clazz, jint addr) { - - // LOGI("ENTER closeRBNFImpl"); - - // get the pointer to the number format - RuleBasedNumberFormat *fmt = (RuleBasedNumberFormat *)(int)addr; - - // close this number format - delete fmt; -} - -static jstring formatLongRBNFImpl(JNIEnv *env, jclass clazz, jint addr, jlong value, - jobject field, jstring fieldType, jobject attributes) { - - // LOGI("ENTER formatLongRBNFImpl"); - - const char * fieldPositionClassName = "java/text/FieldPosition"; - const char * stringBufferClassName = "java/lang/StringBuffer"; - jclass fieldPositionClass = env->FindClass(fieldPositionClassName); - jclass stringBufferClass = env->FindClass(stringBufferClassName); - jmethodID setBeginIndexMethodID = env->GetMethodID(fieldPositionClass, - "setBeginIndex", "(I)V"); - jmethodID setEndIndexMethodID = env->GetMethodID(fieldPositionClass, - "setEndIndex", "(I)V"); - jmethodID appendMethodID = env->GetMethodID(stringBufferClass, - "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); - - const char * fieldName = NULL; - - if(fieldType != NULL) { - fieldName = env->GetStringUTFChars(fieldType, NULL); - } - - uint32_t reslenneeded; - int64_t val = value; - UChar *result = NULL; - - FieldPosition fp; - fp.setField(FieldPosition::DONT_CARE); - - UErrorCode status = U_ZERO_ERROR; - - RuleBasedNumberFormat *fmt = (RuleBasedNumberFormat *)(int)addr; - - UnicodeString res; - - fmt->format(val, res, fp); - - reslenneeded = res.extract(NULL, 0, status); - - if(status==U_BUFFER_OVERFLOW_ERROR) { - status=U_ZERO_ERROR; - - result = (UChar*)malloc(sizeof(UChar) * (reslenneeded + 1)); - - res.extract(result, reslenneeded + 1, status); - } - if (icu4jni_error(env, status) != FALSE) { - free(result); - return NULL; - } - - if(fieldType != NULL) { - env->ReleaseStringUTFChars(fieldType, fieldName); - } - - jstring resulting = env->NewString(result, reslenneeded); - - free(result); - - return resulting; -} - -static jstring formatDoubleRBNFImpl(JNIEnv *env, jclass clazz, jint addr, jdouble value, - jobject field, jstring fieldType, jobject attributes) { - - // LOGI("ENTER formatDoubleRBNFImpl"); - - const char * fieldPositionClassName = "java/text/FieldPosition"; - const char * stringBufferClassName = "java/lang/StringBuffer"; - jclass fieldPositionClass = env->FindClass(fieldPositionClassName); - jclass stringBufferClass = env->FindClass(stringBufferClassName); - jmethodID setBeginIndexMethodID = env->GetMethodID(fieldPositionClass, - "setBeginIndex", "(I)V"); - jmethodID setEndIndexMethodID = env->GetMethodID(fieldPositionClass, - "setEndIndex", "(I)V"); - jmethodID appendMethodID = env->GetMethodID(stringBufferClass, - "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); - - const char * fieldName = NULL; - - if(fieldType != NULL) { - fieldName = env->GetStringUTFChars(fieldType, NULL); - } - - uint32_t reslenneeded; - double val = value; - UChar *result = NULL; - - FieldPosition fp; - fp.setField(FieldPosition::DONT_CARE); - - UErrorCode status = U_ZERO_ERROR; - - RuleBasedNumberFormat *fmt = (RuleBasedNumberFormat *)(int)addr; - - UnicodeString res; - - fmt->format(val, res, fp); - - reslenneeded = res.extract(NULL, 0, status); - - if(status==U_BUFFER_OVERFLOW_ERROR) { - status=U_ZERO_ERROR; - - result = (UChar*)malloc(sizeof(UChar) * (reslenneeded + 1)); - - res.extract(result, reslenneeded + 1, status); - } - if (icu4jni_error(env, status) != FALSE) { - free(result); - return NULL; - } - - if(fieldType != NULL) { - env->ReleaseStringUTFChars(fieldType, fieldName); - } - - jstring resulting = env->NewString(result, reslenneeded); - - free(result); - - return resulting; -} - -static jobject parseRBNFImpl(JNIEnv *env, jclass clazz, jint addr, jstring text, - jobject position, jboolean lenient) { - - // LOGI("ENTER parseRBNFImpl"); - - // TODO: cache these? - jclass parsePositionClass = env->FindClass("java/text/ParsePosition"); - jclass longClass = env->FindClass("java/lang/Long"); - jclass doubleClass = env->FindClass("java/lang/Double"); - - jmethodID getIndexMethodID = env->GetMethodID(parsePositionClass, - "getIndex", "()I"); - jmethodID setIndexMethodID = env->GetMethodID(parsePositionClass, - "setIndex", "(I)V"); - jmethodID setErrorIndexMethodID = env->GetMethodID(parsePositionClass, - "setErrorIndex", "(I)V"); - - jmethodID longInitMethodID = env->GetMethodID(longClass, "<init>", "(J)V"); - jmethodID dblInitMethodID = env->GetMethodID(doubleClass, "<init>", "(D)V"); - - // make sure the ParsePosition is valid. Actually icu4c would parse a number - // correctly even if the parsePosition is set to -1, but since the RI fails - // for that case we have to fail too - int parsePos = env->CallIntMethod(position, getIndexMethodID, NULL); - const int strlength = env->GetStringLength(text); - if(parsePos < 0 || parsePos > strlength) { - return NULL; - } - - Formattable res; - - jchar *str = (UChar *)env->GetStringChars(text, NULL); - - const UnicodeString src((UChar*)str, strlength, strlength); - ParsePosition pp; - - pp.setIndex(parsePos); - - UNumberFormat *fmt = (UNumberFormat *)(int)addr; - if(lenient) { - unum_setAttribute(fmt, UNUM_LENIENT_PARSE, JNI_TRUE); - } - - ((const NumberFormat*)fmt)->parse(src, res, pp); - - if(lenient) { - unum_setAttribute(fmt, UNUM_LENIENT_PARSE, JNI_FALSE); - } - - env->ReleaseStringChars(text, str); - - if(pp.getErrorIndex() == -1) { - parsePos = pp.getIndex(); - } else { - env->CallVoidMethod(position, setErrorIndexMethodID, - (jint) pp.getErrorIndex()); - return NULL; - } - - Formattable::Type numType = res.getType(); - if (numType == Formattable::kDouble) { - double resultDouble = res.getDouble(); - env->CallVoidMethod(position, setIndexMethodID, (jint) parsePos); - return env->NewObject(doubleClass, dblInitMethodID, - (jdouble) resultDouble); - } else if (numType == Formattable::kLong) { - long resultLong = res.getLong(); - env->CallVoidMethod(position, setIndexMethodID, (jint) parsePos); - return env->NewObject(longClass, longInitMethodID, (jlong) resultLong); - } else if (numType == Formattable::kInt64) { - int64_t resultInt64 = res.getInt64(); - env->CallVoidMethod(position, setIndexMethodID, (jint) parsePos); - return env->NewObject(longClass, longInitMethodID, (jlong) resultInt64); - } else { - return NULL; - } -} - -static JNINativeMethod gMethods[] = { - /* name, signature, funcPtr */ - {"openRBNFImpl", "(ILjava/lang/String;)I", (void*) openRBNFImpl1}, - {"openRBNFImpl", "(Ljava/lang/String;Ljava/lang/String;)I", - (void*) openRBNFImpl2}, - {"closeRBNFImpl", "(I)V", (void*) closeRBNFImpl}, - {"formatRBNFImpl", - "(IJLjava/text/FieldPosition;Ljava/lang/String;Ljava/lang/StringBuffer;)Ljava/lang/String;", - (void*) formatLongRBNFImpl}, - {"formatRBNFImpl", - "(IDLjava/text/FieldPosition;Ljava/lang/String;Ljava/lang/StringBuffer;)Ljava/lang/String;", - (void*) formatDoubleRBNFImpl}, - {"parseRBNFImpl", - "(ILjava/lang/String;Ljava/text/ParsePosition;Z)Ljava/lang/Number;", - (void*) parseRBNFImpl}, -}; -int register_com_ibm_icu4jni_text_NativeRBNF(JNIEnv* env) { - return jniRegisterNativeMethods(env, - "com/ibm/icu4jni/text/RuleBasedNumberFormat", gMethods, - NELEM(gMethods)); -} diff --git a/icu/src/main/native/sub.mk b/icu/src/main/native/sub.mk index 41260cf..b101531 100644 --- a/icu/src/main/native/sub.mk +++ b/icu/src/main/native/sub.mk @@ -11,7 +11,6 @@ LOCAL_SRC_FILES := \ NativeDecimalFormat.cpp \ NativeNormalizer.cpp \ NativeRegEx.cpp \ - RuleBasedNumberFormat.cpp \ Resources.cpp \ UCharacter.cpp diff --git a/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java b/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java index 1b95075..92df6fc 100644 --- a/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java +++ b/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(com.ibm.icu4jni.util.ResourcesTest.class); return suite; } diff --git a/icu/src/test/java/com/ibm/icu4jni/util/ResourcesTest.java b/icu/src/test/java/com/ibm/icu4jni/util/ResourcesTest.java index 4112d0b..7dcaa9c 100644 --- a/icu/src/test/java/com/ibm/icu4jni/util/ResourcesTest.java +++ b/icu/src/test/java/com/ibm/icu4jni/util/ResourcesTest.java @@ -16,6 +16,8 @@ package com.ibm.icu4jni.util; +import java.util.Locale; + public class ResourcesTest extends junit.framework.TestCase { public void test_getISOLanguages() throws Exception { // Check that corrupting our array doesn't affect other callers. @@ -55,4 +57,18 @@ public class ResourcesTest extends junit.framework.TestCase { Resources.getDisplayTimeZones(null)[0][0] = null; assertNotNull(Resources.getDisplayTimeZones(null)[0][0]); } + + public void test_localeFromString() throws Exception { + // localeFromString is pretty lenient. Some of these can't be round-tripped + // through Locale.toString. + assertEquals(Locale.ENGLISH, Resources.localeFromString("en")); + assertEquals(Locale.ENGLISH, Resources.localeFromString("en_")); + assertEquals(Locale.ENGLISH, Resources.localeFromString("en__")); + assertEquals(Locale.US, Resources.localeFromString("en_US")); + assertEquals(Locale.US, Resources.localeFromString("en_US_")); + assertEquals(new Locale("", "US", ""), Resources.localeFromString("_US")); + assertEquals(new Locale("", "US", ""), Resources.localeFromString("_US_")); + assertEquals(new Locale("", "", "POSIX"), Resources.localeFromString("__POSIX")); + assertEquals(new Locale("aa", "BB", "CC"), Resources.localeFromString("aa_BB_CC")); + } } diff --git a/json/src/test/java/org/json/AllTests.java b/json/src/test/java/org/json/AllTests.java index 8261a4d..7779c91 100644 --- a/json/src/test/java/org/json/AllTests.java +++ b/json/src/test/java/org/json/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(JSONArrayTest.class); suite.addTestSuite(JSONStringerTest.class); suite.addTestSuite(JSONStringerTest.class); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java index 1094f25..91b3e1a 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java @@ -25,8 +25,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "Suite for org.apache.harmony.logging.tests.java.util.logging"); + TestSuite suite = new TestSuite("Suite for org.apache.harmony.logging.tests.java.util.logging"); // $JUnit-BEGIN$ suite.addTestSuite(ConsoleHandlerTest.class); suite.addTestSuite(ErrorManagerTest.class); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java index 91de2a5..b2204a3 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java @@ -17,17 +17,11 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargets; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.security.Permission; -import java.util.Currency; import java.util.Properties; import java.util.logging.ConsoleHandler; import java.util.logging.Filter; @@ -48,638 +42,542 @@ import tests.util.CallVerificationStack; /** * Test class java.util.logging.ConsoleHandler */ -@TestTargetClass(ConsoleHandler.class) public class ConsoleHandlerTest extends TestCase { - private final static String INVALID_LEVEL = "impossible_level"; - - private final PrintStream err = System.err; - - private OutputStream errSubstituteStream = null; - - private static String className = ConsoleHandlerTest.class.getName(); - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - errSubstituteStream = new MockOutputStream(); - System.setErr(new PrintStream(errSubstituteStream)); - LogManager.getLogManager().reset(); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - LogManager.getLogManager().reset(); - CallVerificationStack.getInstance().clear(); - System.setErr(err); - } - - /* - * Test the constructor with no relevant log manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no relevant log manager properties are set.", - method = "ConsoleHandler", - args = {} - ) - public void testConstructor_NoProperties() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.encoding")); - - ConsoleHandler h = new ConsoleHandler(); - assertSame(h.getLevel(), Level.INFO); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertSame(h.getEncoding(), null); - } - - /* - * Test the constructor with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with insufficient privilege.", - method = "ConsoleHandler", - args = {} - ) - public void testConstructor_InsufficientPrivilege() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.encoding")); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - ConsoleHandler h = new ConsoleHandler(); - assertSame(h.getLevel(), Level.INFO); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertSame(h.getEncoding(), null); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test the constructor with valid relevant log manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with valid relevant log manager properties are set.", - method = "ConsoleHandler", - args = {} - ) - public void testConstructor_ValidProperties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.level", "FINE"); - p.put("java.util.logging.ConsoleHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.ConsoleHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.level"), "FINE"); - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.encoding"), "iso-8859-1"); - ConsoleHandler h = new ConsoleHandler(); - assertSame(h.getLevel(), Level.parse("FINE")); - assertTrue(h.getFormatter() instanceof MockFormatter); - assertTrue(h.getFilter() instanceof MockFilter); - assertEquals(h.getEncoding(), "iso-8859-1"); - } - - /* - * Test the constructor with invalid relevant log manager properties are - * set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with invalid relevant log manager properties are set.", - method = "ConsoleHandler", - args = {} - ) - public void testConstructor_InvalidProperties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL); - p.put("java.util.logging.ConsoleHandler.filter", className); - p.put("java.util.logging.ConsoleHandler.formatter", className); - p.put("java.util.logging.ConsoleHandler.encoding", "XXXX"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.level"), INVALID_LEVEL); - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.ConsoleHandler.encoding"), "XXXX"); - ConsoleHandler h = new ConsoleHandler(); - assertSame(h.getLevel(), Level.INFO); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - h.publish(new LogRecord(Level.SEVERE, "test")); - assertNull(h.getEncoding()); - } - - /* - * Test close() when having sufficient privilege, and a record has been - * written to the output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and a record has been written to the output stream.", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_NormalClose() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - h.publish(new LogRecord(Level.SEVERE, - "testClose_SufficientPrivilege_NormalClose msg")); - h.close(); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - h.close(); - } - - /* - * Test close() when having sufficient privilege, and an output stream that - * always throws exceptions. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and an output stream that always throws exceptions", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_Exception() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - - h.publish(new LogRecord(Level.SEVERE, - "testClose_SufficientPrivilege_Exception msg")); - h.flush(); - h.close(); - } - - /* - * Test close() when having sufficient privilege, and no record has been - * written to the output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks close() when having sufficient privilege, and no record has been written to the output stream", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_DirectClose() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - - h.close(); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test close() when having insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when insufficient privilege is set up.", - method = "close", - args = {} - ) - public void testClose_InsufficientPrivilege() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - h.close(); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test publish(), use no filter, having output stream, normal log record. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use no filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_NoFilter() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter"); - h.setLevel(Level.INFO); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", - this.errSubstituteStream.toString()); - - h.setLevel(Level.WARNING); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", - this.errSubstituteStream.toString()); - - h.setLevel(Level.CONFIG); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", this.errSubstituteStream.toString()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", this.errSubstituteStream.toString()); - } - - /* - * Test publish(), after system err is reset. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), after system err is reset.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_AfterResetSystemErr() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - h.setFilter(new MockFilter()); - - System.setErr(new PrintStream(new ByteArrayOutputStream())); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); - h.setLevel(Level.INFO); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertEquals("", this.errSubstituteStream.toString()); - } - - /* - * Test publish(), use a filter, having output stream, normal log record. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use a filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_WithFilter() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - h.setFilter(new MockFilter()); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); - h.setLevel(Level.INFO); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertEquals("", this.errSubstituteStream.toString()); - - h.setLevel(Level.WARNING); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertEquals("", this.errSubstituteStream.toString()); - - h.setLevel(Level.CONFIG); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertEquals("", this.errSubstituteStream.toString()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertEquals("", this.errSubstituteStream.toString()); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test publish(), null log record, having output stream, spec said - * rather than throw exception, handler should call errormanager to handle - * exception case, so NullPointerException shouldn't be thrown. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), null log record, having output stream, spec said rather than throw exception, handler should call errormanager to handle exception case, so NullPointerException shouldn't be thrown.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_Null() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - h.publish(null); - } - - /* - * Test publish(), a log record with empty msg, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), a log record with empty msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_EmptyMsg() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - LogRecord r = new LogRecord(Level.INFO, ""); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head", this.errSubstituteStream.toString()); - } - - /* - * Test publish(), a log record with null msg, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), a log record with null msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_NullMsg() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - LogRecord r = new LogRecord(Level.INFO, null); - h.publish(r); - h.flush(); - // assertEquals("MockFormatter_Head", - // this.errSubstituteStream.toString()); - } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish method after close.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_AfterClose() throws Exception { - PrintStream backup = System.err; - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - System.setErr(new PrintStream(bos)); - Properties p = new Properties(); - p.put("java.util.logging.ConsoleHandler.level", "FINE"); - p.put("java.util.logging.ConsoleHandler.formatter", className - + "$MockFormatter"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - ConsoleHandler h = new ConsoleHandler(); - assertSame(h.getLevel(), Level.FINE); - LogRecord r1 = new LogRecord(Level.INFO, "testPublish_Record1"); - LogRecord r2 = new LogRecord(Level.INFO, "testPublish_Record2"); - assertTrue(h.isLoggable(r1)); - h.publish(r1); - assertTrue(bos.toString().indexOf("testPublish_Record1") >= 0); - h.close(); - // assertFalse(h.isLoggable(r)); - assertTrue(h.isLoggable(r2)); - h.publish(r2); - assertTrue(bos.toString().indexOf("testPublish_Record2") >= 0); - h.flush(); - // assertEquals("MockFormatter_Head", - // this.errSubstituteStream.toString()); - } catch (IOException e) { - e.printStackTrace(); - } finally { - System.setErr(backup); - } - } - - /* - * Test setOutputStream() under normal condition. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies setOutputStream() under normal condition.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) - public void testSetOutputStream_Normal() { - MockStreamHandler h = new MockStreamHandler(); - h.setFormatter(new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); - h.publish(r); - assertNull(CallVerificationStack.getInstance().pop()); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", - this.errSubstituteStream.toString()); - - ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); - h.setOutputStream(aos2); - - // assertEquals("close", DelegationParameterStack.getInstance() - // .getCurrentSourceMethod()); - // assertNull(DelegationParameterStack.getInstance().pop()); - // assertEquals("flush", DelegationParameterStack.getInstance() - // .getCurrentSourceMethod()); - // assertNull(DelegationParameterStack.getInstance().pop()); - // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - // + "MockFormatter_Tail", this.errSubstituteStream.toString()); - // r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); - // h.publish(r); - // assertSame(r, DelegationParameterStack.getInstance().pop()); - // assertTrue(DelegationParameterStack.getInstance().empty()); - // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", - // aos2 - // .toString()); - // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - // + "MockFormatter_Tail", this.errSubstituteStream.toString()); - } - - /* - * A mock filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - // System.out.println("filter called..."); - return false; - } - } - - /* - * A mock formatter. - */ - public static class MockFormatter extends Formatter { - public String format(LogRecord r) { - // System.out.println("formatter called..."); - return super.formatMessage(r); - } - - /* - * (non-Javadoc) - * - * @see java.util.logging.Formatter#getHead(java.util.logging.Handler) - */ - public String getHead(Handler h) { - return "MockFormatter_Head"; - } - - /* - * (non-Javadoc) - * - * @see java.util.logging.Formatter#getTail(java.util.logging.Handler) - */ - public String getTail(Handler h) { - return "MockFormatter_Tail"; - } - } - - /* - * A mock output stream. - */ - public static class MockOutputStream extends ByteArrayOutputStream { - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#close() - */ - public void close() throws IOException { - CallVerificationStack.getInstance().push(null); - super.close(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#flush() - */ - public void flush() throws IOException { - CallVerificationStack.getInstance().push(null); - super.flush(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(int) - */ - public void write(int oneByte) { - // TODO Auto-generated method stub - super.write(oneByte); - } - } - - /* - * Used to grant all permissions except logging control. - */ - public static class MockSecurityManager extends SecurityManager { - - public MockSecurityManager() { - } - - public void checkPermission(Permission perm) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - - public void checkPermission(Permission perm, Object context) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - } - - /* - * A mock stream handler, expose setOutputStream. - */ - public static class MockStreamHandler extends ConsoleHandler { - public MockStreamHandler() { - super(); - } - - public void setOutputStream(OutputStream out) { - super.setOutputStream(out); - } - - public boolean isLoggable(LogRecord r) { - CallVerificationStack.getInstance().push(r); - return super.isLoggable(r); - } - } + private final static String INVALID_LEVEL = "impossible_level"; + + private final PrintStream err = System.err; + + private OutputStream errSubstituteStream = null; + + private static String className = ConsoleHandlerTest.class.getName(); + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + errSubstituteStream = new MockOutputStream(); + System.setErr(new PrintStream(errSubstituteStream)); + LogManager.getLogManager().reset(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + LogManager.getLogManager().reset(); + CallVerificationStack.getInstance().clear(); + System.setErr(err); + } + + /* + * Test the constructor with no relevant log manager properties are set. + */ + public void testConstructor_NoProperties() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.encoding")); + + ConsoleHandler h = new ConsoleHandler(); + assertSame(h.getLevel(), Level.INFO); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertSame(h.getEncoding(), null); + } + + /* + * Test the constructor with insufficient privilege. + */ + public void testConstructor_InsufficientPrivilege() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.encoding")); + + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + // set a normal value + try { + ConsoleHandler h = new ConsoleHandler(); + assertSame(h.getLevel(), Level.INFO); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertSame(h.getEncoding(), null); + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test the constructor with valid relevant log manager properties are set. + */ + public void testConstructor_ValidProperties() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.level", "FINE"); + p.put("java.util.logging.ConsoleHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.ConsoleHandler.encoding", "iso-8859-1"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.level"), "FINE"); + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.encoding"), "iso-8859-1"); + ConsoleHandler h = new ConsoleHandler(); + assertSame(h.getLevel(), Level.parse("FINE")); + assertTrue(h.getFormatter() instanceof MockFormatter); + assertTrue(h.getFilter() instanceof MockFilter); + assertEquals(h.getEncoding(), "iso-8859-1"); + } + + /* + * Test the constructor with invalid relevant log manager properties are + * set. + */ + public void testConstructor_InvalidProperties() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL); + p.put("java.util.logging.ConsoleHandler.filter", className); + p.put("java.util.logging.ConsoleHandler.formatter", className); + p.put("java.util.logging.ConsoleHandler.encoding", "XXXX"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.level"), INVALID_LEVEL); + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.ConsoleHandler.encoding"), "XXXX"); + ConsoleHandler h = new ConsoleHandler(); + assertSame(h.getLevel(), Level.INFO); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + h.publish(new LogRecord(Level.SEVERE, "test")); + assertNull(h.getEncoding()); + } + + /* + * Test close() when having sufficient privilege, and a record has been + * written to the output stream. + */ + public void testClose_SufficientPrivilege_NormalClose() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + h.publish(new LogRecord(Level.SEVERE, + "testClose_SufficientPrivilege_NormalClose msg")); + h.close(); + assertEquals("flush", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + assertNull(CallVerificationStack.getInstance().pop()); + h.close(); + } + + /* + * Test close() when having sufficient privilege, and an output stream that + * always throws exceptions. + */ + public void testClose_SufficientPrivilege_Exception() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + + h.publish(new LogRecord(Level.SEVERE, + "testClose_SufficientPrivilege_Exception msg")); + h.flush(); + h.close(); + } + + /* + * Test close() when having sufficient privilege, and no record has been + * written to the output stream. + */ + public void testClose_SufficientPrivilege_DirectClose() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + + h.close(); + assertEquals("flush", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + assertNull(CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + } + + /* + * Test close() when having insufficient privilege. + */ + public void testClose_InsufficientPrivilege() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + h.close(); + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test publish(), use no filter, having output stream, normal log record. + */ + public void testPublish_NoFilter() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + + LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter"); + h.setLevel(Level.INFO); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter", + this.errSubstituteStream.toString()); + + h.setLevel(Level.WARNING); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter", + this.errSubstituteStream.toString()); + + h.setLevel(Level.CONFIG); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter" + + "testPublish_NoFilter", this.errSubstituteStream.toString()); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter" + + "testPublish_NoFilter", this.errSubstituteStream.toString()); + } + + /* + * Test publish(), after system err is reset. + */ + public void testPublish_AfterResetSystemErr() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + h.setFilter(new MockFilter()); + + System.setErr(new PrintStream(new ByteArrayOutputStream())); + + LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); + h.setLevel(Level.INFO); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertEquals("", this.errSubstituteStream.toString()); + } + + /* + * Test publish(), use a filter, having output stream, normal log record. + */ + public void testPublish_WithFilter() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + h.setFilter(new MockFilter()); + + LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); + h.setLevel(Level.INFO); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertEquals("", this.errSubstituteStream.toString()); + + h.setLevel(Level.WARNING); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + assertEquals("", this.errSubstituteStream.toString()); + + h.setLevel(Level.CONFIG); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertEquals("", this.errSubstituteStream.toString()); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertEquals("", this.errSubstituteStream.toString()); + assertTrue(CallVerificationStack.getInstance().empty()); + } + + /* + * Test publish(), null log record, having output stream, spec said + * rather than throw exception, handler should call errormanager to handle + * exception case, so NullPointerException shouldn't be thrown. + */ + public void testPublish_Null() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + h.publish(null); + } + + /* + * Test publish(), a log record with empty msg, having output stream + */ + public void testPublish_EmptyMsg() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + LogRecord r = new LogRecord(Level.INFO, ""); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head", this.errSubstituteStream.toString()); + } + + /* + * Test publish(), a log record with null msg, having output stream + */ + public void testPublish_NullMsg() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + LogRecord r = new LogRecord(Level.INFO, null); + h.publish(r); + h.flush(); + // assertEquals("MockFormatter_Head", + // this.errSubstituteStream.toString()); + } + + public void testPublish_AfterClose() throws Exception { + PrintStream backup = System.err; + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + System.setErr(new PrintStream(bos)); + Properties p = new Properties(); + p.put("java.util.logging.ConsoleHandler.level", "FINE"); + p.put("java.util.logging.ConsoleHandler.formatter", className + + "$MockFormatter"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + ConsoleHandler h = new ConsoleHandler(); + assertSame(h.getLevel(), Level.FINE); + LogRecord r1 = new LogRecord(Level.INFO, "testPublish_Record1"); + LogRecord r2 = new LogRecord(Level.INFO, "testPublish_Record2"); + assertTrue(h.isLoggable(r1)); + h.publish(r1); + assertTrue(bos.toString().indexOf("testPublish_Record1") >= 0); + h.close(); + // assertFalse(h.isLoggable(r)); + assertTrue(h.isLoggable(r2)); + h.publish(r2); + assertTrue(bos.toString().indexOf("testPublish_Record2") >= 0); + h.flush(); + // assertEquals("MockFormatter_Head", + // this.errSubstituteStream.toString()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + System.setErr(backup); + } + } + + /* + * Test setOutputStream() under normal condition. + */ + public void testSetOutputStream_Normal() { + MockStreamHandler h = new MockStreamHandler(); + h.setFormatter(new MockFormatter()); + + LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); + h.publish(r); + assertNull(CallVerificationStack.getInstance().pop()); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", + this.errSubstituteStream.toString()); + + ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); + h.setOutputStream(aos2); + + // assertEquals("close", DelegationParameterStack.getInstance() + // .getCurrentSourceMethod()); + // assertNull(DelegationParameterStack.getInstance().pop()); + // assertEquals("flush", DelegationParameterStack.getInstance() + // .getCurrentSourceMethod()); + // assertNull(DelegationParameterStack.getInstance().pop()); + // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + // + "MockFormatter_Tail", this.errSubstituteStream.toString()); + // r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); + // h.publish(r); + // assertSame(r, DelegationParameterStack.getInstance().pop()); + // assertTrue(DelegationParameterStack.getInstance().empty()); + // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", + // aos2 + // .toString()); + // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + // + "MockFormatter_Tail", this.errSubstituteStream.toString()); + } + + /* + * A mock filter, always return false. + */ + public static class MockFilter implements Filter { + + public boolean isLoggable(LogRecord record) { + CallVerificationStack.getInstance().push(record); + // System.out.println("filter called..."); + return false; + } + } + + /* + * A mock formatter. + */ + public static class MockFormatter extends Formatter { + public String format(LogRecord r) { + // System.out.println("formatter called..."); + return super.formatMessage(r); + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Formatter#getHead(java.util.logging.Handler) + */ + public String getHead(Handler h) { + return "MockFormatter_Head"; + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Formatter#getTail(java.util.logging.Handler) + */ + public String getTail(Handler h) { + return "MockFormatter_Tail"; + } + } + + /* + * A mock output stream. + */ + public static class MockOutputStream extends ByteArrayOutputStream { + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#close() + */ + public void close() throws IOException { + CallVerificationStack.getInstance().push(null); + super.close(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#flush() + */ + public void flush() throws IOException { + CallVerificationStack.getInstance().push(null); + super.flush(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#write(int) + */ + public void write(int oneByte) { + // TODO Auto-generated method stub + super.write(oneByte); + } + } + + /* + * Used to grant all permissions except logging control. + */ + public static class MockSecurityManager extends SecurityManager { + + public MockSecurityManager() { + } + + public void checkPermission(Permission perm) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + + public void checkPermission(Permission perm, Object context) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + } + + /* + * A mock stream handler, expose setOutputStream. + */ + public static class MockStreamHandler extends ConsoleHandler { + public MockStreamHandler() { + super(); + } + + public void setOutputStream(OutputStream out) { + super.setOutputStream(out); + } + + public boolean isLoggable(LogRecord r) { + CallVerificationStack.getInstance().push(r); + return super.isLoggable(r); + } + } } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java index 3185351..d8c0053 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; @@ -31,7 +26,6 @@ import java.io.OutputStream; import java.io.PrintStream; import java.util.logging.ErrorManager; -@TestTargetClass(ErrorManager.class) public class ErrorManagerTest extends TestCase { @@ -53,12 +47,6 @@ public class ErrorManagerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies positive case only with ErrorManager.GENERIC_FAILURE, impove MockStream", - method = "error", - args = {java.lang.String.class, java.lang.Exception.class, int.class} - ) public void test_errorCheck() { ErrorManager em = new ErrorManager(); MockStream aos = new MockStream(); @@ -71,12 +59,6 @@ public class ErrorManagerTest extends TestCase { assertTrue("message appears (supertest)", aos.getWrittenData().indexOf("supertest") != -1); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies positive case only with ErrorManager.GENERIC_FAILURE", - method = "error", - args = {java.lang.String.class, java.lang.Exception.class, int.class} - ) public void test_errorStringStringint() { ErrorManager em = new ErrorManager(); em.error(null, new NullPointerException(), @@ -85,12 +67,6 @@ public class ErrorManagerTest extends TestCase { em.error(null, null, ErrorManager.GENERIC_FAILURE); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ErrorManager", - args = {} - ) public void test_constants() { assertEquals(3, ErrorManager.CLOSE_FAILURE); assertEquals(2, ErrorManager.FLUSH_FAILURE); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java index e4ef413..da0111b 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java @@ -17,12 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; @@ -54,7 +48,6 @@ import tests.util.TestEnvironment; /** */ -@TestTargetClass(FileHandler.class) public class FileHandlerTest extends TestCase { static LogManager manager = LogManager.getLogManager(); @@ -133,12 +126,6 @@ public class FileHandlerTest extends TestCase { /* * test for constructor void FileHandler() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "FileHandler", - args = {} - ) public void testFileHandler() throws Exception { assertEquals("character encoding is non equal to actual value", "iso-8859-1", handler.getEncoding()); @@ -164,12 +151,6 @@ public class FileHandlerTest extends TestCase { /* * test for constructor void FileHandler(String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify security exception.", - method = "FileHandler", - args = {java.lang.String.class} - ) public void testFileHandler_1params() throws Exception { handler = new FileHandler("%t/log/string"); @@ -253,12 +234,6 @@ public class FileHandlerTest extends TestCase { /* * test for constructor void FileHandler(String pattern, boolean append) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify security exception.", - method = "FileHandler", - args = {java.lang.String.class, boolean.class} - ) public void testFileHandler_2params() throws Exception { boolean append = false; do { @@ -302,12 +277,6 @@ public class FileHandlerTest extends TestCase { * test for constructor void FileHandler(String pattern, int limit, int * count) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verifysecurity exception.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class} - ) public void testFileHandler_3params() throws Exception { int limit = 120; int count = 1; @@ -357,12 +326,6 @@ public class FileHandlerTest extends TestCase { * test for constructor public FileHandler(String pattern, int limit, int * count, boolean append) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify security exception.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class, boolean.class} - ) public void testFileHandler_4params() throws Exception { int limit = 120; int count = 1; @@ -417,38 +380,6 @@ public class FileHandlerTest extends TestCase { //expected } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getEncoding", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getFormatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getErrorManager", - args = {} - ) - }) public void testDefaultValue() throws Exception { handler.publish(r); handler.close(); @@ -553,12 +484,6 @@ public class FileHandlerTest extends TestCase { e.printStackTrace(); } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class, boolean.class} - ) public void testLimitAndCount() throws Exception { handler.close(); // very small limit value, count=2 @@ -641,44 +566,6 @@ public class FileHandlerTest extends TestCase { reset("log", ""); } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "close", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {java.lang.String.class, boolean.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class, boolean.class} - ) - }) public void testSecurity() throws IOException { SecurityManager currentManager = System.getSecurityManager(); @@ -722,44 +609,6 @@ public class FileHandlerTest extends TestCase { } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "close", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "FileHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "FileHandler", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "FileHandler", - args = {java.lang.String.class, boolean.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class, boolean.class} - ) - }) public void testFileSecurity() throws IOException { SecurityManager currentManager = System.getSecurityManager(); @@ -802,12 +651,6 @@ public class FileHandlerTest extends TestCase { System.setSecurityManager(currentManager); } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies FileHandler when configuration file is invalid.", - method = "FileHandler", - args = {} - ) public void testInvalidProperty() throws Exception { props.put("java.util.logging.FileHandler.level", "null"); props.put("java.util.logging.FileHandler.filter", className @@ -842,33 +685,7 @@ public class FileHandlerTest extends TestCase { } catch (NullPointerException e) { } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies illegal parameters and exceptions: IOException, NullPointerException, IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies illegal parameters and exceptions: IOException, NullPointerException, IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class, boolean.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies illegal parameters and exceptions: IOException, NullPointerException, IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies illegal parameters and exceptions: IOException, NullPointerException, IllegalArgumentException.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - }) - @AndroidOnly("This test fails on RI. Doesn't parse special pattern \"%t/%h.") + // This test fails on RI. Doesn't parse special pattern \"%t/%h." public void testInvalidParams() throws IOException { // %t and %p parsing can add file separator automatically @@ -987,12 +804,6 @@ public class FileHandlerTest extends TestCase { /* * test for method public void publish(LogRecord record) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish() throws Exception { LogRecord[] r = new LogRecord[] { new LogRecord(Level.CONFIG, "msg__"), new LogRecord(Level.WARNING, "message"), @@ -1010,12 +821,6 @@ public class FileHandlerTest extends TestCase { /* * test for method public void close() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "close", - args = {} - ) public void testClose() throws Exception { FileHandler h = new FileHandler("%t/log/stringPublish"); h.publish(r); @@ -1023,12 +828,6 @@ public class FileHandlerTest extends TestCase { assertFileContent(TEMPPATH + SEP + "log", "stringPublish", h .getFormatter()); } - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Doesn't verify SecurityException.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) // set output stream still works, just like super StreamHandler public void testSetOutputStream() throws Exception { MockFileHandler handler = new MockFileHandler("%h/setoutput.log"); @@ -1045,12 +844,6 @@ public class FileHandlerTest extends TestCase { assertFileContent(HOMEPATH, "setoutput.log", handler.getFormatter()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class} - ) public void testEmptyPattern_3params() throws SecurityException, IOException { try { @@ -1060,12 +853,6 @@ public class FileHandlerTest extends TestCase { // Expected } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class, boolean.class} - ) public void testEmptyPattern_2params() throws SecurityException, IOException { try { @@ -1075,12 +862,6 @@ public class FileHandlerTest extends TestCase { // Expected } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IllegalArgumentException.", - method = "FileHandler", - args = {java.lang.String.class, int.class, int.class, boolean.class} - ) public void testEmptyPattern_4params() throws SecurityException, IOException { try { diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java index d7ce843..1d105e0 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java @@ -15,26 +15,8 @@ * limitations under the License. */ -//TODO : -/* - * 1. Don't forget to write tests for org.apache.harmony.logging.internal.nls/Messages.java this file is in logging/src/main/java folder - * 2. inrteface filter / LoggingMXBean tests machen - * 3. XMLFormatter.java should be finish for Monday (not a lot to do) but as I beginn want to finish. - * 3. In my case - * I didn't use the PARTIAL_OK, so I believe that 98% of COMPLETE are PARTIAL_OK - * COMPLETE = Tests finish and should be working. If error check the test before to make a ticket. - * PARTIAL = Tests finish, but need special reviewing - * TODO = A test to do (or not). Mostly a test to complete - * 4. For questions christian.wiederseiner - */ - package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.util.logging.Filter; import java.util.logging.LogRecord; @@ -44,26 +26,19 @@ import junit.framework.TestCase; * This testcase verifies the signature of the interface Filter. * */ -@TestTargetClass(Filter.class) public class FilterTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies interface.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testFilter() { - MockFilter f = new MockFilter(); - assertFalse(f.isLoggable(null)); - } - - /* - * This inner class implements the interface Filter to verify the signature. - */ - private class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - return false; - } - } + public void testFilter() { + MockFilter f = new MockFilter(); + f.isLoggable(null); + } + + /* + * This inner class implements the interface Filter to verify the signature. + */ + private class MockFilter implements Filter { + + public boolean isLoggable(LogRecord record) { + return false; + } + } } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java index ba2345d..47b9170 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java @@ -17,12 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestLevel; - import java.io.File; import java.text.MessageFormat; import java.util.Locale; @@ -40,7 +34,6 @@ import junit.framework.TestCase; import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; -@TestTargetClass(Formatter.class) public class FormatterTest extends TestCase { Formatter f; @@ -97,26 +90,6 @@ public class FormatterTest extends TestCase { /* * test for constructor protected Formatter() */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Formatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {java.util.logging.Handler.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ) - }) public void testFormatter() { assertEquals("head string is not empty", "", f.getHead(null)); assertEquals("tail string is not empty", "", f.getTail(null)); @@ -126,12 +99,6 @@ public class FormatterTest extends TestCase { /* * test for method public String getHead(Handler h) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {Handler.class} - ) public void testGetHead() { assertEquals("head string is not empty", "", f.getHead(null)); assertEquals("head string is not empty", "", f.getHead(h)); @@ -142,12 +109,6 @@ public class FormatterTest extends TestCase { /* * test for method public String getTail(Handler h) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {Handler.class} - ) public void testGetTail() { assertEquals("tail string is not empty", "", f.getTail(null)); assertEquals("tail string is not empty", "", f.getTail(h)); @@ -155,16 +116,10 @@ public class FormatterTest extends TestCase { assertEquals("tail string is not empty", "", f.getTail(h)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "formatMessage", - args = {LogRecord.class} - ) - @AndroidOnly("The RI fails in this test because it uses a MessageFormat " + - "to format the message even though it doesn't contain \"{0\". " + - "The spec says that this would indicate that a MessageFormat " + - "should be used and else no formatting should be done.") + // The RI fails in this test because it uses a MessageFormat + // to format the message even though it doesn't contain "{0". + // The spec says that this would indicate that a MessageFormat + // should be used and else no formatting should be done. public void testFormatMessage() { assertEquals(MSG, f.formatMessage(r)); @@ -200,12 +155,6 @@ public class FormatterTest extends TestCase { assertEquals(pattern, f.formatMessage(r)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "formatMessage", - args = {LogRecord.class} - ) public void testLocalizedFormatMessage() { // normal case r.setMessage("msg"); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java index 5868b1f..2f13f2d 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java @@ -17,16 +17,10 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestLevel; - import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.Permission; -import java.util.EmptyStackException; import java.util.Properties; import java.util.logging.ErrorManager; import java.util.logging.Filter; @@ -46,730 +40,551 @@ import tests.util.CallVerificationStack; * Test suite for the class java.util.logging.Handler. * */ -@TestTargetClass(Handler.class) public class HandlerTest extends TestCase { - private static String className = HandlerTest.class.getName(); - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); + private static String className = HandlerTest.class.getName(); + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); CallVerificationStack.getInstance().clear(); - } - - /* - * Test the constructor. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Handler", - args = {} - ) - public void testConstructor() { - MockHandler h = new MockHandler(); - assertSame(h.getLevel(), Level.ALL); - assertNull(h.getFormatter()); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - assertTrue(h.getErrorManager() instanceof ErrorManager); - } - - /* - * Test the constructor, with properties set - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Handler", - args = {} - ) - public void testConstructor_Properties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.MockHandler.level", "FINE"); - p.put("java.util.logging.MockHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.Handler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.MockHandler.encoding", "utf-8"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.MockHandler.level"), "FINE"); - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.MockHandler.encoding"), "utf-8"); - MockHandler h = new MockHandler(); - assertSame(h.getLevel(), Level.ALL); - assertNull(h.getFormatter()); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - assertTrue(h.getErrorManager() instanceof ErrorManager); - LogManager.getLogManager().reset(); - } - - /* - * Test getEncoding & setEncoding methods with supported encoding. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "getEncoding", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setEncoding", - args = {java.lang.String.class} - ) - }) - public void testGetSetEncoding_Normal() throws Exception { - MockHandler h = new MockHandler(); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test getEncoding & setEncoding methods with null. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "getEncoding", - args = {} - ) - public void testGetSetEncoding_Null() throws Exception { - MockHandler h = new MockHandler(); - h.setEncoding(null); - assertNull(h.getEncoding()); - } - - /* - * Test getEncoding & setEncoding methods with unsupported encoding. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies UnsupportedEncodingException.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testGetSetEncoding_Unsupported() { - MockHandler h = new MockHandler(); - try { - h.setEncoding("impossible"); - fail("Should throw UnsupportedEncodingException!"); - } catch (UnsupportedEncodingException e) { - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify UnsupportedEncodingException.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - h.setEncoding("iso-8859-1"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - System.setSecurityManager(new MockSecurityManager()); - // set an invalid value - try { - - h.setEncoding("impossible"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - } - - /* - * Test getErrorManager & setErrorManager methods with non-null value. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setErrorManager", - args = {java.util.logging.ErrorManager.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getErrorManager", - args = {} - ) - }) - public void testGetSetErrorManager_Normal() throws Exception { - MockHandler h = new MockHandler(); - ErrorManager man = new ErrorManager(); - h.setErrorManager(man); - assertSame(man, h.getErrorManager()); - } - - /* - * Test getErrorManager & setErrorManager methods with null. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "getErrorManager", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "setErrorManager", - args = {java.util.logging.ErrorManager.class} - ) - }) - public void testGetSetErrorManager_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setErrorManager(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setErrorManager(new ErrorManager()); - h.setErrorManager(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test getErrorManager with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "getErrorManager", - args = {} - ) - public void testGetErrorManager_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - h.getErrorManager(); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setErrorManager with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setErrorManager with insufficient privilege.", - method = "setErrorManager", - args = {java.util.logging.ErrorManager.class} - ) - public void testSetErrorManager_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setErrorManager(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setErrorManager(new ErrorManager()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getFilter & setFilter methods with non-null value. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "getFilter", - args = {} - ) - }) - public void testGetSetFilter_Normal() throws Exception { - MockHandler h = new MockHandler(); - Filter f = new MockFilter(); - h.setFilter(f); - assertSame(f, h.getFilter()); - } - - /* - * Test getFilter & setFilter methods with null. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) - public void testGetSetFilter_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - h.setFilter(null); - - // test reset null - h.setFilter(new MockFilter()); - h.setFilter(null); - } - - /* - * Test setFilter with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - public void testSetFilter_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setFilter(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setFilter(new MockFilter()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getFormatter & setFormatter methods with non-null value. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "getFormatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "setFormatter", - args = {java.util.logging.Formatter.class} - ) - }) - public void testGetSetFormatter_Normal() throws Exception { - MockHandler h = new MockHandler(); - Formatter f = new SimpleFormatter(); - h.setFormatter(f); - assertSame(f, h.getFormatter()); - } - - /* - * Test getFormatter & setFormatter methods with null. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "getFormatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "setFormatter", - args = {java.util.logging.Formatter.class} - ) - }) - public void testGetSetFormatter_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setFormatter(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setFormatter(new SimpleFormatter()); - h.setFormatter(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test setFormatter with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "getFormatter", - args = {} - ) - public void testSetFormatter_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setFormatter(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setFormatter(new SimpleFormatter()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getLevel & setLevel methods with non-null value. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) - public void testGetSetLevel_Normal() throws Exception { - MockHandler h = new MockHandler(); - Level f = Level.CONFIG; - h.setLevel(f); - assertSame(f, h.getLevel()); - } - - /* - * Test getLevel & setLevel methods with null. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLevel & setLevel methods with null.", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLevel & setLevel methods with null.", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) - public void testGetSetLevel_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setLevel(Level.CONFIG); - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test setLevel with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException, SecurityException.", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - public void testSetLevel_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setLevel(Level.CONFIG); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Use no filter - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_NoFilter() { - MockHandler h = new MockHandler(); - LogRecord r = new LogRecord(Level.CONFIG, null); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.SEVERE); - assertFalse(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Use a filter - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies isLoggable method with filter.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_WithFilter() { - MockHandler h = new MockHandler(); - LogRecord r = new LogRecord(Level.CONFIG, null); - LogRecord r1 = new LogRecord(Level.CONFIG, null); - LogRecord r2 = new LogRecord(Level.CONFIG, null); - - h.setFilter(new MockFilter()); - assertFalse(h.isLoggable(r)); - assertSame(r,CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r1)); - assertSame(r1, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.SEVERE); - assertFalse(h.isLoggable(r2)); - - try{ - CallVerificationStack.getInstance().pop(); - }catch(EmptyStackException e){ - //normal - } - } - - /** - * @tests java.util.logging.Handler#isLoggable(LogRecord) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_Null() { - MockHandler h = new MockHandler(); - try { - h.isLoggable(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test whether the error manager is actually called with expected - * parameters. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reportError", - args = {java.lang.String.class, java.lang.Exception.class, int.class} - ) - public void testReportError() { - MockHandler h = new MockHandler(); - h.setErrorManager(new MockErrorManager()); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - Exception ex = new Exception("test exception"); - // with non-null parameters - h.reportError("test msg", ex, -1); - assertEquals(-1, CallVerificationStack.getInstance().popInt()); - assertSame(ex, CallVerificationStack.getInstance().pop()); - assertEquals("test msg", CallVerificationStack.getInstance().pop()); - // with null parameters - h.reportError(null, null, 0); - assertEquals(0, CallVerificationStack.getInstance().popInt()); - assertSame(null, CallVerificationStack.getInstance().pop()); - assertNull(CallVerificationStack.getInstance().pop()); - } catch (SecurityException e) { - fail("Should not throw SecurityException!"); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Used to enable the testing of Handler because Handler is an abstract - * class. - */ - public static class MockHandler extends Handler { - - public void close() { - } - - public void flush() { - } - - public void publish(LogRecord record) { - } - - public void reportError(String msg, Exception ex, int code) { - super.reportError(msg, ex, code); - } - } - - /* - * Used to grant all permissions except logging control. - */ - public static class MockSecurityManager extends SecurityManager { - - public MockSecurityManager() { - } - - public void checkPermission(Permission perm) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - - public void checkPermission(Permission perm, Object context) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - } - - /* - * A mock filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return false; - } - } - - /* - * A mock error manager, used to validate the expected method is called with - * the expected parameters. - */ - public static class MockErrorManager extends ErrorManager { - - public void error(String msg, Exception ex, int errorCode) { - CallVerificationStack.getInstance().push(msg); - CallVerificationStack.getInstance().push(ex); - CallVerificationStack.getInstance().push(errorCode); - } - } + } + + /** + * Constructor for HandlerTest. + * + * @param arg0 + */ + public HandlerTest(String arg0) { + super(arg0); + } + + /* + * Test the constructor. + */ + public void testConstructor() { + MockHandler h = new MockHandler(); + assertSame(h.getLevel(), Level.ALL); + assertNull(h.getFormatter()); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + assertTrue(h.getErrorManager() instanceof ErrorManager); + } + + /* + * Test the constructor, with properties set + */ + public void testConstructor_Properties() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.MockHandler.level", "FINE"); + p + .put("java.util.logging.MockHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.Handler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.MockHandler.encoding", "utf-8"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.MockHandler.level"), "FINE"); + assertEquals(LogManager.getLogManager().getProperty( + "java.util.logging.MockHandler.encoding"), "utf-8"); + MockHandler h = new MockHandler(); + assertSame(h.getLevel(), Level.ALL); + assertNull(h.getFormatter()); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + assertTrue(h.getErrorManager() instanceof ErrorManager); + LogManager.getLogManager().reset(); + } + + /* + * Abstract method, no test needed. + */ + public void testClose() { + MockHandler h = new MockHandler(); + h.close(); + } + + /* + * Abstract method, no test needed. + */ + public void testFlush() { + MockHandler h = new MockHandler(); + h.flush(); + } + + /* + * Abstract method, no test needed. + */ + public void testPublish() { + MockHandler h = new MockHandler(); + h.publish(null); + } + + /* + * Test getEncoding & setEncoding methods with supported encoding. + */ + public void testGetSetEncoding_Normal() throws Exception { + MockHandler h = new MockHandler(); + h.setEncoding("iso-8859-1"); + assertEquals("iso-8859-1", h.getEncoding()); + } + + /* + * Test getEncoding & setEncoding methods with null. + */ + public void testGetSetEncoding_Null() throws Exception { + MockHandler h = new MockHandler(); + h.setEncoding(null); + assertNull(h.getEncoding()); + } + + /* + * Test getEncoding & setEncoding methods with unsupported encoding. + */ + public void testGetSetEncoding_Unsupported() { + MockHandler h = new MockHandler(); + try { + h.setEncoding("impossible"); + fail("Should throw UnsupportedEncodingException!"); + } catch (UnsupportedEncodingException e) { + } + assertNull(h.getEncoding()); + } + + /* + * Test setEncoding with insufficient privilege. + */ + public void testSetEncoding_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + // set a normal value + try { + h.setEncoding("iso-8859-1"); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + assertNull(h.getEncoding()); + System.setSecurityManager(new MockSecurityManager()); + // set an invalid value + try { + + h.setEncoding("impossible"); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + assertNull(h.getEncoding()); + } + + /* + * Test getErrorManager & setErrorManager methods with non-null value. + */ + public void testGetSetErrorManager_Normal() throws Exception { + MockHandler h = new MockHandler(); + ErrorManager man = new ErrorManager(); + h.setErrorManager(man); + assertSame(man, h.getErrorManager()); + } + + /* + * Test getErrorManager & setErrorManager methods with null. + */ + public void testGetSetErrorManager_Null() throws Exception { + MockHandler h = new MockHandler(); + // test set null + try { + h.setErrorManager(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + + // test reset null + try { + h.setErrorManager(new ErrorManager()); + h.setErrorManager(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + } + + /* + * Test getErrorManager with insufficient privilege. + */ + public void testGetErrorManager_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + try { + h.getErrorManager(); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test setErrorManager with insufficient privilege. + */ + public void testSetErrorManager_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + // set null + try { + + h.setErrorManager(null); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + // set a normal value + System.setSecurityManager(new MockSecurityManager()); + try { + + h.setErrorManager(new ErrorManager()); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test getFilter & setFilter methods with non-null value. + */ + public void testGetSetFilter_Normal() throws Exception { + MockHandler h = new MockHandler(); + Filter f = new MockFilter(); + h.setFilter(f); + assertSame(f, h.getFilter()); + } + + /* + * Test getFilter & setFilter methods with null. + */ + public void testGetSetFilter_Null() throws Exception { + MockHandler h = new MockHandler(); + // test set null + h.setFilter(null); + + // test reset null + h.setFilter(new MockFilter()); + h.setFilter(null); + } + + /* + * Test setFilter with insufficient privilege. + */ + public void testSetFilter_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + // set null + try { + + h.setFilter(null); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + // set a normal value + System.setSecurityManager(new MockSecurityManager()); + try { + + h.setFilter(new MockFilter()); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test getFormatter & setFormatter methods with non-null value. + */ + public void testGetSetFormatter_Normal() throws Exception { + MockHandler h = new MockHandler(); + Formatter f = new SimpleFormatter(); + h.setFormatter(f); + assertSame(f, h.getFormatter()); + } + + /* + * Test getFormatter & setFormatter methods with null. + */ + public void testGetSetFormatter_Null() throws Exception { + MockHandler h = new MockHandler(); + // test set null + try { + h.setFormatter(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + + // test reset null + try { + h.setFormatter(new SimpleFormatter()); + h.setFormatter(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + } + + /* + * Test setFormatter with insufficient privilege. + */ + public void testSetFormatter_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + // set null + try { + + h.setFormatter(null); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + // set a normal value + System.setSecurityManager(new MockSecurityManager()); + try { + + h.setFormatter(new SimpleFormatter()); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test getLevel & setLevel methods with non-null value. + */ + public void testGetSetLevel_Normal() throws Exception { + MockHandler h = new MockHandler(); + Level f = Level.CONFIG; + h.setLevel(f); + assertSame(f, h.getLevel()); + } + + /* + * Test getLevel & setLevel methods with null. + */ + public void testGetSetLevel_Null() throws Exception { + MockHandler h = new MockHandler(); + // test set null + try { + h.setLevel(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + + // test reset null + try { + h.setLevel(Level.CONFIG); + h.setLevel(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } + } + + /* + * Test setLevel with insufficient privilege. + */ + public void testSetLevel_InsufficientPrivilege() throws Exception { + MockHandler h = new MockHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + // set null + try { + + h.setLevel(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + } finally { + System.setSecurityManager(oldMan); + } + // set a normal value + System.setSecurityManager(new MockSecurityManager()); + try { + + h.setLevel(Level.CONFIG); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Use no filter + */ + public void testIsLoggable_NoFilter() { + MockHandler h = new MockHandler(); + LogRecord r = new LogRecord(Level.CONFIG, null); + assertTrue(h.isLoggable(r)); + + h.setLevel(Level.CONFIG); + assertTrue(h.isLoggable(r)); + + h.setLevel(Level.SEVERE); + assertFalse(h.isLoggable(r)); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + assertFalse(h.isLoggable(r)); + } + + /* + * Use a filter + */ + public void testIsLoggable_WithFilter() { + MockHandler h = new MockHandler(); + LogRecord r = new LogRecord(Level.CONFIG, null); + h.setFilter(new MockFilter()); + assertFalse(h.isLoggable(r)); + + h.setLevel(Level.CONFIG); + assertFalse(h.isLoggable(r)); + assertSame(r, CallVerificationStack.getInstance().pop()); + + h.setLevel(Level.SEVERE); + assertFalse(h.isLoggable(r)); + assertSame(r, CallVerificationStack.getInstance().pop()); + } + + /** + * @tests java.util.logging.Handler#isLoggable(LogRecord) + */ + public void testIsLoggable_Null() { + MockHandler h = new MockHandler(); + try { + h.isLoggable(null); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test whether the error manager is actually called with expected + * parameters. + */ + public void testReportError() { + MockHandler h = new MockHandler(); + h.setErrorManager(new MockErrorManager()); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + try { + Exception ex = new Exception("test exception"); + // with non-null parameters + h.reportError("test msg", ex, -1); + assertEquals(-1, CallVerificationStack.getInstance().popInt()); + assertSame(ex, CallVerificationStack.getInstance().pop()); + assertEquals("test msg", CallVerificationStack.getInstance().pop()); + // with null parameters + h.reportError(null, null, 0); + assertEquals(0, CallVerificationStack.getInstance().popInt()); + assertSame(null, CallVerificationStack.getInstance().pop()); + assertNull(CallVerificationStack.getInstance().pop()); + } catch (SecurityException e) { + fail("Should not throw SecurityException!"); + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Used to enable the testing of Handler because Handler is an abstract + * class. + */ + public static class MockHandler extends Handler { + + public void close() { + } + + public void flush() { + } + + public void publish(LogRecord record) { + } + + public void reportError(String msg, Exception ex, int code) { + super.reportError(msg, ex, code); + } + } + + /* + * Used to grant all permissions except logging control. + */ + public static class MockSecurityManager extends SecurityManager { + + public MockSecurityManager() { + } + + public void checkPermission(Permission perm) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + + public void checkPermission(Permission perm, Object context) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + } + + /* + * A mock filter, always return false. + */ + public static class MockFilter implements Filter { + + public boolean isLoggable(LogRecord record) { + CallVerificationStack.getInstance().push(record); + return false; + } + } + + /* + * A mock error manager, used to validate the expected method is called with + * the expected parameters. + */ + public static class MockErrorManager extends ErrorManager { + + public void error(String msg, Exception ex, int errorCode) { + CallVerificationStack.getInstance().push(msg); + CallVerificationStack.getInstance().push(ex); + CallVerificationStack.getInstance().push(errorCode); + } + } public static class NullOutputStream extends OutputStream{ @Override diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java index 1fee1ba..2dbe206 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestLevel; - import java.io.Serializable; import java.util.ResourceBundle; import java.util.logging.Handler; @@ -36,7 +31,6 @@ import org.apache.harmony.testframework.serialization.SerializationTest.Serializ * This class implements Serializable, so that the non-static inner class * MockLevel can be Serializable. */ -@TestTargetClass(Level.class) public class LevelTest extends TestCase implements Serializable { private static final long serialVersionUID = 1L; @@ -45,20 +39,6 @@ public class LevelTest extends TestCase implements Serializable { * Test the constructor without resource bundle parameter using normal * values. As byproducts, getName & intValue are also tested. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using normal values.", - method = "Level", - args = {java.lang.String.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using normal values.", - method = "getName", - args = {} - ) - }) public void testConstructorNoResBundle_Normal() { MockLevel l = new MockLevel("level1", 1); assertEquals("level1", l.getName()); @@ -70,20 +50,6 @@ public class LevelTest extends TestCase implements Serializable { * Test the constructor without resource bundle parameter using null name. * As byproducts, getName & intValue are also tested. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using null name.", - method = "Level", - args = {java.lang.String.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using null name.", - method = "getName", - args = {} - ) - }) public void testConstructorNoResBundle_NullName() { try { new MockLevel(null, -2); @@ -97,20 +63,6 @@ public class LevelTest extends TestCase implements Serializable { * Test the constructor without resource bundle parameter using empty name. * As byproducts, getName & intValue are also tested. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using empty name.", - method = "Level", - args = {java.lang.String.class, int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks the constructor without resource bundle parameter using empty name.", - method = "getName", - args = {} - ) - }) public void testConstructorNoResBundle_EmptyName() { MockLevel l = new MockLevel("", -3); assertEquals("", l.getName()); @@ -122,20 +74,6 @@ public class LevelTest extends TestCase implements Serializable { * Test the constructor having resource bundle parameter using normal * values. As byproducts, getName & intValue are also tested. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "Level", - args = {java.lang.String.class, int.class, java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getName", - args = {} - ) - }) public void testConstructorHavingResBundle_Normal() { MockLevel l = new MockLevel("level1", 1, "resourceBundle"); assertEquals("level1", l.getName()); @@ -147,12 +85,6 @@ public class LevelTest extends TestCase implements Serializable { * Test the constructor having resource bundle parameter using null names. * As byproducts, getName & intValue are also tested. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks NullPointerException.", - method = "Level", - args = {java.lang.String.class, int.class, java.lang.String.class} - ) public void testConstructorHavingResBundle_NullName() { try { new MockLevel(null, -123, "qwe"); @@ -167,12 +99,6 @@ public class LevelTest extends TestCase implements Serializable { names. * As byproducts, getName & intValue are also tested. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor having resource bundle parameter using empty names.", - method = "Level", - args = {java.lang.String.class, int.class, java.lang.String.class} - ) public void testConstructorHavingResBundle_EmptyName() { MockLevel l = new MockLevel("", -1000, ""); assertEquals("", l.getName()); @@ -183,12 +109,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with the pre-defined string consts. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies parse, with the pre-defined string consts.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_PredefinedConstStrings() { assertSame(Level.SEVERE, Level.parse("SEVERE")); assertSame(Level.WARNING, Level.parse("WARNING")); @@ -204,12 +124,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with an undefined string. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IllegalArgumentException is verified.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_IllegalConstString() { try { Level.parse("SEVERe"); @@ -222,12 +136,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with a null string. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_NullString() { try { Level.parse(null); @@ -240,12 +148,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with pre-defined valid number strings. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies parse, with pre-defined valid number strings.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_PredefinedNumber() { assertSame(Level.SEVERE, Level.parse("SEVERE")); assertSame(Level.WARNING, Level.parse("WARNING")); @@ -270,12 +172,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with an undefined valid number strings. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies parse, with an undefined valid number strings.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_UndefinedNumber() { Level l = Level.parse("0"); assertEquals(0, l.intValue()); @@ -286,12 +182,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method parse, with an undefined valid number strings with spaces. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies parse, with an undefined valid number strings with spaces.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_UndefinedNumberWithSpaces() { try { Level.parse(" 0"); @@ -299,12 +189,6 @@ public class LevelTest extends TestCase implements Serializable { // expected } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies negative number.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_NegativeNumber() { Level l = Level.parse("-4"); assertEquals(-4, l.intValue()); @@ -316,12 +200,6 @@ public class LevelTest extends TestCase implements Serializable { * Test method parse, expecting the same objects will be returned given the * same name, even for non-predefined levels. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies parse, expecting the same objects will be returned given the same name, even for non-predefined levels.", - method = "parse", - args = {java.lang.String.class} - ) public void testParse_SameObject() { Level l = Level.parse("-100"); assertSame(l, Level.parse("-100")); @@ -330,12 +208,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test method hashCode, with normal fields. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void testHashCode_Normal() { assertEquals(100, Level.parse("100").hashCode()); assertEquals(-1, Level.parse("-1").hashCode()); @@ -346,12 +218,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test equals when two objects are equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check negative case.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEquals_Equal() { MockLevel l1 = new MockLevel("level1", 1); MockLevel l2 = new MockLevel("level2", 1); @@ -362,12 +228,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test equals when two objects are not equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks negative case.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEquals_NotEqual() { MockLevel l1 = new MockLevel("level1", 1); MockLevel l2 = new MockLevel("level1", 2); @@ -378,12 +238,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test equals when the other object is null. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEquals_Null() { assertFalse(Level.ALL.equals(null)); } @@ -391,12 +245,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test equals when the other object is not an instance of Level. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks negative case.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEquals_NotLevel() { assertFalse(Level.ALL.equals(new Object())); } @@ -404,12 +252,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test equals when the other object is itself. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks equals when the other object is itself.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEquals_Itself() { assertTrue(Level.ALL.equals(Level.ALL)); } @@ -417,12 +259,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test toString of a normal Level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void testToString_Normal() { assertEquals("ALL", Level.ALL.toString()); @@ -457,12 +293,6 @@ public class LevelTest extends TestCase implements Serializable { * Test serialization of pre-defined const levels. It is expected that the * deserialized cost level should be the same instance as the existing one. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Serialization of pre-defined const levels. ", - method = "!SerializationSelf", - args = {} - ) public void testSerialization_ConstLevel() throws Exception { SerializationTest.verifySelf(Level.ALL, @@ -475,12 +305,6 @@ public class LevelTest extends TestCase implements Serializable { * Test serialization of normal instance of Level. It is expected that the * deserialized level object should be equal to the original one. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Test serialization of normal instance of Level.", - method = "!SerializationSelf", - args = {} - ) public void testSerialization_InstanceLevel() throws Exception { // tests that objects are the same @@ -500,23 +324,11 @@ public class LevelTest extends TestCase implements Serializable { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Serialization/deserialization compatibility", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new MockLevel("123", 123, "bundle"), LEVEL_COMPARATOR); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLocalizedName", - args = {} - ) public void testGetLocalName() { ResourceBundle rb = ResourceBundle.getBundle("bundles/java/util/logging/res"); Level l = new MockLevel("level1", 120, @@ -543,12 +355,6 @@ public class LevelTest extends TestCase implements Serializable { /* * test for method public String getResourceBundleName() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResourceBundleName", - args = {} - ) public void testGetResourceBundleName() { String bundleName = "bundles/java/util/logging/res"; Level l = new MockLevel("level1", 120); @@ -565,12 +371,6 @@ public class LevelTest extends TestCase implements Serializable { /* * test for method public final int intValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "intValue", - args = {} - ) public void testIntValue() { int value1 = 120; Level l = new MockLevel("level1", value1); @@ -582,12 +382,6 @@ public class LevelTest extends TestCase implements Serializable { /* * Test defining new levels in subclasses of Level */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Test defining new levels in subclasses of Level", - method = "parse", - args = {java.lang.String.class} - ) public void testSubclassNewLevel() { MyLevel.DUPLICATENAME.getName();// just to load MyLevel class diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java index 9b41a9d..5e06b70 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java @@ -17,12 +17,8 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; - import java.util.ListResourceBundle; -import java.util.logging.Level; -//@TestTargetClass = No test needed, just test class helper public class LevelTestResource extends ListResourceBundle { public Object[][] getContents() { return contents; diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java index 4768837..eff8745 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java @@ -40,11 +40,6 @@ import junit.framework.TestCase; import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; -import dalvik.annotation.SideEffect; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; import tests.util.TestEnvironment; /** @@ -52,7 +47,6 @@ import tests.util.TestEnvironment; * add/get logger(dot) * */ -@TestTargetClass(LogManager.class) public class LogManagerTest extends TestCase { private static final String FOO = "LogManagerTestFoo"; @@ -113,12 +107,6 @@ public class LogManagerTest extends TestCase { handler = null; } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LogManager", - args = {} - ) public void testLogManager() { class TestLogManager extends LogManager { public TestLogManager() { @@ -129,20 +117,6 @@ public class LogManagerTest extends TestCase { assertNotNull(tlm.toString()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddGetLogger() { Logger log = new MockLogger(FOO, null); Logger foo = mockManager.getLogger(FOO); @@ -176,20 +150,6 @@ public class LogManagerTest extends TestCase { assertEquals(i, 1); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddGetLogger_duplicateName() { // add logger with duplicate name has no effect Logger foo = new MockLogger(FOO, null); @@ -207,20 +167,6 @@ public class LogManagerTest extends TestCase { assertEquals(1, i); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddGetLogger_Hierachy() { Logger foo = new MockLogger("testAddGetLogger_Hierachy.foo", null); Logger child = new MockLogger("testAddGetLogger_Hierachy.foo.child", null); @@ -260,20 +206,6 @@ public class LogManagerTest extends TestCase { assertSame(otherChild, grandson.getParent()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddLoggerReverseOrder() { Logger root = new MockLogger("testAddLoggerReverseOrder", null); Logger foo = new MockLogger("testAddLoggerReverseOrder.foo", null); @@ -306,12 +238,6 @@ public class LogManagerTest extends TestCase { assertSame(realRoot, root.getParent()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ) public void testAddSimiliarLogger() { Logger root = new MockLogger("testAddSimiliarLogger", null); Logger foo = new MockLogger("testAddSimiliarLogger.foo", null); @@ -343,20 +269,6 @@ public class LogManagerTest extends TestCase { assertSame(fooo, foooChild.getParent()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddGetLogger_nameWithSpace() { Logger foo = new MockLogger(FOO, null); Logger fooBeforeSpace = new MockLogger(FOO + " ", null); @@ -373,20 +285,6 @@ public class LogManagerTest extends TestCase { assertSame(fooWithBothSpace, mockManager.getLogger(" " + FOO + " ")); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify NullPointerException", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) - }) public void testAddGetLogger_addRoot() { Logger foo = new MockLogger(FOO, null); Logger fooChild = new MockLogger(FOO + ".child", null); @@ -417,20 +315,6 @@ public class LogManagerTest extends TestCase { /** * @tests java.util.logging.LogManager#addLogger(Logger) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addLogger", - args = {java.util.logging.Logger.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogManager", - args = {} - ) - }) public void test_addLoggerLLogger_Security() throws Exception { // regression test for Harmony-1286 SecurityManager originalSecurityManager = System.getSecurityManager(); @@ -449,12 +333,6 @@ public class LogManagerTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testDefaultLoggerProperties() throws Exception { // mock LogManager has no default logger assertNull(mockManager.getLogger("")); @@ -500,20 +378,6 @@ public class LogManagerTest extends TestCase { * case 4: check correct tested value */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLoggerNames", - args = {} - ) - }) public void testGetLogger() throws Exception { // case 1: test default and valid value @@ -550,20 +414,6 @@ public class LogManagerTest extends TestCase { /* * test for method public Logger getLogger(String name) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "getLoggerNames", - args = {} - ) - }) public void testGetLogger_duplicateName() throws Exception { // test duplicate name // add logger with duplicate name has no effect @@ -587,12 +437,6 @@ public class LogManagerTest extends TestCase { /* * test for method public Logger getLogger(String name) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_hierachy() throws Exception { // test hierachy Logger foo = new MockLogger("testGetLogger_hierachy.foo", null); @@ -605,12 +449,6 @@ public class LogManagerTest extends TestCase { /* * test for method public Logger getLogger(String name) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_nameSpace() throws Exception { // test name with space Logger foo = new MockLogger(FOO, null); @@ -631,20 +469,6 @@ public class LogManagerTest extends TestCase { /* * test for method public void checkAccess() throws SecurityException */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkAccess", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLogManager", - args = {} - ) - }) public void testCheckAccess() { try { manager.checkAccess(); @@ -666,44 +490,6 @@ public class LogManagerTest extends TestCase { System.setSecurityManager(securityManager); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "readConfiguration", - args = {java.io.InputStream.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "readConfiguration", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "checkAccess", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "reset", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "getLogManager", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "addPropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - }) public void testLoggingPermission() throws IOException { System.setSecurityManager(new MockSecurityManagerLogPermission()); mockManager.addLogger(new MockLogger("abc", null)); @@ -756,20 +542,6 @@ public class LogManagerTest extends TestCase { } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "readConfiguration", - args = {java.io.InputStream.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getProperty", - args = {java.lang.String.class} - ) - }) public void testMockGetProperty() throws Exception { // mock manager doesn't read configuration until you call // readConfiguration() @@ -788,12 +560,6 @@ public class LogManagerTest extends TestCase { assertEquals(0, mockManager.getLogger("").getHandlers().length); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getProperty", - args = {java.lang.String.class} - ) public void testGetProperty() throws SecurityException, IOException { Logger root = manager.getLogger(""); @@ -810,12 +576,6 @@ public class LogManagerTest extends TestCase { manager.reset(); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testReadConfiguration_null() throws SecurityException, IOException { try { manager.readConfiguration(null); @@ -892,12 +652,6 @@ public class LogManagerTest extends TestCase { /* * Class under test for void readConfiguration(InputStream) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testReadConfigurationInputStream() throws IOException { Logger foo = new MockLogger(FOO, null); @@ -928,12 +682,6 @@ public class LogManagerTest extends TestCase { assertSame(l, h.getLevel()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testReadConfigurationInputStream_null() throws SecurityException, IOException { try { mockManager.readConfiguration(null); @@ -942,12 +690,6 @@ public class LogManagerTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IOException.", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testReadConfigurationInputStream_IOException_1parm() throws SecurityException { try { mockManager.readConfiguration(new MockInputStream()); @@ -958,12 +700,6 @@ public class LogManagerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testReadConfigurationInputStream_root() throws IOException { manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); @@ -1028,20 +764,6 @@ public class LogManagerTest extends TestCase { assertEquals(0, logger.getHandlers().length); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addPropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "removePropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - }) public void testAddRemovePropertyChangeListener() throws Exception { MockPropertyChangeListener listener1 = new MockPropertyChangeListener(); MockPropertyChangeListener listener2 = new MockPropertyChangeListener(); @@ -1088,20 +810,6 @@ public class LogManagerTest extends TestCase { assertNull(listener2.getEvent()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addPropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "removePropertyChangeListener", - args = {java.beans.PropertyChangeListener.class} - ) - }) public void testAddRemovePropertyChangeListener_null() { // seems nothing happened try{ @@ -1112,12 +820,6 @@ public class LogManagerTest extends TestCase { mockManager.removePropertyChangeListener(null); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "reset", - args = {} - ) public void testReset() throws SecurityException, IOException { // mock LogManager mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); @@ -1153,12 +855,6 @@ public class LogManagerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify SecurityException.", - method = "readConfiguration", - args = {java.io.InputStream.class} - ) public void testGlobalPropertyConfig() throws Exception { PrintStream err = System.err; try { @@ -1232,12 +928,6 @@ public class LogManagerTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "readConfiguration", - args = {} - ) public void testValidConfigClass() throws Exception { // System.setProperty("java.util.logging.config.class", "org.apache.harmony.logging.tests.java.util.logging.LogManagerTest$ConfigClass"); System.setProperty("java.util.logging.config.class", this.getClass().getName() diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java index 6d4f784..7d8757e 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.Serializable; import java.util.Locale; import java.util.ResourceBundle; @@ -36,7 +31,6 @@ import junit.framework.TestCase; import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(LogRecord.class) public class LogRecordTest extends TestCase { static final String MSG = "test msg, pls. ignore itb"; @@ -50,12 +44,6 @@ public class LogRecordTest extends TestCase { lr = new LogRecord(Level.CONFIG, MSG); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LogRecord", - args = {java.util.logging.Level.class, java.lang.String.class} - ) public void testLogRecordWithNullPointers() { try { new LogRecord(null, null); @@ -72,20 +60,6 @@ public class LogRecordTest extends TestCase { assertNull(r.getMessage()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "normally set/get don't need to be tested", - method = "getLoggerName", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "normally set/get don't need to be tested", - method = "setLoggerName", - args = {java.lang.String.class} - ) - }) public void testGetSetLoggerName() { assertNull(lr.getLoggerName()); lr.setLoggerName(null); @@ -94,21 +68,6 @@ public class LogRecordTest extends TestCase { assertEquals("test logger name", lr.getLoggerName()); } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResourceBundle", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setResourceBundle", - args = {java.util.ResourceBundle.class} - ) - }) public void testGetSetResourceBundle() { assertNull(lr.getResourceBundleName()); assertNull(lr.getResourceBundle()); @@ -127,20 +86,6 @@ public class LogRecordTest extends TestCase { assertNull(lr.getResourceBundleName()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResourceBundleName", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setResourceBundleName", - args = {java.lang.String.class} - ) - }) public void testGetSetResourceBundleName() { assertNull(lr.getResourceBundleName()); lr.setResourceBundleName(null); @@ -149,20 +94,6 @@ public class LogRecordTest extends TestCase { assertEquals("test", lr.getResourceBundleName()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "normal behavior of getter/setter don't need to be tested (normally)", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "normal behavior of getter/setter don't need to be tested (normally)", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testGetSetLevelNormal() { assertSame(lr.getLevel(), Level.CONFIG); lr.setLevel(Level.ALL); @@ -171,20 +102,6 @@ public class LogRecordTest extends TestCase { assertSame(lr.getLevel(), Level.FINEST); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testGetSetLevelNullPointerException() { try { lr.setLevel(null); @@ -194,20 +111,6 @@ public class LogRecordTest extends TestCase { assertSame(lr.getLevel(), Level.CONFIG); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSequenceNumber", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setSequenceNumber", - args = {long.class} - ) - }) public void testGetSetSequenceNumber() { long l = lr.getSequenceNumber(); lr.setSequenceNumber(-111); @@ -218,20 +121,6 @@ public class LogRecordTest extends TestCase { assertEquals(lr.getSequenceNumber(), l + 1); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSourceClassName", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setSourceClassName", - args = {java.lang.String.class} - ) - }) public void testGetSetSourceClassName() { lr.setSourceClassName(null); assertNull(lr.getSourceClassName()); @@ -241,20 +130,6 @@ public class LogRecordTest extends TestCase { assertEquals(this.getClass().getName(), lr.getSourceClassName()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getSourceMethodName", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setSourceMethodName", - args = {java.lang.String.class} - ) - }) public void testGetSetSourceMethodName() { lr.setSourceMethodName(null); assertNull(lr.getSourceMethodName()); @@ -264,32 +139,6 @@ public class LogRecordTest extends TestCase { assertEquals(this.getClass().getName(), lr.getSourceMethodName()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getSourceMethodName", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setSourceMethodName", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getSourceClassName", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setSourceClassName", - args = {java.lang.String.class} - ) - }) public void testGetSourceDefaultValue() { assertNull(lr.getSourceMethodName()); assertNull(lr.getSourceClassName()); @@ -363,20 +212,6 @@ public class LogRecordTest extends TestCase { logger.removeHandler(handler); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMessage", - args = {java.lang.String.class} - ) - }) public void testGetSetMessage() { assertEquals(MSG, lr.getMessage()); lr.setMessage(null); @@ -385,20 +220,6 @@ public class LogRecordTest extends TestCase { assertEquals("", lr.getMessage()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getParameters", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParameters", - args = {java.lang.Object[].class} - ) - }) public void testGetSetParameters() { assertNull(lr.getParameters()); lr.setParameters(null); @@ -411,20 +232,6 @@ public class LogRecordTest extends TestCase { assertSame(oa, lr.getParameters()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMillis", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMillis", - args = {long.class} - ) - }) public void testGetSetMillis() { long milli = lr.getMillis(); assertTrue(milli > 0); @@ -434,20 +241,6 @@ public class LogRecordTest extends TestCase { assertEquals(0, lr.getMillis()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMillis", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMillis", - args = {long.class} - ) - }) public void testGetSetTimeCheck() { long before = lr.getMillis(); try { @@ -462,20 +255,6 @@ public class LogRecordTest extends TestCase { - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getThreadID", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setThreadID", - args = {int.class} - ) - }) public void testGetSetThreadID() { int id = lr.getThreadID(); lr = new LogRecord(Level.ALL, "a1"); @@ -489,20 +268,6 @@ public class LogRecordTest extends TestCase { /* * Check threadID are different */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getThreadID", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setThreadID", - args = {int.class} - ) - }) public void testGetSetThreadID_DifferentThread() { int id = lr.getThreadID(); // Create and start the thread @@ -529,20 +294,6 @@ public class LogRecordTest extends TestCase { } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getThrown", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setThrown", - args = {java.lang.Throwable.class} - ) - }) public void testGetSetThrown() { assertNull(lr.getThrown()); lr.setThrown(null); @@ -600,12 +351,6 @@ public class LogRecordTest extends TestCase { /** * @tests serialization/deserialization compatibility. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "serialisation/deserialization", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { LogRecord r = new LogRecord(Level.ALL, "msg"); r.setLoggerName("LoggerName"); @@ -624,12 +369,6 @@ public class LogRecordTest extends TestCase { /** * @tests resolution of resource bundle for serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "tests resolution of resource bundle during deserialization", - method = "!Serialization", - args = {} - ) public void testSerializationResourceBundle() throws Exception { // test case: valid resource bundle name @@ -653,12 +392,6 @@ public class LogRecordTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { LogRecord r = new LogRecord(Level.ALL, "msg"); r.setLoggerName("LoggerName"); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java index f2bd62d..c05b9a5 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java @@ -17,6 +17,8 @@ package org.apache.harmony.logging.tests.java.util.logging; +import dalvik.annotation.SideEffect; + import java.security.Permission; import java.util.Locale; import java.util.MissingResourceException; @@ -37,16 +39,10 @@ import junit.framework.TestCase; import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; import tests.util.CallVerificationStack; -import dalvik.annotation.SideEffect; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; /** * Test suite for the class java.util.logging.Logger. */ -@TestTargetClass(Logger.class) public class LoggerTest extends TestCase { private final static String VALID_RESOURCE_BUNDLE = "bundles/java/util/logging/res"; @@ -95,12 +91,6 @@ public class LoggerTest extends TestCase { /* * Test the global logger */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGlobalLogger() { assertNull(Logger.global.getFilter()); assertEquals(0, Logger.global.getHandlers().length); @@ -118,12 +108,6 @@ public class LoggerTest extends TestCase { /* * Test constructor under normal conditions. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies constructor under normal conditions.", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testConstructor_Normal() { MockLogger mlog = new MockLogger("myname", VALID_RESOURCE_BUNDLE); assertNull(mlog.getFilter()); @@ -140,12 +124,6 @@ public class LoggerTest extends TestCase { /* * Test constructor with null parameters. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies constructor with null parameters.", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testConstructor_Null() { MockLogger mlog = new MockLogger(null, null); assertNull(mlog.getFilter()); @@ -161,12 +139,6 @@ public class LoggerTest extends TestCase { /* * Test constructor with invalid name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies constructor with invalid name.", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testConstructor_InvalidName() { MockLogger mlog = new MockLogger("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", null); @@ -176,12 +148,6 @@ public class LoggerTest extends TestCase { /* * Test constructor with empty name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies constructor with empty name.", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testConstructor_EmptyName() { MockLogger mlog = new MockLogger("", null); assertEquals("", mlog.getName()); @@ -190,12 +156,6 @@ public class LoggerTest extends TestCase { /* * Test constructor with invalid resource bundle name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies MissingResourceException.", - method = "Logger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testConstructor_InvalidResourceBundle() { // try anonymous with invalid resource @@ -225,12 +185,6 @@ public class LoggerTest extends TestCase { /* * Test getAnonymousLogger() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAnonymousLogger", - args = {} - ) public void testGetAnonymousLogger() { Logger alog = Logger.getAnonymousLogger(); assertNotSame(alog, Logger.getAnonymousLogger()); @@ -249,12 +203,6 @@ public class LoggerTest extends TestCase { * Test getAnonymousLogger(String resourceBundleName) with valid resource * bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getAnonymousLogger(String resourceBundleName) with valid resource bundle.", - method = "getAnonymousLogger", - args = {java.lang.String.class} - ) public void testGetAnonymousLogger_ValidResourceBundle() { Logger alog = Logger.getAnonymousLogger(VALID_RESOURCE_BUNDLE); assertNotSame(alog, Logger.getAnonymousLogger(VALID_RESOURCE_BUNDLE)); @@ -273,12 +221,6 @@ public class LoggerTest extends TestCase { * Test getAnonymousLogger(String resourceBundleName) with null resource * bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getAnonymousLogger(String resourceBundleName) with null resource bundle.", - method = "getAnonymousLogger", - args = {java.lang.String.class} - ) public void testGetAnonymousLogger_NullResourceBundle() { Logger alog = Logger.getAnonymousLogger(null); assertNotSame(alog, Logger.getAnonymousLogger(null)); @@ -297,12 +239,6 @@ public class LoggerTest extends TestCase { * Test getAnonymousLogger(String resourceBundleName) with invalid resource * bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getAnonymousLogger(String resourceBundleName) with invalid resource bundle.", - method = "getAnonymousLogger", - args = {java.lang.String.class} - ) public void testGetAnonymousLogger_InvalidResourceBundle() { try { Logger.getAnonymousLogger(INVALID_RESOURCE_BUNDLE); @@ -320,12 +256,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String), getting a logger with no parent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String), getting a logger with no parent.", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_Normal() throws Exception { // config the level Properties p = new Properties(); @@ -359,12 +289,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String), getting a logger with invalid level configured. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String), getting a logger with invalid level configured.", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_InvalidLevel() throws Exception { // config the level Properties p = new Properties(); @@ -390,12 +314,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String) with null name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String) with null name.", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_Null() { try { Logger.getLogger(null); @@ -414,12 +332,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String) with invalid name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String) with invalid name.", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_Invalid() { Logger log = Logger.getLogger("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|"); assertEquals("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", log.getName()); @@ -428,12 +340,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String) with empty name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String) with empty name.", - method = "getLogger", - args = {java.lang.String.class} - ) public void testGetLogger_Empty() { assertNotNull(LogManager.getLogManager().getLogger("")); Logger log = Logger.getLogger(""); @@ -452,12 +358,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String), getting a logger with existing parent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String), getting a logger with existing parent.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLogger_WithParent() { assertNull(LogManager.getLogManager().getLogger( "testGetLogger_WithParent_ParentLogger")); @@ -544,12 +444,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String), getting a logger with no parent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String), getting a logger with no parent.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_Normal() throws Exception { // config the level Properties p = new Properties(); @@ -583,12 +477,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String) with null parameters. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with null parameters.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_Null() { Logger.getLogger("testGetLoggerWithRes_Null_ANewLogger", null); try { @@ -602,12 +490,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String) with invalid resource bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with invalid resource bundle.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_InvalidResourceBundle() { assertNull(LogManager.getLogManager().getLogger( @@ -645,12 +527,6 @@ public class LoggerTest extends TestCase { * Test getLogger(String, String) with valid resource bundle, to get an * existing logger with no associated resource bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with valid resource bundle, to get an existing logger with no associated resource bundle.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_ExistingLoggerWithNoRes() { assertNull(LogManager.getLogManager().getLogger( "testGetLoggerWithRes_ExistingLoggerWithNoRes_ANewLogger")); @@ -671,12 +547,6 @@ public class LoggerTest extends TestCase { * Test getLogger(String, String) with valid resource bundle, to get an * existing logger with the same associated resource bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with valid resource bundle, to get an existing logger with the same associated resource bundle.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_ExistingLoggerWithSameRes() { assertNull(LogManager.getLogManager().getLogger( "testGetLoggerWithRes_ExistingLoggerWithSameRes_ANewLogger")); @@ -697,12 +567,6 @@ public class LoggerTest extends TestCase { * Test getLogger(String, String) with valid resource bundle, to get an * existing logger with different associated resource bundle. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with valid resource bundle, to get an existing logger with different associated resource bundle.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_ExistingLoggerWithDiffRes() { assertNull(LogManager.getLogManager().getLogger( "testGetLoggerWithRes_ExistingLoggerWithDiffRes_ANewLogger")); @@ -734,12 +598,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String) with invalid name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with invalid name.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_InvalidName() { Logger log = Logger.getLogger( "...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|WithRes", @@ -751,12 +609,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String) with empty name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String) with empty name.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) @SideEffect("Attaches ResourceBundle to anonymous logger; irreversible") public void testGetLoggerWithRes_Empty() { Logger log = Logger.getLogger("", VALID_RESOURCE_BUNDLE); @@ -775,12 +627,6 @@ public class LoggerTest extends TestCase { /* * Test getLogger(String, String), getting a logger with existing parent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getLogger(String, String), getting a logger with existing parent.", - method = "getLogger", - args = {java.lang.String.class, java.lang.String.class} - ) public void testGetLoggerWithRes_WithParentNormal() { assertNull(LogManager.getLogManager().getLogger( "testGetLoggerWithRes_WithParent_ParentLogger")); @@ -812,12 +658,6 @@ public class LoggerTest extends TestCase { /* * Test addHandler(Handler) for a named logger with sufficient privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testAddHandler_NamedLoggerSufficientPrivilege"); @@ -832,12 +672,6 @@ public class LoggerTest extends TestCase { * Test addHandler(Handler) for a named logger with sufficient privilege, * add duplicate handlers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_NamedLoggerSufficientPrivilegeDuplicate() { Logger log = Logger .getLogger("testAddHandler_NamedLoggerSufficientPrivilegeDuplicate"); @@ -855,12 +689,6 @@ public class LoggerTest extends TestCase { /* * Test addHandler(Handler) with a null handler. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_Null() { Logger log = Logger.getLogger("testAddHandler_Null"); try { @@ -874,12 +702,6 @@ public class LoggerTest extends TestCase { /* * Test addHandler(Handler) for a named logger with insufficient privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_NamedLoggerInsufficientPrivilege() { Logger log = Logger .getLogger("testAddHandler_NamedLoggerInsufficientPrivilege"); @@ -900,12 +722,6 @@ public class LoggerTest extends TestCase { * Test addHandler(Handler) for a named logger with insufficient privilege, * using a null handler. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_NamedLoggerInsufficientPrivilegeNull() { Logger log = Logger .getLogger("testAddHandler_NamedLoggerInsufficientPrivilege"); @@ -925,12 +741,6 @@ public class LoggerTest extends TestCase { * Test addHandler(Handler) for an anonymous logger with sufficient * privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); MockHandler h = new MockHandler(); @@ -944,12 +754,6 @@ public class LoggerTest extends TestCase { * Test addHandler(Handler) for an anonymous logger with insufficient * privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); MockHandler h = new MockHandler(); @@ -969,12 +773,6 @@ public class LoggerTest extends TestCase { * Test addHandler(Handler) for a null-named mock logger with insufficient * privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies addHandler(Handler) for a null-named mock logger with insufficient privilege, SecurityException.", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testAddHandler_NullNamedMockLoggerInsufficientPrivilege() { MockLogger mlog = new MockLogger(null, null); MockHandler h = new MockHandler(); @@ -993,12 +791,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for a named logger with sufficient privilege, * remove an existing handler. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "addHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testRemoveHandler_NamedLoggerSufficientPrivilege"); @@ -1013,12 +805,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for a named logger with sufficient privilege, * remove a non-existing handler. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_NamedLoggerSufficientPrivilegeNotExisting() { Logger log = Logger .getLogger("testRemoveHandler_NamedLoggerSufficientPrivilegeNotExisting"); @@ -1031,12 +817,6 @@ public class LoggerTest extends TestCase { /* * Test removeHandler(Handler) with a null handler. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_Null() { Logger log = Logger.getLogger("testRemoveHandler_Null"); log.removeHandler(null); @@ -1047,12 +827,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for a named logger with insufficient * privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_NamedLoggerInsufficientPrivilege() { Logger log = Logger .getLogger("testRemoveHandler_NamedLoggerInsufficientPrivilege"); @@ -1073,12 +847,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for a named logger with insufficient * privilege, using a null handler. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_NamedLoggerInsufficientPrivilegeNull() { Logger log = Logger .getLogger("testRemoveHandler_NamedLoggerInsufficientPrivilege"); @@ -1098,12 +866,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for an anonymous logger with sufficient * privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); MockHandler h = new MockHandler(); @@ -1117,12 +879,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for an anonymous logger with insufficient * privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); MockHandler h = new MockHandler(); @@ -1142,12 +898,6 @@ public class LoggerTest extends TestCase { * Test removeHandler(Handler) for a null-named mock logger with * insufficient privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "removeHandler", - args = {java.util.logging.Handler.class} - ) public void testRemoveHandler_NullNamedMockLoggerInsufficientPrivilege() { MockLogger mlog = new MockLogger(null, null); MockHandler h = new MockHandler(); @@ -1165,12 +915,6 @@ public class LoggerTest extends TestCase { /* * Test getHandlers() when there's no handler. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getHandlers() when there's no handler.", - method = "getHandlers", - args = {} - ) public void testGetHandlers_None() { Logger log = Logger.getLogger("testGetHandlers_None"); assertEquals(log.getHandlers().length, 0); @@ -1179,12 +923,6 @@ public class LoggerTest extends TestCase { /* * Test getHandlers() when there are several handlers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getHandlers() when there are several handlers.", - method = "getHandlers", - args = {} - ) public void testGetHandlers_Several() { Logger log = Logger.getLogger("testGetHandlers_None"); assertEquals(log.getHandlers().length, 0); @@ -1210,20 +948,6 @@ public class LoggerTest extends TestCase { * Test getFilter & setFilter with normal value for a named logger, having * sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getFilter & setFilter with normal value for a named logger, having sufficient privilege.", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getFilter & setFilter with normal value for a named logger, having sufficient privilege.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testGetSetFilter_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testGetSetFilter_NamedLoggerSufficientPrivilege"); @@ -1237,20 +961,6 @@ public class LoggerTest extends TestCase { /* * Test getFilter & setFilter with null value, having sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getFilter & setFilter with null value, having sufficient privilege.", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getFilter & setFilter with null value, having sufficient privilege.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testGetSetFilter_Null() { Logger log = Logger.getLogger("testGetSetFilter_Null"); @@ -1266,20 +976,6 @@ public class LoggerTest extends TestCase { * Test setFilter with normal value for a named logger, having insufficient * privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies setFilter with normal value for a named logger, having insufficient privilege.", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies setFilter with normal value for a named logger, having insufficient privilege.", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testGetSetFilter_NamedLoggerInsufficientPrivilege() { Logger log = Logger .getLogger("testGetSetFilter_NamedLoggerInsufficientPrivilege"); @@ -1298,20 +994,6 @@ public class LoggerTest extends TestCase { /* * Test setFilter for an anonymous logger with sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testSetFilter_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); Filter f = new MockFilter(); @@ -1323,20 +1005,6 @@ public class LoggerTest extends TestCase { /* * Test setFilter for an anonymous logger with insufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testSetFilter_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); Filter f = new MockFilter(); @@ -1354,20 +1022,6 @@ public class LoggerTest extends TestCase { /* * Test setFilter for a null-named mock logger with insufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFilter", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setFilter", - args = {java.util.logging.Filter.class} - ) - }) public void testSetFilter_NullNamedMockLoggerInsufficientPrivilege() { MockLogger mlog = new MockLogger(null, null); Filter f = new MockFilter(); @@ -1386,20 +1040,6 @@ public class LoggerTest extends TestCase { * Test getLevel & setLevel with normal value for a named logger, having * sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getLevel & setLevel with normal value for a named logger, having sufficient privilege.", - method = "setLevel", - args = {java.util.logging.Level.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getLevel & setLevel with normal value for a named logger, having sufficient privilege.", - method = "getLevel", - args = {} - ) - }) public void testGetSetLevel_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testGetSetLevel_NamedLoggerSufficientPrivilege"); @@ -1412,20 +1052,6 @@ public class LoggerTest extends TestCase { /* * Test getLevel & setLevel with null value, having sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getLevel & setLevel with null value, having sufficient privilege.", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getLevel & setLevel with null value, having sufficient privilege.", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testGetSetLevel_Null() { Logger log = Logger.getLogger("testGetSetLevel_Null"); @@ -1441,20 +1067,6 @@ public class LoggerTest extends TestCase { * Test setLevel with normal value for a named logger, having insufficient * privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies setLevel with normal value for a named logger, having insufficient privilege.", - method = "setLevel", - args = {java.util.logging.Level.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies setLevel with normal value for a named logger, having insufficient privilege.", - method = "getLevel", - args = {} - ) - }) public void testGetSetLevel_NamedLoggerInsufficientPrivilege() { Logger log = Logger .getLogger("testGetSetLevel_NamedLoggerInsufficientPrivilege"); @@ -1472,20 +1084,6 @@ public class LoggerTest extends TestCase { /* * Test setLevel for an anonymous logger with sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testSetLevel_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); assertNull(log.getLevel()); @@ -1496,20 +1094,6 @@ public class LoggerTest extends TestCase { /* * Test setLevel for an anonymous logger with insufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testSetLevel_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); SecurityManager oldMan = System.getSecurityManager(); @@ -1526,20 +1110,6 @@ public class LoggerTest extends TestCase { /* * Test setLevel for a null-named mock logger with insufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLevel", - args = {java.util.logging.Level.class} - ) - }) public void testSetLevel_NullNamedMockLoggerInsufficientPrivilege() { MockLogger mlog = new MockLogger(null, null); SecurityManager oldMan = System.getSecurityManager(); @@ -1557,20 +1127,6 @@ public class LoggerTest extends TestCase { * Test getUseParentHandlers & setUseParentHandlers with normal value for a * named logger, having sufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getUseParentHandlers", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setUseParentHandlers", - args = {boolean.class} - ) - }) public void testGetSetUseParentHandlers_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testGetSetUseParentHandlers_NamedLoggerSufficientPrivilege"); @@ -1584,20 +1140,6 @@ public class LoggerTest extends TestCase { * Test setUseParentHandlers with normal value for a named logger, having * insufficient privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getUseParentHandlers", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setUseParentHandlers", - args = {boolean.class} - ) - }) public void testGetSetUseParentHandlers_NamedLoggerInsufficientPrivilege() { Logger log = Logger .getLogger("testGetSetUseParentHandlers_NamedLoggerInsufficientPrivilege"); @@ -1616,20 +1158,6 @@ public class LoggerTest extends TestCase { * Test setUseParentHandlers for an anonymous logger with sufficient * privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getUseParentHandlers", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setUseParentHandlers", - args = {boolean.class} - ) - }) public void testSetUseParentHandlers_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); assertTrue(log.getUseParentHandlers()); @@ -1641,20 +1169,6 @@ public class LoggerTest extends TestCase { * Test setUseParentHandlers for an anonymous logger with insufficient * privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getUseParentHandlers", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setUseParentHandlers", - args = {boolean.class} - ) - }) public void testSetUseParentHandlers_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); SecurityManager oldMan = System.getSecurityManager(); @@ -1672,20 +1186,6 @@ public class LoggerTest extends TestCase { * Test setUseParentHandlers for a null-named mock logger with insufficient * privilege. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getUseParentHandlers", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setUseParentHandlers", - args = {boolean.class} - ) - }) public void testSetUseParentHandlers_NullNamedMockLoggerInsufficientPrivilege() { MockLogger mlog = new MockLogger(null, null); SecurityManager oldMan = System.getSecurityManager(); @@ -1702,12 +1202,6 @@ public class LoggerTest extends TestCase { /* * Test getParent() for root logger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getParent() for root logger.", - method = "getParent", - args = {} - ) public void testGetParent_Root() { assertNull(Logger.getLogger("").getParent()); } @@ -1715,12 +1209,6 @@ public class LoggerTest extends TestCase { /* * Test getParent() for normal named loggers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getParent() for normal named loggers.", - method = "getParent", - args = {} - ) public void testGetParent_NormalNamed() { Logger log = Logger.getLogger("testGetParent_NormalNamed"); assertSame(log.getParent(), Logger.getLogger("")); @@ -1733,12 +1221,6 @@ public class LoggerTest extends TestCase { /* * Test getParent() for anonymous loggers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getParent() for anonymous loggers.", - method = "getParent", - args = {} - ) public void testGetParent_Anonymous() { assertSame(Logger.getAnonymousLogger().getParent(), Logger .getLogger("")); @@ -1748,12 +1230,6 @@ public class LoggerTest extends TestCase { * Test setParent(Logger) for the mock logger since it is advised not to * call this method on named loggers. Test normal conditions. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParent", - args = {java.util.logging.Logger.class} - ) public void testSetParent_Normal() { Logger log = new MockLogger(null, null); Logger parent = new MockLogger(null, null); @@ -1765,12 +1241,6 @@ public class LoggerTest extends TestCase { /* * Test setParent(Logger) with null. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParent", - args = {java.util.logging.Logger.class} - ) public void testSetParent_Null() { try { (new MockLogger(null, null)).setParent(null); @@ -1782,12 +1252,6 @@ public class LoggerTest extends TestCase { /* * Test setParent(Logger), having insufficient privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParent", - args = {java.util.logging.Logger.class} - ) public void testSetParent_InsufficientPrivilege() { MockLogger log = new MockLogger(null, null); SecurityManager oldMan = System.getSecurityManager(); @@ -1804,12 +1268,6 @@ public class LoggerTest extends TestCase { /* * Test setParent(Logger) with null, having insufficient privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParent", - args = {java.util.logging.Logger.class} - ) public void testSetParent_InsufficientPrivilegeNull() { MockLogger log = new MockLogger(null, null); SecurityManager oldMan = System.getSecurityManager(); @@ -1827,12 +1285,6 @@ public class LoggerTest extends TestCase { * Test setParent(Logger) for an anonymous logger with insufficient * privilege. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParent", - args = {java.util.logging.Logger.class} - ) public void testSetParent_AnonyLoggerInsufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); SecurityManager oldMan = System.getSecurityManager(); @@ -1849,12 +1301,6 @@ public class LoggerTest extends TestCase { /* * Test getName() for normal names. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getName() for normal names.", - method = "getName", - args = {} - ) public void testGetName_Normal() { Logger log = Logger.getLogger("testGetName_Normal"); assertEquals("testGetName_Normal", log.getName()); @@ -1866,12 +1312,6 @@ public class LoggerTest extends TestCase { /* * Test getName() for empty name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getName() for empty name.", - method = "getName", - args = {} - ) public void testGetName_Empty() { Logger log = Logger.getLogger(""); assertEquals("", log.getName()); @@ -1883,12 +1323,6 @@ public class LoggerTest extends TestCase { /* * Test getName() for null name. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getName() for null name.", - method = "getName", - args = {} - ) public void testGetName_Null() { Logger log = Logger.getAnonymousLogger(); assertNull(log.getName()); @@ -1900,12 +1334,6 @@ public class LoggerTest extends TestCase { /* * Test getResourceBundle() when it it not null. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getResourceBundle() when it it not null.", - method = "getResourceBundle", - args = {} - ) public void testGetResourceBundle_Normal() { Logger log = Logger.getLogger("testGetResourceBundle_Normal", VALID_RESOURCE_BUNDLE); @@ -1918,12 +1346,6 @@ public class LoggerTest extends TestCase { /* * Test getResourceBundle() when it it null. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getResourceBundle() when it it null.", - method = "getResourceBundle", - args = {} - ) public void testGetResourceBundle_Null() { Logger log = Logger.getLogger("testGetResourceBundle_Null", null); assertNull(log.getResourceBundle()); @@ -1936,12 +1358,6 @@ public class LoggerTest extends TestCase { /* * Test getResourceBundleName() when it it not null. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getResourceBundleName() when it it not null.", - method = "getResourceBundleName", - args = {} - ) public void testGetResourceBundleName_Normal() { Logger log = Logger.getLogger("testGetResourceBundleName_Normal", VALID_RESOURCE_BUNDLE); @@ -1954,12 +1370,6 @@ public class LoggerTest extends TestCase { /* * Test getResourceBundleName() when it it null. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies getResourceBundleName() when it it null.", - method = "getResourceBundleName", - args = {} - ) public void testGetResourceBundleName_Null() { Logger log = Logger.getLogger("testGetResourceBundleName_Null", null); assertNull(log.getResourceBundleName()); @@ -1972,12 +1382,6 @@ public class LoggerTest extends TestCase { /* * Test isLoggable(Level). */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isLoggable", - args = {java.util.logging.Level.class} - ) public void testIsLoggable() { MockLogger mlog = new MockLogger(null, null); assertNull(mlog.getLevel()); @@ -2011,12 +1415,6 @@ public class LoggerTest extends TestCase { /* * Test throwing(String, String, Throwable) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "throwing", - args = {java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testThrowing_Normal() { Throwable t = new Throwable(); this.sharedLogger.setLevel(Level.FINER); @@ -2045,12 +1443,6 @@ public class LoggerTest extends TestCase { /* * Test throwing(String, String, Throwable) with null values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "throwing", - args = {java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testThrowing_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2075,12 +1467,6 @@ public class LoggerTest extends TestCase { /* * Test entering(String, String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String) with normal values.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class} - ) public void testEntering_StringString_Normal() { this.sharedLogger.setLevel(Level.FINER); this.sharedLogger.entering("sourceClass", "sourceMethod"); @@ -2105,12 +1491,6 @@ public class LoggerTest extends TestCase { /* * Test entering(String, String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String) with null values.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class} - ) public void testEntering_StringString_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2135,12 +1515,6 @@ public class LoggerTest extends TestCase { /* * Test entering(String, String, Object) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object) with normal values.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testEntering_StringStringObject_Normal() { Object param = new Object(); this.sharedLogger.setLevel(Level.FINER); @@ -2167,12 +1541,6 @@ public class LoggerTest extends TestCase { /* * Test entering(String, String, Object) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object) with null values.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testEntering_StringStringObject_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2198,12 +1566,6 @@ public class LoggerTest extends TestCase { /* * Test entering(String, String, Object[]) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object[]) with normal values.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testEntering_StringStringObjects_Normal() { Object[] params = new Object[2]; params[0] = new Object(); @@ -2234,12 +1596,6 @@ public class LoggerTest extends TestCase { * Test entering(String, String, Object[]) with null class name and method * name and empty parameter array. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object[]) with null class name and method name and empty parameter array.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testEntering_StringStringObjects_NullEmpty() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2265,12 +1621,6 @@ public class LoggerTest extends TestCase { * Test entering(String, String, Object[]) with null values with appropriate * logging level set. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object[]) with null values with appropriate logging level set.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testEntering_StringStringObjects_Null() { sharedLogger.setLevel(Level.FINER); sharedLogger.entering(null, null, (Object[]) null); @@ -2293,12 +1643,6 @@ public class LoggerTest extends TestCase { * Test entering(String, String, Object[]) with null values with * inappropriate logging level set. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies entering(String, String, Object[]) with null values with inappropriate logging level set.", - method = "entering", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testEntering_StringStringObjects_NullDisabled() { this.sharedLogger.setLevel(Level.FINE); this.sharedLogger.entering(null, null, (Object[]) null); @@ -2308,12 +1652,6 @@ public class LoggerTest extends TestCase { /* * Test exiting(String, String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies exiting(String, String) with normal values.", - method = "exiting", - args = {java.lang.String.class, java.lang.String.class} - ) public void testExiting_StringString_Normal() { this.sharedLogger.setLevel(Level.FINER); this.sharedLogger.exiting("sourceClass", "sourceMethod"); @@ -2338,12 +1676,6 @@ public class LoggerTest extends TestCase { /* * Test exiting(String, String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies exiting(String, String) with null values.", - method = "exiting", - args = {java.lang.String.class, java.lang.String.class} - ) public void testExiting_StringString_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2368,12 +1700,6 @@ public class LoggerTest extends TestCase { /* * Test exiting(String, String, Object) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies exiting(String, String, Object) with normal values.", - method = "exiting", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testExiting_StringStringObject_Normal() { Object param = new Object(); this.sharedLogger.setLevel(Level.FINER); @@ -2400,12 +1726,6 @@ public class LoggerTest extends TestCase { /* * Test exiting(String, String, Object) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies exiting(String, String, Object) with null values.", - method = "exiting", - args = {java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testExiting_StringStringObject_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2431,12 +1751,6 @@ public class LoggerTest extends TestCase { /* * Test config(String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "config", - args = {java.lang.String.class} - ) public void testConfig_Normal() { this.sharedLogger.setLevel(Level.CONFIG); this.sharedLogger.config("config msg"); @@ -2461,12 +1775,6 @@ public class LoggerTest extends TestCase { /* * Test config(String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "config", - args = {java.lang.String.class} - ) public void testConfig_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2495,12 +1803,6 @@ public class LoggerTest extends TestCase { /* * Test fine(String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "fine", - args = {java.lang.String.class} - ) public void testFine_Normal() { this.sharedLogger.setLevel(Level.FINE); this.sharedLogger.fine("fine msg"); @@ -2525,12 +1827,6 @@ public class LoggerTest extends TestCase { /* * Test fine(String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies fine(String) with null values.", - method = "fine", - args = {java.lang.String.class} - ) public void testFine_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2559,12 +1855,6 @@ public class LoggerTest extends TestCase { /* * Test finer(String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies finer(String) with normal values.", - method = "finer", - args = {java.lang.String.class} - ) public void testFiner_Normal() { this.sharedLogger.setLevel(Level.FINER); this.sharedLogger.finer("finer msg"); @@ -2589,12 +1879,6 @@ public class LoggerTest extends TestCase { /* * Test finer(String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies finer(String) with null values.", - method = "finer", - args = {java.lang.String.class} - ) public void testFiner_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2623,12 +1907,6 @@ public class LoggerTest extends TestCase { /* * Test finest(String) with normal values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies finest(String) with normal values.", - method = "finest", - args = {java.lang.String.class} - ) public void testFinest_Normal() { this.sharedLogger.setLevel(Level.FINEST); this.sharedLogger.finest("finest msg"); @@ -2653,12 +1931,6 @@ public class LoggerTest extends TestCase { /* * Test finest(String) with null values. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies finest(String) with null values.", - method = "finest", - args = {java.lang.String.class} - ) public void testFinest_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2687,12 +1959,6 @@ public class LoggerTest extends TestCase { /* * Test info(String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "info", - args = {java.lang.String.class} - ) public void testInfo_Normal() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.info("info msg"); @@ -2717,12 +1983,6 @@ public class LoggerTest extends TestCase { /* * Test info(String) with null values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "info", - args = {java.lang.String.class} - ) public void testInfo_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2751,12 +2011,6 @@ public class LoggerTest extends TestCase { /* * Test warning(String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "warning", - args = {java.lang.String.class} - ) public void testWarning_Normal() { this.sharedLogger.setLevel(Level.WARNING); this.sharedLogger.warning("warning msg"); @@ -2781,12 +2035,6 @@ public class LoggerTest extends TestCase { /* * Test warning(String) with null values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "warning", - args = {java.lang.String.class} - ) public void testWarning_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2815,12 +2063,6 @@ public class LoggerTest extends TestCase { /* * Test severe(String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "severe", - args = {java.lang.String.class} - ) public void testSevere_Normal() { this.sharedLogger.setLevel(Level.SEVERE); this.sharedLogger.severe("severe msg"); @@ -2845,12 +2087,6 @@ public class LoggerTest extends TestCase { /* * Test severe(String) with null values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "severe", - args = {java.lang.String.class} - ) public void testSevere_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2879,12 +2115,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class} - ) public void testLog_LevelString_Normal() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.log(Level.INFO, "log(Level, String) msg"); @@ -2911,12 +2141,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String) with null message. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class} - ) public void testLog_LevelString_NullMsg() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -2941,12 +2165,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class} - ) public void testLog_LevelString_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -2959,12 +2177,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object.class} - ) public void testLog_LevelStringObject_Normal() { Object param = new Object(); this.sharedLogger.setLevel(Level.INFO); @@ -2996,12 +2208,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object) with null message and object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object.class} - ) public void testLog_LevelStringObject_NullMsgObj() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3027,12 +2233,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object.class} - ) public void testLog_LevelStringObject_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3046,12 +2246,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object[]) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLog_LevelStringObjects_Normal() { Object[] params = new Object[2]; @@ -3087,12 +2281,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object[]) with null message and object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLog_LevelStringObjects_NullMsgObj() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3117,12 +2305,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Object[]) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLog_LevelStringObjects_NullLevel() { try { this.sharedLogger.log(null, "log(Level, String, Object[]) msg", @@ -3135,12 +2317,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Throwable) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLog_LevelStringThrowable_Normal() { Throwable t = new Throwable(); this.sharedLogger.setLevel(Level.INFO); @@ -3171,12 +2347,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Throwable) with null message and throwable. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLog_LevelStringThrowable_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3201,12 +2371,6 @@ public class LoggerTest extends TestCase { /* * Test log(Level, String, Throwable) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLog_LevelStringThrowable_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3220,12 +2384,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogp_LevelStringStringString_Normal() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logp(Level.INFO, "sourceClass", "sourceMethod", @@ -3255,12 +2413,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String) with null message. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogp_LevelStringStringString_NullMsg() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3285,12 +2437,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogp_LevelStringStringString_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3304,12 +2450,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Object) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogp_LevelStringStringStringObject_Normal() { Object param = new Object(); this.sharedLogger.setLevel(Level.INFO); @@ -3343,12 +2483,6 @@ public class LoggerTest extends TestCase { * Test logp(Level, String, String, String, Object) with null message and * object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogp_LevelStringStringStringObject_NullMsgObj() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3374,13 +2508,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Object) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) - public void testLogp_LevelStringStringStringObject_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3395,13 +2522,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Object[]) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) - public void testLogp_LevelStringStringStringObjects_Normal() { Object[] params = new Object[2]; params[0] = new Object(); @@ -3438,12 +2558,6 @@ public class LoggerTest extends TestCase { * Test logp(Level, String, String, String, Object[]) with null message and * object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLogp_LevelStringStringStringObjects_NullMsgObj() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3468,12 +2582,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Object[]) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLogp_LevelStringStringStringObjects_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3488,12 +2596,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Throwable) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogp_LevelStringStringStringThrowable_Normal() { Throwable t = new Throwable(); this.sharedLogger.setLevel(Level.INFO); @@ -3526,12 +2628,6 @@ public class LoggerTest extends TestCase { * Test logp(Level, String, String, String, Throwable) with null message and * throwable. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogp_LevelStringStringStringThrowable_Null() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -3556,12 +2652,6 @@ public class LoggerTest extends TestCase { /* * Test logp(Level, String, String, String, Throwable) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logp", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogp_LevelStringStringStringThrowable_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3576,12 +2666,6 @@ public class LoggerTest extends TestCase { /* * Test logrb(Level, String, String, String, String) with normal values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogrb_LevelStringStringString_Normal() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logrb(Level.INFO, "sourceClass", "sourceMethod", @@ -3614,12 +2698,6 @@ public class LoggerTest extends TestCase { /* * Test logrb(Level, String, String, String, String) with null message. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogrb_LevelStringStringString_NullMsg() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logrb(Level.INFO, null, null, null, null); @@ -3638,12 +2716,6 @@ public class LoggerTest extends TestCase { /* * Test logrb(Level, String, String, String) with null level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogrb_LevelStringStringString_NullLevel() { try { this.sharedLogger.logrb(null, "sourceClass", "sourceMethod", @@ -3658,12 +2730,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String) with invalid resource * bundle. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void testLogrb_LevelStringStringString_InvalidRes() { this.sharedLogger.setLevel(Level.ALL); this.sharedLogger.logrb(Level.ALL, "sourceClass", "sourceMethod", @@ -3687,12 +2753,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object) with normal * values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogrb_LevelStringStringStringObject_Normal() { Object param = new Object(); this.sharedLogger.setLevel(Level.INFO); @@ -3730,12 +2790,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object) with null * message and object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogrb_LevelStringStringStringObject_NullMsgObj() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logrb(Level.INFO, null, null, null, null, @@ -3757,12 +2811,6 @@ public class LoggerTest extends TestCase { * java.util.logging.Logger#logrb(Level, String, String, String, String, * Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test.", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) public void test_logrbLLevel_LString_LString_LObject_Security() throws Exception { // regression test for Harmony-1290 @@ -3779,12 +2827,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object) with null * level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogrb_LevelStringStringStringObject_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -3801,12 +2843,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object) with invalid * resource bundle. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class} - ) public void testLogrb_LevelStringStringStringObject_InvalidRes() { Object param = new Object(); this.sharedLogger.setLevel(Level.ALL); @@ -3831,13 +2867,7 @@ public class LoggerTest extends TestCase { /* * Test logrb(Level, String, String, String, String, Object[]) with normal * values. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) + */ public void testLogrb_LevelStringStringStringObjects_Normal() { Object[] params = new Object[2]; params[0] = new Object(); @@ -3878,12 +2908,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object[]) with null * message and object. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLogrb_LevelStringStringStringObjects_NullMsgObj() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logrb(Level.INFO, null, null, null, null, @@ -3904,12 +2928,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object[]) with null * level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLogrb_LevelStringStringStringObjects_NullLevel() { try { this.sharedLogger.logrb( @@ -3928,12 +2946,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Object[]) with invalid * resource bundle. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class} - ) public void testLogrb_LevelStringStringStringObjects_InvalidRes() { Object[] params = new Object[2]; params[0] = new Object(); @@ -3962,12 +2974,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Throwable) with normal * values. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogrb_LevelStringStringStringThrowable_Normal() { Throwable t = new Throwable(); this.sharedLogger.setLevel(Level.INFO); @@ -4005,12 +3011,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Throwable) with null * message and throwable. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogrb_LevelStringTStringStringhrowable_NullMsgObj() { this.sharedLogger.setLevel(Level.INFO); this.sharedLogger.logrb(Level.INFO, null, null, null, null, @@ -4031,12 +3031,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Throwable) with null * level. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogrb_LevelStringStringStringThrowable_NullLevel() { // this.sharedLogger.setLevel(Level.OFF); try { @@ -4056,12 +3050,6 @@ public class LoggerTest extends TestCase { * Test logrb(Level, String, String, String, String, Throwable) with invalid * resource bundle. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "logrb", - args = {java.util.logging.Level.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Throwable.class} - ) public void testLogrb_LevelStringStringStringThrowable_InvalidRes() { Throwable t = new Throwable(); this.sharedLogger.setLevel(Level.ALL); @@ -4086,12 +3074,6 @@ public class LoggerTest extends TestCase { * Test log(LogRecord) for a normal log record. Meanwhile the logger has an * appropriate level, no filter, no parent. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_LogRecord_AppropriateLevelNoFilterNoParent() { LogRecord r = new LogRecord(Level.INFO, "testLog_LogRecord_AppropriateLevelNoFilterNoParent"); @@ -4115,12 +3097,6 @@ public class LoggerTest extends TestCase { /* * Test log(LogRecord) with null log record. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_LogRecord_Null() { this.sharedLogger.setLevel(Level.INFO); try { @@ -4134,12 +3110,6 @@ public class LoggerTest extends TestCase { * Test log(LogRecord) for a normal log record. Meanwhile the logger has an * inappropriate level, no filter, no parent. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_LogRecord_InppropriateLevelNoFilterNoParent() { LogRecord r = new LogRecord(Level.INFO, "testLog_LogRecord_InppropriateLevelNoFilterNoParent"); @@ -4158,12 +3128,6 @@ public class LoggerTest extends TestCase { * Test log(LogRecord) for a normal log record. Meanwhile the logger has an * appropriate level, a filter that accepts the fed log record, no parent. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_LogRecord_AppropriateLevelTrueFilterNoParent() { LogRecord r = new LogRecord(Level.INFO, "testLog_LogRecord_AppropriateLevelTrueFilterNoParent"); @@ -4192,12 +3156,6 @@ public class LoggerTest extends TestCase { * Test log(LogRecord) for a normal log record. Meanwhile the logger has an * appropriate level, a filter that rejects the fed log record, no parent. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_LogRecord_AppropriateLevelFalseFilterNoParent() { LogRecord r = new LogRecord(Level.INFO, "testLog_LogRecord_AppropriateLevelFalseFilterNoParent"); @@ -4225,12 +3183,6 @@ public class LoggerTest extends TestCase { * Test that the parent's handler is notified for a new log record when * getUseParentHandlers() is true. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_ParentInformed() { Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); Logger parent = new MockParentLogger("parentLogger", @@ -4283,12 +3235,6 @@ public class LoggerTest extends TestCase { * Test that the ancestor's handler is notified for a new log record when * getUseParentHandlers() is true. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_AncestorInformed() { Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); Logger parent = new MockParentLogger("parentLogger", @@ -4335,12 +3281,6 @@ public class LoggerTest extends TestCase { * Test that the parent's handler is notified for a new log record when * getUseParentHandlers() is false. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_ParentNotInformed() { Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); Logger parent = new MockParentLogger("parentLogger", @@ -4361,12 +3301,6 @@ public class LoggerTest extends TestCase { * Test that a logger with null level and no parent. Defaulted to * Level.INFO. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_NullLevelNoParent() { LogRecord r = new LogRecord(Level.INFO, "testLog_NullLevelNoParent"); assertNull(this.sharedLogger.getLevel()); @@ -4392,12 +3326,6 @@ public class LoggerTest extends TestCase { /* * Test that a logger inherits its parent level when its level is null. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_NullLevelHasParent() { Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -4450,12 +3378,6 @@ public class LoggerTest extends TestCase { * Test that a logger with null resource bundle and no parent. Defaulted to * null. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_NullResNoParent() { Logger log = new MockLogger("Logger", null); log.addHandler(new MockHandler()); @@ -4477,12 +3399,6 @@ public class LoggerTest extends TestCase { * Test that a logger inherits its parent resource bundle when its resource * bundle is null. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_NullResHasParent() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); @@ -4513,12 +3429,6 @@ public class LoggerTest extends TestCase { * Test that a logger inherits its ancestor's resource bundle when its * resource bundle and its parent's resource bundle are both null. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_NullResHasAncestor() { Logger child = new MockLogger("childLogger", null); Logger parent = new MockLogger("parentLogger", null); @@ -4551,12 +3461,6 @@ public class LoggerTest extends TestCase { /* * Test when one handler throws an exception. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "log", - args = {java.util.logging.LogRecord.class} - ) public void testLog_ExceptionalHandler() { MockLogger l = new MockLogger("testLog_ExceptionalHandler", null); l.addHandler(new MockExceptionalHandler()); @@ -4572,12 +3476,6 @@ public class LoggerTest extends TestCase { /* * Test whether privileged code is used to load resource bundles. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAnonymousLogger", - args = {java.lang.String.class} - ) public void testLoadResourceBundle() { // SecurityManager oldMan = System.getSecurityManager(); @@ -4594,12 +3492,6 @@ public class LoggerTest extends TestCase { * java.util.logging.Logger#logrb(Level, String, String, String, String, * Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getLogger", - args = {java.lang.String.class} - ) public void test_init_logger() throws Exception { Properties p = new Properties(); p.put("testGetLogger_Normal_ANewLogger2.level", "ALL"); @@ -4633,12 +3525,6 @@ public class LoggerTest extends TestCase { /* * test initHandler */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "initHandler", - args = {} - ) public void test_initHandler() throws Exception { File logProps = new File(LOGGING_CONFIG_FILE); LogManager lm = LogManager.getLogManager(); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingMXBeanTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingMXBeanTest.java index c9b7d50..36cfb33 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingMXBeanTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingMXBeanTest.java @@ -16,11 +16,6 @@ */ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestLevel; - import junit.framework.TestCase; import tests.util.CallVerificationStack; @@ -31,7 +26,6 @@ import java.util.logging.LoggingMXBean; * This testcase verifies the signature of the interface Filter. * */ -@TestTargetClass(LoggingMXBean.class) public class LoggingMXBeanTest extends TestCase { private MockLoggingMXBean m = null; @@ -53,43 +47,19 @@ public class LoggingMXBeanTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLoggerLevel", - args = {java.lang.String.class} - ) public void testGetLoggerLevel() { assertNull(m.getLoggerLevel(null)); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLoggerNames", - args = {} - ) public void testGetLoggerNames() { assertNull(m.getLoggerNames()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getParentLoggerName", - args = {java.lang.String.class} - ) public void testGetParentLoggerName() { assertNull(m.getParentLoggerName(null)); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLoggerLevel", - args = {java.lang.String.class, java.lang.String.class} - ) public void testSetLoggerLevel() { try{ m.setLoggerLevel(null,null); diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java index 9507bbd..aa8f7fa 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java @@ -17,29 +17,17 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.util.logging.LoggingPermission; import junit.framework.TestCase; import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(LoggingPermission.class) public class LoggingPermissionTest extends TestCase { /** * @tests serialization/deserialization compatibility. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new LoggingPermission("control", "")); } @@ -47,55 +35,43 @@ public class LoggingPermissionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new LoggingPermission("control", "")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LoggingPermission", - args = {java.lang.String.class, java.lang.String.class} - ) - public void testLoggingPermission() { - try { - new LoggingPermission(null, null); - fail("should throw IllegalArgumentException"); - } catch (NullPointerException e) { - } - try { - new LoggingPermission("", null); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - try { - new LoggingPermission("bad name", null); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - try { - new LoggingPermission("Control", null); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - try { - new LoggingPermission("control", - "bad action"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - + public void testLoggingPermission() { + try { + new LoggingPermission(null, null); + fail("should throw IllegalArgumentException"); + } catch (NullPointerException e) { + } + try { + new LoggingPermission("", null); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + new LoggingPermission("bad name", null); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + new LoggingPermission("Control", null); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + new LoggingPermission("control", + "bad action"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + new LoggingPermission("control", ""); - + new LoggingPermission("control", null); - } + } } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java index 9aa344a..89629c7 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; @@ -47,7 +42,6 @@ import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper /** * */ -@TestTargetClass(MemoryHandler.class) public class MemoryHandlerTest extends TestCase { final static LogManager manager = LogManager.getLogManager(); @@ -107,50 +101,6 @@ public class MemoryHandlerTest extends TestCase { System.setErr(err); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "close", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "setPushLevel", - args = {java.util.logging.Level.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "flush", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "push", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "getPushLevel", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SecurityException", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - }) public void testGlobalSecurity() { SecurityManager currentManager = System.getSecurityManager(); System.setSecurityManager(securityManager); @@ -176,12 +126,6 @@ public class MemoryHandlerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "close", - args = {} - ) public void testClose() { Filter filter = handler.getFilter(); Formatter formatter = handler.getFormatter(); @@ -197,12 +141,6 @@ public class MemoryHandlerTest extends TestCase { assertFalse(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "flush", - args = {} - ) public void testFlush() { Filter filter = handler.getFilter(); Formatter formatter = handler.getFormatter(); @@ -218,12 +156,6 @@ public class MemoryHandlerTest extends TestCase { assertTrue(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) public void testIsLoggable() { try { handler.isLoggable(null); @@ -255,12 +187,6 @@ public class MemoryHandlerTest extends TestCase { /* * Class under test for void MemoryHandler() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "check errors", - method = "MemoryHandler", - args = {} - ) public void testMemoryHandler() throws IOException { assertNotNull("Filter should not be null", handler.getFilter()); assertNotNull("Formatter should not be null", handler.getFormatter()); @@ -287,12 +213,6 @@ public class MemoryHandlerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MemoryHandler", - args = {} - ) public void testMemoryHandlerInvalidProps() throws IOException { // null target try { @@ -360,12 +280,6 @@ public class MemoryHandlerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MemoryHandler", - args = {} - ) public void testMemoryHandlerDefaultValue() throws SecurityException, IOException { props.clear(); @@ -386,12 +300,6 @@ public class MemoryHandlerTest extends TestCase { /* * Class under test for void MemoryHandler(Handler, int, Level) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MemoryHandler", - args = {java.util.logging.Handler.class, int.class, java.util.logging.Level.class} - ) public void testMemoryHandlerHandlerintLevel() { handler = new MemoryHandler(target, 2, Level.FINEST); assertNotNull("Filter should not be null", handler.getFilter()); @@ -426,12 +334,6 @@ public class MemoryHandlerTest extends TestCase { } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPushLevel", - args = {} - ) public void testGetPushLevel() { try { handler.setPushLevel(null); @@ -442,12 +344,6 @@ public class MemoryHandlerTest extends TestCase { assertEquals(handler.getPushLevel(), Level.parse("123")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setPushLevel", - args = {java.util.logging.Level.class} - ) public void testSetPushLevel() { // change push level don't trigger push action writer.getBuffer().setLength(0); @@ -462,12 +358,6 @@ public class MemoryHandlerTest extends TestCase { assertEquals(writer.toString(), lr.getMessage() + lr.getMessage()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "push", - args = {} - ) public void testPushPublic() { writer.getBuffer().setLength(0); // loggable but don't trig push diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MessagesTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MessagesTest.java index 74edbcb..e045a4b 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MessagesTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MessagesTest.java @@ -26,15 +26,9 @@ import java.io.OutputStream; import java.io.PrintStream; import java.util.logging.ErrorManager; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; -@TestTargetClass(Messages.class) public class MessagesTest extends TestCase{ @@ -51,68 +45,26 @@ public class MessagesTest extends TestCase{ } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Just check signature, cannot make use of mock, method depend on luni", - method = "getString", - args = {java.lang.String.class} - ) - @AndroidOnly("harmony specific") public void testGetString_String() { m.getString(new String()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Juste check signature, cannot make use of mock, depend on luni", - method = "getString", - args = {java.lang.String.class, java.lang.Object.class} - ) - @AndroidOnly("harmony specific") public void testGetString_StringObject() { m.getString(new String(), new Object()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Juste check signature, cannot make use of mock, depend on luni", - method = "getString", - args = {java.lang.String.class, int.class} - ) - @AndroidOnly("harmony specific") public void testGetString_StringInt() { m.getString(new String(), 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Juste check signature, cannot make use of mock, depend on luni", - method = "getString", - args = {java.lang.String.class, char.class} - ) - @AndroidOnly("harmony specific") public void testGetString_StringChar() { m.getString(new String(), 'a'); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Juste check signature, cannot make use of mock, depend on luni", - method = "getString", - args = {java.lang.String.class, java.lang.Object.class, java.lang.Object.class} - ) - @AndroidOnly("harmony specific") public void testGetString_StringObjectObject() { m.getString(new String(), new Object(), new Object() ); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Juste check signature, cannot make use of mock, depend on luni", - method = "getString", - args = {java.lang.String.class, java.lang.Object[].class} - ) - @AndroidOnly("harmony specific") public void testGetString_StringObjectArray() { m.getString(new String(), new Object[1]); } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java index 79e37e8..16d051d 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.util.Calendar; import java.util.ResourceBundle; import java.util.logging.Handler; @@ -35,7 +30,6 @@ import junit.framework.TestCase; /** * */ -@TestTargetClass(SimpleFormatter.class) public class SimpleFormatterTest extends TestCase { SimpleFormatter sf; @@ -56,38 +50,12 @@ public class SimpleFormatterTest extends TestCase { /* * test for constructor protected SimpleFormatter */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SimpleFormatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {java.util.logging.Handler.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ) - }) public void testSimpleFormatter() { assertEquals("Head for this SimpleFormatter should be empty", "", sf .getHead(null)); assertEquals("Tail for this SimpleFormatter should be empty", "", sf .getTail(null)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testFormatNull() { try { sf.format(null); @@ -97,12 +65,6 @@ public class SimpleFormatterTest extends TestCase { sf.format(new LogRecord(Level.SEVERE, null)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testLocalizedFormat() { // if bundle set, should use localized message ResourceBundle rb = ResourceBundle @@ -122,12 +84,6 @@ public class SimpleFormatterTest extends TestCase { assertTrue(str.indexOf(localeMsg) < 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testFormat() { String str = sf.format(lr); Throwable t; @@ -159,22 +115,10 @@ public class SimpleFormatterTest extends TestCase { assertTrue(str.indexOf(Level.FINE.getLocalizedName()) > 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {java.util.logging.Handler.class} - ) public void testGetHead() { assertEquals("", sf.getHead(null)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ) public void testGetTail() { assertEquals("", sf.getTail(null)); } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SocketHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SocketHandlerTest.java index cc3b165..bbf30b0 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SocketHandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SocketHandlerTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; @@ -52,7 +47,6 @@ import tests.util.CallVerificationStack; /** * Test class java.util.logging.ConsoleHandler */ -@TestTargetClass(SocketHandler.class) public class SocketHandlerTest extends TestCase { private static final LogManager LOG_MANAGER = LogManager.getLogManager(); @@ -116,20 +110,6 @@ public class SocketHandlerTest extends TestCase { /* * Test the constructor with no relevant log manager properties are set. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no relevant log manager properties are set.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no relevant log manager properties are set.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_NoProperties() throws Exception { assertNull(LOG_MANAGER.getProperty( "java.util.logging.SocketHandler.level")); @@ -205,20 +185,6 @@ public class SocketHandlerTest extends TestCase { * Test the constructor with no relevant log manager properties are set * except host and port. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no relevant log manager properties are set except host and port.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no relevant log manager properties are set except host and port.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_NoBasicProperties() throws Exception { assertNull(LOG_MANAGER.getProperty( "java.util.logging.SocketHandler.level")); @@ -258,20 +224,6 @@ public class SocketHandlerTest extends TestCase { /* * Test the constructor with insufficient privilege for connection. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_InsufficientPrivilege() throws Exception { SecurityManager oldMan = null; Properties p = new Properties(); @@ -308,20 +260,6 @@ public class SocketHandlerTest extends TestCase { /* * Test the constructor with valid relevant log manager properties are set. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with valid relevant log manager properties are set.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with valid relevant log manager properties are set.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_ValidProperties() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.level", "FINE"); @@ -368,20 +306,6 @@ public class SocketHandlerTest extends TestCase { * Test the constructor with invalid relevant log manager properties are set * except host and port. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with invalid relevant log manager properties are set except host and port.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with invalid relevant log manager properties are set except host and port.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_InvalidBasicProperties() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.level", INVALID_LEVEL); @@ -430,12 +354,6 @@ public class SocketHandlerTest extends TestCase { * Test the constructor with valid relevant log manager properties are set * except port. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IllegalArgumentException.", - method = "SocketHandler", - args = {} - ) public void testConstructor_InvalidPort() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.level", "FINE"); @@ -461,20 +379,6 @@ public class SocketHandlerTest extends TestCase { * Test the constructor with valid relevant log manager properties are set, * but the port is not open. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that the constructor with valid relevant log manager properties are set, but the port is not open.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that the constructor with valid relevant log manager properties are set, but the port is not open.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_NotOpenPort() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.level", "FINE"); @@ -507,20 +411,6 @@ public class SocketHandlerTest extends TestCase { * Test the constructor with valid relevant log manager properties are set * except port. */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IOException.", - method = "SocketHandler", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IOException.", - method = "SocketHandler", - args = {java.lang.String.class, int.class} - ) - }) public void testConstructor_InvalidHost() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.level", "FINE"); @@ -553,12 +443,6 @@ public class SocketHandlerTest extends TestCase { * Test close() when having sufficient privilege, and a record has been * written to the output stream. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and a record has been written to the output stream.", - method = "close", - args = {} - ) public void testClose_SufficientPrivilege_NormalClose() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -587,12 +471,6 @@ public class SocketHandlerTest extends TestCase { * Test close() when having sufficient privilege, and no record has been * written to the output stream. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and no record has been written to the output stream.", - method = "close", - args = {} - ) public void testClose_SufficientPrivilege_DirectClose() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -618,12 +496,6 @@ public class SocketHandlerTest extends TestCase { /* * Test close() when having insufficient privilege. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having insufficient privilege.", - method = "close", - args = {} - ) public void testClose_InsufficientPrivilege() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -658,12 +530,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), use no filter, having output stream, normal log record. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use no filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_NoFilter() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -703,12 +569,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), use a filter, having output stream, normal log record. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use a filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_WithFilter() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -739,12 +599,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), null log record, having output stream */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), null log record, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_Null() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -772,12 +626,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), a log record with empty msg, having output stream */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish() method, a log record with empty msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_EmptyMsg() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -803,12 +651,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), a log record with null msg, having output stream */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), a log record with null msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_NullMsg() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className @@ -834,12 +676,6 @@ public class SocketHandlerTest extends TestCase { /* * Test publish(), after close. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish() method after close.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) public void testPublish_AfterClose() throws Exception { Properties p = new Properties(); p.put("java.util.logging.SocketHandler.formatter", className diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java index 72270e5..76380e6 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java @@ -17,8 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.*; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -39,7 +37,6 @@ import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.LoggingPermission; import java.util.logging.SimpleFormatter; -import java.util.logging.SocketHandler; import java.util.logging.StreamHandler; import junit.framework.TestCase; @@ -51,1274 +48,1035 @@ import tests.util.CallVerificationStack; /** * Test the class StreamHandler. */ -@TestTargetClass(StreamHandler.class) public class StreamHandlerTest extends TestCase { - private final static String INVALID_LEVEL = "impossible_level"; + private final static String INVALID_LEVEL = "impossible_level"; private final PrintStream err = System.err; private OutputStream errSubstituteStream = null; - private static String className = StreamHandlerTest.class.getName(); + private static String className = StreamHandlerTest.class.getName(); - private static CharsetEncoder encoder; + private static CharsetEncoder encoder; - static { - encoder = Charset.forName("iso-8859-1").newEncoder(); - encoder.onMalformedInput(CodingErrorAction.REPLACE); - encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); - } + static { + encoder = Charset.forName("iso-8859-1").newEncoder(); + encoder.onMalformedInput(CodingErrorAction.REPLACE); + encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + } - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); errSubstituteStream = new NullOutputStream(); System.setErr(new PrintStream(errSubstituteStream)); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - LogManager.getLogManager().reset(); - CallVerificationStack.getInstance().clear(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + LogManager.getLogManager().reset(); + CallVerificationStack.getInstance().clear(); System.setErr(err); super.tearDown(); - } - - /* - * Test the constructor with no parameter, and no relevant log manager - * properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no parameter, and no relevant log manager properties are set.", - method = "StreamHandler", - args = {} - ) - public void testConstructor_NoParameter_NoProperties() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with insufficient privilege.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_NoParameter_InsufficientPrivilege() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test the constructor with no parameter, and valid relevant log manager - * properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no parameter, and valid relevant log manager properties are set.", - method = "StreamHandler", - args = {} - ) - public void testConstructor_NoParameter_ValidProperties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(); - assertSame(h.getLevel(), Level.parse("FINE")); - assertTrue(h.getFormatter() instanceof MockFormatter); - assertTrue(h.getFilter() instanceof MockFilter); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test the constructor with no parameter, and invalid relevant log manager - * properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with no parameter, and invalid relevant log manager properties are set.", - method = "StreamHandler", - args = {} - ) - public void testConstructor_NoParameter_InvalidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); - p.put("java.util.logging.StreamHandler.filter", className + ""); - p.put("java.util.logging.StreamHandler.formatter", className + ""); - p.put("java.util.logging.StreamHandler.encoding", "XXXX"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("XXXX", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - h.publish(new LogRecord(Level.SEVERE, "test")); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with normal parameter values, and no relevant log - * manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with normal parameter values, and no relevant log manager properties are set.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameters_NoProperties() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with insufficient privilege.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameter_InsufficientPrivilege() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test the constructor with normal parameter values, and valid relevant log - * manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with normal parameter values, and valid relevant log manager properties are set.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameters_ValidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(h.getLevel(), Level.parse("FINE")); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertTrue(h.getFilter() instanceof MockFilter); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test the constructor with normal parameter, and invalid relevant log - * manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with normal parameter, and invalid relevant log manager properties are set.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameters_InvalidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); - p.put("java.util.logging.StreamHandler.filter", className + ""); - p.put("java.util.logging.StreamHandler.formatter", className + ""); - p.put("java.util.logging.StreamHandler.encoding", "XXXX"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("XXXX", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with null formatter, and invalid relevant log manager - * properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with null formatter, and invalid relevant log manager properties are set.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameters_ValidPropertiesNullStream() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - try { - new StreamHandler(new ByteArrayOutputStream(), null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test the constructor with null output stream, and invalid relevant log - * manager properties are set. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies the constructor with null output stream, and invalid relevant log manager properties are set.", - method = "StreamHandler", - args = {java.io.OutputStream.class, java.util.logging.Formatter.class} - ) - public void testConstructor_HasParameters_ValidPropertiesNullFormatter() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - try { - new StreamHandler(null, new MockFormatter2()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test close() when having sufficient privilege, and a record has been - * written to the output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and a record has been written to the output stream.", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_NormalClose() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.publish(new LogRecord(Level.SEVERE, - "testClose_SufficientPrivilege_NormalClose msg")); - h.close(); - assertEquals("close", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - CallVerificationStack.getInstance().clear(); - assertTrue(aos.toString().endsWith("MockFormatter_Tail")); - h.close(); - } - - /* - * Test close() when having sufficient privilege, and an output stream that - * always throws exceptions. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() when having sufficient privilege, and an output stream that always throws exceptions.", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_Exception() { - ByteArrayOutputStream aos = new MockExceptionOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.publish(new LogRecord(Level.SEVERE, - "testClose_SufficientPrivilege_Exception msg")); - h.flush(); - h.close(); - } - - /* - * Test close() when having sufficient privilege, and no record has been - * written to the output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() method when having sufficient privilege, and no record has been written to the output stream.", - method = "close", - args = {} - ) - public void testClose_SufficientPrivilege_DirectClose() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.close(); - assertEquals("close", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - CallVerificationStack.getInstance().clear(); - assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString()); - } - - /* - * Test close() when having insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies SecurityException.", - method = "close", - args = {} - ) - public void testClose_InsufficientPrivilege() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter()); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - h.close(); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test close() when having no output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies close() method when having no output stream.", - method = "close", - args = {} - ) - public void testClose_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.close(); - } - - /* - * Test flush(). - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies flush() method.", - method = "flush", - args = {} - ) - public void testFlush_Normal() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.flush(); - assertEquals("flush", CallVerificationStack.getInstance().getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - CallVerificationStack.getInstance().clear(); - } - - /* - * Test flush() when having no output stream. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies flush() when having no output stream.", - method = "flush", - args = {} - ) - public void testFlush_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.flush(); - } - - /* - * Test isLoggable(), use no filter, having no output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies isLoggable(), use no filter, having no output stream.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_NoOutputStream() { - StreamHandler h = new StreamHandler(); - LogRecord r = new LogRecord(Level.INFO, null); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Test isLoggable(), use no filter, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies isLoggable(), use no filter, having output stream.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_NoFilter() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertTrue(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Test isLoggable(), use a filter, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies isLoggable(), use a filter, having output stream.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_WithFilter() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - h.setFilter(new MockFilter()); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); //level to high, data will not reach the filter - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test isLoggable(), null log record, having output stream. Handler should - * call ErrorManager to handle exceptional case - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies isLoggable(), null log record, having output stream. Handler should call ErrorManager to handle exceptional case.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_Null() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - assertFalse(h.isLoggable(null)); - } - - /* - * Test isLoggable(), null log record, without output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies isLoggable(), null log record, without output stream.", - method = "isLoggable", - args = {java.util.logging.LogRecord.class} - ) - public void testIsLoggable_Null_NoOutputStream() { - StreamHandler h = new StreamHandler(); - assertFalse(h.isLoggable(null)); - } - - /* - * Test publish(), use no filter, having output stream, normal log record. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use no filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_NoOutputStream() { - StreamHandler h = new StreamHandler(); - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoOutputStream"); - h.publish(r); - - h.setLevel(Level.WARNING); - h.publish(r); - - h.setLevel(Level.CONFIG); - h.publish(r); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - } - - /* - * Test publish(), use no filter, having output stream, normal log record. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use no filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_NoFilter() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter"); - h.setLevel(Level.INFO); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos - .toString()); - - h.setLevel(Level.WARNING); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos - .toString()); - - h.setLevel(Level.CONFIG); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", aos.toString()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", aos.toString()); - } - - /* - * Test publish(), use a filter, having output stream, normal log record. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), use a filter, having output stream, normal log record.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_WithFilter() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setFilter(new MockFilter()); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); - h.setLevel(Level.INFO); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.WARNING); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertTrue(CallVerificationStack.getInstance().empty()); - - h.setLevel(Level.CONFIG); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertSame(r, CallVerificationStack.getInstance().pop()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test publish(), null log record, handler should call ErrorManager to - * handle exceptional case - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), null log record, handler should call ErrorManager to handle exceptional case.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_Null() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - h.publish(null); - } - - /* - * Test publish(), null log record, without output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), null log record, without output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_Null_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.publish(null); - // regression test for Harmony-1279 - MockFilter filter = new MockFilter(); - h.setLevel(Level.FINER); - h.setFilter(filter); - LogRecord record = new LogRecord(Level.FINE, "abc"); - h.publish(record); - // verify that filter.isLoggable is not called, because there's no - // associated output stream. - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test publish(), a log record with empty msg, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), a log record with empty msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_EmptyMsg() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, ""); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head", aos.toString()); - } - - /* - * Test publish(), a log record with null msg, having output stream - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), a log record with null msg, having output stream.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_NullMsg() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head", aos.toString()); - } - - /* - * Test publish(), after close. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies publish(), after close.", - method = "publish", - args = {java.util.logging.LogRecord.class} - ) - public void testPublish_AfterClose() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - assertSame(h.getLevel(), Level.FINE); - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter"); - assertTrue(h.isLoggable(r)); - h.close(); - assertFalse(h.isLoggable(r)); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString()); - } - - /* - * Test setEncoding() method with supported encoding. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setEncoding() method with supported encoding.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_Normal() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - - byte[] bytes = encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array(); - assertTrue(Arrays.equals(bytes, aos.toByteArray())); - } - - /* - * Test setEncoding() method with supported encoding, after a log record - * has been written. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setEncoding() method with supported encoding, after a log record has been written.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_AfterPublish() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - assertTrue(Arrays.equals(aos.toByteArray(), encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array())); - - h.setEncoding("iso8859-1"); - assertEquals("iso8859-1", h.getEncoding()); - r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - assertFalse(Arrays.equals(aos.toByteArray(), encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69" - + "testSetEncoding_Normal2")).array())); - byte[] b0 = aos.toByteArray(); - byte[] b1 = encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array(); - byte[] b2 = encoder.encode(CharBuffer.wrap("\u6881\u884D\u8F69")) - .array(); - byte[] b3 = new byte[b1.length + b2.length]; - System.arraycopy(b1, 0, b3, 0, b1.length); - System.arraycopy(b2, 0, b3, b1.length, b2.length); - assertTrue(Arrays.equals(b0, b3)); - } - - /* - * Test setEncoding() methods with null. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setEncoding() methods with null.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_Null() throws Exception { - StreamHandler h = new StreamHandler(); - h.setEncoding(null); - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() methods with unsupported encoding. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setEncoding() methods with unsupported encoding.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_Unsupported() { - StreamHandler h = new StreamHandler(); - try { - h.setEncoding("impossible"); - fail("Should throw UnsupportedEncodingException!"); - } catch (UnsupportedEncodingException e) { - // expected - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() with insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setEncoding() method with insufficient privilege.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_InsufficientPrivilege() throws Exception { - StreamHandler h = new StreamHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - h.setEncoding("iso-8859-1"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - System.setSecurityManager(new MockSecurityManager()); - // set an invalid value - try { - - h.setEncoding("impossible"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() methods will flush a stream before setting. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that setEncoding() method will flush a stream before setting.", - method = "setEncoding", - args = {java.lang.String.class} - ) - public void testSetEncoding_FlushBeforeSetting() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, "abcd"); - h.publish(r); - assertFalse(aos.toString().indexOf("abcd") > 0); - h.setEncoding("iso-8859-1"); - assertTrue(aos.toString().indexOf("abcd") > 0); - } - - /* - * Test setOutputStream() with null. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setOutputStream() method with null.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) - public void testSetOutputStream_null() { - MockStreamHandler h = new MockStreamHandler( - new ByteArrayOutputStream(), new SimpleFormatter()); - try { - h.setOutputStream(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test setOutputStream() under normal condition. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setOutputStream() method under normal condition.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) - public void testSetOutputStream_Normal() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos - .toString()); - - ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); - h.setOutputStream(aos2); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 - .toString()); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - } - - /* - * Test setOutputStream() after close. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setOutputStream() method after close.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) - public void testSetOutputStream_AfterClose() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos - .toString()); - h.close(); - - ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); - h.setOutputStream(aos2); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 - .toString()); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - } - - /* - * Test setOutputStream() when having insufficient privilege. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies setOutputStream() method when having insufficient privilege.", - method = "setOutputStream", - args = {java.io.OutputStream.class} - ) - public void testSetOutputStream_InsufficientPrivilege() { - MockStreamHandler h = new MockStreamHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - h.setOutputStream(new ByteArrayOutputStream()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - - h = new MockStreamHandler(); - System.setSecurityManager(new MockSecurityManager()); - try { - h.setOutputStream(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * A mock stream handler, expose setOutputStream. - */ - public static class MockStreamHandler extends StreamHandler { - public MockStreamHandler() { - super(); - } - - public MockStreamHandler(OutputStream out, Formatter formatter) { - super(out, formatter); - } - - public void setOutputStream(OutputStream out) { - super.setOutputStream(out); - } - - public boolean isLoggable(LogRecord r) { - CallVerificationStack.getInstance().push(r); - return super.isLoggable(r); - } - } - - /* - * A mock filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return false; - } - } - - /* - * A mock formatter. - */ - public static class MockFormatter extends java.util.logging.Formatter { - public String format(LogRecord r) { - // System.out.println("formatter called..."); - return super.formatMessage(r); - } - - /* - * (non-Javadoc) - * - * @see java.util.logging.Formatter#getHead(java.util.logging.Handler) - */ - public String getHead(Handler h) { - return "MockFormatter_Head"; - } - - /* - * (non-Javadoc) - * - * @see java.util.logging.Formatter#getTail(java.util.logging.Handler) - */ - public String getTail(Handler h) { - return "MockFormatter_Tail"; - } - } - - /* - * Another mock formatter. - */ - public static class MockFormatter2 extends java.util.logging.Formatter { - public String format(LogRecord r) { - // System.out.println("formatter2 called..."); - return r.getMessage(); - } - } - - /* - * A mock output stream. - */ - public static class MockOutputStream extends ByteArrayOutputStream { - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#close() - */ - public void close() throws IOException { - CallVerificationStack.getInstance().push(null); - super.close(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#flush() - */ - public void flush() throws IOException { - CallVerificationStack.getInstance().push(null); - super.flush(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(int) - */ - public void write(int oneByte) { - super.write(oneByte); - } - } - - /* - * A mock output stream that always throw exception. - */ - public static class MockExceptionOutputStream extends ByteArrayOutputStream { - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#close() - */ - public void close() throws IOException { - throw new IOException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#flush() - */ - public void flush() throws IOException { - throw new IOException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(byte[], int, int) - */ - public synchronized void write(byte[] buffer, int offset, int count) { - throw new NullPointerException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(int) - */ - public synchronized void write(int oneByte) { - throw new NullPointerException(); - } - } - - /* - * Used to grant all permissions except logging control. - */ - public static class MockSecurityManager extends SecurityManager { - - public MockSecurityManager() { - } - - public void checkPermission(Permission perm) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - - public void checkPermission(Permission perm, Object context) { - // grant all permissions except logging control - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - } - } + } + + /* + * Test the constructor with no parameter, and no relevant log manager + * properties are set. + */ + public void testConstructor_NoParameter_NoProperties() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + + StreamHandler h = new StreamHandler(); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + } + + /* + * Test the constructor with insufficient privilege. + */ + public void testConstructor_NoParameter_InsufficientPrivilege() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + // set a normal value + try { + StreamHandler h = new StreamHandler(); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test the constructor with no parameter, and valid relevant log manager + * properties are set. + */ + public void testConstructor_NoParameter_ValidProperties() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", "FINE"); + p.put("java.util.logging.StreamHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.StreamHandler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals("FINE", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + StreamHandler h = new StreamHandler(); + assertSame(h.getLevel(), Level.parse("FINE")); + assertTrue(h.getFormatter() instanceof MockFormatter); + assertTrue(h.getFilter() instanceof MockFilter); + assertEquals("iso-8859-1", h.getEncoding()); + } + + /* + * Test the constructor with no parameter, and invalid relevant log manager + * properties are set. + */ + public void testConstructor_NoParameter_InvalidProperties() + throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); + p.put("java.util.logging.StreamHandler.filter", className + ""); + p.put("java.util.logging.StreamHandler.formatter", className + ""); + p.put("java.util.logging.StreamHandler.encoding", "XXXX"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("XXXX", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + StreamHandler h = new StreamHandler(); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof SimpleFormatter); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + h.publish(new LogRecord(Level.SEVERE, "test")); + assertTrue(CallVerificationStack.getInstance().empty()); + assertNull(h.getEncoding()); + } + + /* + * Test the constructor with normal parameter values, and no relevant log + * manager properties are set. + */ + public void testConstructor_HasParameters_NoProperties() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new MockFormatter2()); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof MockFormatter2); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + } + + /* + * Test the constructor with insufficient privilege. + */ + public void testConstructor_HasParameter_InsufficientPrivilege() { + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.filter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.formatter")); + assertNull(LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + // set a normal value + try { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new MockFormatter2()); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof MockFormatter2); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test the constructor with normal parameter values, and valid relevant log + * manager properties are set. + */ + public void testConstructor_HasParameters_ValidProperties() + throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", "FINE"); + p.put("java.util.logging.StreamHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.StreamHandler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals("FINE", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new MockFormatter2()); + assertSame(h.getLevel(), Level.parse("FINE")); + assertTrue(h.getFormatter() instanceof MockFormatter2); + assertTrue(h.getFilter() instanceof MockFilter); + assertEquals("iso-8859-1", h.getEncoding()); + } + + /* + * Test the constructor with normal parameter, and invalid relevant log + * manager properties are set. + */ + public void testConstructor_HasParameters_InvalidProperties() + throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); + p.put("java.util.logging.StreamHandler.filter", className + ""); + p.put("java.util.logging.StreamHandler.formatter", className + ""); + p.put("java.util.logging.StreamHandler.encoding", "XXXX"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("XXXX", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new MockFormatter2()); + assertSame(Level.INFO, h.getLevel()); + assertTrue(h.getFormatter() instanceof MockFormatter2); + assertNull(h.getFilter()); + assertNull(h.getEncoding()); + } + + /* + * Test the constructor with null formatter, and invalid relevant log manager + * properties are set. + */ + public void testConstructor_HasParameters_ValidPropertiesNullStream() + throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", "FINE"); + p.put("java.util.logging.StreamHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.StreamHandler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals("FINE", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + try { + new StreamHandler(new ByteArrayOutputStream(), null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the constructor with null output stream, and invalid relevant log + * manager properties are set. + */ + public void testConstructor_HasParameters_ValidPropertiesNullFormatter() + throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", "FINE"); + p.put("java.util.logging.StreamHandler.filter", className + + "$MockFilter"); + p.put("java.util.logging.StreamHandler.formatter", className + + "$MockFormatter"); + p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + assertEquals("FINE", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.level")); + assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( + "java.util.logging.StreamHandler.encoding")); + try { + new StreamHandler(null, new MockFormatter2()); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test close() when having sufficient privilege, and a record has been + * written to the output stream. + */ + public void testClose_SufficientPrivilege_NormalClose() { + ByteArrayOutputStream aos = new MockOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.publish(new LogRecord(Level.SEVERE, + "testClose_SufficientPrivilege_NormalClose msg")); + h.close(); + assertEquals("close", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + assertNull(CallVerificationStack.getInstance().pop()); + assertEquals("flush", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + CallVerificationStack.getInstance().clear(); + assertTrue(aos.toString().endsWith("MockFormatter_Tail")); + h.close(); + } + + /* + * Test close() when having sufficient privilege, and an output stream that + * always throws exceptions. + */ + public void testClose_SufficientPrivilege_Exception() { + ByteArrayOutputStream aos = new MockExceptionOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.publish(new LogRecord(Level.SEVERE, + "testClose_SufficientPrivilege_Exception msg")); + h.flush(); + h.close(); + } + + /* + * Test close() when having sufficient privilege, and no record has been + * written to the output stream. + */ + public void testClose_SufficientPrivilege_DirectClose() { + ByteArrayOutputStream aos = new MockOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.close(); + assertEquals("close", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + assertNull(CallVerificationStack.getInstance().pop()); + assertEquals("flush", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + CallVerificationStack.getInstance().clear(); + assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString() + ); + } + + /* + * Test close() when having insufficient privilege. + */ + public void testClose_InsufficientPrivilege() { + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new MockFormatter()); + h.close(); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + // expected + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * Test close() when having no output stream. + */ + public void testClose_NoOutputStream() { + StreamHandler h = new StreamHandler(); + h.close(); + } + + /* + * Test flush(). + */ + public void testFlush_Normal() { + ByteArrayOutputStream aos = new MockOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.flush(); + assertEquals("flush", CallVerificationStack.getInstance() + .getCurrentSourceMethod()); + assertNull(CallVerificationStack.getInstance().pop()); + CallVerificationStack.getInstance().clear(); + } + + /* + * Test flush() when having no output stream. + */ + public void testFlush_NoOutputStream() { + StreamHandler h = new StreamHandler(); + h.flush(); + } + + /* + * Test isLoggable(), use no filter, having output stream + */ + public void testIsLoggable_NoOutputStream() { + StreamHandler h = new StreamHandler(); + LogRecord r = new LogRecord(Level.INFO, null); + assertFalse(h.isLoggable(r)); + + h.setLevel(Level.WARNING); + assertFalse(h.isLoggable(r)); + + h.setLevel(Level.CONFIG); + assertFalse(h.isLoggable(r)); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + assertFalse(h.isLoggable(r)); + } + + /* + * Test isLoggable(), use no filter, having output stream + */ + public void testIsLoggable_NoFilter() { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new SimpleFormatter()); + LogRecord r = new LogRecord(Level.INFO, null); + assertTrue(h.isLoggable(r)); + + h.setLevel(Level.WARNING); + assertFalse(h.isLoggable(r)); + + h.setLevel(Level.CONFIG); + assertTrue(h.isLoggable(r)); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + assertFalse(h.isLoggable(r)); + } + + /* + * Test isLoggable(), use a filter, having output stream + */ + public void testIsLoggable_WithFilter() { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new SimpleFormatter()); + LogRecord r = new LogRecord(Level.INFO, null); + h.setFilter(new MockFilter()); + assertFalse(h.isLoggable(r)); + assertSame(r, CallVerificationStack.getInstance().pop()); + + h.setLevel(Level.CONFIG); + assertFalse(h.isLoggable(r)); + assertSame(r, CallVerificationStack.getInstance().pop()); + + h.setLevel(Level.WARNING); + assertFalse(h.isLoggable(r)); + assertTrue(CallVerificationStack.getInstance().empty()); + } + + /* + * Test isLoggable(), null log record, having output stream. Handler should + * call ErrorManager to handle exceptional case + */ + public void testIsLoggable_Null() { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new SimpleFormatter()); + assertFalse(h.isLoggable(null)); + } + + /* + * Test isLoggable(), null log record, without output stream + */ + public void testIsLoggable_Null_NoOutputStream() { + StreamHandler h = new StreamHandler(); + assertFalse(h.isLoggable(null)); + } + + /* + * Test publish(), use no filter, having output stream, normal log record. + */ + public void testPublish_NoOutputStream() { + StreamHandler h = new StreamHandler(); + LogRecord r = new LogRecord(Level.INFO, "testPublish_NoOutputStream"); + h.publish(r); + + h.setLevel(Level.WARNING); + h.publish(r); + + h.setLevel(Level.CONFIG); + h.publish(r); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + h.publish(r); + } + + /* + * Test publish(), use no filter, having output stream, normal log record. + */ + public void testPublish_NoFilter() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + + LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter"); + h.setLevel(Level.INFO); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos + .toString()); + + h.setLevel(Level.WARNING); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos + .toString()); + + h.setLevel(Level.CONFIG); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter" + + "testPublish_NoFilter", aos.toString()); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head" + "testPublish_NoFilter" + + "testPublish_NoFilter", aos.toString()); + } + + /* + * Test publish(), use a filter, having output stream, normal log record. + */ + public void testPublish_WithFilter() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.setFilter(new MockFilter()); + + LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); + h.setLevel(Level.INFO); + h.publish(r); + h.flush(); + assertEquals("", aos.toString()); + assertSame(r, CallVerificationStack.getInstance().pop()); + + h.setLevel(Level.WARNING); + h.publish(r); + h.flush(); + assertEquals("", aos.toString()); + assertTrue(CallVerificationStack.getInstance().empty()); + + h.setLevel(Level.CONFIG); + h.publish(r); + h.flush(); + assertEquals("", aos.toString()); + assertSame(r, CallVerificationStack.getInstance().pop()); + + r.setLevel(Level.OFF); + h.setLevel(Level.OFF); + h.publish(r); + h.flush(); + assertEquals("", aos.toString()); + assertTrue(CallVerificationStack.getInstance().empty()); + } + + /* + * Test publish(), null log record, handler should call ErrorManager to + * handle exceptional case + */ + public void testPublish_Null() { + StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), + new SimpleFormatter()); + h.publish(null); + } + + /* + * Test publish(), null log record, without output stream + */ + public void testPublish_Null_NoOutputStream() { + StreamHandler h = new StreamHandler(); + h.publish(null); + // regression test for Harmony-1279 + MockFilter filter = new MockFilter(); + h.setLevel(Level.FINER); + h.setFilter(filter); + LogRecord record = new LogRecord(Level.FINE, "abc"); + h.publish(record); + // verify that filter.isLoggable is not called, because there's no + // associated output stream. + assertTrue(CallVerificationStack.getInstance().empty()); + } + + /* + * Test publish(), a log record with empty msg, having output stream + */ + public void testPublish_EmptyMsg() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + LogRecord r = new LogRecord(Level.INFO, ""); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head", aos.toString()); + } + + /* + * Test publish(), a log record with null msg, having output stream + */ + public void testPublish_NullMsg() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + LogRecord r = new LogRecord(Level.INFO, null); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_Head", aos.toString()); + } + + /* + * Test publish(), after close. + */ + public void testPublish_AfterClose() throws Exception { + Properties p = new Properties(); + p.put("java.util.logging.StreamHandler.level", "FINE"); + LogManager.getLogManager().readConfiguration( + EnvironmentHelper.PropertiesToInputStream(p)); + + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + assertSame(h.getLevel(), Level.FINE); + LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter"); + assertTrue(h.isLoggable(r)); + h.close(); + assertFalse(h.isLoggable(r)); + h.publish(r); + h.flush(); + assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString()); + } + + /* + * Test setEncoding() method with supported encoding. + */ + public void testSetEncoding_Normal() throws Exception { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.setEncoding("iso-8859-1"); + assertEquals("iso-8859-1", h.getEncoding()); + LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); + h.publish(r); + h.flush(); + + byte[] bytes = encoder.encode( + CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) + .array(); + assertTrue(Arrays.equals(bytes, aos.toByteArray())); + } + + /* + * Test setEncoding() method with supported encoding, after a log record + * has been written. + */ + public void testSetEncoding_AfterPublish() throws Exception { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + h.setEncoding("iso-8859-1"); + assertEquals("iso-8859-1", h.getEncoding()); + LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); + h.publish(r); + h.flush(); + assertTrue(Arrays.equals(aos.toByteArray(), encoder.encode( + CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) + .array())); + + h.setEncoding("iso8859-1"); + assertEquals("iso8859-1", h.getEncoding()); + r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); + h.publish(r); + h.flush(); + assertFalse(Arrays.equals(aos.toByteArray(), encoder.encode( + CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69" + + "testSetEncoding_Normal2")).array())); + byte[] b0 = aos.toByteArray(); + byte[] b1 = encoder.encode( + CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) + .array(); + byte[] b2 = encoder.encode(CharBuffer.wrap("\u6881\u884D\u8F69")) + .array(); + byte[] b3 = new byte[b1.length + b2.length]; + System.arraycopy(b1, 0, b3, 0, b1.length); + System.arraycopy(b2, 0, b3, b1.length, b2.length); + assertTrue(Arrays.equals(b0, b3)); + } + + /* + * Test setEncoding() methods with null. + */ + public void testSetEncoding_Null() throws Exception { + StreamHandler h = new StreamHandler(); + h.setEncoding(null); + assertNull(h.getEncoding()); + } + + /* + * Test setEncoding() methods with unsupported encoding. + */ + public void testSetEncoding_Unsupported() { + StreamHandler h = new StreamHandler(); + try { + h.setEncoding("impossible"); + fail("Should throw UnsupportedEncodingException!"); + } catch (UnsupportedEncodingException e) { + // expected + } + assertNull(h.getEncoding()); + } + + /* + * Test setEncoding() with insufficient privilege. + */ + public void testSetEncoding_InsufficientPrivilege() throws Exception { + StreamHandler h = new StreamHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + // set a normal value + try { + h.setEncoding("iso-8859-1"); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + // expected + } finally { + System.setSecurityManager(oldMan); + } + assertNull(h.getEncoding()); + System.setSecurityManager(new MockSecurityManager()); + // set an invalid value + try { + + h.setEncoding("impossible"); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + // expected + } finally { + System.setSecurityManager(oldMan); + } + assertNull(h.getEncoding()); + } + + /* + * Test setEncoding() methods will flush a stream before setting. + */ + public void testSetEncoding_FlushBeforeSetting() throws Exception { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + StreamHandler h = new StreamHandler(aos, new MockFormatter()); + LogRecord r = new LogRecord(Level.INFO, "abcd"); + h.publish(r); + assertFalse(aos.toString().indexOf("abcd") > 0); + h.setEncoding("iso-8859-1"); + assertTrue(aos.toString().indexOf("abcd") > 0); + } + + /* + * Test setOutputStream() with null. + */ + public void testSetOutputStream_null() { + MockStreamHandler h = new MockStreamHandler( + new ByteArrayOutputStream(), new SimpleFormatter()); + try { + h.setOutputStream(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test setOutputStream() under normal condition. + */ + public void testSetOutputStream_Normal() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); + + LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); + h.publish(r); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + h.flush(); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos + .toString()); + + ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); + h.setOutputStream(aos2); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + + "MockFormatter_Tail", aos.toString()); + r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); + h.publish(r); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + h.flush(); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 + .toString()); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + + "MockFormatter_Tail", aos.toString()); + } + + /* + * Test setOutputStream() after close. + */ + public void testSetOutputStream_AfterClose() { + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); + + LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); + h.publish(r); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + h.flush(); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos + .toString()); + h.close(); + + ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); + h.setOutputStream(aos2); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + + "MockFormatter_Tail", aos.toString()); + r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); + h.publish(r); + assertSame(r, CallVerificationStack.getInstance().pop()); + assertTrue(CallVerificationStack.getInstance().empty()); + h.flush(); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 + .toString()); + assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" + + "MockFormatter_Tail", aos.toString()); + } + + /* + * Test setOutputStream() when having insufficient privilege. + */ + public void testSetOutputStream_InsufficientPrivilege() { + MockStreamHandler h = new MockStreamHandler(); + SecurityManager oldMan = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + try { + h.setOutputStream(new ByteArrayOutputStream()); + fail("Should throw SecurityException!"); + } catch (SecurityException e) { + // expected + } finally { + System.setSecurityManager(oldMan); + } + + h = new MockStreamHandler(); + System.setSecurityManager(new MockSecurityManager()); + try { + h.setOutputStream(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } finally { + System.setSecurityManager(oldMan); + } + } + + /* + * A mock stream handler, expose setOutputStream. + */ + public static class MockStreamHandler extends StreamHandler { + public MockStreamHandler() { + super(); + } + + public MockStreamHandler(OutputStream out, Formatter formatter) { + super(out, formatter); + } + + public void setOutputStream(OutputStream out) { + super.setOutputStream(out); + } + + public boolean isLoggable(LogRecord r) { + CallVerificationStack.getInstance().push(r); + return super.isLoggable(r); + } + } + + /* + * A mock filter, always return false. + */ + public static class MockFilter implements Filter { + + public boolean isLoggable(LogRecord record) { + CallVerificationStack.getInstance().push(record); + return false; + } + } + + /* + * A mock formatter. + */ + public static class MockFormatter extends java.util.logging.Formatter { + public String format(LogRecord r) { + // System.out.println("formatter called..."); + return super.formatMessage(r); + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Formatter#getHead(java.util.logging.Handler) + */ + public String getHead(Handler h) { + return "MockFormatter_Head"; + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Formatter#getTail(java.util.logging.Handler) + */ + public String getTail(Handler h) { + return "MockFormatter_Tail"; + } + } + + /* + * Another mock formatter. + */ + public static class MockFormatter2 extends java.util.logging.Formatter { + public String format(LogRecord r) { + // System.out.println("formatter2 called..."); + return r.getMessage(); + } + } + + /* + * A mock output stream. + */ + public static class MockOutputStream extends ByteArrayOutputStream { + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#close() + */ + public void close() throws IOException { + CallVerificationStack.getInstance().push(null); + super.close(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#flush() + */ + public void flush() throws IOException { + CallVerificationStack.getInstance().push(null); + super.flush(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#write(int) + */ + public void write(int oneByte) { + // TODO Auto-generated method stub + super.write(oneByte); + } + } + + /* + * A mock output stream that always throw exception. + */ + public static class MockExceptionOutputStream extends ByteArrayOutputStream { + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#close() + */ + public void close() throws IOException { + throw new IOException(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#flush() + */ + public void flush() throws IOException { + throw new IOException(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#write(byte[], int, int) + */ + public synchronized void write(byte[] buffer, int offset, int count) { + throw new NullPointerException(); + } + + /* + * (non-Javadoc) + * + * @see java.io.OutputStream#write(int) + */ + public synchronized void write(int oneByte) { + throw new NullPointerException(); + } + } + + /* + * Used to grant all permissions except logging control. + */ + public static class MockSecurityManager extends SecurityManager { + + public MockSecurityManager() { + } + + public void checkPermission(Permission perm) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + + public void checkPermission(Permission perm, Object context) { + // grant all permissions except logging control + if (perm instanceof LoggingPermission) { + throw new SecurityException(); + } + } + } } diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java index 90c93c9..175ffb5 100644 --- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java +++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java @@ -17,12 +17,6 @@ package org.apache.harmony.logging.tests.java.util.logging; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import java.io.UnsupportedEncodingException; @@ -32,7 +26,6 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.XMLFormatter; -@TestTargetClass(XMLFormatter.class) public class XMLFormatterTest extends TestCase { XMLFormatter formatter = null; @@ -52,26 +45,6 @@ public class XMLFormatterTest extends TestCase { * test for constructor public XMLFormatter() * */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "XMLFormatter", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {java.util.logging.Handler.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ) - }) public void testXMLFormatter() throws SecurityException, UnsupportedEncodingException { @@ -93,12 +66,6 @@ public class XMLFormatterTest extends TestCase { .getTail(handler).indexOf("/log>") > 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testLocalFormat() { // if set resource bundle, output will use localized message, // but put the original message into the key element @@ -130,12 +97,6 @@ public class XMLFormatterTest extends TestCase { assertTrue(result.indexOf("<key>") < 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testFullFormat() { lr.setSourceClassName("source class"); lr.setSourceMethodName("source method"); @@ -168,12 +129,6 @@ public class XMLFormatterTest extends TestCase { assertTrue(output.indexOf("<key>pattern</key>") > 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ) public void testFormat() { String output = formatter.format(lr); // System.out.println(output); @@ -193,12 +148,6 @@ public class XMLFormatterTest extends TestCase { assertTrue(output.indexOf("<key>") < 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getHead", - args = {java.util.logging.Handler.class} - ) public void testGetHead() throws SecurityException, UnsupportedEncodingException { String result = formatter.getHead(handler); @@ -230,12 +179,6 @@ public class XMLFormatterTest extends TestCase { /* * test for method public String getTail(Handler h) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ) public void testGetTail() { assertEquals( "Tail string with null handler should be equal expected value", @@ -248,28 +191,7 @@ public class XMLFormatterTest extends TestCase { "</log>", formatter.getTail(handler).trim()); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "format", - args = {java.util.logging.LogRecord.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getTail", - args = {java.util.logging.Handler.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "XMLFormatter", - args = {} - ) - }) - @AndroidOnly("This test fails on RI. Output doesn't contain " + - "<message/>.") + // This test fails on RI. Output doesn't contain <message/>. public void testInvalidParameter() { formatter.getTail(null); try { diff --git a/logging/src/test/java/tests/logging/AllTests.java b/logging/src/test/java/tests/logging/AllTests.java index c6032df..aa0cb15 100644 --- a/logging/src/test/java/tests/logging/AllTests.java +++ b/logging/src/test/java/tests/logging/AllTests.java @@ -24,16 +24,11 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Logging project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Logging test suites"); + TestSuite suite = new TestSuite("All Logging test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.logging.tests.java.util.logging.AllTests.suite()); // $JUnit-END$ return suite; } -}
\ No newline at end of file +} diff --git a/luni-kernel/src/main/java/java/lang/Class.java b/luni-kernel/src/main/java/java/lang/Class.java index 101d593..571f5b1 100644 --- a/luni-kernel/src/main/java/java/lang/Class.java +++ b/luni-kernel/src/main/java/java/lang/Class.java @@ -124,14 +124,16 @@ public final class Class<T> implements Serializable, AnnotatedElement, GenericDe private static final long serialVersionUID = 3206093459760846163L; - // TODO How is this field being initialized? What's it being used for? - private ProtectionDomain pd; + /** + * This field is initialized by dalvikvm when the class is loaded. + */ + private transient ProtectionDomain pd; /** * null-ok; cache of reflective information, wrapped in a soft * reference */ - private volatile SoftReference<ClassCache<T>> cacheRef; + private transient volatile SoftReference<ClassCache<T>> cacheRef; private Class() { // Prevent this class to be instantiated, instance diff --git a/luni-kernel/src/test/java/java/lang/reflect/AllTests.java b/luni-kernel/src/test/java/java/lang/reflect/AllTests.java index 7cf1475..8d99672 100644 --- a/luni-kernel/src/test/java/java/lang/reflect/AllTests.java +++ b/luni-kernel/src/test/java/java/lang/reflect/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.lang.reflect.ConstructorTest.class); suite.addTestSuite(java.lang.reflect.MethodTest.class); return suite; diff --git a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java index a59cc3e..e9cf80e 100644 --- a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java +++ b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(tests.api.org.apache.harmony.kernel.dalvik.ThreadsTest.class); return suite; } diff --git a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java index c24e297..8ba2445 100644 --- a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java +++ b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java @@ -21,15 +21,10 @@ import java.lang.reflect.Field; import junit.framework.Assert; import junit.framework.TestCase; import sun.misc.Unsafe; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; /** * Tests for the <code>park()</code> functionality of {@link Unsafe}. */ -@TestTargetClass(Unsafe.class) public class ThreadsTest extends TestCase { private static Unsafe UNSAFE = null; private static RuntimeException INITIALIZEFAILED = null; @@ -54,13 +49,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the park times out. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkFor_1() { Parker parker = new Parker(false, 500); Thread parkerThread = new Thread(parker); @@ -73,13 +61,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the unpark happens before the timeout. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkFor_2() { Parker parker = new Parker(false, 1000); Thread parkerThread = new Thread(parker); @@ -92,13 +73,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the thread is preemptively unparked. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkFor_3() { Parker parker = new Parker(false, 1000); Thread parkerThread = new Thread(parker); @@ -109,13 +83,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the park times out. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkUntil_1() { Parker parker = new Parker(true, 500); Thread parkerThread = new Thread(parker); @@ -128,13 +95,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the unpark happens before the timeout. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkUntil_2() { Parker parker = new Parker(true, 1000); Thread parkerThread = new Thread(parker); @@ -147,13 +107,6 @@ public class ThreadsTest extends TestCase { } /** Test the case where the thread is preemptively unparked. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "unpark", - args = {Object.class} - ) - @AndroidOnly("Accesses Android-specific private field") public void test_parkUntil_3() { Parker parker = new Parker(true, 1000); Thread parkerThread = new Thread(parker); diff --git a/luni/src/main/java/java/lang/String.java b/luni/src/main/java/java/lang/String.java index 8e4c9a8..9ee16d9 100644 --- a/luni/src/main/java/java/lang/String.java +++ b/luni/src/main/java/java/lang/String.java @@ -1202,6 +1202,16 @@ public final class String implements Serializable, Comparable<String>, native public String intern(); /** + * Returns true if the length of this string is 0. + * + * @since 1.6 + * @hide + */ + public boolean isEmpty() { + return count == 0; + } + + /** * Searches in this string for the last index of the specified character. * The search for the character starts at the end and moves towards the * beginning of this string. diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java index ad96ed6..4827e70 100644 --- a/luni/src/main/java/java/net/InetAddress.java +++ b/luni/src/main/java/java/net/InetAddress.java @@ -27,8 +27,10 @@ import java.io.Serializable; import java.security.AccessController; import java.util.Arrays; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; +import java.util.List; import java.util.StringTokenizer; import org.apache.harmony.luni.net.NetUtil; @@ -114,40 +116,12 @@ public class InetAddress implements Serializable { super(); } - // BEGIN android-removed - /** - * Constructs an {@code InetAddress}, representing the {@code address} and - * {@code hostName}. - * - * @param address - * the network address. - */ - // InetAddress(byte[] address) { - // super(); - // this.ipaddress = address; - // } - // END android-removed - - // BEGIN android-removed - /** - * Constructs an {@code InetAddress}, representing the {@code address} and - * {@code hostName}. - * - * @param address - * the network address. - * - */ - // InetAddress(byte[] address, String hostName) { - // super(); - // this.ipaddress = address; - // this.hostName = hostName; - // } + // BEGIN android-removed: use Inet4Address/Inet6Address instead, as appropriate. + // InetAddress(byte[] address) { ... } // END android-removed - // BEGIN android-removed - // CacheElement cacheElement() { - // return new CacheElement(); - // } + // BEGIN android-removed: use Inet4Address/Inet6Address instead, as appropriate. + // InetAddress(byte[] address, String hostName) { ... } // END android-removed /** @@ -744,7 +718,7 @@ public class InetAddress implements Serializable { * ICMP <i>(ICMP ECHO REQUEST)</i>. When first step fails, a TCP connection * on port 7 (Echo) of the remote host is established. * - * @param netif + * @param networkInterface * the network interface on which to connection should be * established. * @param ttl @@ -759,36 +733,16 @@ public class InetAddress implements Serializable { * @throws IllegalArgumentException * if ttl or timeout is less than zero. */ - public boolean isReachable(NetworkInterface netif, final int ttl, + public boolean isReachable(NetworkInterface networkInterface, final int ttl, final int timeout) throws IOException { - if (0 > ttl || 0 > timeout) { + if (ttl < 0 || timeout < 0) { throw new IllegalArgumentException(Msg.getString("K0051")); //$NON-NLS-1$ } - boolean reachable = false; - if (null == netif) { - // network interface is null, binds to no address - // BEGIN android-changed - // reachable = NETIMPL.isReachableByICMP(this, null, ttl, timeout); - // if (!reachable) { - reachable = isReachableByTCP(this, null, timeout); - // } - // END android-changed + if (networkInterface == null) { + return isReachableByTCP(this, null, timeout); } else { - // Not Bind to any address - if (null == netif.addresses) { - return false; - } - // binds to all address on this NetworkInterface, tries ICMP ping - // first - // BEGIN android-changed - // reachable = isReachableByICMPUseMultiThread(netif, ttl, timeout); - // if (!reachable) { - // tries TCP echo if ICMP ping fails - reachable = isReachableByMultiThread(netif, ttl, timeout); - // } - // END adnroid-changed + return isReachableByMultiThread(networkInterface, ttl, timeout); } - return reachable; } /* @@ -800,16 +754,14 @@ public class InetAddress implements Serializable { final int ttl, final int timeout) // END android-changed throws IOException { - if (null == netif.addresses) { + List<InetAddress> addresses = Collections.list(netif.getInetAddresses()); + if (addresses.isEmpty()) { return false; } - Enumeration<InetAddress> addresses = netif.getInetAddresses(); reached = false; - addrCount = netif.addresses.length; + addrCount = addresses.size(); boolean needWait = false; - while (addresses.hasMoreElements()) { - final InetAddress addr = addresses.nextElement(); - + for (final InetAddress addr : addresses) { // loopback interface can only reach to local addresses if (addr.isLoopbackAddress()) { Enumeration<NetworkInterface> NetworkInterfaces = NetworkInterface diff --git a/luni/src/main/java/java/net/InterfaceAddress.java b/luni/src/main/java/java/net/InterfaceAddress.java index 7bc3936..2fa99f7 100644 --- a/luni/src/main/java/java/net/InterfaceAddress.java +++ b/luni/src/main/java/java/net/InterfaceAddress.java @@ -20,22 +20,131 @@ package java.net; * Identifies one of a network interface's addresses. * These are passed back from the JNI behind NetworkInterface.getNetworkInterfaces. * Multiple addresses for the same interface are collected together on the Java side. + * + * @hide + * @since 1.6 */ -class InterfaceAddress { - // An IPv4 or IPv6 address. - final InetAddress address; - - // The kernel's interface index for the network interface this address - // is currently assigned to. Values start at 1, because 0 means "unknown" - // or "any", depending on context. +public class InterfaceAddress { + /** + * The kernel's interface index for the network interface this address + * is currently assigned to. Values start at 1, because 0 means "unknown" + * or "any", depending on context. + */ final int index; - // The network interface's name. "lo" or "eth0", for example. + /** + * The network interface's name. "lo" or "eth0", for example. + */ final String name; - InterfaceAddress(int index, String name, InetAddress address) { + /** + * An IPv4 or IPv6 address. + */ + final InetAddress address; + + /** + * The IPv4 broadcast address, or null for IPv6. + */ + private final InetAddress broadcastAddress; + + private final short prefixLength; + + InterfaceAddress(int index, String name, InetAddress address, InetAddress mask) { + assert ((address instanceof Inet4Address) == (mask instanceof Inet4Address)); this.index = index; this.name = name; this.address = address; + this.broadcastAddress = makeBroadcastAddress(address, mask); + this.prefixLength = countPrefixLength(mask); + } + + private static InetAddress makeBroadcastAddress(InetAddress address, InetAddress mask) { + if (!(address instanceof Inet4Address)) { + return null; + } + byte[] broadcast = new byte[4]; + byte[] maskBytes = mask.ipaddress; + byte[] addrBytes = address.ipaddress; + if (maskBytes[0] != 0) { + for (int i = 0; i < broadcast.length; ++i) { + broadcast[i] = (byte) (addrBytes[i] | ~maskBytes[i]); + } + } + return new Inet4Address(broadcast); + } + + private static short countPrefixLength(InetAddress mask) { + short count = 0; + for (byte b : mask.ipaddress) { + for (int i = 0; i < 8; ++i) { + if ((b & (1 << i)) != 0) { + ++count; + } + } + } + return count; + } + + /** + * Tests whether this object is equal to another one. Returns true if + * the address, broadcast address and prefix length are all equal. + * + * @param obj the object to be compared. + * @return true if 'obj' is equal to this InterfaceAddress, false otherwise. + */ + @Override + public boolean equals(Object obj) { + if (obj == this){ + return true; + } + if (!(obj instanceof InterfaceAddress)) { + return false; + } + InterfaceAddress rhs = (InterfaceAddress) obj; + return ((address == null) ? rhs.address == null : address.equals(rhs.address)) && + (rhs.prefixLength == prefixLength) && + ((broadcastAddress == null) ? rhs.broadcastAddress == null : broadcastAddress.equals(rhs.broadcastAddress)); + } + + @Override + public int hashCode() { + int hashCode = address == null ? 0 : -address.hashCode(); + hashCode += broadcastAddress == null ? 0 : broadcastAddress.hashCode(); + hashCode += prefixLength; + return hashCode; + } + + /** + * Returns a string representation for this interface address. + * The string is of the form: InetAddress / prefix length [ broadcast address ]. + * + * @return a string representation of this interface address. + */ + @Override + public String toString() { + return address + "/" + prefixLength + " [" + broadcastAddress + "]"; + } + + /** + * Returns the InetAddress for this address. + */ + public InetAddress getAddress() { + return address; + } + + /** + * Returns the subnet-directed broadcast address if this is an IPv4 interface, null otherwise. + */ + public InetAddress getBroadcast() { + return broadcastAddress; + } + + /** + * Returns the network prefix length in bits. + * (In IPv4 parlance, this is known as the subnet mask, + * but this method applies to IPv6 addresses too.) + */ + public short getNetworkPrefixLength() { + return prefixLength; } } diff --git a/luni/src/main/java/java/net/NetworkInterface.java b/luni/src/main/java/java/net/NetworkInterface.java index 93a30cb..b3e242e 100644 --- a/luni/src/main/java/java/net/NetworkInterface.java +++ b/luni/src/main/java/java/net/NetworkInterface.java @@ -17,9 +17,12 @@ package java.net; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Vector; @@ -37,49 +40,45 @@ public final class NetworkInterface extends Object { private static final int CHECK_CONNECT_NO_PORT = -1; static final int NO_INTERFACE_INDEX = 0; - static final int UNSET_INTERFACE_INDEX = -1; - private String name; - - private String displayName; + private final String name; + private final String displayName; + private final List<InterfaceAddress> interfaceAddresses = new LinkedList<InterfaceAddress>(); - InetAddress addresses[]; + private final List<InetAddress> addresses = new LinkedList<InetAddress>(); // The interface index is a positive integer which is non-negative. Where // value is zero then we do not have an index for the interface (which // occurs in systems which only support IPV4) private int interfaceIndex; - private int hashCode; + private NetworkInterface parent = null; + + private final List<NetworkInterface> children = new LinkedList<NetworkInterface>(); // BEGIN android-changed: we pay this extra complexity on the Java side // in return for vastly simpler native code. - private static native InterfaceAddress[] getInterfaceAddresses() throws SocketException; + private static native InterfaceAddress[] getAllInterfaceAddressesImpl() throws SocketException; private static NetworkInterface[] getNetworkInterfacesImpl() throws SocketException { Map<String, NetworkInterface> networkInterfaces = new LinkedHashMap<String, NetworkInterface>(); - for (InterfaceAddress ia : getInterfaceAddresses()) { + for (InterfaceAddress ia : getAllInterfaceAddressesImpl()) { if (ia != null) { // The array may contain harmless null elements. String name = ia.name; NetworkInterface ni = networkInterfaces.get(name); if (ni == null) { ni = new NetworkInterface(name, name, new InetAddress[] { ia.address }, ia.index); + ni.interfaceAddresses.add(ia); networkInterfaces.put(name, ni); } else { - ni.addInterfaceAddress(ia.address); + ni.addresses.add(ia.address); + ni.interfaceAddresses.add(ia); } } } return networkInterfaces.values().toArray(new NetworkInterface[networkInterfaces.size()]); } - - private void addInterfaceAddress(InetAddress address) { - InetAddress[] newAddresses = new InetAddress[addresses.length + 1]; - System.arraycopy(addresses, 0, newAddresses, 0, addresses.length); - newAddresses[addresses.length] = address; - addresses = newAddresses; - } // END android-changed /** @@ -96,12 +95,16 @@ public final class NetworkInterface extends Object { * an index for the interface. Only set for platforms that * support IPV6. */ - NetworkInterface(String name, String displayName, InetAddress addresses[], + NetworkInterface(String name, String displayName, InetAddress[] addresses, int interfaceIndex) { this.name = name; this.displayName = displayName; - this.addresses = addresses; this.interfaceIndex = interfaceIndex; + if (addresses != null) { + for (InetAddress address : addresses) { + this.addresses.add(address); + } + } } /** @@ -122,8 +125,8 @@ public final class NetworkInterface extends Object { * @return the first address if one exists, otherwise null. */ InetAddress getFirstAddress() { - if ((addresses != null) && (addresses.length >= 1)) { - return addresses[0]; + if (addresses.size() >= 1) { + return addresses.get(0); } return null; } @@ -143,63 +146,21 @@ public final class NetworkInterface extends Object { * @return the address list of the represented network interface. */ public Enumeration<InetAddress> getInetAddresses() { - /* - * create new vector from which Enumeration to be returned can be - * generated set the initial capacity to be the number of addresses for - * the network interface which is the maximum required size - */ - - /* - * return an empty enumeration if there are no addresses associated with - * the interface - */ - if (addresses == null) { - return new Vector<InetAddress>(0).elements(); - } - - /* - * for those configuration that support the security manager we only - * return addresses for which checkConnect returns true - */ - Vector<InetAddress> accessibleAddresses = new Vector<InetAddress>( - addresses.length); - - /* - * get the security manager. If one does not exist just return the full - * list - */ - SecurityManager security = System.getSecurityManager(); - if (security == null) { - return (new Vector<InetAddress>(Arrays.asList(addresses))) - .elements(); + SecurityManager sm = System.getSecurityManager(); + if (sm == null || addresses.isEmpty()) { + return Collections.enumeration(addresses); } - - /* - * ok security manager exists so check each address and return those - * that pass - */ - for (InetAddress element : addresses) { - if (security != null) { - try { - /* - * since we don't have a port in this case we pass in - * NO_PORT - */ - security.checkConnect(element.getHostName(), - CHECK_CONNECT_NO_PORT); - accessibleAddresses.add(element); - } catch (SecurityException e) { - } + // 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); } - - Enumeration<InetAddress> theAccessibleElements = accessibleAddresses - .elements(); - if (theAccessibleElements.hasMoreElements()) { - return accessibleAddresses.elements(); - } - - return new Vector<InetAddress>(0).elements(); + return Collections.enumeration(result); } /** @@ -232,24 +193,13 @@ public final class NetworkInterface extends Object { * @throws NullPointerException * if the given interface's name is {@code null}. */ - public static NetworkInterface getByName(String interfaceName) - throws SocketException { - + public static NetworkInterface getByName(String interfaceName) throws SocketException { if (interfaceName == null) { throw new NullPointerException(Msg.getString("K0330")); //$NON-NLS-1$ } - - /* - * get the list of interfaces, and then loop through the list to look - * for one with a matching name - */ - Enumeration<NetworkInterface> interfaces = getNetworkInterfaces(); - if (interfaces != null) { - while (interfaces.hasMoreElements()) { - NetworkInterface netif = interfaces.nextElement(); - if (netif.getName().equals(interfaceName)) { - return netif; - } + for (NetworkInterface networkInterface : getNetworkInterfacesList()) { + if (networkInterface.name.equals(interfaceName)) { + return networkInterface; } } return null; @@ -268,38 +218,13 @@ public final class NetworkInterface extends Object { * @throws NullPointerException * if the given interface address is invalid. */ - public static NetworkInterface getByInetAddress(InetAddress address) - throws SocketException { - + public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException { if (address == null) { throw new NullPointerException(Msg.getString("K0331")); //$NON-NLS-1$ } - - /* - * get the list of interfaces, and then loop through the list. For each - * interface loop through the associated set of internet addresses and - * see if one matches. If so return that network interface - */ - Enumeration<NetworkInterface> interfaces = getNetworkInterfaces(); - if (interfaces != null) { - while (interfaces.hasMoreElements()) { - NetworkInterface netif = interfaces.nextElement(); - /* - * to be compatible use the raw addresses without any security - * filtering - */ - // Enumeration netifAddresses = netif.getInetAddresses(); - if ((netif.addresses != null) && (netif.addresses.length != 0)) { - Enumeration<InetAddress> netifAddresses = (new Vector<InetAddress>( - Arrays.asList(netif.addresses))).elements(); - if (netifAddresses != null) { - while (netifAddresses.hasMoreElements()) { - if (address.equals(netifAddresses.nextElement())) { - return netif; - } - } - } - } + for (NetworkInterface networkInterface : getNetworkInterfacesList()) { + if (networkInterface.addresses.contains(address)) { + return networkInterface; } } return null; @@ -315,32 +240,53 @@ public final class NetworkInterface extends Object { * if an error occurs while getting the network interface * information. */ - public static Enumeration<NetworkInterface> getNetworkInterfaces() - throws SocketException { + public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException { + return Collections.enumeration(getNetworkInterfacesList()); + } + + private static List<NetworkInterface> getNetworkInterfacesList() throws SocketException { NetworkInterface[] interfaces = getNetworkInterfacesImpl(); - if (interfaces == null) { - return null; - } for (NetworkInterface netif : interfaces) { // Ensure that current NetworkInterface is bound to at least // one InetAddress before processing - if (netif.addresses != null) { - for (InetAddress addr : netif.addresses) { - if (16 == addr.ipaddress.length) { - if (addr.isLinkLocalAddress() - || addr.isSiteLocalAddress()) { - ((Inet6Address) addr).scopedIf = netif; - ((Inet6Address) addr).ifname = netif.name; - ((Inet6Address) addr).scope_ifname_set = true; - } + for (InetAddress addr : netif.addresses) { + if (addr.ipaddress.length == 16) { + if (addr.isLinkLocalAddress() || addr.isSiteLocalAddress()) { + ((Inet6Address) addr).scopedIf = netif; + ((Inet6Address) addr).ifname = netif.name; + ((Inet6Address) addr).scope_ifname_set = true; } } } } - return (new Vector<NetworkInterface>(Arrays.asList(interfaces))) - .elements(); + List<NetworkInterface> result = new ArrayList<NetworkInterface>(); + boolean[] peeked = new boolean[interfaces.length]; + for (int counter = 0; counter < interfaces.length; counter++) { + // If this interface has been touched, continue. + if (peeked[counter]) { + continue; + } + int counter2 = counter; + // Checks whether the following interfaces are children. + for (; counter2 < interfaces.length; counter2++) { + if (peeked[counter2]) { + continue; + } + if (interfaces[counter2].name.startsWith(interfaces[counter].name + ":")) { + // Tagged as peeked + peeked[counter2] = true; + interfaces[counter].children.add(interfaces[counter2]); + interfaces[counter2].parent = interfaces[counter]; + interfaces[counter].addresses.addAll(interfaces[counter2].addresses); + } + } + // Tagged as peeked + result.add(interfaces[counter]); + peeked[counter] = true; + } + return result; } /** @@ -357,77 +303,27 @@ public final class NetworkInterface extends Object { */ @Override public boolean equals(Object obj) { - // Return true if it is the exact same object. if (obj == this) { return true; } - - // Ensure it is the right type. if (!(obj instanceof NetworkInterface)) { return false; } - - /* - * Make sure that some simple checks pass. If the name is not the same - * then we are sure it is not the same one. We don't check the hashcode - * as it is generated from the name which we check - */ - NetworkInterface netif = (NetworkInterface) obj; - - if (netif.getIndex() != interfaceIndex) { - return false; - } - - if (!(name.equals("")) && (!netif.getName().equals(name))) { //$NON-NLS-1$ - return false; - } - - if ((name.equals("")) && (!netif.getName().equals(displayName))) { //$NON-NLS-1$ - return false; - } - - // Now check that the collection of internet addresses are equal. - Enumeration<InetAddress> netifAddresses = netif.getInetAddresses(); - Enumeration<InetAddress> localifAddresses = getInetAddresses(); - - // Check for both null (same), or one null (not same). - if (netifAddresses == null) { - return localifAddresses == null; - } - if (localifAddresses == null) { - return false; - } - - // Both are not null, check InetAddress elements. - while (netifAddresses.hasMoreElements() - && localifAddresses.hasMoreElements()) { - if (!(localifAddresses.nextElement()).equals( - netifAddresses.nextElement())) { - return false; - } - } - - /* - * Now make sure that they had the same number of addresses, if not they - * are not the same interface. - */ - return !netifAddresses.hasMoreElements() - && !localifAddresses.hasMoreElements(); + NetworkInterface rhs = (NetworkInterface) obj; + // TODO: should the order of the addresses matter (we use List.equals)? + return interfaceIndex == rhs.interfaceIndex && + name.equals(rhs.name) && displayName.equals(rhs.displayName) && + addresses.equals(rhs.addresses); } /** - * Gets the hashcode for this {@code NetworkInterface} instance. Since the - * name should be unique for each network interface the hashcode is + * Returns the hash code for this {@code NetworkInterface}. Since the + * name should be unique for each network interface the hash code is * generated using this name. - * - * @return the hashcode value for this {@code NetworkInterface} instance. */ @Override public int hashCode() { - if (hashCode == 0) { - hashCode = name.hashCode(); - } - return hashCode; + return name.hashCode(); } /** @@ -464,4 +360,174 @@ public final class NetworkInterface extends Object { } return string.toString(); } + + /** + * 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. + * @since 1.6 + * @hide + */ + 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; + } + + /** + * Returns an {@code Enumeration} of all the sub-interfaces of this network interface. + * Sub-interfaces are also known as virtual interfaces. + * <p> + * For example, {@code eth0:1} would be a sub-interface of {@code eth0}. + * + * @return an Enumeration of all the sub-interfaces of this network interface + * @since 1.6 + * @hide + */ + public Enumeration<NetworkInterface> getSubInterfaces() { + return Collections.enumeration(children); + } + + /** + * Returns the parent NetworkInterface of this interface if this is a + * sub-interface, or null if it's a physical (non virtual) interface. + * + * @return the NetworkInterface this interface is attached to. + * @since 1.6 + * @hide + */ + public NetworkInterface getParent() { + return parent; + } + + /** + * Returns true if this network interface is up. + * + * @return true if the interface is up. + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public boolean isUp() throws SocketException { + if (addresses.isEmpty()) { + return false; + } + return isUpImpl(name, interfaceIndex); + } + private static native boolean isUpImpl(String n, int index) throws SocketException; + + /** + * Returns true if this network interface is a loopback interface. + * + * @return true if the interface is a loopback interface. + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public boolean isLoopback() throws SocketException { + if (addresses.isEmpty()) { + return false; + } + return isLoopbackImpl(name, interfaceIndex); + } + private static native boolean isLoopbackImpl(String n, int index) throws SocketException; + + /** + * Returns true if this network interface is a point-to-point interface. + * (For example, a PPP connection using a modem.) + * + * @return true if the interface is point-to-point. + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public boolean isPointToPoint() throws SocketException { + if (addresses.isEmpty()) { + return false; + } + return isPointToPointImpl(name, interfaceIndex); + } + private static native boolean isPointToPointImpl(String n, int index) throws SocketException; + + /** + * Returns true if this network interface supports multicast. + * + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public boolean supportsMulticast() throws SocketException { + if (addresses.isEmpty()) { + return false; + } + return supportsMulticastImpl(name, interfaceIndex); + } + private static native boolean supportsMulticastImpl(String n, int index) throws SocketException; + + /** + * Returns the hardware address of the interface, if it has one, and the + * user has the necessary privileges to access the address. + * + * @return a byte array containing the address or null if the address + * doesn't exist or is not accessible. + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public byte[] getHardwareAddress() throws SocketException { + if (addresses.isEmpty()) { + return new byte[0]; + } + return getHardwareAddressImpl(name, interfaceIndex); + } + private static native byte[] getHardwareAddressImpl(String n, int index) throws SocketException; + + /** + * Returns the Maximum Transmission Unit (MTU) of this interface. + * + * @return the value of the MTU for the interface. + * @throws SocketException if an I/O error occurs. + * @since 1.6 + * @hide + */ + public int getMTU() throws SocketException { + if (addresses.isEmpty()) { + return 0; + } + return getMTUImpl(name, interfaceIndex); + } + private static native int getMTUImpl(String n, int index) throws SocketException; + + /** + * Returns true if this interface is a virtual interface (also called + * a sub-interface). Virtual interfaces are, on some systems, interfaces + * created as a child of a physical interface and given different settings + * (like address or MTU). Usually the name of the interface will the name of + * the parent followed by a colon (:) and a number identifying the child, + * since there can be several virtual interfaces attached to a single + * physical interface. + * + * @return true if this interface is a virtual interface. + * @since 1.6 + * @hide + */ + public boolean isVirtual() { + return parent != null; + } } diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java index 2fe6b5c..ce7b84f 100644 --- a/luni/src/main/java/java/net/ServerSocket.java +++ b/luni/src/main/java/java/net/ServerSocket.java @@ -61,13 +61,7 @@ public class ServerSocket { } /** - * Unspecified constructor. - * - * Warning: this function is technically part of API#1. - * Hiding it for API#2 broke source compatibility. - * Removing it entirely would theoretically break binary compatibility, - * and would be better done with some visibility over the extent - * of the compatibility breakage (expected to be non-existent). + * Unspecified constructor needed by ServerSocketChannelImpl.ServerSocketAdapter. * * @hide */ diff --git a/luni/src/main/java/java/util/Calendar.java b/luni/src/main/java/java/util/Calendar.java index 7f2e92d..4d7ede9 100644 --- a/luni/src/main/java/java/util/Calendar.java +++ b/luni/src/main/java/java/util/Calendar.java @@ -285,36 +285,48 @@ import com.ibm.icu4jni.util.LocaleData; * @see GregorianCalendar * @see TimeZone */ -public abstract class Calendar implements Serializable, Cloneable, - Comparable<Calendar> { +public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> { private static final long serialVersionUID = -1807547505821590642L; /** - * Set to {@code true} when the calendar fields have been set from the time, set to - * {@code false} when a field is changed and the fields must be recomputed. + * True iff the values in {@code fields[]} correspond to {@code time}. Despite the name, this + * is effectively "are the values in fields[] up-to-date?" --- {@code fields[]} may contain + * non-zero values and {@code isSet[]} may contain {@code true} values even when + * {@code areFieldsSet} is false. + * Accessing the fields via {@code get} will ensure the fields are up-to-date. */ protected boolean areFieldsSet; /** - * An integer array of calendar fields. The length is {@code FIELD_COUNT}. + * Contains broken-down field values for the current value of {@code time} if + * {@code areFieldsSet} is true, or stale data corresponding to some previous value otherwise. + * Accessing the fields via {@code get} will ensure the fields are up-to-date. + * The array length is always {@code FIELD_COUNT}. */ protected int[] fields; /** - * A boolean array. Each element indicates if the corresponding field has - * been set. The length is {@code FIELD_COUNT}. + * Whether the corresponding element in {@code field[]} has been set. Initially, these are all + * false. The first time the fields are computed, these are set to true and remain set even if + * the data becomes stale: you <i>must</i> check {@code areFieldsSet} if you want to know + * whether the value is up-to-date. + * Note that {@code isSet} is <i>not</i> a safe alternative to accessing this array directly, + * and will likewise return stale data! + * The array length is always {@code FIELD_COUNT}. */ protected boolean[] isSet; /** - * Set to {@code true} when the time has been set, set to {@code false} when a field is - * changed and the time must be recomputed. + * Whether {@code time} corresponds to the values in {@code fields[]}. If false, {@code time} + * is out-of-date with respect to changes {@code fields[]}. + * Accessing the time via {@code getTimeInMillis} will always return the correct value. */ protected boolean isTimeSet; /** - * The time in milliseconds since January 1, 1970. + * A time in milliseconds since January 1, 1970. See {@code isTimeSet}. + * Accessing the time via {@code getTimeInMillis} will always return the correct value. */ protected long time; @@ -1116,7 +1128,16 @@ public abstract class Calendar implements Serializable, Cloneable, } /** - * Returns whether the specified field is set. + * Returns whether the specified field is set. Note that the interpretation of "is set" is + * somewhat technical. In particular, it does <i>not</i> mean that the field's value is up + * to date. If you want to know whether a field contains an up-to-date value, you must also + * check {@code areFieldsSet}, making this method somewhat useless unless you're a subclass, + * in which case you can access the {@code isSet} array directly. + * <p> + * A field remains "set" from the first time its value is computed until it's cleared by one + * of the {@code clear} methods. Thus "set" does not mean "valid". You probably want to call + * {@code get} -- which will update fields as necessary -- rather than try to make use of + * this method. * * @param field * a {@code Calendar} field number. diff --git a/luni/src/main/java/java/util/Currency.java b/luni/src/main/java/java/util/Currency.java index 6aa295a..6b6e902 100644 --- a/luni/src/main/java/java/util/Currency.java +++ b/luni/src/main/java/java/util/Currency.java @@ -58,8 +58,17 @@ public final class Currency implements Serializable { return; } + // Ensure that we throw if the our currency code isn't an ISO currency code. + String symbol = Resources.getCurrencySymbolNative(Locale.US.toString(), currencyCode); + if (symbol == null) { + throw new IllegalArgumentException(Msg.getString("K0322", currencyCode)); + } + this.defaultFractionDigits = Resources.getCurrencyFractionDigitsNative(currencyCode); if (defaultFractionDigits < 0) { + // In practice, I don't think this can fail because ICU doesn't care whether you give + // it a valid country code, and will just return a sensible default for the default + // locale's currency. throw new IllegalArgumentException(Msg.getString("K0322", currencyCode)); } // END android-changed diff --git a/luni/src/main/java/java/util/Formatter.java b/luni/src/main/java/java/util/Formatter.java index 744df1f..09ea5fc 100644 --- a/luni/src/main/java/java/util/Formatter.java +++ b/luni/src/main/java/java/util/Formatter.java @@ -605,7 +605,7 @@ public final class Formatter implements Closeable, Flushable { * then no localization will be used. */ public Formatter(Appendable a, Locale l) { - if (null == a) { + if (a == null) { out = new StringBuilder(); } else { out = a; @@ -867,7 +867,7 @@ public final class Formatter implements Closeable, Flushable { * be raised. */ public Formatter(PrintStream ps) { - if (null == ps) { + if (ps == null) { throw new NullPointerException(); } out = ps; @@ -1107,7 +1107,7 @@ public final class Formatter implements Closeable, Flushable { throw new MissingFormatArgumentException("<"); //$NON-NLS-1$ } - if (null == args) { + if (args == null) { return null; } @@ -1123,7 +1123,7 @@ public final class Formatter implements Closeable, Flushable { } private static void closeOutputStream(OutputStream os) { - if (null == os) { + if (os == null) { return; } try { @@ -1171,28 +1171,14 @@ public final class Formatter implements Closeable, Flushable { // Tests whether there were no flags, no width, and no precision specified. boolean isDefault() { - // TODO: call hasDefaultFlags when the JIT can inline it. return !flagAdd && !flagComma && !flagMinus && !flagParenthesis && !flagSharp && !flagSpace && !flagZero && width == UNSET && precision == UNSET; } - boolean hasDefaultFlags() { - return !flagAdd && !flagComma && !flagMinus && !flagParenthesis && !flagSharp && - !flagSpace && !flagZero; - } - boolean isPrecisionSet() { return precision != UNSET; } - boolean isWidthSet() { - return width != UNSET; - } - - boolean hasArg() { - return argIndex != UNSET; - } - int getArgIndex() { return argIndex; } @@ -1289,22 +1275,133 @@ public final class Formatter implements Closeable, Flushable { return conversionType != '%' && conversionType != 'n'; } - void checkMissingWidth() { - if (flagMinus && width == UNSET) { + void checkFlags(Object arg) { + // Work out which flags are allowed. + boolean allowAdd = false; + boolean allowComma = false; + boolean allowMinus = true; + boolean allowParenthesis = false; + boolean allowSharp = false; + boolean allowSpace = false; + boolean allowZero = false; + // Precision and width? + boolean allowPrecision = true; + boolean allowWidth = true; + // Argument? + boolean allowArgument = true; + switch (conversionType) { + // Character and date/time. + case 'c': case 'C': case 't': case 'T': + // Only '-' is allowed. + allowPrecision = false; + break; + + // String. + case 's': case 'S': + if (arg instanceof Formattable) { + allowSharp = true; + } + break; + + // Floating point. + case 'g': case 'G': + allowAdd = allowComma = allowParenthesis = allowSpace = allowZero = true; + break; + case 'f': + allowAdd = allowComma = allowParenthesis = allowSharp = allowSpace = allowZero = true; + break; + case 'e': case 'E': + allowAdd = allowParenthesis = allowSharp = allowSpace = allowZero = true; + break; + case 'a': case 'A': + allowAdd = allowSharp = allowSpace = allowZero = true; + break; + + // Integral. + case 'd': + allowAdd = allowComma = allowParenthesis = allowSpace = allowZero = true; + allowPrecision = false; + break; + case 'o': case 'x': case 'X': + allowSharp = allowZero = true; + if (arg == null || arg instanceof BigInteger) { + allowAdd = allowParenthesis = allowSpace = true; + } + allowPrecision = false; + break; + + // Special. + case 'n': + // Nothing is allowed. + allowMinus = false; + allowArgument = allowPrecision = allowWidth = false; + break; + case '%': + // The only flag allowed is '-', and no argument or precision is allowed. + allowArgument = false; + allowPrecision = false; + break; + + // Booleans and hash codes. + case 'b': case 'B': case 'h': case 'H': + break; + + default: + throw new AssertionError(conversionType); + } + + // Check for disallowed flags. + String mismatch = null; + if (!allowAdd && flagAdd) { + mismatch = "+"; + } else if (!allowComma && flagComma) { + mismatch = ","; + } else if (!allowMinus && flagMinus) { + mismatch = "-"; + } else if (!allowParenthesis && flagParenthesis) { + mismatch = "("; + } else if (!allowSharp && flagSharp) { + mismatch = "#"; + } else if (!allowSpace && flagSpace) { + mismatch = " "; + } else if (!allowZero && flagZero) { + mismatch = "0"; + } + if (mismatch != null) { + if (conversionType == 'n') { + // For no good reason, %n is a special case... + throw new IllegalFormatFlagsException(mismatch); + } else { + throw new FormatFlagsConversionMismatchException(mismatch, conversionType); + } + } + + // Check for a missing width with flags that require a width. + if ((flagMinus || flagZero) && width == UNSET) { throw new MissingFormatWidthException("-" + conversionType); } - } - - void ensureOnlyMinus() { - if (flagAdd || flagComma || flagParenthesis || flagSharp || flagSpace || flagZero) { - throw new FormatFlagsConversionMismatchException(getStrFlags(), conversionType); + + // Check that no-argument conversion types don't have an argument. + // Note: the RI doesn't enforce this. + if (!allowArgument && argIndex != UNSET) { + throw new IllegalFormatFlagsException(getStrFlags()); } - } - - void ensureNoPrecision() { - if (isPrecisionSet()) { + + // Check that we don't have a precision or width where they're not allowed. + if (!allowPrecision && precision != UNSET) { throw new IllegalFormatPrecisionException(precision); } + if (!allowWidth && width != UNSET) { + throw new IllegalFormatWidthException(width); + } + + // Some combinations make no sense... + if (flagAdd && flagSpace) { + throw new IllegalFormatFlagsException("the '+' and ' ' flags are incompatible"); + } + if (flagMinus && flagZero) { + throw new IllegalFormatFlagsException("the '-' and '0' flags are incompatible"); + } } } @@ -1329,7 +1426,7 @@ public final class Formatter implements Closeable, Flushable { Transformer(Formatter formatter, Locale locale) { this.formatter = formatter; - this.locale = (null == locale ? Locale.US : locale); + this.locale = (locale == null ? Locale.US : locale); } private NumberFormat getNumberFormat() { @@ -1378,6 +1475,7 @@ public final class Formatter implements Closeable, Flushable { } } + formatToken.checkFlags(arg); CharSequence result; switch (token.getConversionType()) { case 'B': @@ -1404,7 +1502,7 @@ public final class Formatter implements Closeable, Flushable { case 'o': case 'x': case 'X': { - if (null == arg || arg instanceof BigInteger) { + if (arg == null || arg instanceof BigInteger) { result = transformFromBigInteger(); } else { result = transformFromInteger(); @@ -1457,8 +1555,6 @@ public final class Formatter implements Closeable, Flushable { * Transforms the Boolean argument to a formatted string. */ private CharSequence transformFromBoolean() { - formatToken.checkMissingWidth(); - formatToken.ensureOnlyMinus(); CharSequence result; if (arg instanceof Boolean) { result = arg.toString(); @@ -1474,8 +1570,6 @@ public final class Formatter implements Closeable, Flushable { * Transforms the hash code of the argument to a formatted string. */ private CharSequence transformFromHashCode() { - formatToken.checkMissingWidth(); - formatToken.ensureOnlyMinus(); CharSequence result; if (arg == null) { result = "null"; //$NON-NLS-1$ @@ -1489,23 +1583,18 @@ public final class Formatter implements Closeable, Flushable { * Transforms the String to a formatted string. */ private CharSequence transformFromString() { - formatToken.checkMissingWidth(); if (arg instanceof Formattable) { - // only minus and sharp flag is valid - if (formatToken.flagAdd || formatToken.flagComma || formatToken.flagParenthesis || formatToken.flagSpace || formatToken.flagZero) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - int flag = 0; + int flags = 0; if (formatToken.flagMinus) { - flag |= FormattableFlags.LEFT_JUSTIFY; + flags |= FormattableFlags.LEFT_JUSTIFY; } if (formatToken.flagSharp) { - flag |= FormattableFlags.ALTERNATE; + flags |= FormattableFlags.ALTERNATE; } if (Character.isUpperCase(formatToken.getConversionType())) { - flag |= FormattableFlags.UPPERCASE; + flags |= FormattableFlags.UPPERCASE; } - ((Formattable) arg).formatTo(formatter, flag, formatToken.getWidth(), + ((Formattable) arg).formatTo(formatter, flags, formatToken.getWidth(), formatToken.getPrecision()); // all actions have been taken out in the // Formattable.formatTo, thus there is nothing to do, just @@ -1513,8 +1602,6 @@ public final class Formatter implements Closeable, Flushable { // output. return null; } - // only '-' is valid for flags if the argument is not an instance of Formattable - formatToken.ensureOnlyMinus(); CharSequence result = arg != null ? arg.toString() : "null"; return padding(result, 0); } @@ -1523,10 +1610,6 @@ public final class Formatter implements Closeable, Flushable { * Transforms the Character to a formatted string. */ private CharSequence transformFromCharacter() { - formatToken.checkMissingWidth(); - formatToken.ensureOnlyMinus(); - formatToken.ensureNoPrecision(); - if (arg == null) { return padding("null", 0); } @@ -1551,12 +1634,6 @@ public final class Formatter implements Closeable, Flushable { * Precision and arguments are illegal. */ private CharSequence transformFromPercent() { - formatToken.checkMissingWidth(); - formatToken.ensureOnlyMinus(); - formatToken.ensureNoPrecision(); - if (formatToken.hasArg()) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } return padding("%", 0); } @@ -1565,16 +1642,6 @@ public final class Formatter implements Closeable, Flushable { * precision or argument is illegal. */ private CharSequence transformFromLineSeparator() { - formatToken.ensureNoPrecision(); - - if (formatToken.isWidthSet()) { - throw new IllegalFormatWidthException(formatToken.getWidth()); - } - - if (!formatToken.hasDefaultFlags() || formatToken.hasArg()) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - if (lineSeparator == null) { lineSeparator = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { @@ -1660,16 +1727,6 @@ public final class Formatter implements Closeable, Flushable { StringBuilder result = new StringBuilder(); char currentConversionType = formatToken.getConversionType(); - if (formatToken.flagMinus || formatToken.flagZero) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - // Combination of '+' and ' ' is illegal. - if (formatToken.flagAdd && formatToken.flagSpace) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - formatToken.ensureNoPrecision(); long value; if (arg instanceof Long) { value = ((Long) arg).longValue(); @@ -1682,19 +1739,9 @@ public final class Formatter implements Closeable, Flushable { } else { throw badArgumentType(); } - if ('d' != currentConversionType) { - if (formatToken.flagAdd || formatToken.flagSpace || formatToken.flagComma || - formatToken.flagParenthesis) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - } if (formatToken.flagSharp) { - if ('d' == currentConversionType) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } else if ('o' == currentConversionType) { + if (currentConversionType == 'o') { result.append("0"); //$NON-NLS-1$ startIndex += 1; } else { @@ -1703,10 +1750,6 @@ public final class Formatter implements Closeable, Flushable { } } - if (formatToken.flagMinus && formatToken.flagZero) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - if ('d' == currentConversionType) { if (formatToken.flagComma) { NumberFormat numberFormat = getNumberFormat(); @@ -1798,34 +1841,6 @@ public final class Formatter implements Closeable, Flushable { BigInteger bigInt = (BigInteger) arg; char currentConversionType = formatToken.getConversionType(); - if (formatToken.flagMinus || formatToken.flagZero) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - - // Combination of '+' & ' ' is illegal. - if (formatToken.flagAdd && formatToken.flagSpace) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - // Combination of '-' & '0' is illegal. - if (formatToken.flagZero && formatToken.flagMinus) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - formatToken.ensureNoPrecision(); - - if ('d' != currentConversionType && formatToken.flagComma) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - - if (formatToken.flagSharp && 'd' == currentConversionType) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - if (bigInt == null) { return transformFromNull(); } @@ -1884,38 +1899,7 @@ public final class Formatter implements Closeable, Flushable { int startIndex = 0; char currentConversionType = formatToken.getConversionType(); - if (formatToken.flagMinus || formatToken.flagZero) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - - if (formatToken.flagAdd && formatToken.flagSpace) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (formatToken.flagMinus && formatToken.flagZero) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (currentConversionType == 'e' || currentConversionType == 'E') { - if (formatToken.flagComma) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - } else if (currentConversionType == 'g' || currentConversionType == 'G') { - if (formatToken.flagSharp) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - } else if (currentConversionType == 'a' || currentConversionType == 'A') { - if (formatToken.flagComma || formatToken.flagParenthesis) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - } - - if (null == arg) { + if (arg == null) { return transformFromNull(); } @@ -1972,21 +1956,7 @@ public final class Formatter implements Closeable, Flushable { * Transforms a Date to a formatted string. */ private CharSequence transformFromDateTime() { - formatToken.ensureNoPrecision(); - - char currentConversionType = formatToken.getConversionType(); - - if (formatToken.flagSharp) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - currentConversionType); - } - - if (formatToken.flagMinus && formatToken.getWidth() == FormatToken.UNSET) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + currentConversionType); - } - - if (null == arg) { + if (arg == null) { return transformFromNull(); } @@ -2006,7 +1976,7 @@ public final class Formatter implements Closeable, Flushable { calendar.setTime(date); } - if (null == dateTimeUtil) { + if (dateTimeUtil == null) { dateTimeUtil = new DateTimeUtil(locale); } StringBuilder result = new StringBuilder(); @@ -2016,6 +1986,7 @@ public final class Formatter implements Closeable, Flushable { } } + // TODO: merge this into Transformer; the distinction is not obviously useful. private static class FloatUtil { private final StringBuilder result; private final DecimalFormat decimalFormat; @@ -2188,14 +2159,11 @@ public final class Formatter implements Closeable, Flushable { if (argument instanceof Float) { Float F = (Float) argument; result.append(Float.toHexString(F.floatValue())); - } else if (argument instanceof Double) { Double D = (Double) argument; result.append(Double.toHexString(D.doubleValue())); } else { - // BigInteger is not supported. - throw new IllegalFormatConversionException( - formatToken.getConversionType(), argument.getClass()); + throw badArgumentType(); } if (!formatToken.isPrecisionSet()) { @@ -2220,6 +2188,11 @@ public final class Formatter implements Closeable, Flushable { } result.delete(indexOfFirstFractionalDigit + precision, indexOfP); } + + private IllegalFormatConversionException badArgumentType() { + throw new IllegalFormatConversionException(formatToken.getConversionType(), + argument.getClass()); + } } private static class DateTimeUtil { @@ -2592,7 +2565,7 @@ public final class Formatter implements Closeable, Flushable { } private DateFormatSymbols getDateFormatSymbols() { - if (null == dateFormatSymbols) { + if (dateFormatSymbols == null) { dateFormatSymbols = new DateFormatSymbols(locale); } return dateFormatSymbols; @@ -2638,11 +2611,15 @@ public final class Formatter implements Closeable, Flushable { private char advance() { if (i >= length) { - throw new UnknownFormatConversionException(getFormatSpecifierText()); + throw unknownFormatConversionException(); } return format.charAt(i++); } - + + private UnknownFormatConversionException unknownFormatConversionException() { + throw new UnknownFormatConversionException(getFormatSpecifierText()); + } + private FormatToken parseArgumentIndexAndFlags(FormatToken token) { // Parse the argument index, if there is one. int position = i; @@ -2708,7 +2685,7 @@ public final class Formatter implements Closeable, Flushable { return parseConversionType(token); } else { // The precision is required but not given by the format string. - throw new UnknownFormatConversionException(getFormatSpecifierText()); + throw unknownFormatConversionException(); } } diff --git a/luni/src/main/java/java/util/Grego.java b/luni/src/main/java/java/util/Grego.java new file mode 100644 index 0000000..df7a7fa --- /dev/null +++ b/luni/src/main/java/java/util/Grego.java @@ -0,0 +1,214 @@ +/**
+ *******************************************************************************
+ * Copyright (C) 2003-2008, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ *******************************************************************************
+ * Partial port from ICU4C's Grego class in i18n/gregoimp.h.
+ *
+ * Methods ported, or moved here from OlsonTimeZone, initially
+ * for work on Jitterbug 5470:
+ * tzdata2006n Brazil incorrect fall-back date 2009-mar-01
+ * Only the methods necessary for that work are provided - this is not a full
+ * port of ICU4C's Grego class (yet).
+ *
+ * These utilities are used by both OlsonTimeZone and SimpleTimeZone.
+ */
+
+package java.util; // android-changed: com.ibm.icu.impl (ICU4J 4.2)
+
+// android-changed: import com.ibm.icu.util.Calendar;
+
+/**
+ * A utility class providing proleptic Gregorian calendar functions
+ * used by time zone and calendar code. Do not instantiate.
+ *
+ * Note: Unlike GregorianCalendar, all computations performed by this
+ * class occur in the pure proleptic GregorianCalendar.
+ */
+// android-changed: public
+class Grego {
+
+ // Max/min milliseconds
+ public static final long MIN_MILLIS = -184303902528000000L;
+ public static final long MAX_MILLIS = 183882168921600000L;
+
+ public static final int MILLIS_PER_SECOND = 1000;
+ public static final int MILLIS_PER_MINUTE = 60*MILLIS_PER_SECOND;
+ public static final int MILLIS_PER_HOUR = 60*MILLIS_PER_MINUTE;
+ public static final int MILLIS_PER_DAY = 24*MILLIS_PER_HOUR;
+
+ // January 1, 1 CE Gregorian
+ private static final int JULIAN_1_CE = 1721426;
+
+ // January 1, 1970 CE Gregorian
+ private static final int JULIAN_1970_CE = 2440588;
+
+ private static final int[] MONTH_LENGTH = new int[] {
+ 31,28,31,30,31,30,31,31,30,31,30,31,
+ 31,29,31,30,31,30,31,31,30,31,30,31
+ };
+
+ private static final int[] DAYS_BEFORE = new int[] {
+ 0,31,59,90,120,151,181,212,243,273,304,334,
+ 0,31,60,91,121,152,182,213,244,274,305,335 };
+
+ /**
+ * Return true if the given year is a leap year.
+ * @param year Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+ * @return true if the year is a leap year
+ */
+ public static final boolean isLeapYear(int year) {
+ // year&0x3 == year%4
+ return ((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0));
+ }
+
+ /**
+ * Return the number of days in the given month.
+ * @param year Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+ * @param month 0-based month, with 0==Jan
+ * @return the number of days in the given month
+ */
+ public static final int monthLength(int year, int month) {
+ return MONTH_LENGTH[month + (isLeapYear(year) ? 12 : 0)];
+ }
+
+ /**
+ * Return the length of a previous month of the Gregorian calendar.
+ * @param year Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+ * @param month 0-based month, with 0==Jan
+ * @return the number of days in the month previous to the given month
+ */
+ public static final int previousMonthLength(int year, int month) {
+ return (month > 0) ? monthLength(year, month-1) : 31;
+ }
+
+ /**
+ * Convert a year, month, and day-of-month, given in the proleptic
+ * Gregorian calendar, to 1970 epoch days.
+ * @param year Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+ * @param month 0-based month, with 0==Jan
+ * @param dom 1-based day of month
+ * @return the day number, with day 0 == Jan 1 1970
+ */
+ public static long fieldsToDay(int year, int month, int dom) {
+ int y = year - 1;
+ long julian =
+ 365 * y + floorDivide(y, 4) + (JULIAN_1_CE - 3) + // Julian cal
+ floorDivide(y, 400) - floorDivide(y, 100) + 2 + // => Gregorian cal
+ DAYS_BEFORE[month + (isLeapYear(year) ? 12 : 0)] + dom; // => month/dom
+ return julian - JULIAN_1970_CE; // JD => epoch day
+ }
+
+ /**
+ * Return the day of week on the 1970-epoch day
+ * @param day the 1970-epoch day (integral value)
+ * @return the day of week
+ */
+ public static int dayOfWeek(long day) {
+ long[] remainder = new long[1];
+ floorDivide(day + Calendar.THURSDAY, 7, remainder);
+ int dayOfWeek = (int)remainder[0];
+ dayOfWeek = (dayOfWeek == 0) ? 7 : dayOfWeek;
+ return dayOfWeek;
+ }
+
+ public static int[] dayToFields(long day, int[] fields) {
+ if (fields == null || fields.length < 5) {
+ fields = new int[5];
+ }
+ // Convert from 1970 CE epoch to 1 CE epoch (Gregorian calendar)
+ day += JULIAN_1970_CE - JULIAN_1_CE;
+
+ long[] rem = new long[1];
+ long n400 = floorDivide(day, 146097, rem);
+ long n100 = floorDivide(rem[0], 36524, rem);
+ long n4 = floorDivide(rem[0], 1461, rem);
+ long n1 = floorDivide(rem[0], 365, rem);
+
+ int year = (int)(400 * n400 + 100 * n100 + 4 * n4 + n1);
+ int dayOfYear = (int)rem[0];
+ if (n100 == 4 || n1 == 4) {
+ dayOfYear = 365; // Dec 31 at end of 4- or 400-yr cycle
+ }
+ else {
+ ++year;
+ }
+
+ boolean isLeap = isLeapYear(year);
+ int correction = 0;
+ int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
+ if (dayOfYear >= march1) {
+ correction = isLeap ? 1 : 2;
+ }
+ int month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
+ int dayOfMonth = dayOfYear - DAYS_BEFORE[isLeap ? month + 12 : month] + 1; // one-based DOM
+ int dayOfWeek = (int)((day + 2) % 7); // day 0 is Monday(2)
+ if (dayOfWeek < 1 /* Sunday */) {
+ dayOfWeek += 7;
+ }
+ dayOfYear++; // 1-based day of year
+
+ fields[0] = year;
+ fields[1] = month;
+ fields[2] = dayOfMonth;
+ fields[3] = dayOfWeek;
+ fields[4] = dayOfYear;
+
+ return fields;
+ }
+
+ /*
+ * Convert long time to date/time fields
+ *
+ * result[0] : year
+ * result[1] : month
+ * result[2] : dayOfMonth
+ * result[3] : dayOfWeek
+ * result[4] : dayOfYear
+ * result[5] : millisecond in day
+ */
+ public static int[] timeToFields(long time, int[] fields) {
+ if (fields == null || fields.length < 6) {
+ fields = new int[6];
+ }
+ long[] remainder = new long[1];
+ long day = floorDivide(time, 24*60*60*1000 /* milliseconds per day */, remainder);
+ dayToFields(day, fields);
+ fields[5] = (int)remainder[0];
+ return fields;
+ }
+
+ public static long floorDivide(long numerator, long denominator) {
+ // We do this computation in order to handle
+ // a numerator of Long.MIN_VALUE correctly
+ return (numerator >= 0) ?
+ numerator / denominator :
+ ((numerator + 1) / denominator) - 1;
+ }
+
+ private static long floorDivide(long numerator, long denominator, long[] remainder) {
+ if (numerator >= 0) {
+ remainder[0] = numerator % denominator;
+ return numerator / denominator;
+ }
+ long quotient = ((numerator + 1) / denominator) - 1;
+ remainder[0] = numerator - (quotient * denominator);
+ return quotient;
+ }
+
+ /*
+ * Returns the ordinal number for the specified day of week in the month.
+ * The valid return value is 1, 2, 3, 4 or -1.
+ */
+ public static int getDayOfWeekInMonth(int year, int month, int dayOfMonth) {
+ int weekInMonth = (dayOfMonth + 6)/7;
+ if (weekInMonth == 4) {
+ if (dayOfMonth + 7 > monthLength(year, month)) {
+ weekInMonth = -1;
+ }
+ } else if (weekInMonth == 5) {
+ weekInMonth = -1;
+ }
+ return weekInMonth;
+ }
+}
diff --git a/luni/src/main/java/java/util/GregorianCalendar.java b/luni/src/main/java/java/util/GregorianCalendar.java index 7339151..18a10ad 100644 --- a/luni/src/main/java/java/util/GregorianCalendar.java +++ b/luni/src/main/java/java/util/GregorianCalendar.java @@ -591,15 +591,14 @@ public class GregorianCalendar extends Calendar { @Override protected void computeFields() { - int zoneOffset = getTimeZone().getRawOffset(); - - if(!isSet[ZONE_OFFSET]) { - fields[ZONE_OFFSET] = zoneOffset; - } + TimeZone timeZone = getTimeZone(); + int dstOffset = timeZone.inDaylightTime(new Date(time)) ? timeZone.getDSTSavings() : 0; + int zoneOffset = timeZone.getRawOffset(); + fields[DST_OFFSET] = dstOffset; + fields[ZONE_OFFSET] = zoneOffset; int millis = (int) (time % 86400000); int savedMillis = millis; - int dstOffset = fields[DST_OFFSET]; // compute without a change in daylight saving time int offset = zoneOffset + dstOffset; long newTime = time + offset; @@ -610,6 +609,8 @@ public class GregorianCalendar extends Calendar { newTime = 0x8000000000000000L; } + // FIXME: I don't think this caching ever really gets used, because it requires that the + // time zone doesn't use daylight savings (ever). So unless you're somewhere like Taiwan... if (isCached) { if (millis < 0) { millis += 86400000; @@ -636,11 +637,11 @@ public class GregorianCalendar extends Calendar { fields[AM_PM] = fields[HOUR_OF_DAY] > 11 ? 1 : 0; fields[HOUR] = fields[HOUR_OF_DAY] % 12; + // FIXME: this has to be wrong; useDaylightTime doesn't mean what they think it means! long newTimeAdjusted = newTime; - if (getTimeZone().useDaylightTime()) { + if (timeZone.useDaylightTime()) { // BEGIN android-changed: removed unnecessary cast - int dstSavings = (/* (SimpleTimeZone) */ getTimeZone()) - .getDSTSavings(); + int dstSavings = timeZone.getDSTSavings(); // END android-changed newTimeAdjusted += (dstOffset == 0) ? dstSavings : -dstSavings; } @@ -665,7 +666,7 @@ public class GregorianCalendar extends Calendar { if (!isCached && newTime != 0x7fffffffffffffffL && newTime != 0x8000000000000000L - && (!getTimeZone().useDaylightTime() || getTimeZone() instanceof SimpleTimeZone)) { + && (!timeZone.useDaylightTime() || timeZone instanceof SimpleTimeZone)) { int cacheMillis = 0; cachedFields[0] = fields[YEAR]; @@ -992,6 +993,12 @@ public class GregorianCalendar extends Calendar { */ @Override public boolean equals(Object object) { + if (!(object instanceof GregorianCalendar)) { + return false; + } + if (object == this) { + return true; + } return super.equals(object) && gregorianCutover == ((GregorianCalendar) object).gregorianCutover; } @@ -1151,7 +1158,7 @@ public class GregorianCalendar extends Calendar { return minimums[field]; } - int getOffset(long localTime) { + private int getOffset(long localTime) { TimeZone timeZone = getTimeZone(); if (!timeZone.useDaylightTime()) { return timeZone.getRawOffset(); diff --git a/luni/src/main/java/java/util/Locale.java b/luni/src/main/java/java/util/Locale.java index 5337e48..9b35a0f 100644 --- a/luni/src/main/java/java/util/Locale.java +++ b/luni/src/main/java/java/util/Locale.java @@ -157,6 +157,15 @@ public final class Locale implements Cloneable, Serializable { public static final Locale PRC = new Locale("zh", "CN"); //$NON-NLS-1$//$NON-NLS-2$ /** + * Locale constant for the root locale. The root locale has an empty language, + * country, and variant. + * + * @since 1.6 + * @hide + */ + public static final Locale ROOT = new Locale("", "", ""); + + /** * Locale constant for zh_CN. */ public static final Locale SIMPLIFIED_CHINESE = new Locale("zh", "CN"); //$NON-NLS-1$//$NON-NLS-2$ @@ -327,31 +336,6 @@ public final class Locale implements Cloneable, Serializable { return false; } - // BEGIN android-added - static Locale[] find() { - String[] locales = Resources.getAvailableLocales(); - ArrayList<Locale> temp = new ArrayList<Locale>(); - for (int i = 0; i < locales.length; i++) { - String s = locales[i]; - int first = s.indexOf('_'); - int second = s.indexOf('_', first + 1); - - if (first == -1) { - // Language only - temp.add(new Locale(s)); - } else if (second == -1) { - // Language and country - temp.add(new Locale(s.substring(0, first), s.substring(first + 1))); - } else { - // Language and country and variant - temp.add(new Locale(s.substring(0, first), s.substring(first + 1, second), s.substring(second + 1))); - } - } - Locale[] result = new Locale[temp.size()]; - return temp.toArray(result); - } - // END android-added - /** * Gets the list of installed {@code Locale}s. At least a {@code Locale} that is equal to * {@code Locale.US} must be contained in this array. @@ -360,14 +344,8 @@ public final class Locale implements Cloneable, Serializable { */ public static Locale[] getAvailableLocales() { // BEGIN android-changed - // ULocale[] ulocales = ULocale.getAvailableLocales(); - // Locale[] locales = new Locale[ulocales.length]; - // for (int i = 0; i < locales.length; i++) { - // locales[i] = ulocales[i].toLocale(); - // } - // return locales; if (availableLocales == null) { - availableLocales = find(); + availableLocales = Resources.localesFromStrings(Resources.getAvailableLocales()); } return availableLocales.clone(); // END android-changed diff --git a/luni/src/main/java/java/util/ResourceBundle.java b/luni/src/main/java/java/util/ResourceBundle.java index ec669d6..452ba8a 100644 --- a/luni/src/main/java/java/util/ResourceBundle.java +++ b/luni/src/main/java/java/util/ResourceBundle.java @@ -17,6 +17,7 @@ package java.util; +import com.ibm.icu4jni.util.Resources; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; @@ -444,25 +445,8 @@ public abstract class ResourceBundle { } private void setLocale(String name) { - String language = "", country = "", variant = ""; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ - if (name.length() > 1) { - int nextIndex = name.indexOf('_', 1); - if (nextIndex == -1) { - nextIndex = name.length(); - } - language = name.substring(1, nextIndex); - if (nextIndex + 1 < name.length()) { - int index = nextIndex; - nextIndex = name.indexOf('_', nextIndex + 1); - if (nextIndex == -1) { - nextIndex = name.length(); - } - country = name.substring(index + 1, nextIndex); - if (nextIndex + 1 < name.length()) { - variant = name.substring(nextIndex + 1, name.length()); - } - } - } - locale = new Locale(language, country, variant); + // BEGIN android-changed: remove duplication. + locale = Resources.localeFromString(name); + // END android-changed } } diff --git a/luni/src/main/java/java/util/SimpleTimeZone.java b/luni/src/main/java/java/util/SimpleTimeZone.java index 702b6ef..61d31fc 100644 --- a/luni/src/main/java/java/util/SimpleTimeZone.java +++ b/luni/src/main/java/java/util/SimpleTimeZone.java @@ -94,8 +94,6 @@ public class SimpleTimeZone extends TimeZone { private boolean useDaylight; - private GregorianCalendar daylightSavings; - private int dstSavings = 3600000; // BEGIN android-removed @@ -349,9 +347,6 @@ public class SimpleTimeZone extends TimeZone { @Override public Object clone() { SimpleTimeZone zone = (SimpleTimeZone) super.clone(); - if (daylightSavings != null) { - zone.daylightSavings = (GregorianCalendar) daylightSavings.clone(); - } return zone; } @@ -530,15 +525,13 @@ public class SimpleTimeZone extends TimeZone { @Override public int getOffset(long time) { - // BEGIN android-changed - // return icuTZ.getOffset(time); + // BEGIN android-changed: simplified variant of the ICU4J code. if (!useDaylightTime()) { return rawOffset; } - if (daylightSavings == null) { - daylightSavings = new GregorianCalendar(this); - } - return daylightSavings.getOffset(time + 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 } @@ -588,17 +581,8 @@ public class SimpleTimeZone extends TimeZone { @Override public boolean inDaylightTime(Date time) { - // BEGIN android-changed - // return icuTZ.inDaylightTime(time); - // check for null pointer - long millis = time.getTime(); - if (!useDaylightTime()) { - return false; - } - if (daylightSavings == null) { - daylightSavings = new GregorianCalendar(this); - } - return daylightSavings.getOffset(millis + rawOffset) != rawOffset; + // BEGIN android-changed: reuse getOffset. + return useDaylightTime() && getOffset(time.getTime()) != rawOffset; // END android-changed } diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java index bdd1d0a..f919b39 100644 --- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java +++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java @@ -19,7 +19,8 @@ package org.apache.harmony.luni.internal.net.www.protocol.http; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; +import java.util.SortedMap; +import java.util.TreeMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -30,13 +31,9 @@ import java.util.Map.Entry; * constructed by hashtable with key indexed in a vector for position lookup. */ public class Header implements Cloneable { - /* - * we use the non-synchronized ArrayList and HashMap instead of the - * synchronized Vector and Hashtable - */ private ArrayList<String> props; - private HashMap<String, LinkedList<String>> keyTable; + private SortedMap<String, LinkedList<String>> keyTable; private String statusLine; @@ -48,7 +45,8 @@ public class Header implements Cloneable { public Header() { super(); this.props = new ArrayList<String>(20); - this.keyTable = new HashMap<String, LinkedList<String>>(20); + this.keyTable = new TreeMap<String, LinkedList<String>>( + String.CASE_INSENSITIVE_ORDER); } /** @@ -62,11 +60,11 @@ public class Header implements Cloneable { this(); // initialize fields for (Entry<String, List<String>> next : map.entrySet()) { String key = next.getKey(); - props.add(key); List<String> value = next.getValue(); LinkedList<String> linkedList = new LinkedList<String>(); for (String element : value) { linkedList.add(element); + props.add(key); props.add(element); } keyTable.put(key, linkedList); @@ -79,7 +77,8 @@ public class Header implements Cloneable { try { Header clone = (Header) super.clone(); clone.props = (ArrayList<String>) props.clone(); - clone.keyTable = new HashMap<String, LinkedList<String>>(20); + clone.keyTable = new TreeMap<String, LinkedList<String>>( + String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, LinkedList<String>> next : this.keyTable .entrySet()) { LinkedList<String> v = (LinkedList<String>) next.getValue() @@ -102,14 +101,11 @@ public class Header implements Cloneable { if (key == null) { throw new NullPointerException(); } - // BEGIN android-changed - key = key.toLowerCase(); LinkedList<String> list = keyTable.get(key); if (list == null) { list = new LinkedList<String>(); keyTable.put(key, list); } - // END android-changed list.add(value); props.add(key); props.add(value); @@ -126,9 +122,6 @@ public class Header implements Cloneable { if (key == null) { throw new NullPointerException(); } - // BEGIN android-added - key = key.toLowerCase(); - // END android-added LinkedList<String> list = keyTable.get(key); if (list == null) { add(key, value); @@ -154,8 +147,7 @@ public class Header implements Cloneable { * @since 1.4 */ public Map<String, List<String>> getFieldMap() { - Map<String, List<String>> result = new HashMap<String, List<String>>( - keyTable.size()); + Map<String, List<String>> result = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); // android-changed for (Map.Entry<String, LinkedList<String>> next : keyTable.entrySet()) { List<String> v = next.getValue(); result.put(next.getKey(), Collections.unmodifiableList(v)); @@ -203,7 +195,7 @@ public class Header implements Cloneable { * such key exists. */ public String get(String key) { - LinkedList<String> result = keyTable.get(key.toLowerCase()); + LinkedList<String> result = keyTable.get(key); if (result == null) { return null; } diff --git a/luni/src/main/native/ifaddrs-android.h b/luni/src/main/native/ifaddrs-android.h index 0c3d203..de87b02 100644 --- a/luni/src/main/native/ifaddrs-android.h +++ b/luni/src/main/native/ifaddrs-android.h @@ -17,8 +17,13 @@ #ifndef IFADDRS_ANDROID_H_included #define IFADDRS_ANDROID_H_included +#include <arpa/inet.h> #include <cstring> +#include <errno.h> +#include <net/if.h> +#include <netinet/in.h> #include <new> +#include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> @@ -43,11 +48,14 @@ struct ifaddrs { // Interface flags. unsigned int ifa_flags; - // Interface address. + // Interface network address. sockaddr* ifa_addr; + // Interface netmask. + sockaddr* ifa_netmask; + ifaddrs(ifaddrs* next) - : ifa_next(next), ifa_name(NULL), ifa_flags(0), ifa_addr(NULL) + : ifa_next(next), ifa_name(NULL), ifa_flags(0), ifa_addr(NULL), ifa_netmask(NULL) { } @@ -55,6 +63,7 @@ struct ifaddrs { delete ifa_next; delete[] ifa_name; delete ifa_addr; + delete ifa_netmask; } // Sadly, we can't keep the interface index for portability with BSD. @@ -91,16 +100,41 @@ struct ifaddrs { // stitch the two bits together into the sockaddr that's part of // our portable interface. void setAddress(int family, void* data, size_t byteCount) { + // Set the address proper... + sockaddr_storage* ss = new sockaddr_storage; + memset(ss, 0, sizeof(*ss)); + ifa_addr = reinterpret_cast<sockaddr*>(ss); + ss->ss_family = family; + uint8_t* dst = sockaddrBytes(family, ss); + memcpy(dst, data, byteCount); + } + + // Netlink gives us the prefix length as a bit count. We need to turn + // that into a BSD-compatible netmask represented by a sockaddr*. + void setNetmask(int family, size_t prefixLength) { + // ...and work out the netmask from the prefix length. sockaddr_storage* ss = new sockaddr_storage; + memset(ss, 0, sizeof(*ss)); + ifa_netmask = reinterpret_cast<sockaddr*>(ss); ss->ss_family = family; + uint8_t* dst = sockaddrBytes(family, ss); + memset(dst, 0xff, prefixLength / 8); + if ((prefixLength % 8) != 0) { + dst[prefixLength/8] = (0xff << (8 - (prefixLength % 8))); + } + } + + // Returns a pointer to the first byte in the address data (which is + // stored in network byte order). + uint8_t* sockaddrBytes(int family, sockaddr_storage* ss) { if (family == AF_INET) { - void* dst = &reinterpret_cast<sockaddr_in*>(ss)->sin_addr; - memcpy(dst, data, byteCount); + sockaddr_in* ss4 = reinterpret_cast<sockaddr_in*>(ss); + return reinterpret_cast<uint8_t*>(&ss4->sin_addr); } else if (family == AF_INET6) { - void* dst = &reinterpret_cast<sockaddr_in6*>(ss)->sin6_addr; - memcpy(dst, data, byteCount); + sockaddr_in6* ss6 = reinterpret_cast<sockaddr_in6*>(ss); + return reinterpret_cast<uint8_t*>(&ss6->sin6_addr); } - ifa_addr = reinterpret_cast<sockaddr*>(ss); + return NULL; } }; @@ -167,6 +201,7 @@ inline int getifaddrs(ifaddrs** result) { return -1; } (*result)->setAddress(family, RTA_DATA(rta), RTA_PAYLOAD(rta)); + (*result)->setNetmask(family, address->ifa_prefixlen); } } rta = RTA_NEXT(rta, ifaPayloadLength); diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp index ed25ce7..bd81361 100644 --- a/luni/src/main/native/java_io_File.cpp +++ b/luni/src/main/native/java_io_File.cpp @@ -128,7 +128,7 @@ static jbyteArray java_io_File_getLinkImpl(JNIEnv* env, jobject, jbyteArray path // An error occurred. return pathBytes; } - if (len < buf.size() - 1) { + if (static_cast<size_t>(len) < buf.size() - 1) { // The buffer was big enough. // TODO: why do we bother with the NUL termination? (if you change this, remove the "- 1"s above.) buf[len] = '\0'; // readlink(2) doesn't NUL-terminate. diff --git a/luni/src/main/native/java_net_NetworkInterface.cpp b/luni/src/main/native/java_net_NetworkInterface.cpp index 420c045..724e988 100644 --- a/luni/src/main/native/java_net_NetworkInterface.cpp +++ b/luni/src/main/native/java_net_NetworkInterface.cpp @@ -18,6 +18,7 @@ #include "AndroidSystemNatives.h" #include "JNIHelp.h" #include "jni.h" +#include "ScopedFd.h" #include <errno.h> #include <netinet/in.h> @@ -30,7 +31,7 @@ #include <net/if.h> // Note: Can't appear before <sys/socket.h> on OS X. -#ifdef ANDROID +#ifdef HAVE_ANDROID_OS #include "ifaddrs-android.h" #else #include <ifaddrs.h> @@ -64,27 +65,34 @@ static void jniThrowSocketException(JNIEnv* env) { jniStrError(errno, buf, sizeof(buf))); } -static jobject makeInterfaceAddress(JNIEnv* env, jint interfaceIndex, const char* name, sockaddr_storage* ss) { +static jobject makeInterfaceAddress(JNIEnv* env, jint interfaceIndex, ifaddrs* ifa) { jclass clazz = env->FindClass("java/net/InterfaceAddress"); if (clazz == NULL) { return NULL; } - jmethodID constructor = env->GetMethodID(clazz, "<init>", "(ILjava/lang/String;Ljava/net/InetAddress;)V"); + jmethodID constructor = env->GetMethodID(clazz, "<init>", + "(ILjava/lang/String;Ljava/net/InetAddress;Ljava/net/InetAddress;)V"); if (constructor == NULL) { return NULL; } - jobject javaName = env->NewStringUTF(name); + jobject javaName = env->NewStringUTF(ifa->ifa_name); if (javaName == NULL) { return NULL; } - jobject javaAddress = socketAddressToInetAddress(env, ss); + sockaddr_storage* addr = reinterpret_cast<sockaddr_storage*>(ifa->ifa_addr); + jobject javaAddress = socketAddressToInetAddress(env, addr); if (javaAddress == NULL) { return NULL; } - return env->NewObject(clazz, constructor, interfaceIndex, javaName, javaAddress); + sockaddr_storage* mask = reinterpret_cast<sockaddr_storage*>(ifa->ifa_netmask); + jobject javaMask = socketAddressToInetAddress(env, mask); + if (javaMask == NULL) { + return NULL; + } + return env->NewObject(clazz, constructor, interfaceIndex, javaName, javaAddress, javaMask); } -static jobjectArray getInterfaceAddresses(JNIEnv* env, jclass) { +static jobjectArray getAllInterfaceAddressesImpl(JNIEnv* env, jclass) { // Get the list of interface addresses. ScopedInterfaceAddresses addresses; if (!addresses.init()) { @@ -128,8 +136,7 @@ static jobjectArray getInterfaceAddresses(JNIEnv* env, jclass) { continue; } // Make a new InterfaceAddress, and insert it into the array. - sockaddr_storage* ss = reinterpret_cast<sockaddr_storage*>(ifa->ifa_addr); - jobject element = makeInterfaceAddress(env, interfaceIndex, ifa->ifa_name, ss); + jobject element = makeInterfaceAddress(env, interfaceIndex, ifa); if (element == NULL) { return NULL; } @@ -142,9 +149,89 @@ static jobjectArray getInterfaceAddresses(JNIEnv* env, jclass) { return result; } +static bool doIoctl(JNIEnv* env, jstring name, int request, ifreq& ifr) { + // Copy the name into the ifreq structure, if there's room... + jsize nameLength = env->GetStringLength(name); + if (nameLength >= IFNAMSIZ) { + errno = ENAMETOOLONG; + jniThrowSocketException(env); + return false; + } + memset(&ifr, 0, sizeof(ifr)); + env->GetStringUTFRegion(name, 0, nameLength, ifr.ifr_name); + + // ...and do the ioctl. + ScopedFd fd(socket(AF_INET, SOCK_DGRAM, 0)); + if (fd.get() == -1) { + jniThrowSocketException(env); + return false; + } + int rc = ioctl(fd.get(), request, &ifr); + if (rc == -1) { + jniThrowSocketException(env); + return false; + } + return true; +} + +static jboolean hasFlag(JNIEnv* env, jstring name, int flag) { + ifreq ifr; + doIoctl(env, name, SIOCGIFFLAGS, ifr); // May throw. + return (ifr.ifr_flags & flag) != 0; +} + +static jbyteArray getHardwareAddressImpl(JNIEnv* env, jclass, jstring name, jint index) { + ifreq ifr; + if (!doIoctl(env, name, SIOCGIFHWADDR, ifr)) { + return NULL; + } + jbyte bytes[IFHWADDRLEN]; + bool isEmpty = true; + for (int i = 0; i < IFHWADDRLEN; ++i) { + bytes[i] = ifr.ifr_hwaddr.sa_data[i]; + if (bytes[i] != 0) { + isEmpty = false; + } + } + if (isEmpty) { + return NULL; + } + jbyteArray result = env->NewByteArray(IFHWADDRLEN); + env->SetByteArrayRegion(result, 0, IFHWADDRLEN, bytes); + return result; +} + +static jint getMTUImpl(JNIEnv* env, jclass, jstring name, jint index) { + ifreq ifr; + doIoctl(env, name, SIOCGIFMTU, ifr); // May throw. + return ifr.ifr_mtu; +} + +static jboolean isLoopbackImpl(JNIEnv* env, jclass, jstring name, jint index) { + return hasFlag(env, name, IFF_LOOPBACK); +} + +static jboolean isPointToPointImpl(JNIEnv* env, jclass, jstring name, jint index) { + return hasFlag(env, name, IFF_POINTOPOINT); // Unix API typo! +} + +static jboolean isUpImpl(JNIEnv* env, jclass, jstring name, jint index) { + return hasFlag(env, name, IFF_UP); +} + +static jboolean supportsMulticastImpl(JNIEnv* env, jclass, jstring name, jint index) { + return hasFlag(env, name, IFF_MULTICAST); +} + static JNINativeMethod gMethods[] = { /* name, signature, funcPtr */ - { "getInterfaceAddresses", "()[Ljava/net/InterfaceAddress;", (void*) getInterfaceAddresses }, + { "getAllInterfaceAddressesImpl", "()[Ljava/net/InterfaceAddress;", (void*) getAllInterfaceAddressesImpl }, + { "getHardwareAddressImpl", "(Ljava/lang/String;I)[B", (void*) getHardwareAddressImpl }, + { "getMTUImpl", "(Ljava/lang/String;I)I", (void*) getMTUImpl }, + { "isLoopbackImpl", "(Ljava/lang/String;I)Z", (void*) isLoopbackImpl }, + { "isPointToPointImpl", "(Ljava/lang/String;I)Z", (void*) isPointToPointImpl }, + { "isUpImpl", "(Ljava/lang/String;I)Z", (void*) isUpImpl }, + { "supportsMulticastImpl", "(Ljava/lang/String;I)Z", (void*) supportsMulticastImpl }, }; int register_java_net_NetworkInterface(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/net/NetworkInterface", diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp index 12c3dd9..1a8f3a4 100644 --- a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp +++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp @@ -331,38 +331,70 @@ jobject socketAddressToInetAddress(JNIEnv* env, sockaddr_storage* sockAddress) { return byteArrayToInetAddress(env, byteArray); } -/** - * Converts an IPv4 address to an IPv4-mapped IPv6 address if fd is an IPv6 - * socket. - * @param fd the socket. - * @param sin_ss the address. - * @param sin6_ss scratch space where we can store the mapped address if necessary. - * @param mapUnspecified if true, convert 0.0.0.0 to ::ffff:0:0; if false, to :: - * @return either sin_ss or sin6_ss, depending on which the caller should use. - */ -static const sockaddr* convertIpv4ToMapped(int fd, - const sockaddr_storage* sin_ss, sockaddr_storage* sin6_ss, bool mapUnspecified) { - // We need to map if we have an IPv4 address but an IPv6 socket. - bool needsMapping = (sin_ss->ss_family == AF_INET && getSocketAddressFamily(fd) == AF_INET6); - if (!needsMapping) { - return reinterpret_cast<const sockaddr*>(sin_ss); - } - // Map the IPv4 address in sin_ss into an IPv6 address in sin6_ss. - const sockaddr_in* sin = reinterpret_cast<const sockaddr_in*>(sin_ss); - sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(sin6_ss); - memset(sin6, 0, sizeof(*sin6)); - sin6->sin6_family = AF_INET6; - sin6->sin6_port = sin->sin_port; - // TODO: mapUnspecified was introduced because kernels < 2.6.31 don't allow - // you to bind to ::ffff:0.0.0.0. When we move to something >= 2.6.31, we - // should make the code behave as if mapUnspecified were always true, and - // remove the parameter. - if (sin->sin_addr.s_addr != 0 || mapUnspecified) { - memset(&(sin6->sin6_addr.s6_addr[10]), 0xff, 2); - } - memcpy(&sin6->sin6_addr.s6_addr[12], &sin->sin_addr.s_addr, 4); - return reinterpret_cast<const sockaddr*>(sin6_ss); -} +// Handles translating between IPv4 and IPv6 addresses so -- where possible -- +// we can use either class of address with either an IPv4 or IPv6 socket. +class CompatibleSocketAddress { +public: + // Constructs an address corresponding to 'ss' that's compatible with 'fd'. + CompatibleSocketAddress(int fd, const sockaddr_storage& ss, bool mapUnspecified) { + const int desiredFamily = getSocketAddressFamily(fd); + if (ss.ss_family == AF_INET6) { + if (desiredFamily == AF_INET6) { + // Nothing to do. + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&ss); + } else { + sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(&mTmp); + const sockaddr_in6* sin6 = reinterpret_cast<const sockaddr_in6*>(&ss); + memset(sin, 0, sizeof(*sin)); + sin->sin_family = AF_INET; + sin->sin_port = sin6->sin6_port; + if (IN6_IS_ADDR_V4COMPAT(&sin6->sin6_addr)) { + // We have an IPv6-mapped IPv4 address, but need plain old IPv4. + // Unmap the mapped address in ss into an IPv6 address in mTmp. + memcpy(&sin->sin_addr.s_addr, &sin6->sin6_addr.s6_addr[12], 4); + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&mTmp); + } else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)) { + // Translate the IPv6 loopback address to the IPv4 one. + sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK); + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&mTmp); + } else { + // We can't help you. We return what you gave us, and assume you'll + // get a sensible error when you use the address. + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&ss); + } + } + } else /* ss.ss_family == AF_INET */ { + if (desiredFamily == AF_INET) { + // Nothing to do. + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&ss); + } else { + // We have IPv4 and need IPv6. + // Map the IPv4 address in ss into an IPv6 address in mTmp. + const sockaddr_in* sin = reinterpret_cast<const sockaddr_in*>(&ss); + sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(&mTmp); + memset(sin6, 0, sizeof(*sin6)); + sin6->sin6_family = AF_INET6; + sin6->sin6_port = sin->sin_port; + // TODO: mapUnspecified was introduced because kernels < 2.6.31 don't allow + // you to bind to ::ffff:0.0.0.0. When we move to something >= 2.6.31, we + // should make the code behave as if mapUnspecified were always true, and + // remove the parameter. + if (sin->sin_addr.s_addr != 0 || mapUnspecified) { + memset(&(sin6->sin6_addr.s6_addr[10]), 0xff, 2); + } + memcpy(&sin6->sin6_addr.s6_addr[12], &sin->sin_addr.s_addr, 4); + mCompatibleAddress = reinterpret_cast<const sockaddr*>(&mTmp); + } + } + } + // Returns a pointer to an address compatible with the socket. + const sockaddr* get() const { + return mCompatibleAddress; + } +private: + const sockaddr* mCompatibleAddress; + sockaddr_storage mTmp; +}; /** * Converts an InetAddress object and port number to a native address structure. @@ -926,9 +958,8 @@ static int pollSelectWait(JNIEnv *env, jobject fileDescriptor, int timeout) { * @param socketAddress the address to connect to */ static int doConnect(int fd, const sockaddr_storage* socketAddress) { - sockaddr_storage tmp; - const sockaddr* realAddress = convertIpv4ToMapped(fd, socketAddress, &tmp, true); - return TEMP_FAILURE_RETRY(connect(fd, realAddress, sizeof(sockaddr_storage))); + const CompatibleSocketAddress compatibleAddress(fd, *socketAddress, true); + return TEMP_FAILURE_RETRY(connect(fd, compatibleAddress.get(), sizeof(sockaddr_storage))); } /** @@ -1442,12 +1473,12 @@ static int createSocketFileDescriptor(JNIEnv* env, jobject fileDescriptor, return -1; } - int sock; - sock = socket(PF_INET6, type, 0); - if (sock < 0 && errno == EAFNOSUPPORT) { + // Try IPv6 but fall back to IPv4... + int sock = socket(PF_INET6, type, 0); + if (sock == -1 && errno == EAFNOSUPPORT) { sock = socket(PF_INET, type, 0); } - if (sock < 0) { + if (sock == -1) { jniThrowSocketException(env, errno); return sock; } @@ -1774,9 +1805,8 @@ static void osNetworkSystem_socketBindImpl(JNIEnv* env, jclass clazz, return; } - sockaddr_storage tmp; - const sockaddr* realAddress = convertIpv4ToMapped(fd, &socketAddress, &tmp, false); - int rc = TEMP_FAILURE_RETRY(bind(fd, realAddress, sizeof(sockaddr_storage))); + const CompatibleSocketAddress compatibleAddress(fd, socketAddress, false); + int rc = TEMP_FAILURE_RETRY(bind(fd, compatibleAddress.get(), sizeof(sockaddr_storage))); if (rc == -1) { jniThrowBindException(env, errno); } @@ -1936,12 +1966,14 @@ static void osNetworkSystem_disconnectDatagramImpl(JNIEnv* env, jclass, return; } - sockaddr_storage sockAddr; - memset(&sockAddr, 0, sizeof(sockAddr)); - sockAddr.ss_family = AF_UNSPEC; - - int result = doConnect(fd, &sockAddr); - if (result < 0) { + // To disconnect a datagram socket, we connect to a bogus address with + // the family AF_UNSPEC. + sockaddr_storage ss; + memset(&ss, 0, sizeof(ss)); + ss.ss_family = AF_UNSPEC; + const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss); + int rc = TEMP_FAILURE_RETRY(connect(fd, sa, sizeof(ss))); + if (rc == -1) { jniThrowSocketException(env, errno); } } diff --git a/luni/src/test/java/java/io/AllTests.java b/luni/src/test/java/java/io/AllTests.java index 5e25922..43a28e0 100644 --- a/luni/src/test/java/java/io/AllTests.java +++ b/luni/src/test/java/java/io/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.io.FileTest.class); return suite; } diff --git a/luni/src/test/java/java/lang/AllTests.java b/luni/src/test/java/java/lang/AllTests.java index a40ef3a..d8b7ade 100644 --- a/luni/src/test/java/java/lang/AllTests.java +++ b/luni/src/test/java/java/lang/AllTests.java @@ -21,9 +21,10 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.lang.FloatTest.class); suite.addTestSuite(java.lang.ProcessBuilderTest.class); + suite.addTestSuite(SystemTest.class); return suite; } } diff --git a/luni/src/test/java/java/lang/SystemTest.java b/luni/src/test/java/java/lang/SystemTest.java new file mode 100644 index 0000000..b6fc5de --- /dev/null +++ b/luni/src/test/java/java/lang/SystemTest.java @@ -0,0 +1,64 @@ +/* + * 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 java.lang; + +import junit.framework.TestCase; + +public class SystemTest extends TestCase { + + public void testArrayCopyTargetNotArray() { + try { + System.arraycopy(new char[5], 0, "Hello", 0, 3); + fail(); + } catch (ArrayStoreException e) { + assertEquals("source and destination must be arrays, but were " + + "[C and Ljava/lang/String;", e.getMessage()); + } + } + + public void testArrayCopySourceNotArray() { + try { + System.arraycopy("Hello", 0, new char[5], 0, 3); + fail(); + } catch (ArrayStoreException e) { + assertEquals("source and destination must be arrays, but were " + + "Ljava/lang/String; and [C", e.getMessage()); + } + } + + public void testArrayCopyArrayTypeMismatch() { + try { + System.arraycopy(new char[5], 0, new Object[5], 0, 3); + fail(); + } catch (ArrayStoreException e) { + assertEquals("source and destination arrays are incompatible: " + + "[C and [Ljava/lang/Object;", e.getMessage()); + } + } + + public void testArrayCopyElementTypeMismatch() { + try { + System.arraycopy(new Object[] { null, 5, "hello" }, 0, + new Integer[] { 1, 2, 3, null, null }, 0, 3); + fail(); + } catch (ArrayStoreException e) { + assertEquals("source[2] of type Ljava/lang/String; cannot be " + + "stored in destination array of type [Ljava/lang/Integer;", + e.getMessage()); + } + } +} diff --git a/luni/src/test/java/java/net/AllTests.java b/luni/src/test/java/java/net/AllTests.java index 3731af4..664d755 100644 --- a/luni/src/test/java/java/net/AllTests.java +++ b/luni/src/test/java/java/net/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.net.SocketTest.class); suite.addTestSuite(java.net.URLConnectionTest.class); return suite; diff --git a/luni/src/test/java/java/net/URLConnectionTest.java b/luni/src/test/java/java/net/URLConnectionTest.java index c5fd43f..f4ed499 100644 --- a/luni/src/test/java/java/net/URLConnectionTest.java +++ b/luni/src/test/java/java/net/URLConnectionTest.java @@ -19,32 +19,30 @@ package java.net; import java.io.BufferedReader; import java.io.InputStreamReader; -import tests.support.Support_PortManager; import tests.support.Support_TestWebServer; import junit.framework.Test; import junit.framework.TestSuite; public class URLConnectionTest extends junit.framework.TestCase { - private int port; - private Support_TestWebServer server; + private int mPort; + private Support_TestWebServer mServer; @Override public void setUp() throws Exception { super.setUp(); - port = Support_PortManager.getNextPort(); - server = new Support_TestWebServer(); - server.initServer(port, false); + mServer = new Support_TestWebServer(); + mPort = mServer.initServer(0, false); } @Override - public void tearDown()throws Exception { + public void tearDown() throws Exception { super.tearDown(); - server.close(); + mServer.close(); } private String readFirstLine() throws Exception { - URLConnection connection = new URL("http://localhost:" + port + "/test1").openConnection(); + URLConnection connection = new URL("http://localhost:" + mPort + "/test1").openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = in.readLine(); in.close(); @@ -55,8 +53,8 @@ public class URLConnectionTest extends junit.framework.TestCase { // recycled connection doesn't get the unread tail of the first request's response. // http://code.google.com/p/android/issues/detail?id=2939 public void test_2939() throws Exception { - server.setChunked(true); - server.setMaxChunkSize(8); + mServer.setChunked(true); + mServer.setMaxChunkSize(8); assertTrue(readFirstLine().equals("<html>")); assertTrue(readFirstLine().equals("<html>")); } diff --git a/luni/src/test/java/java/nio/charset/AllTests.java b/luni/src/test/java/java/nio/charset/AllTests.java index 6f45162..67957d4 100644 --- a/luni/src/test/java/java/nio/charset/AllTests.java +++ b/luni/src/test/java/java/nio/charset/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.nio.charset.CharsetDecoderTest.class); return suite; } diff --git a/luni/src/test/java/java/text/AllTests.java b/luni/src/test/java/java/text/AllTests.java index efb27da..77cad25 100644 --- a/luni/src/test/java/java/text/AllTests.java +++ b/luni/src/test/java/java/text/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(java.text.DecimalFormatTest.class); suite.addTestSuite(java.text.NormalizerTest.class); suite.addTestSuite(java.text.NumberFormatTest.class); diff --git a/luni/src/test/java/java/util/AllTests.java b/luni/src/test/java/java/util/AllTests.java index 774d48b..3050c30 100644 --- a/luni/src/test/java/java/util/AllTests.java +++ b/luni/src/test/java/java/util/AllTests.java @@ -21,7 +21,8 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); + suite.addTestSuite(java.util.CalendarTest.class); suite.addTestSuite(java.util.CurrencyTest.class); suite.addTestSuite(java.util.DateTest.class); suite.addTestSuite(java.util.FormatterTest.class); diff --git a/luni/src/test/java/java/util/CalendarTest.java b/luni/src/test/java/java/util/CalendarTest.java new file mode 100644 index 0000000..f9f6fbe --- /dev/null +++ b/luni/src/test/java/java/util/CalendarTest.java @@ -0,0 +1,33 @@ +/* + * 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 java.util; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class CalendarTest extends junit.framework.TestCase { + // http://code.google.com/p/android/issues/detail?id=6184 + public void test_setTimeZone() { + // The specific time zones don't matter; they just have to be different so we can see that + // get(Calendar.ZONE_OFFSET) returns the zone offset of the time zone passed to setTimeZone. + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US); + assertEquals(0, cal.get(Calendar.ZONE_OFFSET)); + TimeZone tz = java.util.TimeZone.getTimeZone("GMT+7"); + cal.setTimeZone(tz); + assertEquals(25200000, cal.get(Calendar.ZONE_OFFSET)); + } +} diff --git a/luni/src/test/java/java/util/CurrencyTest.java b/luni/src/test/java/java/util/CurrencyTest.java index 16111d5..66354f5 100644 --- a/luni/src/test/java/java/util/CurrencyTest.java +++ b/luni/src/test/java/java/util/CurrencyTest.java @@ -31,4 +31,15 @@ public class CurrencyTest extends junit.framework.TestCase { // Canada that Canadians give it a localized (to Canada) symbol. assertEquals("AED", Currency.getInstance("AED").getSymbol(Locale.CANADA)); } + + // Regression test to ensure that Currency.getInstance(String) throws if + // given an invalid ISO currency code. + public void test_getInstance_illegal_currency_code() throws Exception { + Currency.getInstance("USD"); + try { + Currency.getInstance("BOGO-DOLLARS"); + fail("expected IllegalArgumentException for invalid ISO currency code"); + } catch (IllegalArgumentException expected) { + } + } } diff --git a/luni/src/test/java/java/util/zip/ZipEntryTest.java b/luni/src/test/java/java/util/zip/ZipEntryTest.java new file mode 100644 index 0000000..4c7cccf --- /dev/null +++ b/luni/src/test/java/java/util/zip/ZipEntryTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package java.util.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class ZipEntryTest extends junit.framework.TestCase { + // http://code.google.com/p/android/issues/detail?id=4690 + public void test_utf8FileNames() throws Exception { + // Create a zip file containing non-ASCII filenames. + File f = File.createTempFile("your", "mum"); + List<String> filenames = Arrays.asList("us-ascii", + "\u043c\u0430\u0440\u0442\u0430", // russian + "\u1f00\u03c0\u1f78", // greek + "\u30b3\u30f3\u30cb\u30c1\u30cf"); // japanese + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f)); + for (String filename : filenames) { + out.putNextEntry(new ZipEntry(filename)); + out.closeEntry(); // Empty files are fine. + } + out.close(); + // Read it back, and check we find all those names. + // This failed when we were mangling the encoding. + ZipFile zipFile = new ZipFile(f); + for (String filename : filenames) { + assertNotNull(filename, zipFile.getEntry(filename)); + } + // Check that ZipInputStream works too. + ZipInputStream in = new ZipInputStream(new FileInputStream(f)); + ZipEntry entry; + int entryCount = 0; + while ((entry = in.getNextEntry()) != null) { + assertTrue(entry.getName(), filenames.contains(entry.getName())); + ++entryCount; + } + assertEquals(filenames.size(), entryCount); + in.close(); + } +} diff --git a/luni/src/test/java/javax/xml/parsers/AllTests.java b/luni/src/test/java/javax/xml/parsers/AllTests.java index 3e4a9c6..a838d3b 100644 --- a/luni/src/test/java/javax/xml/parsers/AllTests.java +++ b/luni/src/test/java/javax/xml/parsers/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(javax.xml.parsers.DocumentBuilderTest.class); return suite; } diff --git a/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java b/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java new file mode 100644 index 0000000..3dc411e --- /dev/null +++ b/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.luni.internal.net.www.protocol.http; + +import java.util.Arrays; +import junit.framework.Test; +import junit.framework.TestSuite; + +public class HeaderTest extends junit.framework.TestCase { + // http://code.google.com/p/android/issues/detail?id=6684 + public void test_caseInsensitiveButCasePreserving() { + Header h = new Header(); + h.add("Content-Type", "text/plain"); + // Case-insensitive: + assertEquals("text/plain", h.get("Content-Type")); + assertEquals("text/plain", h.get("Content-type")); + assertEquals("text/plain", h.get("content-type")); + assertEquals("text/plain", h.get("CONTENT-TYPE")); + // ...but case-preserving: + assertEquals("Content-Type", h.getFieldMap().keySet().toArray()[0]); + + // We differ from the RI in that the Map we return is also case-insensitive. + // Our behavior seems more consistent. (And code that works on the RI will work on Android.) + assertEquals(Arrays.asList("text/plain"), h.getFieldMap().get("Content-Type")); + assertEquals(Arrays.asList("text/plain"), h.getFieldMap().get("Content-type")); // RI fails this. + } + + // The copy constructor used to be broken for headers with multiple values. + // http://code.google.com/p/android/issues/detail?id=6722 + public void test_copyConstructor() { + Header h1 = new Header(); + h1.add("key", "value1"); + h1.add("key", "value2"); + Header h2 = new Header(h1.getFieldMap()); + assertEquals(2, h2.length()); + assertEquals("key", h2.getKey(0)); + assertEquals("value1", h2.get(0)); + assertEquals("key", h2.getKey(1)); + assertEquals("value2", h2.get(1)); + } +} diff --git a/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java index be28d41..bfba0b5 100644 --- a/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java @@ -27,7 +27,7 @@ public class AllTests { } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for org.apache.harmony.luni.platform"); + TestSuite suite = new TestSuite("Tests for org.apache.harmony.luni.platform"); suite.addTestSuite(OSMemoryTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java b/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java index a546289..fc34219 100644 --- a/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java @@ -17,24 +17,12 @@ package org.apache.harmony.luni.platform; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.AndroidOnly; - import junit.framework.TestCase; /** * Tests org.apache.harmony.luni.platform.OSMemory (via IMemorySystem). */ -@TestTargetClass(org.apache.harmony.luni.platform.OSMemory.class) public class OSMemoryTest extends TestCase { - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "memset", - args = {} - ) public void testMemset() { IMemorySystem memory = Platform.getMemorySystem(); @@ -62,12 +50,6 @@ public class OSMemoryTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setIntArray", - args = {} - ) public void testSetIntArray() { IMemorySystem memory = Platform.getMemorySystem(); @@ -115,12 +97,6 @@ public class OSMemoryTest extends TestCase { (((n >> 24) & 0xff) << 0); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setShortArray", - args = {} - ) public void testSetShortArray() { IMemorySystem memory = Platform.getMemorySystem(); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java index 6b4cbd0..89faac1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for HttpURLConnecton, HttpsURLConnection."); + TestSuite suite = new TestSuite("Tests for HttpURLConnecton, HttpsURLConnection."); // $JUnit-BEGIN$ suite.addTestSuite(HttpURLConnectionTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java index a58850b..e03633d 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java @@ -25,13 +25,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for HttpURLConnecton, HttpsURLConnection."); + TestSuite suite = new TestSuite("Tests for HttpURLConnecton, HttpsURLConnection."); // $JUnit-BEGIN$ suite.addTestSuite(HttpsURLConnectionTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java index e26cf74..4825cfb 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java @@ -147,9 +147,6 @@ public class HttpsURLConnectionTest extends TestCase { method = "setDefaultHostnameVerifier", args = {javax.net.ssl.HostnameVerifier.class} ) - @KnownFailure("Handshake fails.") - @BrokenTest("Different behavior between cts host and run-core-test") - @AndroidOnly("we only have a .bks key store in the test resources") public void testHttpsConnection() throws Throwable { // set up the properties defining the default values needed by SSL stuff setUpStoreProperties(); @@ -202,9 +199,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {int.class} ) }) - @KnownFailure("Handshake fails.") - @BrokenTest("Different behavior between cts host and run-core-test") - @AndroidOnly("we only have a .bks key store in the test resources") public void testHttpsConnection_Not_Found_Response() throws Throwable { // set up the properties defining the default values needed by SSL stuff setUpStoreProperties(); @@ -247,8 +241,6 @@ public class HttpsURLConnectionTest extends TestCase { method = "setDefaultSSLSocketFactory", args = {javax.net.ssl.SSLSocketFactory.class} ) - @AndroidOnly("we only have a .bks key store in the test resources") - @KnownFailure("End to end test fails. No response data is transferred from server to client") public void testSetDefaultSSLSocketFactory() throws Throwable { // create the SSLServerSocket which will be used by server side SSLContext ctx = getContext(); @@ -304,8 +296,6 @@ public class HttpsURLConnectionTest extends TestCase { method = "setSSLSocketFactory", args = {javax.net.ssl.SSLSocketFactory.class} ) - @AndroidOnly("we only have a .bks key store in the test resources") - @KnownFailure("End to end test fails. No response data is transferred from server to client") public void testSetSSLSocketFactory() throws Throwable { // create the SSLServerSocket which will be used by server side SSLContext ctx = getContext(); @@ -424,9 +414,6 @@ public class HttpsURLConnectionTest extends TestCase { method = "setHostnameVerifier", args = {javax.net.ssl.HostnameVerifier.class} ) - @KnownFailure("Handshake fails.") - @BrokenTest("Different behavior between cts host and run-core-test") - @AndroidOnly("we only have a .bks key store in the test resources") public void testSetHostnameVerifier() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -470,9 +457,6 @@ public class HttpsURLConnectionTest extends TestCase { method = "setDoOutput", args = {boolean.class} ) - @KnownFailure("Handshake fails.") - @BrokenTest("Different behavior between cts host and run-core-test") - @AndroidOnly("we only have a .bks key store in the test resources") public void test_doOutput() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -523,8 +507,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {int.class} ) }) - @KnownFailure("Handshake fails.") - @AndroidOnly("we only have a .bks key store in the test resources") public void testProxyConnection() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -576,8 +558,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {int.class} ) }) - @KnownFailure("Handshake fails.") - @AndroidOnly("we only have a .bks key store in the test resources") public void testProxyAuthConnection() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -639,8 +619,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {} ) }) - @KnownFailure("Handshake fails.") - @AndroidOnly("we only have a .bks key store in the test resources") public void testConsequentProxyConnection() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -707,8 +685,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {boolean.class} ) }) - @KnownFailure("Handshake fails.") - @AndroidOnly("we only have a .bks key store in the test resources") public void testProxyAuthConnection_doOutput() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); @@ -825,8 +801,6 @@ public class HttpsURLConnectionTest extends TestCase { args = {int.class} ) }) - @KnownFailure("Handshake fails.") - @AndroidOnly("we only have a .bks key store in the test resources") public void testProxyConnection_Not_Found_Response() throws Throwable { // setting up the properties pointing to the key/trust stores setUpStoreProperties(); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java index 778e527..e266b7c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java @@ -31,7 +31,7 @@ public class AllTests } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io"); + TestSuite suite = new TestSuite("Tests for java.io"); suite.addTestSuite(BufferedReaderTest.class); suite.addTestSuite(FilePermissionTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java index 55e8c6f..6f0ef40 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java @@ -1,134 +1,592 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; import java.io.BufferedReader; +import java.io.ByteArrayInputStream; import java.io.CharArrayReader; import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedReader; +import java.io.Reader; import java.io.StringReader; import junit.framework.TestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -@TestTargetClass(BufferedReader.class) +import tests.support.Support_StringReader; + public class BufferedReaderTest extends TestCase { - /** - * @tests java.io.BufferedReader#read(char[], int, int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks exceptions.", - method = "read", - args = {char[].class, int.class, int.class} - ) - public void test_read$CII() throws IOException { - char[] in = {'L', 'o', 'r', 'e', 'm'}; - char[] ch = new char[3]; - BufferedReader reader = new BufferedReader(new CharArrayReader(in)); - - try { - reader.read(null, 1, 0); - fail("Test 1: NullPointerException expected."); - } catch (NullPointerException e) { - // Expected. + BufferedReader br; + + String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; + + /** + * The spec says that BufferedReader.readLine() considers only "\r", "\n" + * and "\r\n" to be line separators. We must not permit additional separator + * characters. + */ + public void test_readLine_IgnoresEbcdic85Characters() throws IOException { + assertLines("A\u0085B", "A\u0085B"); } - try { - reader.read(ch , -1, 1); - fail("Test 2: IndexOutOfBoundsException expected."); - } catch (IndexOutOfBoundsException e) { - // Expected. + public void test_readLine_Separators() throws IOException { + assertLines("A\nB\nC", "A", "B", "C"); + assertLines("A\rB\rC", "A", "B", "C"); + assertLines("A\r\nB\r\nC", "A", "B", "C"); + assertLines("A\n\rB\n\rC", "A", "", "B", "", "C"); + assertLines("A\n\nB\n\nC", "A", "", "B", "", "C"); + assertLines("A\r\rB\r\rC", "A", "", "B", "", "C"); + assertLines("A\n\n", "A", ""); + assertLines("A\n\r", "A", ""); + assertLines("A\r\r", "A", ""); + assertLines("A\r\n", "A"); + assertLines("A\r\n\r\n", "A", ""); } - - try { - reader.read(ch , 1, -1); - fail("Test 3: IndexOutOfBoundsException expected."); - } catch (IndexOutOfBoundsException e) { - // Expected. + + private void assertLines(String in, String... lines) throws IOException { + BufferedReader bufferedReader + = new BufferedReader(new Support_StringReader(in)); + for (String line : lines) { + assertEquals(line, bufferedReader.readLine()); + } + assertNull(bufferedReader.readLine()); } + /** + * @tests java.io.BufferedReader#BufferedReader(java.io.Reader) + */ + public void test_ConstructorLjava_io_Reader() { + // Test for method java.io.BufferedReader(java.io.Reader) + assertTrue("Used in tests", true); + } + + /** + * @tests java.io.BufferedReader#BufferedReader(java.io.Reader, int) + */ + public void test_ConstructorLjava_io_ReaderI() { + // Test for method java.io.BufferedReader(java.io.Reader, int) + assertTrue("Used in tests", true); + } + + /** + * @tests java.io.BufferedReader#close() + */ + public void test_close() { + // Test for method void java.io.BufferedReader.close() + try { + br = new BufferedReader(new Support_StringReader(testString)); + br.close(); + br.read(); + fail("Read on closed stream"); + } catch (IOException x) { + return; + } + } + + /** + * @tests java.io.BufferedReader#mark(int) + */ + public void test_markI() throws IOException { + // Test for method void java.io.BufferedReader.mark(int) + char[] buf = null; + br = new BufferedReader(new Support_StringReader(testString)); + br.skip(500); + br.mark(1000); + br.skip(250); + br.reset(); + buf = new char[testString.length()]; + br.read(buf, 0, 500); + assertTrue("Failed to set mark properly", testString.substring(500, + 1000).equals(new String(buf, 0, 500))); + + try { + br = new BufferedReader(new Support_StringReader(testString), 800); + br.skip(500); + br.mark(250); + br.read(buf, 0, 1000); + br.reset(); + fail("Failed to invalidate mark properly"); + } catch (IOException x) { + // Expected + } + + char[] chars = new char[256]; + for (int i = 0; i < 256; i++) + chars[i] = (char) i; + Reader in = new BufferedReader(new Support_StringReader(new String( + chars)), 12); + + in.skip(6); + in.mark(14); + in.read(new char[14], 0, 14); + in.reset(); + assertTrue("Wrong chars", in.read() == (char) 6 + && in.read() == (char) 7); + + in = new BufferedReader(new Support_StringReader(new String(chars)), 12); + in.skip(6); + in.mark(8); + in.skip(7); + in.reset(); + assertTrue("Wrong chars 2", in.read() == (char) 6 + && in.read() == (char) 7); + + BufferedReader br = new BufferedReader(new StringReader("01234"), 2); + br.mark(3); + char[] carray = new char[3]; + int result = br.read(carray); + assertEquals(3, result); + assertEquals("Assert 0:", '0', carray[0]); + assertEquals("Assert 1:", '1', carray[1]); + assertEquals("Assert 2:", '2', carray[2]); + assertEquals("Assert 3:", '3', br.read()); + + br = new BufferedReader(new StringReader("01234"), 2); + br.mark(3); + carray = new char[4]; + result = br.read(carray); + assertEquals("Assert 4:", 4, result); + assertEquals("Assert 5:", '0', carray[0]); + assertEquals("Assert 6:", '1', carray[1]); + assertEquals("Assert 7:", '2', carray[2]); + assertEquals("Assert 8:", '3', carray[3]); + assertEquals("Assert 9:", '4', br.read()); + assertEquals("Assert 10:", -1, br.read()); + + BufferedReader reader = new BufferedReader(new StringReader("01234")); + reader.mark(Integer.MAX_VALUE); + reader.read(); + reader.close(); + } + + /** + * @tests java.io.BufferedReader#markSupported() + */ + public void test_markSupported() { + // Test for method boolean java.io.BufferedReader.markSupported() + br = new BufferedReader(new Support_StringReader(testString)); + assertTrue("markSupported returned false", br.markSupported()); + } + + /** + * @tests java.io.BufferedReader#read() + */ + public void test_read() throws IOException { + // Test for method int java.io.BufferedReader.read() + try { + br = new BufferedReader(new Support_StringReader(testString)); + int r = br.read(); + assertTrue("Char read improperly", testString.charAt(0) == r); + br = new BufferedReader(new Support_StringReader(new String( + new char[] { '\u8765' }))); + assertTrue("Wrong double byte character", br.read() == '\u8765'); + } catch (java.io.IOException e) { + fail("Exception during read test"); + } + + char[] chars = new char[256]; + for (int i = 0; i < 256; i++) + chars[i] = (char) i; + Reader in = new BufferedReader(new Support_StringReader(new String( + chars)), 12); + try { + assertEquals("Wrong initial char", 0, in.read()); // Fill the + // buffer + char[] buf = new char[14]; + in.read(buf, 0, 14); // Read greater than the buffer + assertTrue("Wrong block read data", new String(buf) + .equals(new String(chars, 1, 14))); + assertEquals("Wrong chars", 15, in.read()); // Check next byte + } catch (IOException e) { + fail("Exception during read test 2:" + e); + } + + // regression test for HARMONY-841 + assertTrue(new BufferedReader(new CharArrayReader(new char[5], 1, 0), 2).read() == -1); + } + + /** + * @tests java.io.BufferedReader#read(char[], int, int) + */ + public void test_read$CII() throws Exception{ + char[] ca = new char[2]; + BufferedReader toRet = new BufferedReader(new InputStreamReader( + new ByteArrayInputStream(new byte[0]))); + + /* Null buffer should throw NPE even when len == 0 */ + try { + toRet.read(null, 1, 0); + fail("null buffer reading zero bytes should throw NPE"); + } catch (NullPointerException e) { + //expected + } + + try { + toRet.close(); + } catch (IOException e) { + fail("unexpected 1: " + e); + } + + try { + toRet.read(null, 1, 0); + fail("null buffer reading zero bytes on closed stream should throw IOException"); + } catch (IOException e) { + //expected + } + + /* Closed reader should throw IOException reading zero bytes */ + try { + toRet.read(ca, 0, 0); + fail("Reading zero bytes on a closed reader should not work"); + } catch (IOException e) { + // expected + } + + /* + * Closed reader should throw IOException in preference to index out of + * bounds + */ + try { + // Read should throw IOException before + // ArrayIndexOutOfBoundException + toRet.read(ca, 1, 5); + fail("IOException should have been thrown"); + } catch (IOException e) { + // expected + } + + // Test to ensure that a drained stream returns 0 at EOF + toRet = new BufferedReader(new InputStreamReader( + new ByteArrayInputStream(new byte[2]))); + try { + assertEquals("Emptying the reader should return two bytes", 2, + toRet.read(ca, 0, 2)); + assertEquals("EOF on a reader should be -1", -1, toRet.read(ca, 0, + 2)); + assertEquals("Reading zero bytes at EOF should work", 0, toRet + .read(ca, 0, 0)); + } catch (IOException ex) { + fail("Unexpected IOException : " + ex.getLocalizedMessage()); + } + + // Test for method int java.io.BufferedReader.read(char [], int, int) + try { + char[] buf = new char[testString.length()]; + br = new BufferedReader(new Support_StringReader(testString)); + br.read(buf, 50, 500); + assertTrue("Chars read improperly", new String(buf, 50, 500) + .equals(testString.substring(0, 500))); + } catch (java.io.IOException e) { + fail("Exception during read test"); + } + + BufferedReader bufin = new BufferedReader(new Reader() { + int size = 2, pos = 0; + + char[] contents = new char[size]; + + public int read() throws IOException { + if (pos >= size) + throw new IOException("Read past end of data"); + return contents[pos++]; + } + + public int read(char[] buf, int off, int len) throws IOException { + if (pos >= size) + throw new IOException("Read past end of data"); + int toRead = len; + if (toRead > (size - pos)) + toRead = size - pos; + System.arraycopy(contents, pos, buf, off, toRead); + pos += toRead; + return toRead; + } + + public boolean ready() throws IOException { + return size - pos > 0; + } + + public void close() throws IOException { + } + }); + try { + bufin.read(); + int result = bufin.read(new char[2], 0, 2); + assertTrue("Incorrect result: " + result, result == 1); + } catch (IOException e) { + fail("Unexpected: " + e); + } + + //regression for HARMONY-831 + try{ + new BufferedReader(new PipedReader(), 9).read(new char[] {}, 7, 0); + fail("should throw IndexOutOfBoundsException"); + }catch(IndexOutOfBoundsException e){ + } + + // Regression for HARMONY-54 + char[] ch = {}; + BufferedReader reader = new BufferedReader(new CharArrayReader(ch)); try { - reader.read(ch, 1, 3); - fail("Test 4: IndexOutOfBoundsException expected."); - } catch (IndexOutOfBoundsException e) { - // Expected. + // Check exception thrown when the reader is open. + reader.read(null, 1, 0); + fail("Assert 0: NullPointerException expected"); + } catch (NullPointerException e) { + // Expected } + // Now check IOException is thrown in preference to + // NullPointerexception when the reader is closed. reader.close(); try { - reader.read(ch, 1, 1); - fail("Test 5: IOException expected."); + reader.read(null, 1, 0); + fail("Assert 1: IOException expected"); } catch (IOException e) { - // Expected. + // Expected } - } - - /** - * @tests java.io.BufferedReader#mark(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "mark", - args = {int.class} - ) - public void test_markI() throws IOException { - BufferedReader buf = new BufferedReader(new StringReader("01234"), 2); try { - buf.mark(-1); - fail("Test 1: IllegalArgumentException expected."); - } catch (IllegalArgumentException e) { - // Expected. + // And check that the IOException is thrown before + // ArrayIndexOutOfBoundException + reader.read(ch, 0, 42); + fail("Assert 2: IOException expected"); + } catch (IOException e) { + // expected } - - buf.mark(3); - char[] chars = new char[3]; - int result = buf.read(chars); - assertEquals(3, result); - assertEquals("Assert 0:", '0', chars[0]); - assertEquals("Assert 1:", '1', chars[1]); - assertEquals("Assert 2:", '2', chars[2]); - assertEquals("Assert 3:", '3', buf.read()); - - buf = new BufferedReader(new StringReader("01234"), 2); - buf.mark(3); - chars = new char[4]; - result = buf.read(chars); - assertEquals("Assert 4:", 4, result); - assertEquals("Assert 5:", '0', chars[0]); - assertEquals("Assert 6:", '1', chars[1]); - assertEquals("Assert 7:", '2', chars[2]); - assertEquals("Assert 8:", '3', chars[3]); - assertEquals("Assert 9:", '4', buf.read()); - assertEquals("Assert 10:", -1, buf.read()); + } - BufferedReader reader = new BufferedReader(new StringReader("01234")); - reader.mark(Integer.MAX_VALUE); - reader.read(); - reader.close(); - + /** + * @tests java.io.BufferedReader#read(char[], int, int) + */ + public void test_read_$CII_Exception() throws IOException { + br = new BufferedReader(new Support_StringReader(testString)); + char[] nullCharArray = null; + char[] charArray = testString.toCharArray(); + + try { + br.read(nullCharArray, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + br.read(nullCharArray, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + br.read(nullCharArray, 0, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + br.read(nullCharArray, 0, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + br.read(nullCharArray, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + br.read(charArray, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + br.read(charArray, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + br.read(charArray, 0, 0); + br.read(charArray, 0, charArray.length); + br.read(charArray, charArray.length, 0); + + try { + br.read(charArray, charArray.length + 1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + + try { + br.read(charArray, charArray.length + 1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + + br.close(); + + try { + br.read(nullCharArray, -1, -1); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + + try { + br.read(charArray, -1, 0); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + + try { + br.read(charArray, 0, -1); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + } + /** + * @tests java.io.BufferedReader#readLine() + */ + public void test_readLine() { + // Test for method java.lang.String java.io.BufferedReader.readLine() + try { + br = new BufferedReader(new Support_StringReader(testString)); + String r = br.readLine(); + assertEquals("readLine returned incorrect string", "Test_All_Tests", r + ); + } catch (java.io.IOException e) { + fail("Exception during readLine test"); + } + } + + /** + * @tests java.io.BufferedReader#ready() + */ + public void test_ready() { + // Test for method boolean java.io.BufferedReader.ready() + try { + br = new BufferedReader(new Support_StringReader(testString)); + assertTrue("ready returned false", br.ready()); + } catch (java.io.IOException e) { + fail("Exception during ready test" + e.toString()); + } + } + + /** + * @tests java.io.BufferedReader#reset() + */ + public void test_reset() { + // Test for method void java.io.BufferedReader.reset() + try { + br = new BufferedReader(new Support_StringReader(testString)); + br.skip(500); + br.mark(900); + br.skip(500); + br.reset(); + char[] buf = new char[testString.length()]; + br.read(buf, 0, 500); + assertTrue("Failed to reset properly", testString.substring(500, + 1000).equals(new String(buf, 0, 500))); + } catch (java.io.IOException e) { + fail("Exception during reset test"); + } + try { + br = new BufferedReader(new Support_StringReader(testString)); + br.skip(500); + br.reset(); + fail("Reset succeeded on unmarked stream"); + } catch (IOException x) { + return; + + } + } + + public void test_reset_IOException() throws Exception { + int[] expected = new int[] { '1', '2', '3', '4', '5', '6', '7', '8', + '9', '0', -1 }; + br = new BufferedReader(new Support_StringReader("1234567890"), 9); + br.mark(9); + for (int i = 0; i < 11; i++) { + assertEquals(expected[i], br.read()); + } try { - reader.mark(1); - fail("Test 2: IOException expected."); + br.reset(); + fail("should throw IOException"); } catch (IOException e) { - // Expected. + // Expected + } + for (int i = 0; i < 11; i++) { + assertEquals(-1, br.read()); + } + + br = new BufferedReader(new Support_StringReader("1234567890")); + br.mark(10); + for (int i = 0; i < 10; i++) { + assertEquals(expected[i], br.read()); + } + br.reset(); + for (int i = 0; i < 11; i++) { + assertEquals(expected[i], br.read()); } } + /** + * @tests java.io.BufferedReader#skip(long) + */ + public void test_skipJ() { + // Test for method long java.io.BufferedReader.skip(long) + try { + br = new BufferedReader(new Support_StringReader(testString)); + br.skip(500); + char[] buf = new char[testString.length()]; + br.read(buf, 0, 500); + assertTrue("Failed to set skip properly", testString.substring(500, + 1000).equals(new String(buf, 0, 500))); + } catch (java.io.IOException e) { + fail("Exception during skip test"); + } + + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + try { + br.close(); + } catch (Exception e) { + } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java index a358cc5..5b5a759 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java @@ -1,41 +1,166 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; import java.io.File; import java.io.FilePermission; +import java.security.PermissionCollection; import junit.framework.TestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -@TestTargetClass(FilePermission.class) + public class FilePermissionTest extends TestCase { + FilePermission readAllFiles = new FilePermission("<<ALL FILES>>", "read"); + + FilePermission alsoReadAllFiles = new FilePermission("<<ALL FILES>>", + "read"); + + FilePermission allInCurrent = new FilePermission("*", + "read, write, execute,delete"); + + FilePermission readInCurrent = new FilePermission("*", "read"); + + FilePermission readInFile = new FilePermission("aFile.file", "read"); + + FilePermission readInSubdir = new FilePermission("-", "read"); + + /** + * @tests java.io.FilePermission#FilePermission(java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_String() { + assertTrue("Used to test", true); + FilePermission constructFile = new FilePermission("test constructor", + "write"); + assertEquals( + "action given to the constructor did not correspond - constructor failed", + "write", constructFile.getActions()); + assertTrue( + "name given to the constructor did not correspond - constructor failed", + constructFile.getName() == "test constructor"); + + // Regression test for HARMONY-1050 + try { + new FilePermission(null, "drink"); + fail("Expected IAE"); + } catch (IllegalArgumentException e) { + // Expected + } + + try { + new FilePermission(null, "read"); + fail("Expected NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + new FilePermission(null, null); + fail("Expected IAE"); + } catch (IllegalArgumentException e) { + // Expected + } + } + + /** + * @tests java.io.FilePermission#getActions() + */ + public void test_getActions() { + assertEquals("getActions should have returned only read", "read", + readAllFiles.getActions()); + assertEquals("getActions should have returned all actions", + "read,write,execute,delete", allInCurrent.getActions()); + } + + /** + * @tests java.io.FilePermission#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + assertTrue( + "Should not returned false when two instance of FilePermission is equal", + readAllFiles.equals(alsoReadAllFiles)); + assertFalse( + "Should not returned true when two instance of FilePermission is not equal", + readInCurrent.equals(readInFile)); + } + /** * @tests java.io.FilePermission#implies(java.security.Permission) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "implies", - args = {java.security.Permission.class} - ) - public void test_impliesLjava_io_FilePermission() { + public void test_impliesLjava_security_Permission() { + assertFalse("Should not return true for non-subset of actions", readAllFiles + .implies(allInCurrent)); + assertFalse("Should not return true for non-subset of files", allInCurrent + .implies(readAllFiles)); + assertTrue("Should not return false for subset of actions", allInCurrent + .implies(readInCurrent)); + assertTrue("Should not return false for subset of files", readAllFiles + .implies(readInCurrent)); + assertTrue("Should not return false for subset of files and actions", + allInCurrent.implies(readInFile)); + assertTrue("Should not return false for equal FilePermissions", readAllFiles + .implies(alsoReadAllFiles)); + assertTrue("Should not return false for subdir self", readInSubdir.implies(readInSubdir)); + assertTrue("Should not return false for current self", readInCurrent.implies(readInCurrent)); + assertTrue("Should not return false for subdir", readInSubdir.implies(readInCurrent)); + + FilePermission fp13 = new FilePermission(File.separator, "read"); + FilePermission fp14 = new FilePermission(File.separator + "*", "read"); + assertFalse("/ should not imply /*", fp13.implies(fp14)); + fp14 = new FilePermission(File.separator + "-", "read"); + assertFalse("/ should not imply /-", fp13.implies(fp14)); + + FilePermission fp3 = new FilePermission("/bob/*".replace('/', + File.separatorChar), "read,write"); + FilePermission fp4 = new FilePermission("/bob/".replace('/', + File.separatorChar), "write"); + assertFalse("Should not return true for same dir using * and not *", fp3 + .implies(fp4)); + FilePermission fp5 = new FilePermission("/bob/file".replace('/', + File.separatorChar), "write"); + assertTrue("Should not return false for same dir using * and file", fp3 + .implies(fp5)); + + FilePermission fp6 = new FilePermission("/bob/".replace('/', + File.separatorChar), "read,write"); + FilePermission fp7 = new FilePermission("/bob/*".replace('/', + File.separatorChar), "write"); + assertFalse("Should not return true for same dir using not * and *", fp6 + .implies(fp7)); + assertTrue("Should not return false for same subdir", fp6.implies(fp4)); + + FilePermission fp8 = new FilePermission("/".replace('/', + File.separatorChar), "read,write"); + FilePermission fp9 = new FilePermission("/".replace('/', + File.separatorChar), "write"); + assertTrue("Should not return false for same dir", fp8.implies(fp9)); + + FilePermission fp10 = new FilePermission("/".replace('/', + File.separatorChar), "read,write"); + FilePermission fp11 = new FilePermission("/".replace('/', + File.separatorChar), "write"); + assertTrue("Should not return false for same dir", fp10.implies(fp11)); + + FilePermission fp12 = new FilePermission("/*".replace('/', + File.separatorChar), "read,write"); + assertFalse("Should not return true for same dir using * and dir", fp12 + .implies(fp10)); + // Regression for HARMONY-47 char separator = File.separatorChar; char nonSeparator = (separator == '/') ? '\\' : '/'; @@ -46,4 +171,52 @@ public class FilePermissionTest extends TestCase { fp1 = new FilePermission(nonSeparator + "-", "read"); assertFalse("Assert 1: non-separator worked", fp1.implies(fp2)); } + + /** + * @tests java.io.FilePermission#newPermissionCollection() + */ + public void test_newPermissionCollection() { + char s = File.separatorChar; + FilePermission perm[] = new FilePermission[4]; + perm[0] = readAllFiles; + perm[1] = allInCurrent; + perm[2] = new FilePermission(s + "tmp" + s + "test" + s + "*", + "read,write"); + perm[3] = new FilePermission(s + "tmp" + s + "test" + s + + "collection.file", "read"); + + PermissionCollection collect = perm[0].newPermissionCollection(); + for (int i = 0; i < perm.length; i++) { + collect.add(perm[i]); + } + assertTrue("Should not return false for subset of files", collect + .implies(new FilePermission("*", "write"))); + assertTrue("Should not return false for subset of name and action", collect + .implies(new FilePermission(s + "tmp", "read"))); + assertTrue("Should not return false for non subset of file and action", collect + .implies(readInFile)); + + FilePermission fp1 = new FilePermission("/tmp/-".replace('/', + File.separatorChar), "read"); + PermissionCollection fpc = fp1.newPermissionCollection(); + fpc.add(fp1); + fpc.add(new FilePermission("/tmp/scratch/foo/*".replace('/', + File.separatorChar), "write")); + FilePermission fp2 = new FilePermission("/tmp/scratch/foo/file" + .replace('/', File.separatorChar), "read,write"); + assertTrue("collection does not collate", fpc.implies(fp2)); + } + + /** + * @tests java.io.FilePermission#hashCode() + */ + public void test_hashCode() { + assertTrue( + "two equal filePermission instances returned different hashCode", + readAllFiles.hashCode() == alsoReadAllFiles.hashCode()); + assertTrue( + "two filePermission instances with same permission name returned same hashCode", + readInCurrent.hashCode() != allInCurrent.hashCode()); + + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java index 53ce506..8cae683 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java @@ -1,136 +1,1015 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.ObjectStreamClass; +import java.io.ObjectStreamField; +import java.io.RandomAccessFile; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; import junit.framework.TestCase; import org.apache.harmony.testframework.serialization.SerializationTest; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import tests.util.TestEnvironment; +import tests.support.Support_Exec; +import tests.support.Support_PlatformFile; -@TestTargetClass(File.class) public class FileTest extends TestCase { + + private static String platformId = "JDK" + + System.getProperty("java.vm.version").replace('.', '-'); + + private static void deleteTempFolder(File dir) { + String files[] = dir.list(); + if (files != null) { + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + if (f.isDirectory()) { + deleteTempFolder(f); + } else { + f.delete(); + } + } + } + dir.delete(); + } + + private static String addTrailingSlash(String path) { + if (File.separatorChar == path.charAt(path.length() - 1)) { + return path; + } + return path + File.separator; + } + + /** Location to store tests in */ + private File tempDirectory; - @Override protected void setUp() throws Exception { - super.setUp(); - TestEnvironment.reset(); + public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; + + protected void setUp() throws IOException { + /** Setup the temporary directory */ + tempDirectory = new File(addTrailingSlash(System.getProperty("java.io.tmpdir")) + "harmony-test-" + getClass().getSimpleName() + File.separator); + tempDirectory.mkdirs(); } - @Override protected void tearDown() throws Exception { - TestEnvironment.reset(); - super.tearDown(); + protected void tearDown() { + if (tempDirectory != null) { + deleteTempFolder(tempDirectory); + tempDirectory = null; + } } /** * @tests java.io.File#File(java.io.File, java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "File", - args = {java.io.File.class, java.lang.String.class} - ) - public void test_ConstructorLjava_io_FileLjava_lang_String() { + public void test_ConstructorLjava_io_FileLjava_lang_String0() { + File f = new File(tempDirectory.getPath(), "input.tst"); + assertEquals("Created Incorrect File ", addTrailingSlash(tempDirectory.getPath()) + "input.tst", f.getPath()); + } + + public void test_ConstructorLjava_io_FileLjava_lang_String1() { + try { + new File(tempDirectory, null); + fail("NullPointerException Not Thrown."); + } catch (NullPointerException e) { + } + } + + public void test_ConstructorLjava_io_FileLjava_lang_String2() throws IOException { + File f = new File((File)null, "input.tst"); + assertEquals("Created Incorrect File", + new File("input.tst").getAbsolutePath(), + f.getAbsolutePath()); + } + + public void test_ConstructorLjava_io_FileLjava_lang_String3() { + // Regression test for HARMONY-382 + File f = new File("/abc"); + File d = new File((File)null, "/abc"); + assertEquals("Test3: Created Incorrect File", + d.getAbsolutePath(), f.getAbsolutePath()); + } + + public void test_ConstructorLjava_io_FileLjava_lang_String4() { // Regression test for HARMONY-21 File path = new File("/dir/file"); File root = new File("/"); File file = new File(root, "/dir/file"); assertEquals("Assert 1: wrong path result ", path.getPath(), file .getPath()); - assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b").isAbsolute()); - assertTrue("Assert 1.1: path absolute ", new File("///a/b").isAbsolute()); - + if (File.separatorChar == '\\') { + assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b") + .isAbsolute()); + } else { + assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b") + .isAbsolute()); + } + } + + public void test_ConstructorLjava_io_FileLjava_lang_String5() { // Test data used in a few places below - String dirName = System.getProperty("java.io.tmpdir"); + String dirName = tempDirectory.getPath(); String fileName = "input.tst"; - // change user.dir to a folder that's writeable on android. - String oldUserDir = System.getProperty("user.dir"); - System.setProperty("user.dir", dirName); - // Check filename is preserved correctly File d = new File(dirName); File f = new File(d, fileName); - if (!dirName - .regionMatches((dirName.length() - 1), File.separator, 0, 1)) { - dirName += File.separator; - } + dirName = addTrailingSlash(dirName); dirName += fileName; - assertTrue("Assert 2: Created incorrect file " + f.getPath(), f - .getPath().equals(dirName)); + assertEquals("Assert 1: Created incorrect file ", + dirName, f.getPath()); // Check null argument is handled try { f = new File(d, null); - fail("Assert 3: NullPointerException not thrown."); + fail("Assert 2: NullPointerException not thrown."); } catch (NullPointerException e) { // Expected. } - - f = new File((File) null, fileName); - assertEquals("Assert 4: Created incorrect file " + f.getPath(), dirName, - f.getAbsolutePath()); - + } + + public void test_ConstructorLjava_io_FileLjava_lang_String6() { // Regression for HARMONY-46 File f1 = new File("a"); File f2 = new File("a/"); - assertEquals("Assert 5: Trailing slash file name is incorrect", f1, f2); + assertEquals("Trailing slash file name is incorrect", f1, f2); + } - // reset user.dir - System.setProperty("user.dir", oldUserDir); + /** + * @tests java.io.File#File(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + String fileName = null; + try { + new File(fileName); + fail("NullPointerException Not Thrown."); + } catch (NullPointerException e) { + // Expected + } + + fileName = addTrailingSlash(tempDirectory.getPath()); + fileName += "input.tst"; + + File f = new File(fileName); + assertEquals("Created incorrect File", fileName, f.getPath()); } - + /** - * @tests java.io.File#hashCode() + * @tests java.io.File#File(java.lang.String, java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) - public void test_hashCode() { - // Regression for HARMONY-53 - String mixedFname = "SoMe FiLeNaMe"; - File mfile = new File(mixedFname); - File lfile = new File(mixedFname.toLowerCase()); + public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException { + String dirName = null; + String fileName = "input.tst"; + File f = new File(dirName, fileName); + assertEquals("Test 1: Created Incorrect File", + new File("input.tst").getAbsolutePath(), + f.getAbsolutePath()); - if (mfile.equals(lfile)) { - assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile.hashCode()); + dirName = tempDirectory.getPath(); + fileName = null; + try { + f = new File(dirName, fileName); + fail("NullPointerException Not Thrown."); + } catch (NullPointerException e) { + // Expected + } + + fileName = "input.tst"; + f = new File(dirName, fileName); + assertEquals("Test 2: Created Incorrect File", + addTrailingSlash(tempDirectory.getPath()) + "input.tst", + f.getPath()); + + // Regression test for HARMONY-382 + String s = null; + f = new File("/abc"); + File d = new File(s, "/abc"); + assertEquals("Test3: Created Incorrect File", d.getAbsolutePath(), f + .getAbsolutePath()); + } + + /** + * @tests java.io.File#File(java.lang.String, java.lang.String) + */ + public void test_Constructor_String_String_112270() { + File ref1 = new File("/dir1/file1"); + + File file1 = new File("/", "/dir1/file1"); + assertEquals("wrong result 1", ref1.getPath(), file1.getPath()); + File file2 = new File("/", "//dir1/file1"); + assertEquals("wrong result 2", ref1.getPath(), file2.getPath()); + + if (File.separatorChar == '\\') { + File file3 = new File("\\", "\\dir1\\file1"); + assertEquals("wrong result 3", ref1.getPath(), file3.getPath()); + File file4 = new File("\\", "\\\\dir1\\file1"); + assertEquals("wrong result 4", ref1.getPath(), file4.getPath()); + } + + File ref2 = new File("/lib/content-types.properties"); + File file5 = new File("/", "lib/content-types.properties"); + assertEquals("wrong result 5", ref2.getPath(), file5.getPath()); + } + + /** + * @tests java.io.File#File(java.io.File, java.lang.String) + */ + public void test_Constructor_File_String_112270() { + File ref1 = new File("/dir1/file1"); + + File root = new File("/"); + File file1 = new File(root, "/dir1/file1"); + assertEquals("wrong result 1", ref1.getPath(), file1.getPath()); + File file2 = new File(root, "//dir1/file1"); + assertEquals("wrong result 2", ref1.getPath(), file2.getPath()); + + if (File.separatorChar == '\\') { + File file3 = new File(root, "\\dir1\\file1"); + assertEquals("wrong result 3", ref1.getPath(), file3.getPath()); + File file4 = new File(root, "\\\\dir1\\file1"); + assertEquals("wrong result 4", ref1.getPath(), file4.getPath()); + } + + File ref2 = new File("/lib/content-types.properties"); + File file5 = new File(root, "lib/content-types.properties"); + assertEquals("wrong result 5", ref2.getPath(), file5.getPath()); + } + + /** + * @tests java.io.File#File(java.net.URI) + */ + public void test_ConstructorLjava_net_URI() throws URISyntaxException { + URI uri = null; + try { + new File(uri); + fail("NullPointerException Not Thrown."); + } catch (NullPointerException e) { + // Expected + } + + // invalid file URIs + String[] uris = new String[] { "mailto:user@domain.com", // not + // hierarchical + "ftp:///path", // not file scheme + "//host/path/", // not absolute + "file://host/path", // non empty authority + "file:///path?query", // non empty query + "file:///path#fragment", // non empty fragment + "file:///path?", "file:///path#" }; + + for (int i = 0; i < uris.length; i++) { + uri = new URI(uris[i]); + try { + new File(uri); + fail("Expected IllegalArgumentException for new File(" + uri + + ")"); + } catch (IllegalArgumentException e) { + // Expected + } + } + + // a valid File URI + File f = new File(new URI("file:///pa%20th/another\u20ac/pa%25th")); + assertTrue("Created incorrect File " + f.getPath(), f.getPath().equals( + File.separator + "pa th" + File.separator + "another\u20ac" + File.separator + "pa%th")); + } + + /** + * @tests java.io.File#canRead() + */ + public void test_canRead() throws IOException { + // canRead only returns if the file exists so cannot be fully tested. + File f = new File(tempDirectory, platformId + "canRead.tst"); + try { + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + assertTrue("canRead returned false", f.canRead()); + } finally { + f.delete(); + } + } + + /** + * @tests java.io.File#canWrite() + */ + public void test_canWrite() throws IOException { + // canWrite only returns if the file exists so cannot be fully tested. + File f = new File(tempDirectory, platformId + "canWrite.tst"); + try { + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + assertTrue("canWrite returned false", f.canWrite()); + } finally { + f.delete(); + } + } + + /** + * @tests java.io.File#compareTo(java.io.File) + */ + public void test_compareToLjava_io_File() { + File f1 = new File("thisFile.file"); + File f2 = new File("thisFile.file"); + File f3 = new File("thatFile.file"); + assertEquals("Equal files did not answer zero for compareTo", 0, f1 + .compareTo(f2)); + assertTrue("f3.compareTo(f1) did not result in value < 0", f3 + .compareTo(f1) < 0); + assertTrue("f1.compareTo(f3) did not result in value > 0", f1 + .compareTo(f3) > 0); + } + + /** + * @tests java.io.File#createNewFile() + */ + public void test_createNewFile_EmptyString() { + File f = new File(""); + try { + f.createNewFile(); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + } + + /** + * @tests java.io.File#createNewFile() + */ + public void test_createNewFile() throws IOException { + String base = tempDirectory.getPath(); + boolean dirExists = true; + int numDir = 1; + File dir = new File(base, String.valueOf(numDir)); + // Making sure that the directory does not exist. + while (dirExists) { + // If the directory exists, add one to the directory number + // (making it a new directory name.) + if (dir.exists()) { + numDir++; + dir = new File(base, String.valueOf(numDir)); + } else { + dirExists = false; + } + } + + // Test for trying to create a file in a directory that does not + // exist. + try { + // Try to create a file in a directory that does not exist + File f1 = new File(dir, "tempfile.tst"); + f1.createNewFile(); + fail("IOException not thrown"); + } catch (IOException e) { + // Expected + } + + dir.mkdir(); + + File f1 = new File(dir, "tempfile.tst"); + File f2 = new File(dir, "tempfile.tst"); + f1.deleteOnExit(); + f2.deleteOnExit(); + dir.deleteOnExit(); + assertFalse("File Should Not Exist", f1.isFile()); + f1.createNewFile(); + assertTrue("File Should Exist.", f1.isFile()); + assertTrue("File Should Exist.", f2.isFile()); + String dirName = f1.getParent(); + if (!dirName.endsWith(File.separator)) { + dirName += File.separator; + } + assertEquals("File Saved To Wrong Directory.", + dir.getPath() + File.separator, dirName); + assertEquals("File Saved With Incorrect Name.", "tempfile.tst", + f1.getName()); + + // Test for creating a file that already exists. + assertFalse("File Already Exists, createNewFile Should Return False.", + f2.createNewFile()); + + // Test create an illegal file + String sep = File.separator; + f1 = new File(sep + ".."); + try { + f1.createNewFile(); + fail("should throw IOE"); + } catch (IOException e) { + // expected; + } + f1 = new File(sep + "a" + sep + ".." + sep + ".." + sep); + try { + f1.createNewFile(); + fail("should throw IOE"); + } catch (IOException e) { + // expected; + } + + // This test is invalid. createNewFile should return false + // not IOE when the file exists (in this case it exists and is + // a directory). TODO: We should probably replace this test + // with some that cover this behaviour. It might even be + // different on unix and windows since it directly reflects + // the open syscall behaviour. + // + // // Test create an exist path + // f1 = new File(base); + // try { + // assertFalse(f1.createNewFile()); + // fail("should throw IOE"); + // } catch (IOException e) { + // // expected; + // } + } + + /** + * @tests java.io.File#createTempFile(java.lang.String, java.lang.String) + */ + public void test_createTempFileLjava_lang_StringLjava_lang_String() + throws IOException { + // Error protection against using a suffix without a "."? + File f1 = null; + File f2 = null; + try { + f1 = File.createTempFile("harmony-test-FileTest_tempFile_abc", ".tmp"); + f2 = File.createTempFile("harmony-test-FileTest_tempFile_tf", null); + + String fileLocation = addTrailingSlash(f1.getParent()); + + String tempDir = addTrailingSlash(System.getProperty("java.io.tmpdir")); + + assertEquals( + "File did not save to the default temporary-file location.", + tempDir, fileLocation); + + // Test to see if correct suffix was used to create the tempfile. + File currentFile; + String fileName; + // Testing two files, one with suffix ".tmp" and one with null + for (int i = 0; i < 2; i++) { + currentFile = i == 0 ? f1 : f2; + fileName = currentFile.getPath(); + assertTrue("File Created With Incorrect Suffix.", fileName + .endsWith(".tmp")); + } + + // Tests to see if the correct prefix was used to create the + // tempfiles. + fileName = f1.getName(); + assertTrue("Test 1: File Created With Incorrect Prefix.", fileName + .startsWith("harmony-test-FileTest_tempFile_abc")); + fileName = f2.getName(); + assertTrue("Test 2: File Created With Incorrect Prefix.", fileName + .startsWith("harmony-test-FileTest_tempFile_tf")); + + // Tests for creating a tempfile with a filename shorter than 3 + // characters. + try { + File f3 = File.createTempFile("ab", ".tst"); + f3.delete(); + fail("IllegalArgumentException Not Thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + try { + File f3 = File.createTempFile("a", ".tst"); + f3.delete(); + fail("IllegalArgumentException Not Thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + try { + File f3 = File.createTempFile("", ".tst"); + f3.delete(); + fail("IllegalArgumentException Not Thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + } finally { + if (f1 != null) { + f1.delete(); + } + if (f2 != null) { + f2.delete(); + } + } + } + + /** + * @tests java.io.File#createTempFile(java.lang.String, java.lang.String, + * java.io.File) + */ + public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File() + throws IOException { + File f1 = null; + File f2 = null; + String base = System.getProperty("java.io.tmpdir"); + try { + // Test to make sure that the tempfile was saved in the correct + // location and with the correct prefix/suffix. + f1 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, null); + File dir = new File(base); + f2 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", ".tmp", dir); + File currentFile; + String fileLocation; + String fileName; + for (int i = 0; i < 2; i++) { + currentFile = i == 0 ? f1 : f2; + fileLocation = addTrailingSlash(currentFile.getParent()); + base = addTrailingSlash(base); + assertEquals( + "File not created in the default temporary-file location.", + base, fileLocation); + fileName = currentFile.getName(); + assertTrue("File created with incorrect suffix.", fileName + .endsWith(".tmp")); + assertTrue("File created with incorrect prefix.", fileName + .startsWith("harmony-test-FileTest_tempFile2_tf")); + currentFile.delete(); + } + + // Test for creating a tempfile in a directory that does not exist. + int dirNumber = 1; + boolean dirExists = true; + // Set dir to a non-existent directory inside the temporary + // directory + dir = new File(base, String.valueOf(dirNumber)); + // Making sure that the directory does not exist. + while (dirExists) { + // If the directory exists, add one to the directory number + // (making it + // a new directory name.) + if (dir.exists()) { + dirNumber++; + dir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + try { + // Try to create a file in a directory that does not exist + File f3 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, dir); + f3.delete(); + fail("IOException not thrown"); + } catch (IOException e) { + // Expected + } + dir.delete(); + + // Tests for creating a tempfile with a filename shorter than 3 + // characters. + try { + File f4 = File.createTempFile("ab", null, null); + f4.delete(); + fail("IllegalArgumentException not thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + try { + File f4 = File.createTempFile("a", null, null); + f4.delete(); + fail("IllegalArgumentException not thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + try { + File f4 = File.createTempFile("", null, null); + f4.delete(); + fail("IllegalArgumentException not thrown."); + } catch (IllegalArgumentException e) { + // Expected + } + } finally { + if (f1 != null) { + f1.delete(); + } + if (f2 != null) { + f1.delete(); + } + } + } + + /** + * @tests java.io.File#delete() + */ + public void test_delete() throws IOException { + File dir = new File(tempDirectory, platformId + + "filechk"); + dir.mkdir(); + assertTrue("Directory does not exist", dir.exists()); + assertTrue("Directory is not directory", dir.isDirectory()); + File f = new File(dir, "filechk.tst"); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + assertTrue("Error Creating File For Delete Test", f.exists()); + dir.delete(); + assertTrue("Directory Should Not Have Been Deleted.", dir.exists()); + f.delete(); + assertTrue("File Was Not Deleted", !f.exists()); + dir.delete(); + assertTrue("Directory Was Not Deleted", !dir.exists()); + } + + // GCH + // TODO : This test passes on Windows but fails on Linux with a + // java.lang.NoClassDefFoundError. Temporarily removing from the test + // suite while I investigate the cause. + // /** + // * @tests java.io.File#deleteOnExit() + // */ + // public void test_deleteOnExit() { + // File f1 = new File(System.getProperty("java.io.tmpdir"), platformId + // + "deleteOnExit.tst"); + // try { + // FileOutputStream fos = new FileOutputStream(f1); + // fos.close(); + // } catch (IOException e) { + // fail("Unexpected IOException During Test : " + e.getMessage()); + // } + // assertTrue("File Should Exist.", f1.exists()); + // + // try { + // Support_Exec.execJava(new String[] { + // "tests.support.Support_DeleteOnExitTest", f1.getPath() }, + // null, true); + // } catch (IOException e) { + // fail("Unexpected IOException During Test + " + e.getMessage()); + // } catch (InterruptedException e) { + // fail("Unexpected InterruptedException During Test: " + e); + // } + // + // boolean gone = !f1.exists(); + // f1.delete(); + // assertTrue("File Should Already Be Deleted.", gone); + // } + + /** + * @tests java.io.File#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() throws IOException { + File f1 = new File("filechk.tst"); + File f2 = new File("filechk.tst"); + File f3 = new File("xxxx"); + + assertTrue("Equality test failed", f1.equals(f2)); + assertTrue("Files Should Not Return Equal.", !f1.equals(f3)); + + f3 = new File("FiLeChK.tst"); + boolean onWindows = File.separatorChar == '\\'; + boolean onUnix = File.separatorChar == '/'; + if (onWindows) { + assertTrue("Files Should Return Equal.", f1.equals(f3)); + } else if (onUnix) { + assertTrue("Files Should NOT Return Equal.", !f1.equals(f3)); + } + + f1 = new File(tempDirectory, "casetest.tmp"); + f2 = new File(tempDirectory, "CaseTest.tmp"); + new FileOutputStream(f1).close(); // create the file + if (f1.equals(f2)) { + try { + FileInputStream fis = new FileInputStream(f2); + fis.close(); + } catch (IOException e) { + fail("File system is case sensitive"); + } } else { - assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile.hashCode()); + boolean exception = false; + try { + FileInputStream fis = new FileInputStream(f2); + fis.close(); + } catch (IOException e) { + exception = true; + } + assertTrue("File system is case insensitive", exception); } + f1.delete(); + } + + /** + * @tests java.io.File#exists() + */ + public void test_exists() throws IOException { + File f = new File(tempDirectory, platformId + + "exists.tst"); + assertTrue("Exists returned true for non-existent file", !f.exists()); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + assertTrue("Exists returned false file", f.exists()); + f.delete(); + } + + /** + * @tests java.io.File#getAbsoluteFile() + */ + public void test_getAbsoluteFile() { + String base = addTrailingSlash(tempDirectory.getPath()); + File f = new File(base, "temp.tst"); + File f2 = f.getAbsoluteFile(); + assertEquals("Test 1: Incorrect File Returned.", 0, f2.compareTo(f + .getAbsoluteFile())); + f = new File(base + "Temp" + File.separator + File.separator + "temp.tst"); + f2 = f.getAbsoluteFile(); + assertEquals("Test 2: Incorrect File Returned.", 0, f2.compareTo(f + .getAbsoluteFile())); + f = new File(base + File.separator + ".." + File.separator + "temp.tst"); + f2 = f.getAbsoluteFile(); + assertEquals("Test 3: Incorrect File Returned.", 0, f2.compareTo(f + .getAbsoluteFile())); + f.delete(); + f2.delete(); + } + + /** + * @tests java.io.File#getAbsolutePath() + */ + public void test_getAbsolutePath() { + String base = addTrailingSlash(tempDirectory.getPath()); + File f = new File(base, "temp.tst"); + assertEquals("Test 1: Incorrect Path Returned.", + base + "temp.tst", f.getAbsolutePath()); + + f = new File(base + "Temp" + File.separator + File.separator + File.separator + "Testing" + File.separator + + "temp.tst"); + assertEquals("Test 2: Incorrect Path Returned.", + base + "Temp" + File.separator + "Testing" + File.separator + "temp.tst", + f.getAbsolutePath()); + + f = new File(base + "a" + File.separator + File.separator + ".." + File.separator + "temp.tst"); + assertEquals("Test 3: Incorrect Path Returned.", + base + "a" + File.separator + ".." + File.separator + "temp.tst", + f.getAbsolutePath()); + f.delete(); + } + + /** + * @tests java.io.File#getCanonicalFile() + */ + public void test_getCanonicalFile() throws IOException { + String base = addTrailingSlash(tempDirectory.getPath()); + File f = new File(base, "temp.tst"); + File f2 = f.getCanonicalFile(); + assertEquals("Test 1: Incorrect File Returned.", 0, f2 + .getCanonicalFile().compareTo(f.getCanonicalFile())); + f = new File(base + "Temp" + File.separator + File.separator + "temp.tst"); + f2 = f.getCanonicalFile(); + assertEquals("Test 2: Incorrect File Returned.", 0, f2 + .getCanonicalFile().compareTo(f.getCanonicalFile())); + f = new File(base + "Temp" + File.separator + File.separator + ".." + File.separator + "temp.tst"); + f2 = f.getCanonicalFile(); + assertEquals("Test 3: Incorrect File Returned.", 0, f2 + .getCanonicalFile().compareTo(f.getCanonicalFile())); + + // Test for when long directory/file names in Windows + boolean onWindows = File.separatorChar == '\\'; + if (onWindows) { + File testdir = new File(base, "long-" + platformId); + testdir.mkdir(); + File dir = new File(testdir, "longdirectory" + platformId); + try { + dir.mkdir(); + f = new File(dir, "longfilename.tst"); + f2 = f.getCanonicalFile(); + assertEquals("Test 4: Incorrect File Returned.", 0, f2 + .getCanonicalFile().compareTo(f.getCanonicalFile())); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + f2 = new File(testdir + File.separator + "longdi~1" + File.separator + + "longfi~1.tst"); + File canonicalf2 = f2.getCanonicalFile(); + /* + * If the "short file name" doesn't exist, then assume that the + * 8.3 file name compatibility is disabled. + */ + if (canonicalf2.exists()) { + assertTrue("Test 5: Incorrect File Returned: " + + canonicalf2, canonicalf2.compareTo(f + .getCanonicalFile()) == 0); + } + } finally { + f.delete(); + f2.delete(); + dir.delete(); + testdir.delete(); + } + } + } + + /** + * @tests java.io.File#getCanonicalPath() + */ + public void test_getCanonicalPath() throws IOException { + // Should work for Unix/Windows. + String dots = ".."; + String base = tempDirectory.getCanonicalPath(); + base = addTrailingSlash(base); + File f = new File(base, "temp.tst"); + assertEquals("Test 1: Incorrect Path Returned.", base + "temp.tst", f + .getCanonicalPath()); + f = new File(base + "Temp" + File.separator + dots + File.separator + "temp.tst"); + assertEquals("Test 2: Incorrect Path Returned.", base + "temp.tst", f + .getCanonicalPath()); + + // Finding a non-existent directory for tests 3 and 4 + // This is necessary because getCanonicalPath is case sensitive and + // could cause a failure in the test if the directory exists but with + // different case letters (e.g "Temp" and "temp") + int dirNumber = 1; + boolean dirExists = true; + File dir1 = new File(base, String.valueOf(dirNumber)); + while (dirExists) { + if (dir1.exists()) { + dirNumber++; + dir1 = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + f = new File(base + dirNumber + File.separator + dots + File.separator + dirNumber + + File.separator + "temp.tst"); + assertEquals("Test 3: Incorrect Path Returned.", base + dirNumber + + File.separator + "temp.tst", f.getCanonicalPath()); + f = new File(base + dirNumber + File.separator + "Temp" + File.separator + dots + File.separator + + "Test" + File.separator + "temp.tst"); + assertEquals("Test 4: Incorrect Path Returned.", base + dirNumber + + File.separator + "Test" + File.separator + "temp.tst", f.getCanonicalPath()); + + f = new File(base + "1234.567"); + assertEquals("Test 5: Incorrect Path Returned.", base + "1234.567", f + .getCanonicalPath()); + + // Test for long file names on Windows + boolean onWindows = (File.separatorChar == '\\'); + if (onWindows) { + File testdir = new File(base, "long-" + platformId); + testdir.mkdir(); + File f1 = new File(testdir, "longfilename" + platformId + ".tst"); + FileOutputStream fos = new FileOutputStream(f1); + File f2 = null, f3 = null, dir2 = null; + try { + fos.close(); + String dirName1 = f1.getCanonicalPath(); + File f4 = new File(testdir, "longfi~1.tst"); + /* + * If the "short file name" doesn't exist, then assume that the + * 8.3 file name compatibility is disabled. + */ + if (f4.exists()) { + String dirName2 = f4.getCanonicalPath(); + assertEquals("Test 6: Incorrect Path Returned.", dirName1, + dirName2); + dir2 = new File(testdir, "longdirectory" + platformId); + if (!dir2.exists()) { + assertTrue("Could not create dir: " + dir2, dir2 + .mkdir()); + } + f2 = new File(testdir.getPath() + File.separator + "longdirectory" + + platformId + File.separator + "Test" + File.separator + dots + + File.separator + "longfilename.tst"); + FileOutputStream fos2 = new FileOutputStream(f2); + fos2.close(); + dirName1 = f2.getCanonicalPath(); + f3 = new File(testdir.getPath() + File.separator + "longdi~1" + + File.separator + "Test" + File.separator + dots + File.separator + + "longfi~1.tst"); + dirName2 = f3.getCanonicalPath(); + assertEquals("Test 7: Incorrect Path Returned.", dirName1, + dirName2); + } + } finally { + f1.delete(); + if (f2 != null) { + f2.delete(); + } + if (dir2 != null) { + dir2.delete(); + } + testdir.delete(); + } + } + } + + /** + * @tests java.io.File#getName() + */ + public void test_getName() { + File f = new File("name.tst"); + assertEquals("Test 1: Returned incorrect name", "name.tst", f.getName()); + + f = new File(""); + assertEquals("Test 2: Returned incorrect name", "", f.getName()); + + f.delete(); + } + + /** + * @tests java.io.File#getParent() + */ + public void test_getParent() { + File f = new File("p.tst"); + assertNull("Incorrect path returned", f.getParent()); + f = new File(System.getProperty("user.home"), "p.tst"); + assertEquals("Incorrect path returned", + System.getProperty("user.home"), f.getParent()); + f.delete(); + + File f1 = new File("/directory"); + assertEquals("Wrong parent test 1", File.separator, f1.getParent()); + f1 = new File("/directory/file"); + assertEquals("Wrong parent test 2", + File.separator + "directory", f1.getParent()); + f1 = new File("directory/file"); + assertEquals("Wrong parent test 3", "directory", f1.getParent()); + f1 = new File("/"); + assertNull("Wrong parent test 4", f1.getParent()); + f1 = new File("directory"); + assertNull("Wrong parent test 5", f1.getParent()); + + if (File.separatorChar == '\\' && new File("d:/").isAbsolute()) { + f1 = new File("d:/directory"); + assertEquals("Wrong parent test 1a", "d:" + File.separator, f1.getParent()); + f1 = new File("d:/directory/file"); + assertEquals("Wrong parent test 2a", + "d:" + File.separator + "directory", f1.getParent()); + f1 = new File("d:directory/file"); + assertEquals("Wrong parent test 3a", "d:directory", f1.getParent()); + f1 = new File("d:/"); + assertNull("Wrong parent test 4a", f1.getParent()); + f1 = new File("d:directory"); + assertEquals("Wrong parent test 5a", "d:", f1.getParent()); + } + } + + /** + * @tests java.io.File#getParentFile() + */ + public void test_getParentFile() { + File f = new File("tempfile.tst"); + assertNull("Incorrect path returned", f.getParentFile()); + f = new File(tempDirectory, "tempfile1.tmp"); + File f2 = new File(tempDirectory, "tempfile2.tmp"); + File f3 = new File(tempDirectory, "/a/tempfile.tmp"); + assertEquals("Incorrect File Returned", 0, f.getParentFile().compareTo( + f2.getParentFile())); + assertTrue("Incorrect File Returned", f.getParentFile().compareTo( + f3.getParentFile()) != 0); + f.delete(); + f2.delete(); + f3.delete(); } /** * @tests java.io.File#getPath() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPath", - args = {} - ) public void test_getPath() { + String base = System.getProperty("user.home"); + String fname; + File f1; + if (!base.regionMatches((base.length() - 1), File.separator, 0, 1)) { + base += File.separator; + } + fname = base + "filechk.tst"; + f1 = new File(base, "filechk.tst"); + File f2 = new File("filechk.tst"); + File f3 = new File("c:"); + File f4 = new File(base + "a" + File.separator + File.separator + ".." + File.separator + + "filechk.tst"); + assertEquals("getPath returned incorrect path(f1)", + fname, f1.getPath()); + assertEquals("getPath returned incorrect path(f2)", + "filechk.tst", f2.getPath()); + assertEquals("getPath returned incorrect path(f3)","c:", f3.getPath()); + assertEquals("getPath returned incorrect path(f4)", + base + "a" + File.separator + ".." + File.separator + "filechk.tst", + f4.getPath()); + f1.delete(); + f2.delete(); + f3.delete(); + f4.delete(); + // Regression for HARMONY-444 File file; String separator = File.separator; @@ -140,46 +1019,1234 @@ public class FileTest extends TestCase { file = new File((String) null, "x/y/z"); assertEquals("x" + separator + "y" + separator + "z", file.getPath()); - } - - /** - * @tests java.io.File#getPath() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPath", - args = {} - ) - public void test_getPath_With_Empty_FileName() { + // Regression for HARMONY-829 String f1ParentName = "01"; - File f1 = new File(f1ParentName, ""); + f1 = new File(f1ParentName, ""); assertEquals(f1ParentName, f1.getPath()); - + String f2ParentName = "0"; - File f2 = new File(f2ParentName, ""); + f2 = new File(f2ParentName, ""); assertEquals(-1, f2.compareTo(f1)); assertEquals(1, f1.compareTo(f2)); - File parent = new File(System.getProperty("java.io.tmpdir")); - File f3 = new File(parent, ""); + File parent = tempDirectory; + f3 = new File(parent, ""); assertEquals(parent.getPath(), f3.getPath()); + + // Regression for HARMONY-3869 + File file1 = new File("", ""); + assertEquals(File.separator, file1.getPath()); + + File file2 = new File(new File(""), ""); + assertEquals(File.separator, file2.getPath()); + } + + /** + * @tests java.io.File#hashCode() + */ + public void test_hashCode() { + // Regression for HARMONY-53 + String mixedFname = "SoMe FiLeNaMe"; + File mfile = new File(mixedFname); + File lfile = new File(mixedFname.toLowerCase()); + + if (mfile.equals(lfile)) { + assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile + .hashCode()); + } else { + assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile + .hashCode()); + } + } + + /** + * @tests java.io.File#isAbsolute() + */ + public void test_isAbsolute() { + if (File.separatorChar == '\\') { + File f = new File("c:\\test"); + File f1 = new File("\\test"); + // One or the other should be absolute on Windows or CE + assertTrue("Absolute returned false", (f.isAbsolute() && !f1 + .isAbsolute()) + || (!f.isAbsolute() && f1.isAbsolute())); + + assertTrue(new File("C:/").isAbsolute()); + assertTrue(new File("f:/").isAbsolute()); + assertTrue(new File("f:\\").isAbsolute()); + assertFalse(new File("f:").isAbsolute()); + assertFalse(new File("K:").isAbsolute()); + assertTrue(new File("\\\\").isAbsolute()); + assertTrue(new File("\\\\\\").isAbsolute()); + assertTrue(new File("\\\\hello").isAbsolute()); + assertFalse(new File("\\").isAbsolute()); + assertFalse(new File("/").isAbsolute()); + } else { + File f = new File("/test"); + File f1 = new File("\\test"); + assertTrue("Absolute returned false", f.isAbsolute()); + assertFalse("Absolute returned true", f1.isAbsolute()); + assertTrue(new File("//test").isAbsolute()); + assertFalse(new File("test").isAbsolute()); + assertFalse(new File("c:/").isAbsolute()); + assertFalse(new File("c:\\").isAbsolute()); + assertFalse(new File("c:").isAbsolute()); + assertFalse(new File("\\").isAbsolute()); + assertFalse(new File("\\\\").isAbsolute()); + } + assertTrue("Non-Absolute returned true", !new File("../test") + .isAbsolute()); + } + + /** + * @tests java.io.File#isDirectory() + */ + public void test_isDirectory() { + String base = addTrailingSlash(tempDirectory.getPath()); + File f = new File(base); + assertTrue("Test 1: Directory Returned False", f.isDirectory()); + f = new File(base + "zxzxzxz" + platformId); + assertTrue("Test 2: (Not Created) Directory Returned True.", !f + .isDirectory()); + f.mkdir(); + try { + assertTrue("Test 3: Directory Returned False.", f.isDirectory()); + } finally { + f.delete(); + } + } + + /** + * @tests java.io.File#isFile() + */ + public void test_isFile() throws IOException { + String base = tempDirectory.getPath(); + File f = new File(base); + assertFalse("Directory Returned True As Being A File.", f.isFile()); - + base = addTrailingSlash(base); + f = new File(base, platformId + "amiafile"); + assertTrue("Non-existent File Returned True", !f.isFile()); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + assertTrue("File returned false", f.isFile()); + f.delete(); } - + + /** + * @tests java.io.File#isHidden() + */ + public void test_isHidden() throws IOException, InterruptedException { + boolean onUnix = File.separatorChar == '/'; + File f = File.createTempFile("harmony-test-FileTest_isHidden_", ".tmp"); + // On Unix hidden files are marked with a "." at the beginning + // of the file name. + if (onUnix) { + File f2 = new File(".test.tst" + platformId); + FileOutputStream fos2 = new FileOutputStream(f2); + fos2.close(); + assertTrue("File returned hidden on Unix", !f.isHidden()); + assertTrue("File returned visible on Unix", f2.isHidden()); + assertTrue("File did not delete.", f2.delete()); + } else { + // For windows, the file is being set hidden by the attrib + // command. + Runtime r = Runtime.getRuntime(); + assertTrue("File returned hidden", !f.isHidden()); + Process p = r.exec("attrib +h \"" + f.getAbsolutePath() + "\""); + p.waitFor(); + assertTrue("File returned visible", f.isHidden()); + p = r.exec("attrib -h \"" + f.getAbsolutePath() + "\""); + p.waitFor(); + assertTrue("File returned hidden", !f.isHidden()); + } + f.delete(); + } + + /** + * @tests java.io.File#lastModified() + */ + public void test_lastModified() throws IOException { + File f = new File(System.getProperty("java.io.tmpdir"), platformId + + "lModTest.tst"); + f.delete(); + long lastModifiedTime = f.lastModified(); + assertEquals("LastModified Time Should Have Returned 0.", 0, + lastModifiedTime); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + f.setLastModified(315550800000L); + lastModifiedTime = f.lastModified(); + assertEquals("LastModified Time Incorrect", + 315550800000L, lastModifiedTime); + f.delete(); + + // Regression for HARMONY-2146 + f = new File("/../"); + assertTrue(f.lastModified() > 0); + } + + /** + * @tests java.io.File#length() + */ + public void test_length() throws IOException { + File f = new File(tempDirectory, platformId + + "input.tst"); + assertEquals("File Length Should Have Returned 0.", 0, f.length()); + FileOutputStream fos = new FileOutputStream(f); + fos.write(fileString.getBytes()); + fos.close(); + assertEquals("Incorrect file length returned", + fileString.length(), f.length()); + f.delete(); + + // regression test for HARMONY-1497 + f = File.createTempFile("test", "tmp"); + f.deleteOnExit(); + RandomAccessFile raf = new RandomAccessFile(f, "rwd"); + raf.write(0x41); + assertEquals(1, f.length()); + } + + /** + * @tests java.io.File#list() + */ + public void test_list() throws IOException { + String base = tempDirectory.getPath(); + // Old test left behind "garbage files" so this time it creates a + // directory that is guaranteed not to already exist (and deletes it + // afterward.) + int dirNumber = 1; + boolean dirExists = true; + File dir = null; + dir = new File(base, platformId + String.valueOf(dirNumber)); + while (dirExists) { + if (dir.exists()) { + dirNumber++; + dir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + + String[] flist = dir.list(); + + assertNull("Method list() Should Have Returned null.", flist); + + assertTrue("Could not create parent directory for list test", dir + .mkdir()); + + String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" }; + try { + assertEquals( + "Method list() Should Have Returned An Array Of Length 0.", + 0, dir.list().length); + + File file = new File(dir, "notADir.tst"); + try { + FileOutputStream fos = new FileOutputStream(file); + fos.close(); + assertNull( + "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.", + file.list()); + } finally { + file.delete(); + } + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + + flist = dir.list(); + if (flist.length != files.length) { + fail("Incorrect list returned"); + } + + // Checking to make sure the correct files were are listed in the + // array. + boolean[] check = new boolean[flist.length]; + for (int i = 0; i < check.length; i++) { + check[i] = false; + } + for (int i = 0; i < files.length; i++) { + for (int j = 0; j < flist.length; j++) { + if (flist[j].equals(files[i])) { + check[i] = true; + break; + } + } + } + int checkCount = 0; + for (int i = 0; i < check.length; i++) { + if (check[i] == false) { + checkCount++; + } + } + assertEquals("Invalid file returned in listing", 0, checkCount); + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + + assertTrue("Could not delete parent directory for list test.", dir + .delete()); + } finally { + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + dir.delete(); + } + } + + /** + * @tests java.io.File#listFiles() + */ + public void test_listFiles() throws IOException, InterruptedException { + String base = tempDirectory.getPath(); + // Finding a non-existent directory to create. + int dirNumber = 1; + boolean dirExists = true; + File dir = new File(base, platformId + String.valueOf(dirNumber)); + // Making sure that the directory does not exist. + while (dirExists) { + // If the directory exists, add one to the directory number + // (making it a new directory name.) + if (dir.exists()) { + dirNumber++; + dir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + // Test for attempting to call listFiles on a non-existent directory. + assertNull("listFiles Should Return Null.", dir.listFiles()); + + assertTrue("Failed To Create Parent Directory.", dir.mkdir()); + + String[] files = { "1.tst", "2.tst", "3.tst", "" }; + try { + assertEquals("listFiles Should Return An Array Of Length 0.", 0, + dir.listFiles().length); + + File file = new File(dir, "notADir.tst"); + try { + FileOutputStream fos = new FileOutputStream(file); + fos.close(); + assertNull( + "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.", + file.listFiles()); + } finally { + file.delete(); + } + + for (int i = 0; i < (files.length - 1); i++) { + File f = new File(dir, files[i]); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + + new File(dir, "doesNotExist.tst"); + File[] flist = dir.listFiles(); + + // Test to make sure that only the 3 files that were created are + // listed. + assertEquals("Incorrect Number Of Files Returned.", 3, flist.length); + + // Test to make sure that listFiles can read hidden files. + boolean onUnix = File.separatorChar == '/'; + boolean onWindows = File.separatorChar == '\\'; + if (onWindows) { + files[3] = "4.tst"; + File f = new File(dir, "4.tst"); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + Runtime r = Runtime.getRuntime(); + Process p = r.exec("attrib +h \"" + f.getPath() + "\""); + p.waitFor(); + } + if (onUnix) { + files[3] = ".4.tst"; + File f = new File(dir, ".4.tst"); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + flist = dir.listFiles(); + assertEquals("Incorrect Number Of Files Returned.", 4, flist.length); + + // Checking to make sure the correct files were are listed in + // the array. + boolean[] check = new boolean[flist.length]; + for (int i = 0; i < check.length; i++) { + check[i] = false; + } + for (int i = 0; i < files.length; i++) { + for (int j = 0; j < flist.length; j++) { + if (flist[j].getName().equals(files[i])) { + check[i] = true; + break; + } + } + } + int checkCount = 0; + for (int i = 0; i < check.length; i++) { + if (check[i] == false) { + checkCount++; + } + } + assertEquals("Invalid file returned in listing", 0, checkCount); + + if (onWindows) { + Runtime r = Runtime.getRuntime(); + Process p = r.exec("attrib -h \"" + + new File(dir, files[3]).getPath() + "\""); + p.waitFor(); + } + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + assertTrue("Parent Directory Not Deleted.", dir.delete()); + } finally { + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + dir.delete(); + } + } + + /** + * @tests java.io.File#listFiles(java.io.FileFilter) + */ + public void test_listFilesLjava_io_FileFilter() throws IOException { + String base = System.getProperty("java.io.tmpdir"); + // Finding a non-existent directory to create. + int dirNumber = 1; + boolean dirExists = true; + File baseDir = new File(base, platformId + String.valueOf(dirNumber)); + // Making sure that the directory does not exist. + while (dirExists) { + // If the directory exists, add one to the directory number (making + // it a new directory name.) + if (baseDir.exists()) { + dirNumber++; + baseDir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + + // Creating a filter that catches directories. + FileFilter dirFilter = new FileFilter() { + public boolean accept(File f) { + return f.isDirectory(); + } + }; + + assertNull("listFiles Should Return Null.", baseDir + .listFiles(dirFilter)); + + assertTrue("Failed To Create Parent Directory.", baseDir.mkdir()); + + File dir1 = null; + String[] files = { "1.tst", "2.tst", "3.tst" }; + try { + assertEquals("listFiles Should Return An Array Of Length 0.", 0, + baseDir.listFiles(dirFilter).length); + + File file = new File(baseDir, "notADir.tst"); + try { + FileOutputStream fos = new FileOutputStream(file); + fos.close(); + assertNull( + "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.", + file.listFiles(dirFilter)); + } finally { + file.delete(); + } + + for (int i = 0; i < files.length; i++) { + File f = new File(baseDir, files[i]); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + dir1 = new File(baseDir, "Temp1"); + dir1.mkdir(); + + // Creating a filter that catches files. + FileFilter fileFilter = new FileFilter() { + public boolean accept(File f) { + return f.isFile(); + } + }; + + // Test to see if the correct number of directories are returned. + File[] directories = baseDir.listFiles(dirFilter); + assertEquals("Incorrect Number Of Directories Returned.", 1, + directories.length); + + // Test to see if the directory was saved with the correct name. + assertEquals("Incorrect Directory Returned.", 0, directories[0] + .compareTo(dir1)); + + // Test to see if the correct number of files are returned. + File[] flist = baseDir.listFiles(fileFilter); + assertEquals("Incorrect Number Of Files Returned.", + files.length, flist.length); + + // Checking to make sure the correct files were are listed in the + // array. + boolean[] check = new boolean[flist.length]; + for (int i = 0; i < check.length; i++) { + check[i] = false; + } + for (int i = 0; i < files.length; i++) { + for (int j = 0; j < flist.length; j++) { + if (flist[j].getName().equals(files[i])) { + check[i] = true; + break; + } + } + } + int checkCount = 0; + for (int i = 0; i < check.length; i++) { + if (check[i] == false) { + checkCount++; + } + } + assertEquals("Invalid file returned in listing", 0, checkCount); + + for (int i = 0; i < files.length; i++) { + File f = new File(baseDir, files[i]); + f.delete(); + } + dir1.delete(); + assertTrue("Parent Directory Not Deleted.", baseDir.delete()); + } finally { + for (int i = 0; i < files.length; i++) { + File f = new File(baseDir, files[i]); + f.delete(); + } + if (dir1 != null) { + dir1.delete(); + } + baseDir.delete(); + } + } + + /** + * @tests java.io.File#listFiles(java.io.FilenameFilter) + */ + public void test_listFilesLjava_io_FilenameFilter() throws IOException { + String base = System.getProperty("java.io.tmpdir"); + // Finding a non-existent directory to create. + int dirNumber = 1; + boolean dirExists = true; + File dir = new File(base, platformId + String.valueOf(dirNumber)); + // Making sure that the directory does not exist. + while (dirExists) { + // If the directory exists, add one to the directory number (making + // it a new directory name.) + if (dir.exists()) { + dirNumber++; + dir = new File(base, platformId + String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + + // Creating a filter that catches "*.tst" files. + FilenameFilter tstFilter = new FilenameFilter() { + public boolean accept(File f, String fileName) { + return fileName.endsWith(".tst"); + } + }; + + assertNull("listFiles Should Return Null.", dir.listFiles(tstFilter)); + + assertTrue("Failed To Create Parent Directory.", dir.mkdir()); + + String[] files = { "1.tst", "2.tst", "3.tmp" }; + try { + assertEquals("listFiles Should Return An Array Of Length 0.", 0, + dir.listFiles(tstFilter).length); + + File file = new File(dir, "notADir.tst"); + try { + FileOutputStream fos = new FileOutputStream(file); + fos.close(); + assertNull( + "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.", + file.listFiles(tstFilter)); + } finally { + file.delete(); + } + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + + // Creating a filter that catches "*.tmp" files. + FilenameFilter tmpFilter = new FilenameFilter() { + public boolean accept(File f, String fileName) { + // If the suffix is ".tmp" then send it to the array + if (fileName.endsWith(".tmp")) { + return true; + } else { + return false; + } + } + }; + + // Tests to see if the correct number of files were returned. + File[] flist = dir.listFiles(tstFilter); + assertEquals("Incorrect Number Of Files Passed Through tstFilter.", + 2, flist.length); + for (int i = 0; i < flist.length; i++) { + assertTrue("File Should Not Have Passed The tstFilter.", + flist[i].getPath().endsWith(".tst")); + } + + flist = dir.listFiles(tmpFilter); + assertEquals("Incorrect Number Of Files Passed Through tmpFilter.", + 1, flist.length); + assertTrue("File Should Not Have Passed The tmpFilter.", flist[0] + .getPath().endsWith(".tmp")); + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + assertTrue("Parent Directory Not Deleted.", dir.delete()); + } finally { + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + dir.delete(); + } + } + + /** + * @tests java.io.File#list(java.io.FilenameFilter) + */ + public void test_listLjava_io_FilenameFilter() throws IOException { + String base = tempDirectory.getPath(); + // Old test left behind "garbage files" so this time it creates a + // directory that is guaranteed not to already exist (and deletes it + // afterward.) + int dirNumber = 1; + boolean dirExists = true; + File dir = new File(base, platformId + String.valueOf(dirNumber)); + while (dirExists) { + if (dir.exists()) { + dirNumber++; + dir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return !name.equals("mtzz1.xx"); + } + }; + + String[] flist = dir.list(filter); + assertNull("Method list(FilenameFilter) Should Have Returned Null.", + flist); + + assertTrue("Could not create parent directory for test", dir.mkdir()); + + String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" }; + try { + /* + * Do not return null when trying to use list(Filename Filter) on a + * file rather than a directory. All other "list" methods return + * null for this test case. + */ + /* + * File file = new File(dir, "notADir.tst"); try { FileOutputStream + * fos = new FileOutputStream(file); fos.close(); } catch + * (IOException e) { fail("Unexpected IOException During Test."); } + * flist = dir.list(filter); assertNull("listFiles Should Have + * Returned Null When Used On A File Instead Of A Directory.", + * flist); file.delete(); + */ + + flist = dir.list(filter); + assertEquals("Array Of Length 0 Should Have Returned.", 0, + flist.length); + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + FileOutputStream fos = new FileOutputStream(f); + fos.close(); + } + + flist = dir.list(filter); + + assertEquals("Incorrect list returned", flist.length, + files.length - 1); + + // Checking to make sure the correct files were are listed in the + // array. + boolean[] check = new boolean[flist.length]; + for (int i = 0; i < check.length; i++) { + check[i] = false; + } + String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" }; + for (int i = 0; i < wantedFiles.length; i++) { + for (int j = 0; j < flist.length; j++) { + if (flist[j].equals(wantedFiles[i])) { + check[i] = true; + break; + } + } + } + int checkCount = 0; + for (int i = 0; i < check.length; i++) { + if (check[i] == false) { + checkCount++; + } + } + assertEquals("Invalid file returned in listing", 0, checkCount); + + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + assertTrue("Could not delete parent directory for test.", dir + .delete()); + } finally { + for (int i = 0; i < files.length; i++) { + File f = new File(dir, files[i]); + f.delete(); + } + dir.delete(); + } + } + + /** + * @tests java.io.File#listRoots() + */ + public void test_listRoots() { + File[] roots = File.listRoots(); + boolean onUnix = File.separatorChar == '/'; + boolean onWindows = File.separatorChar == '\\'; + if (onUnix) { + assertEquals("Incorrect Number Of Root Directories.", 1, + roots.length); + String fileLoc = roots[0].getPath(); + assertTrue("Incorrect Root Directory Returned.", fileLoc + .startsWith(File.separator)); + } else if (onWindows) { + // Need better test for Windows + assertTrue("Incorrect Number Of Root Directories.", + roots.length > 0); + } + } + + /** + * @tests java.io.File#mkdir() + */ + public void test_mkdir() throws IOException { + String base = tempDirectory.getPath(); + // Old test left behind "garbage files" so this time it creates a + // directory that is guaranteed not to already exist (and deletes it + // afterward.) + int dirNumber = 1; + boolean dirExists = true; + File dir = new File(base, String.valueOf(dirNumber)); + while (dirExists) { + if (dir.exists()) { + dirNumber++; + dir = new File(base, String.valueOf(dirNumber)); + } else { + dirExists = false; + } + } + + assertTrue("mkdir failed", dir.mkdir()); + assertTrue("mkdir worked but exists check failed", dir.exists()); + dir.deleteOnExit(); + + String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars + String newbase = new String(dir + File.separator); + StringBuilder sb = new StringBuilder(dir + File.separator); + StringBuilder sb2 = new StringBuilder(dir + File.separator); + + // Test make a long path + while (dir.getCanonicalPath().length() < 256 - longDirName.length()) { + sb.append(longDirName + File.separator); + dir = new File(sb.toString()); + assertTrue("mkdir failed", dir.mkdir()); + assertTrue("mkdir worked but exists check failed", dir.exists()); + dir.deleteOnExit(); + } + + while (dir.getCanonicalPath().length() < 256) { + sb.append(0); + dir = new File(sb.toString()); + assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed", + dir.mkdir()); + assertTrue("mkdir " + dir.getCanonicalPath().length() + + " worked but exists check failed", dir.exists()); + dir.deleteOnExit(); + } + dir = new File(sb2.toString()); + // Test make many paths + while (dir.getCanonicalPath().length() < 256) { + sb2.append(0); + dir = new File(sb2.toString()); + assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed", + dir.mkdir()); + assertTrue("mkdir " + dir.getCanonicalPath().length() + + " worked but exists check failed", dir.exists()); + dir.deleteOnExit(); + } + + // Regression test for HARMONY-3656 + String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&", + "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D", + "\u4E03\u516B\u4E5D" }; + for (int i = 0; i < ss.length; i++) { + dir = new File(newbase, ss[i]); + assertTrue("mkdir " + dir.getCanonicalPath() + " failed", + dir.mkdir()); + assertTrue("mkdir " + dir.getCanonicalPath() + + " worked but exists check failed", + dir.exists()); + dir.deleteOnExit(); + } + } + + /** + * @tests java.io.File#mkdir() + * + * HARMONY-6041 + */ + public void test_mkdir_special_unicode() throws IOException { + File specialDir = new File(this.tempDirectory,"\u5C73"); + int i = 0; + while (specialDir.exists()) { + specialDir = new File("\u5C73" + i); + ++i; + } + assertFalse(specialDir.exists()); + assertTrue(specialDir.mkdir()); + assertTrue(specialDir.exists()); + } + + /** + * @tests java.io.File#mkdirs() + */ + public void test_mkdirs() { + String userHome = addTrailingSlash(tempDirectory.getPath()); + File f = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2", + "p.tst"); + File g = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2"); + File h = new File(userHome + "mdtest" + platformId); + f.mkdirs(); + try { + assertTrue("Base Directory not created", h.exists()); + assertTrue("Directories not created", g.exists()); + assertTrue("File not created", f.exists()); + } finally { + f.delete(); + g.delete(); + h.delete(); + } + } + + /** + * @tests java.io.File#renameTo(java.io.File) + */ + public void test_renameToLjava_io_File() throws IOException { + String base = tempDirectory.getPath(); + File dir = new File(base, platformId); + dir.mkdir(); + File f = new File(dir, "xxx.xxx"); + File rfile = new File(dir, "yyy.yyy"); + File f2 = new File(dir, "zzz.zzz"); + try { + FileOutputStream fos = new FileOutputStream(f); + fos.write(fileString.getBytes()); + fos.close(); + long lengthOfFile = f.length(); + + rfile.delete(); // in case it already exists + + assertTrue("Test 1: File Rename Failed", f.renameTo(rfile)); + assertTrue("Test 2: File Rename Failed.", rfile.exists()); + assertEquals("Test 3: Size Of File Changed.", + lengthOfFile, rfile.length()); + + fos = new FileOutputStream(rfile); + fos.close(); + + f2.delete(); // in case it already exists + assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2)); + assertTrue("Test 5: File Rename Failed.", f2.exists()); + } finally { + f.delete(); + rfile.delete(); + f2.delete(); + dir.delete(); + } + } + + /** + * @tests java.io.File#setLastModified(long) + */ + public void test_setLastModifiedJ() throws IOException { + File f1 = null; + try { + f1 = new File(Support_PlatformFile.getNewPlatformFile( + "harmony-test-FileTest_setLastModified", ".tmp")); + f1.createNewFile(); + long orgTime = f1.lastModified(); + // Subtracting 100 000 milliseconds from the orgTime of File f1 + f1.setLastModified(orgTime - 100000); + long lastModified = f1.lastModified(); + assertEquals("Test 1: LastModifed time incorrect", + orgTime - 100000, lastModified); + // Subtracting 10 000 000 milliseconds from the orgTime of File f1 + f1.setLastModified(orgTime - 10000000); + lastModified = f1.lastModified(); + assertEquals("Test 2: LastModifed time incorrect", + orgTime - 10000000, lastModified); + // Adding 100 000 milliseconds to the orgTime of File f1 + f1.setLastModified(orgTime + 100000); + lastModified = f1.lastModified(); + assertEquals("Test 3: LastModifed time incorrect", + orgTime + 100000, lastModified); + // Adding 10 000 000 milliseconds from the orgTime of File f1 + f1.setLastModified(orgTime + 10000000); + lastModified = f1.lastModified(); + assertEquals("Test 4: LastModifed time incorrect", + orgTime + 10000000, lastModified); + // Trying to set time to an exact number + f1.setLastModified(315550800000L); + lastModified = f1.lastModified(); + assertEquals("Test 5: LastModified time incorrect", + 315550800000L, lastModified); + String osName = System.getProperty("os.name", "unknown"); + if (osName.equals("Windows 2000") || osName.equals("Windows NT")) { + // Trying to set time to a large exact number + boolean result = f1.setLastModified(4354837199000L); + long next = f1.lastModified(); + // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and + // the call fails + if (result) { + assertEquals("Test 6: LastModified time incorrect", + 4354837199000L, next); + } + } + // Trying to set time to a negative number + try { + f1.setLastModified(-25); + fail("IllegalArgumentException Not Thrown."); + } catch (IllegalArgumentException e) { + } + } finally { + if (f1 != null) { + f1.delete(); + } + } + } + + /** + * @tests java.io.File#setReadOnly() + */ + public void test_setReadOnly() throws IOException, InterruptedException { + File f1 = null; + File f2 = null; + try { + f1 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp"); + f2 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp"); + // Assert is flawed because canWrite does not work. + // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite()); + f1.setReadOnly(); + // Assert is flawed because canWrite does not work. + // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite()); + try { + // Attempt to write to a file that is setReadOnly. + new FileOutputStream(f1); + fail("IOException not thrown."); + } catch (IOException e) { + // Expected + } + Runtime r = Runtime.getRuntime(); + Process p; + boolean onUnix = File.separatorChar == '/'; + if (onUnix) { + p = r.exec("chmod +w " + f1.getAbsolutePath()); + } else { + p = r.exec("attrib -r \"" + f1.getAbsolutePath() + "\""); + } + p.waitFor(); + // Assert is flawed because canWrite does not work. + // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite()); + FileOutputStream fos = new FileOutputStream(f1); + fos.write(fileString.getBytes()); + fos.close(); + assertTrue("File Was Not Able To Be Written To.", + f1.length() == fileString.length()); + assertTrue("File f1 Did Not Delete", f1.delete()); + + // Assert is flawed because canWrite does not work. + // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite()); + fos = new FileOutputStream(f2); + // Write to a file. + fos.write(fileString.getBytes()); + fos.close(); + f2.setReadOnly(); + // Assert is flawed because canWrite does not work. + // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite()); + try { + // Attempt to write to a file that has previously been written + // to. + // and is now set to read only. + fos = new FileOutputStream(f2); + fail("IOException not thrown."); + } catch (IOException e) { + // Expected + } + r = Runtime.getRuntime(); + if (onUnix) { + p = r.exec("chmod +w " + f2.getAbsolutePath()); + } else { + p = r.exec("attrib -r \"" + f2.getAbsolutePath() + "\""); + } + p.waitFor(); + assertTrue("File f2 Is Set To ReadOnly.", f2.canWrite()); + fos = new FileOutputStream(f2); + fos.write(fileString.getBytes()); + fos.close(); + f2.setReadOnly(); + assertTrue("File f2 Did Not Delete", f2.delete()); + // Similarly, trying to delete a read-only directory should succeed + f2 = new File(tempDirectory, "deltestdir"); + f2.mkdir(); + f2.setReadOnly(); + assertTrue("Directory f2 Did Not Delete", f2.delete()); + assertTrue("Directory f2 Did Not Delete", !f2.exists()); + } finally { + if (f1 != null) { + f1.delete(); + } + if (f2 != null) { + f2.delete(); + } + } + } + + /** + * @tests java.io.File#toString() + */ + public void test_toString() { + String fileName = System.getProperty("user.home") + File.separator + "input.tst"; + File f = new File(fileName); + assertEquals("Incorrect string returned", fileName, f.toString()); + + if (File.separatorChar == '\\') { + String result = new File("c:\\").toString(); + assertEquals("Removed backslash", "c:\\", result); + } + } + + /** + * @tests java.io.File#toURI() + */ + public void test_toURI() throws URISyntaxException { + // Need a directory that exists + File dir = tempDirectory; + + // Test for toURI when the file is a directory. + String newURIPath = dir.getAbsolutePath(); + newURIPath = newURIPath.replace(File.separatorChar, '/'); + if (!newURIPath.startsWith("/")) { + newURIPath = "/" + newURIPath; + } + if (!newURIPath.endsWith("/")) { + newURIPath += '/'; + } + + URI uri = dir.toURI(); + assertEquals("Test 1A: Incorrect URI Returned.", dir.getAbsoluteFile(), new File(uri)); + assertEquals("Test 1B: Incorrect URI Returned.", + new URI("file", null, newURIPath, null, null), uri); + + // Test for toURI with a file name with illegal chars. + File f = new File(dir, "te% \u20ac st.tst"); + newURIPath = f.getAbsolutePath(); + newURIPath = newURIPath.replace(File.separatorChar, '/'); + if (!newURIPath.startsWith("/")) { + newURIPath = "/" + newURIPath; + } + + uri = f.toURI(); + assertEquals("Test 2A: Incorrect URI Returned.", + f.getAbsoluteFile(), new File(uri)); + assertEquals("Test 2B: Incorrect URI Returned.", + new URI("file", null, newURIPath, null, null), uri); + + // Regression test for HARMONY-3207 + dir = new File(""); // current directory + uri = dir.toURI(); + assertTrue("Test current dir: URI does not end with slash.", uri + .toString().endsWith("/")); + } + + /** + * @tests java.io.File#toURL() + */ + public void test_toURL() throws MalformedURLException { + // Need a directory that exists + File dir = tempDirectory; + + // Test for toURL when the file is a directory. + String newDirURL = dir.getAbsolutePath(); + newDirURL = newDirURL.replace(File.separatorChar, '/'); + if (newDirURL.startsWith("/")) { + newDirURL = "file:" + newDirURL; + } else { + newDirURL = "file:/" + newDirURL; + } + if (!newDirURL.endsWith("/")) { + newDirURL += '/'; + } + assertEquals("Test 1: Incorrect URL Returned.", + dir.toURL().toString(), newDirURL); + + // Test for toURL with a file. + File f = new File(dir, "test.tst"); + String newURL = f.getAbsolutePath(); + newURL = newURL.replace(File.separatorChar, '/'); + if (newURL.startsWith("/")) { + newURL = "file:" + newURL; + } else { + newURL = "file:/" + newURL; + } + assertEquals("Test 2: Incorrect URL Returned.", + f.toURL().toString(), newURL); + + // Regression test for HARMONY-3207 + dir = new File(""); // current directory + newDirURL = dir.toURL().toString(); + assertTrue("Test current dir: URL does not end with slash.", newDirURL + .endsWith("/")); + } + + /** + * @tests java.io.File#toURI() + */ + public void test_toURI2() throws URISyntaxException { + File f = new File(tempDirectory, "a/b/c/../d/e/./f"); + + String path = f.getAbsolutePath(); + path = path.replace(File.separatorChar, '/'); + if (!path.startsWith("/")) { + path = "/" + path; + } + + URI uri1 = new URI("file", null, path, null); + URI uri2 = f.toURI(); + assertEquals("uris not equal", uri1, uri2); + } + + /** + * @tests java.io.File#toURL() + */ + public void test_toURL2() throws MalformedURLException { + File f = new File(tempDirectory, "a/b/c/../d/e/./f"); + + String path = f.getAbsolutePath(); + path = path.replace(File.separatorChar, '/'); + if (!path.startsWith("/")) { + path = "/" + path; + } + + URL url1 = new URL("file", "", path); + URL url2 = f.toURL(); + assertEquals("urls not equal", url1, url2); + } + + /** + * @tests java.io.File#deleteOnExit() + */ + /* BEGIN android-removed: we don't have Support_Exec.execJava. + public void test_deleteOnExit() throws IOException, InterruptedException { + File dir = new File("dir4filetest"); + dir.mkdir(); + assertTrue(dir.exists()); + File subDir = new File("dir4filetest/subdir"); + subDir.mkdir(); + assertTrue(subDir.exists()); + + Support_Exec.execJava(new String[] { + "tests.support.Support_DeleteOnExitTest", + dir.getAbsolutePath(), subDir.getAbsolutePath() }, + new String[] {}, false); + assertFalse(dir.exists()); + assertFalse(subDir.exists()); + } + */ + + /** + * @tests serilization + */ + public void test_objectStreamClass_getFields() throws Exception { + // Regression for HARMONY-2674 + ObjectStreamClass objectStreamClass = ObjectStreamClass + .lookup(File.class); + ObjectStreamField[] objectStreamFields = objectStreamClass.getFields(); + assertEquals(1, objectStreamFields.length); + ObjectStreamField objectStreamField = objectStreamFields[0]; + assertEquals("path", objectStreamField.getName()); + assertEquals(String.class, objectStreamField.getType()); + } + + // Regression test for HARMONY-4493 + public void test_list_withUnicodeFileName() throws Exception { + File rootDir = new File("P"); + if (!rootDir.exists()) { + rootDir.mkdir(); + rootDir.deleteOnExit(); + } + + String dirName = new String("src\u3400"); + File dir = new File(rootDir, dirName); + if (!dir.exists()) { + dir.mkdir(); + dir.deleteOnExit(); + } + boolean exist = false; + String[] fileNames = rootDir.list(); + for (String fileName : fileNames) { + if (dirName.equals(fileName)) { + exist = true; + break; + } + } + assertTrue(exist); + } + /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies self serialization/deserialization.", - method = "!SerializationSelf", - args = {} - ) public void test_serialization_self() throws Exception { File testFile = new File("test.ser"); SerializationTest.verifySelf(testFile); @@ -188,15 +2255,8 @@ public class FileTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void test_serialization_compatibility() throws Exception { File file = new File("FileTest.golden.ser"); SerializationTest.verifyGolden(this, file); } - } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java index 08c8627..642c8dd 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java @@ -1,82 +1,537 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - +import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.util.Arrays; import junit.framework.TestCase; -@TestTargetClass(InputStreamReader.class) + public class InputStreamReaderTest extends TestCase { - - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InputStreamReader", - args = {java.io.InputStream.class, java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getEncoding", - args = {} - ) - }) - public void testGetEncoding_StreamClosed() throws IOException { - InputStreamReader in = null; - byte b[] = new byte[5]; - in = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE"); + + static class LimitedByteArrayInputStream extends ByteArrayInputStream { + + // A ByteArrayInputStream that only returns a single byte per read + byte[] bytes; + + int count; + + public LimitedByteArrayInputStream(int type) { + super(new byte[0]); + switch (type) { + case 0: + bytes = new byte[] { 0x61, 0x72 }; + break; + case 1: + bytes = new byte[] { (byte) 0xff, (byte) 0xfe, 0x61, 0x72 }; + break; + case 2: + bytes = new byte[] { '\u001b', '$', 'B', '6', 'e', 'B', 'h', + '\u001b', '(', 'B' }; + break; + } + count = bytes.length; + } + + @Override + public int available() { + return count; + } + + @Override + public int read() { + if (count == 0) { + return -1; + } + count--; + return bytes[bytes.length - count]; + } + + @Override + public int read(byte[] buffer, int offset, int length) { + if (count == 0) { + return -1; + } + if (length == 0) { + return 0; + } + buffer[offset] = bytes[bytes.length - count]; + count--; + return 1; + } + } + + public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n"; + + private InputStream fis; + + private InputStream in; + + private InputStreamReader is; + + private InputStreamReader reader; + + private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese"; + + /* + * @see TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + + in = new ByteArrayInputStream(source.getBytes("UTF-8")); + reader = new InputStreamReader(in, "UTF-8"); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(bos); + char[] buf = new char[fileString.length()]; + fileString.getChars(0, fileString.length(), buf, 0); + osw.write(buf); + osw.close(); + fis = new ByteArrayInputStream(bos.toByteArray()); + is = new InputStreamReader(fis); + } + + /* + * @see TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + try { + in.close(); + is.close(); + fis.close(); + } catch (IOException e) { + // Ignored + } + + super.tearDown(); + } + + /** + * @tests java.io.InputStreamReader#close() + */ + public void test_close() throws IOException { + is.close(); + try { + is.read(); + fail("Should throw IOException"); + } catch (IOException e) { + // Expected + } + + reader.close(); + try { + reader.ready(); + fail("Should throw IOException"); + } catch (IOException e) { + // Expected + } + + // Should be a no-op + reader.close(); + + // Tests after reader closed + in = new BufferedInputStream( + this + .getClass() + .getClassLoader() + .getResourceAsStream( + "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt")); + reader = new InputStreamReader(in, "utf-8"); in.close(); - String result = in.getEncoding(); - assertNull(result); + try { + int count = reader.read(new char[1]); + fail("count:" + count); + } catch (IOException e) { + // Expected + } + try { + reader.read(); + fail(); + } catch (IOException e) { + // Expected + } + + assertFalse(reader.ready()); + Charset cs = Charset.forName("utf-8"); + assertEquals(cs, Charset.forName(reader.getEncoding())); + } + + /** + * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream) + */ + public void test_ConstructorLjava_io_InputStream() throws IOException { + try { + reader = new InputStreamReader(null); + fail(); + } catch (NullPointerException e) { + // Expected + } + InputStreamReader reader2 = new InputStreamReader(in); + reader2.close(); + } + + /** + * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream, + * java.lang.String) + */ + public void test_ConstructorLjava_io_InputStreamLjava_lang_String() + throws IOException { + is = new InputStreamReader(fis, "8859_1"); + + try { + is = new InputStreamReader(fis, "Bogus"); + fail("Failed to throw Unsupported Encoding exception"); + } catch (UnsupportedEncodingException e) { + // Expected + } + + try { + reader = new InputStreamReader(null, "utf-8"); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + reader = new InputStreamReader(in, (String) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + reader = new InputStreamReader(in, ""); + fail(); + } catch (UnsupportedEncodingException e) { + // Expected + } + try { + reader = new InputStreamReader(in, "badname"); + fail(); + } catch (UnsupportedEncodingException e) { + // Expected + } + InputStreamReader reader2 = new InputStreamReader(in, "utf-8"); + assertEquals(Charset.forName(reader2.getEncoding()), Charset + .forName("utf-8")); + reader2.close(); + reader2 = new InputStreamReader(in, "utf8"); + assertEquals(Charset.forName(reader2.getEncoding()), Charset + .forName("utf-8")); + reader2.close(); } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InputStreamReader", - args = {java.io.InputStream.class, java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getEncoding", - args = {} - ) - }) - public void testGetEncoding_NotHistorical() { - InputStreamReader in = null; - try { - in = new InputStreamReader(System.in, "UTF-16BE"); + /** + * @tests java.io.InputStreamReader(java.io.InputStream, + * java.nio.charset.Charset) + */ + public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_Charset() + throws IOException { + Charset cs = Charset.forName("utf-8"); + try { + reader = new InputStreamReader(null, cs); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + reader = new InputStreamReader(in, (Charset) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + InputStreamReader reader2 = new InputStreamReader(in, cs); + assertEquals(Charset.forName(reader2.getEncoding()), cs); + reader2.close(); + } + + /** + * @tests java.io.InputStreamReader(java.io.InputStream, + * java.nio.charset.CharsetDecoder) + */ + public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_CharsetDecoder() + throws IOException { + CharsetDecoder decoder = Charset.forName("utf-8").newDecoder(); + try { + reader = new InputStreamReader(null, decoder); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + reader = new InputStreamReader(in, (CharsetDecoder) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + InputStreamReader reader2 = new InputStreamReader(in, decoder); + assertEquals(Charset.forName(reader2.getEncoding()), decoder.charset()); + reader2.close(); + } + + /** + * @tests java.io.InputStreamReader#getEncoding() + */ + public void test_getEncoding() throws IOException { + InputStreamReader isr = new InputStreamReader(fis, "8859_1"); + assertEquals("Returned incorrect encoding when setting 8859_1", + "ISO8859_1", isr.getEncoding()); + + isr = new InputStreamReader(fis, "ISO-8859-1"); + assertEquals("Returned incorrect encoding when setting ISO-8859-1", + "ISO8859_1", isr.getEncoding()); + + byte b[] = new byte[5]; + isr = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE"); + isr.close(); + assertNull(isr.getEncoding()); + + try { + isr = new InputStreamReader(System.in, "UTF-16BE"); + } catch (UnsupportedEncodingException e) { + // Ignored + } + assertEquals("UnicodeBigUnmarked", isr.getEncoding()); + } + + /** + * @tests java.io.InputStreamReader#read() + */ + public void test_read() throws IOException { + assertEquals('T', (char) reader.read()); + assertEquals('h', (char) reader.read()); + assertEquals('i', (char) reader.read()); + assertEquals('s', (char) reader.read()); + assertEquals(' ', (char) reader.read()); + reader.read(new char[source.length() - 5], 0, source.length() - 5); + assertEquals(-1, reader.read()); + + int c = is.read(); + assertTrue("returned incorrect char", (char) c == fileString.charAt(0)); + InputStreamReader reader = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0xe8, (byte) 0x9d, + (byte) 0xa5 }), "UTF8"); + assertTrue("wrong double byte char", reader.read() == '\u8765'); + + // Regression for HARMONY-166 + InputStream in; + + in = new LimitedByteArrayInputStream(0); + reader = new InputStreamReader(in, "UTF-16BE"); + assertEquals("Incorrect byte UTF-16BE", '\u6172', reader.read()); + + in = new LimitedByteArrayInputStream(0); + reader = new InputStreamReader(in, "UTF-16LE"); + assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read()); + + in = new LimitedByteArrayInputStream(1); + reader = new InputStreamReader(in, "UTF-16"); + assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read()); + + /* + * Temporarily commented out due to lack of ISO2022 support in ICU4J 3.8 + * in = new LimitedByteArrayInputStream(2); reader = new + * InputStreamReader(in, "ISO2022JP"); assertEquals("Incorrect byte + * ISO2022JP 1", '\u4e5d', reader.read()); assertEquals("Incorrect byte + * ISO2022JP 2", '\u7b2c', reader.read()); + */ + } + + /* + * Class under test for int read() Regression for Harmony-411 + */ + public void test_read_1() throws IOException { + // if the decoder is constructed by InputStreamReader itself, the + // decoder's default error action is REPLACE + InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream( + new byte[] { -32, -96 }), "UTF-8"); + assertEquals("read() return incorrect value", 65533, isr.read()); + + InputStreamReader isr2 = new InputStreamReader( + new ByteArrayInputStream(new byte[] { -32, -96 }), Charset + .forName("UTF-8")); + assertEquals("read() return incorrect value", 65533, isr2.read()); + + // if the decoder is passed in, keep its status intact + CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); + decoder.onMalformedInput(CodingErrorAction.REPORT); + InputStreamReader isr3 = new InputStreamReader( + new ByteArrayInputStream(new byte[] { -32, -96 }), decoder); + try { + isr3.read(); + fail("Should throw MalformedInputException"); + } catch (MalformedInputException e) { + // expected + } + + CharsetDecoder decoder2 = Charset.forName("UTF-8").newDecoder(); + decoder2.onMalformedInput(CodingErrorAction.IGNORE); + InputStreamReader isr4 = new InputStreamReader( + new ByteArrayInputStream(new byte[] { -32, -96 }), decoder2); + assertEquals("read() return incorrect value", -1, isr4.read()); + + CharsetDecoder decoder3 = Charset.forName("UTF-8").newDecoder(); + decoder3.onMalformedInput(CodingErrorAction.REPLACE); + InputStreamReader isr5 = new InputStreamReader( + new ByteArrayInputStream(new byte[] { -32, -96 }), decoder3); + assertEquals("read() return incorrect value", 65533, isr5.read()); + } + + public void test_read_specialCharset() throws IOException { + reader.close(); + in = this.getClass().getClassLoader().getResourceAsStream( + "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt"); + reader = new InputStreamReader(in, "utf-8"); + int c; + StringBuffer sb = new StringBuffer(); + while ((c = reader.read()) != -1) { + sb.append((char) c); + } + // delete BOM + assertEquals(source, sb.deleteCharAt(0).toString()); + + sb.setLength(0); + reader.close(); + in = this.getClass().getClassLoader().getResourceAsStream( + "org/apache/harmony/luni/tests/java/io/testfile.txt"); + try { + reader = new InputStreamReader(in, "gb18030"); } catch (UnsupportedEncodingException e) { - // ok + System.out + .println("GB18030 is not supported, abort test InputStreamReaderTest.testSpecialCharsetReading()."); + } + while ((c = reader.read()) != -1) { + sb.append((char) c); + } + assertEquals(source, sb.toString()); + } + + /** + * @tests java.io.InputStreamReader#read(char[], int, int) + */ + public void test_read$CII() throws IOException { + char[] rbuf = new char[100]; + char[] sbuf = new char[100]; + fileString.getChars(0, 100, sbuf, 0); + is.read(rbuf, 0, 100); + for (int i = 0; i < rbuf.length; i++) { + assertTrue("returned incorrect chars", rbuf[i] == sbuf[i]); + } + + // Test successive reads + byte[] data = new byte[8192 * 2]; + Arrays.fill(data, (byte) 116); // 116 = ISO-8859-1 value for 't' + ByteArrayInputStream bis = new ByteArrayInputStream(data); + InputStreamReader isr = new InputStreamReader(bis, "ISO-8859-1"); + + // One less than the InputStreamReader.BUFFER_SIZE + char[] buf = new char[8191]; + int bytesRead = isr.read(buf, 0, buf.length); + assertFalse(-1 == bytesRead); + bytesRead = isr.read(buf, 0, buf.length); + assertFalse(-1 == bytesRead); + + bis = new ByteArrayInputStream(source.getBytes("UTF-8")); + isr = new InputStreamReader(in, "UTF-8"); + char[] chars = new char[source.length()]; + assertEquals(source.length() - 3, isr.read(chars, 0, chars.length - 3)); + assertEquals(3, isr.read(chars, 0, 10)); + } + + /* + * Class under test for int read(char[], int, int) + */ + public void test_read$CII_1() throws IOException { + try { + // Throws IndexOutOfBoundsException before NullPointerException + reader.read(null, -1, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + // Throws NullPointerException before IndexOutOfBoundsException + reader.read(null, 0, -1); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected } - String result = in.getEncoding(); - assertEquals("UnicodeBigUnmarked", result); + try { + reader.read(null, 0, 1); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + reader.read(new char[3], -1, 1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + reader.read(new char[3], 0, -1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + reader.read(new char[3], 1, 3); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + assertEquals(0, reader.read(new char[3], 3, 0)); + char[] chars = new char[source.length()]; + assertEquals(0, reader.read(chars, 0, 0)); + assertEquals(0, chars[0]); + assertEquals(3, reader.read(chars, 0, 3)); + assertEquals(5, reader.read(chars, 3, 5)); + assertEquals(source.length() - 8, reader.read(chars, 8, + chars.length - 8)); + assertTrue(Arrays.equals(chars, source.toCharArray())); + assertEquals(-1, reader.read(chars, 0, chars.length)); + assertTrue(Arrays.equals(chars, source.toCharArray())); } + /** + * @tests java.io.InputStreamReader#ready() + */ + public void test_ready() throws IOException { + assertTrue("Ready test failed", is.ready()); + is.read(); + assertTrue("More chars, but not ready", is.ready()); + + assertTrue(reader.ready()); + reader.read(new char[source.length()]); + assertFalse(reader.ready()); + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java index 5710dd3..f2eea47 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java @@ -1,309 +1,1179 @@ /* - * 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 - * + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; +import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.Externalizable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.InvalidClassException; +import java.io.InvalidObjectException; +import java.io.NotActiveException; +import java.io.ObjectInput; import java.io.ObjectInputStream; +import java.io.ObjectInputValidation; +import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; -import java.io.ObjectStreamException; -import java.io.OptionalDataException; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; import java.io.Serializable; +import java.io.SerializablePermission; import java.io.StreamCorruptedException; -import java.util.ArrayList; +import java.lang.reflect.Proxy; +import java.security.Permission; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Vector; import junit.framework.TestCase; import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -import tests.support.Support_ASimpleInputStream; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - -@TestTargetClass(ObjectInputStream.class) -public class ObjectInputStreamTest extends TestCase { +@SuppressWarnings("serial") +public class ObjectInputStreamTest extends TestCase implements + Serializable { ObjectInputStream ois; ObjectOutputStream oos; ByteArrayOutputStream bao; - - private final String testString = "Lorem ipsum..."; - protected void setUp() throws Exception { - super.setUp(); - oos = new ObjectOutputStream(bao = new ByteArrayOutputStream()); + public class SerializableTestHelper implements Serializable { + + public String aField1; + + public String aField2; + + SerializableTestHelper() { + aField1 = null; + aField2 = null; + } + + SerializableTestHelper(String s, String t) { + aField1 = s; + aField2 = t; + } + + private void readObject(ObjectInputStream ois) throws Exception { + // note aField2 is not read + ObjectInputStream.GetField fields = ois.readFields(); + aField1 = (String) fields.get("aField1", "Zap"); + } + + private void writeObject(ObjectOutputStream oos) throws IOException { + // note aField2 is not written + ObjectOutputStream.PutField fields = oos.putFields(); + fields.put("aField1", aField1); + oos.writeFields(); + } + + public String getText1() { + return aField1; + } + + public void setText1(String s) { + aField1 = s; + } + + public String getText2() { + return aField2; + } + + public void setText2(String s) { + aField2 = s; + } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks ObjectStreamException and OptionalDataException.", - method = "readUnshared", - args = {} - ) - public void test_readUnshared_1() throws IOException, ClassNotFoundException { - oos.writeObject(testString); - oos.writeObject(testString); - oos.writeInt(42); - oos.close(); + public static class A1 implements Serializable { + + private static final long serialVersionUID = 5942584913446079661L; + + B1 b1 = new B1(); + B1 b2 = b1; + + Vector v = new Vector(); + } + + public static class B1 implements Serializable { + + int i = 5; + + Hashtable h = new Hashtable(); + } + + /** + * @tests java.io.ObjectInputStream#readObject() + */ + public void test_readObjectMissingClasses() throws Exception { + SerializationTest.verifySelf(new A1(), new SerializableAssert() { + public void assertDeserialized(Serializable initial, + Serializable deserialized) { + assertEquals(5, ((A1) deserialized).b1.i); + } + }); + } + + /** + * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream) + */ + public void test_ConstructorLjava_io_InputStream() throws IOException { + oos.writeDouble(Double.MAX_VALUE); + oos.close(); ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.close(); + oos.close(); + try { - ois.readUnshared(); - ois.readObject(); - fail("Test 1: ObjectStreamException expected."); - } catch (ObjectStreamException e) { - // Expected. + ois = new ObjectInputStream(new ByteArrayInputStream(new byte[90])); + fail("StreamCorruptedException expected"); + } catch (StreamCorruptedException e) { + // Expected } - + } + + /** + * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream) + */ + public void test_ConstructorLjava_io_InputStream_subtest0() throws IOException { + SecurityManager sm = System.getSecurityManager(); + System.setSecurityManager(new SecurityManager() { + Permission golden = new SerializablePermission("enableSubclassImplementation"); + + @Override + public void checkPermission(Permission p) { + if (golden.equals(p)) { + throw new SecurityException(); + } + } + }); + try { - ois.readUnshared(); - fail("Test 2: OptionalDataException expected."); - } catch (OptionalDataException e) { - // Expected. + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream obout = new ObjectOutputStream(out); + obout.write(0); + obout.close(); + + InputStream in = new ByteArrayInputStream(out.toByteArray()); + + // should not cause SecurityException + new ObjectInputStream(in); + in.reset(); + + // should not cause SecurityException + new ObjectInputStream(in) {}; + in.reset(); + + try { + new ObjectInputStream(in) { + @Override + public Object readUnshared() throws IOException, ClassNotFoundException { + return null; + } + }; + fail("should throw SecurityException 1"); + } catch (SecurityException e) { + // Expected + } + + in.reset(); + try { + new ObjectInputStream(in) { + @Override + public GetField readFields() throws IOException, + ClassNotFoundException, NotActiveException { + return null; + } + }; + fail("should throw SecurityException 2"); + } catch (SecurityException e) { + // Expected + } + } finally { + System.setSecurityManager(sm); + } + } + + /** + * @tests {@link java.io.ObjectInputStream#resolveProxyClass(String[])} + */ + public void test_resolveProxyClass() throws IOException, + ClassNotFoundException { + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + MockObjectInputStream mockIn = new MockObjectInputStream( + new ByteArrayInputStream(bao.toByteArray())); + Class[] clazzs = { java.io.ObjectInputStream.class, + java.io.Reader.class }; + for (int i = 0; i < clazzs.length; i++) { + Class clazz = clazzs[i]; + Class[] interfaceNames = clazz.getInterfaces(); + String[] interfaces = new String[interfaceNames.length]; + int index = 0; + for (Class c : interfaceNames) { + interfaces[index] = c.getName(); + index++; + } + Class<?> s = mockIn.resolveProxyClass(interfaces); + + if (Proxy.isProxyClass(s)) { + Class[] implementedInterfaces = s.getInterfaces(); + for (index = 0; index < implementedInterfaces.length; index++) { + assertEquals(interfaceNames[index], + implementedInterfaces[index]); + } + } else { + fail("Should return a proxy class that implements the interfaces named in a proxy class descriptor"); + } } + mockIn.close(); + } + + class MockObjectInputStream extends ObjectInputStream { + + public MockObjectInputStream(InputStream input) + throws StreamCorruptedException, IOException { + super(input); + } + + @Override + public Class<?> resolveProxyClass(String[] interfaceNames) throws IOException, ClassNotFoundException { + return super.resolveProxyClass(interfaceNames); + } + + } + + /** + * @tests java.io.ObjectInputStream#available() + */ + public void test_available() throws IOException { + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect bytes", 10, ois.available()); ois.close(); - } + } + + /** + * @tests java.io.ObjectInputStream#close() + */ + public void test_close() throws IOException { + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.close(); + } /** - * @tests java.io.ObjectInputStream#readUnshared() + * @tests java.io.ObjectInputStream#defaultReadObject() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks StreamCorruptedException.", - method = "readUnshared", - args = {} - ) - public void test_readUnshared_2() throws IOException, ClassNotFoundException { + public void test_defaultReadObject() throws Exception { + // SM. This method may as well be private, as if called directly it + // throws an exception. + String s = "HelloWorld"; + oos.writeObject(s); oos.close(); - bao.write(testString.getBytes()); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); try { - ois.readUnshared(); - fail("Test 1: StreamCorruptedException expected."); - } catch (StreamCorruptedException e) { - // Expected. + ois.defaultReadObject(); + fail("NotActiveException expected"); + } catch (NotActiveException e) { + // Desired behavior + } finally { + ois.close(); } + } + + /** + * @tests java.io.ObjectInputStream#read() + */ + public void test_read() throws IOException { + oos.write('T'); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect byte value", 'T', ois.read()); ois.close(); } /** - * @tests java.io.ObjectInputStream#readUnshared() + * @tests java.io.ObjectInputStream#read(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks IOException.", - method = "readUnshared", - args = {} - ) - public void test_readUnshared_3() throws IOException, ClassNotFoundException { - bao.write(testString.getBytes()); + public void test_read$BII() throws IOException { + byte[] buf = new byte[10]; + oos.writeBytes("HelloWorld"); oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.read(buf, 0, 10); + ois.close(); + assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, + 10, "UTF-8")); + } - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.readUnshared(); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; + /** + * @tests java.io.ObjectInputStream#readBoolean() + */ + public void test_readBoolean() throws IOException { + oos.writeBoolean(true); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect boolean value", ois.readBoolean()); ois.close(); } /** - * Micro-scenario of de/serialization of an object with non-serializable superclass. - * The super-constructor only should be invoked on the deserialized instance. + * @tests java.io.ObjectInputStream#readByte() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "readObject", - args = {} - ) - public void test_readObject_Hierarchy() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(new B()); - oos.close(); - - ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); - B b = (B) ois.readObject(); + public void test_readByte() throws IOException { + oos.writeByte(127); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect byte value", 127, ois.readByte()); ois.close(); - - assertTrue("should construct super", A.list.contains(b)); - assertFalse("should not construct self", B.list.contains(b)); - assertEquals("super field A.s", A.DEFAULT, ((A)b).s); - assertNull("transient field B.s", b.s); } - + /** - * @tests {@link java.io.ObjectInputStream#readNewLongString()} + * @tests java.io.ObjectInputStream#readChar() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization.", - method = "!SerializationSelf", - args = {} - ) - public void test_readNewLongString() throws Exception { - LongString longString = new LongString(); - SerializationTest.verifySelf(longString); + public void test_readChar() throws IOException { + oos.writeChar('T'); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect char value", 'T', ois.readChar()); + ois.close(); } - - private static class LongString implements Serializable{ - private static final long serialVersionUID = 1L; - String lString; - - public LongString() { - StringBuilder builder = new StringBuilder(); - // construct a string whose length > 64K - for (int i = 0; i < 65636; i++) { - builder.append('1'); + + /** + * @tests java.io.ObjectInputStream#readDouble() + */ + public void test_readDouble() throws IOException { + oos.writeDouble(Double.MAX_VALUE); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect double value", + ois.readDouble() == Double.MAX_VALUE); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readFields() + */ + public void test_readFields() throws Exception { + + SerializableTestHelper sth; + + /* + * "SerializableTestHelper" is an object created for these tests with + * two fields (Strings) and simple implementations of readObject and + * writeObject which simply read and write the first field but not the + * second + */ + + oos.writeObject(new SerializableTestHelper("Gabba", "Jabba")); + oos.flush(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + sth = (SerializableTestHelper) (ois.readObject()); + assertEquals("readFields / writeFields failed--first field not set", + "Gabba", sth.getText1()); + assertNull( + "readFields / writeFields failed--second field should not have been set", + sth.getText2()); + } + + /** + * @tests java.io.ObjectInputStream#readFloat() + */ + public void test_readFloat() throws IOException { + oos.writeFloat(Float.MAX_VALUE); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect float value", + ois.readFloat() == Float.MAX_VALUE); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readFully(byte[]) + */ + public void test_readFully$B() throws IOException { + byte[] buf = new byte[10]; + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.readFully(buf); + ois.close(); + assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, + 10, "UTF-8")); + } + + /** + * @tests java.io.ObjectInputStream#readFully(byte[], int, int) + */ + public void test_readFully$BII() throws IOException { + byte[] buf = new byte[10]; + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.readFully(buf, 0, 10); + ois.close(); + assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, + 10, "UTF-8")); + } + + /** + * @tests java.io.ObjectInputStream#readInt() + */ + public void test_readInt() throws IOException { + oos.writeInt(Integer.MAX_VALUE); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect int value", + ois.readInt() == Integer.MAX_VALUE); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readLine() + */ + @SuppressWarnings("deprecation") + public void test_readLine() throws IOException { + oos.writeBytes("HelloWorld\nSecondLine"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.readLine(); + assertEquals("Read incorrect string value", "SecondLine", ois + .readLine()); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readLong() + */ + public void test_readLong() throws IOException { + oos.writeLong(Long.MAX_VALUE); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect long value", + ois.readLong() == Long.MAX_VALUE); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readObject() + */ + public void test_readObject() throws Exception { + String s = "HelloWorld"; + oos.writeObject(s); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect Object value", s, ois.readObject()); + ois.close(); + + // Regression for HARMONY-91 + // dynamically create serialization byte array for the next hierarchy: + // - class A implements Serializable + // - class C extends A + + byte[] cName = C.class.getName().getBytes("UTF-8"); + byte[] aName = A.class.getName().getBytes("UTF-8"); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + byte[] begStream = new byte[] { (byte) 0xac, (byte) 0xed, // STREAM_MAGIC + (byte) 0x00, (byte) 0x05, // STREAM_VERSION + (byte) 0x73, // TC_OBJECT + (byte) 0x72, // TC_CLASSDESC + (byte) 0x00, // only first byte for C class name length + }; + + out.write(begStream, 0, begStream.length); + out.write(cName.length); // second byte for C class name length + out.write(cName, 0, cName.length); // C class name + + byte[] midStream = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x21, // serialVersionUID = 33L + (byte) 0x02, // flags + (byte) 0x00, (byte) 0x00, // fields : none + (byte) 0x78, // TC_ENDBLOCKDATA + (byte) 0x72, // Super class for C: TC_CLASSDESC for A class + (byte) 0x00, // only first byte for A class name length + }; + + out.write(midStream, 0, midStream.length); + out.write(aName.length); // second byte for A class name length + out.write(aName, 0, aName.length); // A class name + + byte[] endStream = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x0b, // serialVersionUID = 11L + (byte) 0x02, // flags + (byte) 0x00, (byte) 0x01, // fields + + (byte) 0x4c, // field description: type L (object) + (byte) 0x00, (byte) 0x04, // length + // field = 'name' + (byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65, + + (byte) 0x74, // className1: TC_STRING + (byte) 0x00, (byte) 0x12, // length + // + (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, + (byte) 0x61, (byte) 0x2f, (byte) 0x6c, (byte) 0x61, + (byte) 0x6e, (byte) 0x67, (byte) 0x2f, (byte) 0x53, + (byte) 0x74, (byte) 0x72, (byte) 0x69, (byte) 0x6e, + (byte) 0x67, (byte) 0x3b, + + (byte) 0x78, // TC_ENDBLOCKDATA + (byte) 0x70, // NULL super class for A class + + // classdata + (byte) 0x74, // TC_STRING + (byte) 0x00, (byte) 0x04, // length + (byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65, // value + }; + + out.write(endStream, 0, endStream.length); + out.flush(); + + // read created serial. form + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( + out.toByteArray())); + Object o = ois.readObject(); + assertEquals(C.class, o.getClass()); + + // Regression for HARMONY-846 + assertNull(new ObjectInputStream() {}.readObject()); + } + + /** + * @tests java.io.ObjectInputStream#readObjectOverride() + */ + public void test_readObjectOverride() throws Exception { + // Regression for HARMONY-846 + assertNull(new ObjectInputStream() { + + @Override + public Object readObjectOverride() throws IOException, + ClassNotFoundException { + return super.readObjectOverride(); } - lString = builder.toString(); + + }.readObjectOverride()); + } + + public static class A implements Serializable { + + private static final long serialVersionUID = 11L; + + public String name = "name"; + } + + public static class B extends A {} + + public static class C extends B { + + private static final long serialVersionUID = 33L; + } + + /** + * @tests java.io.ObjectInputStream#readObject() + */ + public void test_readObjectCorrupt() throws IOException, ClassNotFoundException { + byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00, + 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 }; + ByteArrayInputStream bin = new ByteArrayInputStream(bytes); + try { + ObjectInputStream in = new ObjectInputStream(bin); + in.readObject(); + fail("Unexpected read of corrupted stream"); + } catch (StreamCorruptedException e) { + // Expected } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (o instanceof LongString) { - LongString l = (LongString) o; - return l.lString.equals(l.lString); - } - return true; + } + + /** + * @tests java.io.ObjectInputStream#readShort() + */ + public void test_readShort() throws IOException { + oos.writeShort(Short.MAX_VALUE); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertTrue("Read incorrect short value", + ois.readShort() == Short.MAX_VALUE); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readUnsignedByte() + */ + public void test_readUnsignedByte() throws IOException { + oos.writeByte(-1); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect unsignedByte value", 255, ois + .readUnsignedByte()); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readUnsignedShort() + */ + public void test_readUnsignedShort() throws IOException { + oos.writeShort(-1); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect unsignedShort value", 65535, ois + .readUnsignedShort()); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#readUTF() + */ + public void test_readUTF() throws IOException { + oos.writeUTF("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Read incorrect utf value", "HelloWorld", ois.readUTF()); + ois.close(); + } + + /** + * @tests java.io.ObjectInputStream#skipBytes(int) + */ + public void test_skipBytesI() throws IOException { + byte[] buf = new byte[10]; + oos.writeBytes("HelloWorld"); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.skipBytes(5); + ois.read(buf, 0, 5); + ois.close(); + assertEquals("Skipped incorrect bytes", "World", new String(buf, 0, 5, "UTF-8")); + + // Regression for HARMONY-844 + try { + new ObjectInputStream() {}.skipBytes(0); + fail("NullPointerException expected"); + } catch (NullPointerException e) {} + } + + // Regression Test for JIRA 2192 + public void test_readObject_withPrimitiveClass() throws Exception { + File file = new File("test.ser"); + file.deleteOnExit(); + Test test = new Test(); + ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( + file)); + out.writeObject(test); + out.close(); + + ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); + Test another = (Test) in.readObject(); + in.close(); + assertEquals(test, another); + } + + //Regression Test for JIRA-2249 + public static class ObjectOutputStreamWithWriteDesc extends + ObjectOutputStream { + public ObjectOutputStreamWithWriteDesc(OutputStream os) + throws IOException { + super(os); } - + @Override - public int hashCode() { - return lString.hashCode(); + public void writeClassDescriptor(ObjectStreamClass desc) + throws IOException { } } - static class A { - static final ArrayList<A> list = new ArrayList<A>(); - String s; - public static final String DEFAULT = "aaa"; - public A() { - s = DEFAULT; - list.add(this); - } - } + public static class ObjectIutputStreamWithReadDesc extends + ObjectInputStream { + private Class returnClass; - static class B extends A implements Serializable { - private static final long serialVersionUID = 1L; - static final ArrayList<A> list = new ArrayList<A>(); - transient String s; - public B() { - s = "bbb"; - list.add(this); + public ObjectIutputStreamWithReadDesc(InputStream is, Class returnClass) + throws IOException { + super(is); + this.returnClass = returnClass; } - } - - class OIS extends ObjectInputStream { - - OIS () throws IOException { - super(); - } - - void test() throws ClassNotFoundException,IOException { - readClassDescriptor(); - } - - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "readClassDescriptor", - args = {} - ) - public void test_readClassDescriptor() throws ClassNotFoundException, IOException { - try { - new OIS().test(); - fail("Test 1: NullPointerException expected."); - } catch (NullPointerException e) { - // Expected. + + @Override + public ObjectStreamClass readClassDescriptor() throws IOException, + ClassNotFoundException { + return ObjectStreamClass.lookup(returnClass); + } } - static class TestObjectInputStream extends ObjectInputStream { - public TestObjectInputStream(InputStream in) throws IOException { + static class TestClassForSerialization implements Serializable { + private static final long serialVersionUID = 1L; + } + + public void test_ClassDescriptor() throws IOException, + ClassNotFoundException { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc( + baos); + oos.writeObject(String.class); + oos.close(); + Class cls = TestClassForSerialization.class; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectIutputStreamWithReadDesc ois = new ObjectIutputStreamWithReadDesc( + bais, cls); + Object obj = ois.readObject(); + ois.close(); + assertEquals(cls, obj); + } + + // Regression Test for JIRA-2340 + public static class ObjectOutputStreamWithWriteDesc1 extends + ObjectOutputStream { + public ObjectOutputStreamWithWriteDesc1(OutputStream os) + throws IOException { + super(os); + } + + @Override + public void writeClassDescriptor(ObjectStreamClass desc) + throws IOException { + super.writeClassDescriptor(desc); + } + } + + public static class ObjectIutputStreamWithReadDesc1 extends + ObjectInputStream { + + public ObjectIutputStreamWithReadDesc1(InputStream is) + throws IOException { + super(is); + } + + @Override + public ObjectStreamClass readClassDescriptor() throws IOException, + ClassNotFoundException { + return super.readClassDescriptor(); + } + } + + // Regression test for Harmony-1921 + public static class ObjectInputStreamWithResolve extends ObjectInputStream { + public ObjectInputStreamWithResolve(InputStream in) throws IOException { super(in); } - protected Class<?> resolveClass(ObjectStreamClass desc) + @Override + @SuppressWarnings("unchecked") + protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { - if (desc.getName().endsWith("ObjectInputStreamTest$TestClass1")) { - return TestClass2.class; + if (desc.getName().equals( + "org.apache.harmony.luni.tests.pkg1.TestClass")) { + return org.apache.harmony.luni.tests.pkg2.TestClass.class; } return super.resolveClass(desc); } } - static class TestClass1 implements Serializable { - private static final long serialVersionUID = 11111L; - int i = 0; + public void test_resolveClass() throws Exception { + org.apache.harmony.luni.tests.pkg1.TestClass to1 = new org.apache.harmony.luni.tests.pkg1.TestClass(); + to1.i = 555; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(to1); + oos.flush(); + byte[] bytes = baos.toByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStreamWithResolve(bais); + org.apache.harmony.luni.tests.pkg2.TestClass to2 = (org.apache.harmony.luni.tests.pkg2.TestClass) ois + .readObject(); + + if (to2.i != to1.i) { + fail("Wrong object read. Expected val: " + to1.i + ", got: " + + to2.i); + } } - static class TestClass2 implements Serializable { - private static final long serialVersionUID = 11111L; - int i = 0; + static class ObjectInputStreamWithResolveObject extends ObjectInputStream { + + public static Integer intObj = Integer.valueOf(1000); + + public ObjectInputStreamWithResolveObject(InputStream in) throws IOException { + super(in); + enableResolveObject(true); + } + + @Override + protected Object resolveObject(Object obj) throws IOException { + if(obj instanceof Integer){ + obj = intObj; + } + return super.resolveObject(obj); + } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks InvalidClassException.", - method = "resolveClass", - args = {java.io.ObjectStreamClass.class} - ) - public void test_resolveClass_invalidClassName() - throws Exception { - // Regression test for HARMONY-1920 - TestClass1 to1 = new TestClass1(); + + /** + * @tests java.io.ObjectInputStream#resolveObject(Object) + */ + public void test_resolveObjectLjava_lang_Object() throws Exception { + // Write an Integer object into memory + Integer original = new Integer(10); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); - ByteArrayInputStream bais; - ObjectInputStream ois; - - to1.i = 555; - oos.writeObject(to1); + oos.writeObject(original); oos.flush(); + oos.close(); + + // Read the object from memory byte[] bytes = baos.toByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectInputStreamWithResolveObject ois = + new ObjectInputStreamWithResolveObject(bais); + Integer actual = (Integer) ois.readObject(); + ois.close(); + + // object should be resolved from 10 to 1000 + assertEquals(ObjectInputStreamWithResolveObject.intObj, actual); + } + + public void test_readClassDescriptor() throws IOException, + ClassNotFoundException { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1( + baos); + ObjectStreamClass desc = ObjectStreamClass + .lookup(TestClassForSerialization.class); + oos.writeClassDescriptor(desc); + oos.close(); + + byte[] bytes = baos.toByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectIutputStreamWithReadDesc1 ois = new ObjectIutputStreamWithReadDesc1( + bais); + Object obj = ois.readClassDescriptor(); + ois.close(); + assertEquals(desc.getClass(), obj.getClass()); + + //eof bais = new ByteArrayInputStream(bytes); - ois = new TestObjectInputStream(bais); + ExceptionalBufferedInputStream bis = new ExceptionalBufferedInputStream( + bais); + ois = new ObjectIutputStreamWithReadDesc1(bis); + + bis.setEOF(true); try { - ois.readObject(); - fail("Test 1: InvalidClassException expected."); - } catch (InvalidClassException ice) { - // Expected. + obj = ois.readClassDescriptor(); + } catch (IOException e) { + //e.printStackTrace(); + } finally { + ois.close(); + } + + //throw exception + bais = new ByteArrayInputStream(bytes); + bis = new ExceptionalBufferedInputStream(bais); + ois = new ObjectIutputStreamWithReadDesc1(bis); + + bis.setException(new IOException()); + + try { + obj = ois.readClassDescriptor(); + } catch (IOException e) { + //e.printStackTrace(); + } finally { + ois.close(); + } + + //corrupt + bais = new ByteArrayInputStream(bytes); + bis = new ExceptionalBufferedInputStream(bais); + ois = new ObjectIutputStreamWithReadDesc1(bis); + + bis.setCorrupt(true); + + try { + obj = ois.readClassDescriptor(); + } catch (IOException e) { + //e.printStackTrace(); + } finally { + ois.close(); + } + } + + static class ExceptionalBufferedInputStream extends BufferedInputStream { + private boolean eof = false; + private IOException exception = null; + private boolean corrupt = false; + + public ExceptionalBufferedInputStream(InputStream in) { + super(in); + } + + @Override + public int read() throws IOException { + if (exception != null) { + throw exception; + } + + if (eof) { + return -1; + } + + if (corrupt) { + return 0; + } + return super.read(); + } + + public void setEOF(boolean eof) { + this.eof = eof; + } + + public void setException(IOException exception) { + this.exception = exception; + } + + public void setCorrupt(boolean corrupt) { + this.corrupt = corrupt; + } + } + + public static class ObjectIutputStreamWithReadDesc2 extends + ObjectInputStream { + private Class returnClass; + + public ObjectIutputStreamWithReadDesc2(InputStream is, Class returnClass) + throws IOException { + super(is); + this.returnClass = returnClass; + } + + @Override + public ObjectStreamClass readClassDescriptor() throws IOException, + ClassNotFoundException { + ObjectStreamClass osc = super.readClassDescriptor(); + + if (osc.getName().equals(returnClass.getName())) { + return ObjectStreamClass.lookup(returnClass); + } + return osc; } } + + /* + * Testing classDescriptor replacement with the value generated by + * ObjectStreamClass.lookup() method. + * Regression test for HARMONY-4638 + */ + public void test_readClassDescriptor_1() throws IOException, ClassNotFoundException { + A a = new A(); + a.name = "It's a test"; + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pin = new PipedInputStream(pout); + ObjectOutputStream out = new ObjectOutputStream(pout); + ObjectInputStream in = new ObjectIutputStreamWithReadDesc2(pin, A.class); + + // test single object + out.writeObject(a); + A a1 = (A) in.readObject(); + assertEquals("Single case: incorrectly read the field of A", a.name, a1.name); + + // test cyclic reference + HashMap m = new HashMap(); + a = new A(); + a.name = "It's a test 0"; + a1 = new A(); + a1.name = "It's a test 1"; + m.put("0", a); + m.put("1", a1); + out.writeObject(m); + HashMap m1 = (HashMap) in.readObject(); + assertEquals("Incorrectly read the field of A", a.name, ((A) m1.get("0")).name); + assertEquals("Incorrectly read the field of A1", a1.name, ((A) m1.get("1")).name); + } + + public void test_registerValidation() throws Exception { + // Regression Test for Harmony-2402 + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + new ObjectOutputStream(baos); + ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream(baos.toByteArray())); + + try { + ois.registerValidation(null, 256); + fail("NotActiveException should be thrown"); + } catch (NotActiveException nae) { + // expected + } + + // Regression Test for Harmony-3916 + baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(new RegisterValidationClass()); + oos.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream fis = new ObjectInputStream(bais); + // should not throw NotActiveException + fis.readObject(); + } + + private static class RegisterValidationClass implements Serializable { + @SuppressWarnings("unused") + private A a = new A(); + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + stream.registerValidation(new MockObjectInputValidation(), 0); + } + } + + private static class MockObjectInputValidation implements ObjectInputValidation { + public void validateObject() throws InvalidObjectException { + + } + } + + //Regression Test for HARMONY-3726 + public void test_readObject_array() throws Exception { + + final String resourcePrefix = ObjectInputStreamTest.class.getPackage().getName().replace('.', '/'); + +// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_strings.ser")); +// TestArray ta = new TestArray(new String[] { "AAA", "BBB" }); +// oos.writeObject(ta); +// oos.close(); +// oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_integers.ser")); +// ta = new TestArray(new Integer[] { 10, 20 }); +// oos.writeObject(ta); +// oos.close(); + + ObjectInputStream oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream( + "serialization/" + resourcePrefix + "/test_array_strings.ser")); + TestArray testArray = (TestArray) oin.readObject(); + String[] strings = new String[] { "AAA", "BBB" }; + assertTrue(java.util.Arrays.equals(strings, testArray.array)); + + oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream( + "serialization/" + resourcePrefix + "/test_array_integers.ser")); + testArray = (TestArray) oin.readObject(); + Integer[] integers = new Integer[] { 10, 20 }; + assertTrue(java.util.Arrays.equals(integers, testArray.array)); + } + + public static class TestExtObject implements Externalizable { + public void writeExternal(ObjectOutput out) throws IOException { + out.writeInt(10); + } + + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + in.readInt(); + } + } + + static class TestObjectOutputStream extends ObjectOutputStream { + private ObjectStreamClass[] objs; + private int pos = 0; + + public TestObjectOutputStream(OutputStream out, ObjectStreamClass[] objs) throws IOException { + super(out); + this.objs = objs; + } + + @Override + protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException { + objs[pos++] = osc; } + } + + static class TestObjectInputStream extends ObjectInputStream { + private ObjectStreamClass[] objs; + private int pos = 0; + + public TestObjectInputStream(InputStream in, ObjectStreamClass[] objs) throws IOException { + super(in); + this.objs = objs; + } + + @Override + protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { + return objs[pos++]; + } + } + + // Regression test for HARMONY-4996 + public void test_readObject_replacedClassDescriptor() throws Exception { + ObjectStreamClass[] objs = new ObjectStreamClass[1000]; + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pin = new PipedInputStream(pout); + ObjectOutputStream oout = new TestObjectOutputStream(pout, objs); + oout.writeObject(new TestExtObject()); + oout.writeObject("test"); + oout.close(); + ObjectInputStream oin = new TestObjectInputStream(pin, objs); + oin.readObject(); + oin.readObject(); + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + oos = new ObjectOutputStream(bao = new ByteArrayOutputStream()); + } +} + +class TestArray implements Serializable +{ + private static final long serialVersionUID = 1L; + + public Object[] array; + + public TestArray(Object[] array) { + this.array = array; + } + } +class Test implements Serializable { + private static final long serialVersionUID = 1L; + + Class classes[] = new Class[] { byte.class, short.class, int.class, + long.class, boolean.class, char.class, float.class, double.class }; + @Override + public boolean equals(Object o) { + if (!(o instanceof Test)) { + return false; + } + return Arrays.equals(classes, ((Test) o).classes); + } +} diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java index f13c537..b86e9f6 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java @@ -19,25 +19,27 @@ package org.apache.harmony.luni.tests.java.io; import java.io.ObjectStreamConstants; import junit.framework.TestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -@TestTargetClass(ObjectStreamConstants.class) public class ObjectStreamConstantsTest extends TestCase { /** * @tests java.io.ObjectStreamConstants#TC_ENUM */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Constant test, still many constants not tested", - method = "!Constants", - args = {} - ) - public void test_Constants() { + public void test_TC_ENUM() { assertEquals(126, ObjectStreamConstants.TC_ENUM); + } + + /** + * @tests java.io.ObjectStreamConstants#SC_ENUM + */ + public void test_SC_ENUM() { assertEquals(16, ObjectStreamConstants.SC_ENUM); + } + + /** + * @tests java.io.ObjectStreamConstants#TC_MAX + */ + public void test_TC_MAX() { assertEquals(126, ObjectStreamConstants.TC_MAX); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java index 732ee50..837b443 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java @@ -1,81 +1,703 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; +import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; import junit.framework.TestCase; -@TestTargetClass(OutputStreamWriter.class) + public class OutputStreamWriterTest extends TestCase { - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks IOException", - method = "getEncoding", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks IOException", - method = "close", - args = {} - ) - }) - public void testGetEncoding_StreamClosed() { - OutputStreamWriter out = null; + + private static final int UPPER = 0xd800; + + private static final int BUFFER_SIZE = 10000; + + private ByteArrayOutputStream out; + + private OutputStreamWriter writer; + + static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese"; + + static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII", + "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" }; + + OutputStreamWriter osw; + + InputStreamReader isr; + + private ByteArrayOutputStream fos; + + String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n"; + + /* + * @see TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + out = new ByteArrayOutputStream(); + writer = new OutputStreamWriter(out, "utf-8"); + + fos = new ByteArrayOutputStream(); + osw = new OutputStreamWriter(fos); + } + + /* + * @see TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { try { - out = new OutputStreamWriter(new ByteArrayOutputStream(), - "UTF-16BE"); + writer.close(); + + if (isr != null) { + isr.close(); + } + osw.close(); + } catch (Exception e) { + // Ignored + } + + super.tearDown(); + } + + public void testClose() throws Exception { + writer.flush(); + writer.close(); + try { + writer.flush(); + fail(); + } catch (IOException e) { + // Expected + } + } + + public void testFlush() throws Exception { + writer.write(source); + writer.flush(); + String result = out.toString("utf-8"); + assertEquals(source, result); + } + + /* + * Class under test for void write(char[], int, int) + */ + public void testWritecharArrayintint() throws IOException { + char[] chars = source.toCharArray(); + + // Throws IndexOutOfBoundsException if offset is negative + try { + writer.write((char[]) null, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + // throws NullPointerException though count is negative + try { + writer.write((char[]) null, 1, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + + try { + writer.write((char[]) null, 1, 1); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + writer.write(new char[0], 0, 1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + writer.write(chars, -1, 1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + writer.write(chars, 0, -1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + writer.write(chars, 1, chars.length); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + writer.write(chars, 1, 2); + writer.flush(); + assertEquals("hi", out.toString("utf-8")); + writer.write(chars, 0, chars.length); + writer.flush(); + assertEquals("hi" + source, out.toString("utf-8")); + + writer.close(); + // After the stream is closed, should throw IOException first + try { + writer.write((char[]) null, -1, -1); + fail("should throw IOException"); + } catch (IOException e) { + // Expected + } + } + + /* + * Class under test for void write(int) + */ + public void testWriteint() throws IOException { + writer.write(1); + writer.flush(); + String str = new String(out.toByteArray(), "utf-8"); + assertEquals("\u0001", str); + + writer.write(2); + writer.flush(); + str = new String(out.toByteArray(), "utf-8"); + assertEquals("\u0001\u0002", str); + + writer.write(-1); + writer.flush(); + str = new String(out.toByteArray(), "utf-8"); + assertEquals("\u0001\u0002\uffff", str); + + writer.write(0xfedcb); + writer.flush(); + str = new String(out.toByteArray(), "utf-8"); + assertEquals("\u0001\u0002\uffff\uedcb", str); + + writer.close(); + // After the stream is closed, should throw IOException + try { + writer.write(1); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + } + + /* + * Class under test for void write(String, int, int) + */ + public void testWriteStringintint() throws IOException { + try { + writer.write((String) null, 1, 1); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + writer.write("", 0, 1); + fail(); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + try { + writer.write("abc", -1, 1); + fail(); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + try { + writer.write("abc", 0, -1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + writer.write("abc", 1, 3); + fail(); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + // Throws IndexOutOfBoundsException before NullPointerException if count + // is negative + try { + writer.write((String) null, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + // Throws NullPointerException before StringIndexOutOfBoundsException + try { + writer.write((String) null, -1, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + writer.write("abc", 1, 2); + writer.flush(); + assertEquals("bc", out.toString("utf-8")); + writer.write(source, 0, source.length()); + writer.flush(); + assertEquals("bc" + source, out.toString("utf-8")); + + writer.close(); + // Throws IndexOutOfBoundsException first if count is negative + try { + writer.write((String) null, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + writer.write((String) null, -1, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + + try { + writer.write("abc", -1, 0); + fail("should throw StringIndexOutOfBoundsException"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + // Throws IOException + try { + writer.write("abc", 0, 1); + fail("should throw IOException"); + } catch (IOException e) { + // expected + } + } + + /* + * Class under test for void OutputStreamWriter(OutputStream) + */ + public void testOutputStreamWriterOutputStream() throws IOException { + try { + writer = new OutputStreamWriter(null); + fail(); + } catch (NullPointerException e) { + // Expected + } + OutputStreamWriter writer2 = new OutputStreamWriter(out); + writer2.close(); + } + + /* + * Class under test for void OutputStreamWriter(OutputStream, String) + */ + public void testOutputStreamWriterOutputStreamString() throws IOException { + try { + writer = new OutputStreamWriter(null, "utf-8"); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + writer = new OutputStreamWriter(out, ""); + fail(); + } catch (UnsupportedEncodingException e) { + // Expected + } + try { + writer = new OutputStreamWriter(out, "badname"); + fail(); + } catch (UnsupportedEncodingException e) { + // Expected + } + try { + writer = new OutputStreamWriter(out, (String) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + OutputStreamWriter writer2 = new OutputStreamWriter(out, "ascii"); + assertEquals(Charset.forName("ascii"), Charset.forName(writer2 + .getEncoding())); + writer2.close(); + } + + /* + * Class under test for void OutputStreamWriter(OutputStream) + */ + public void testOutputStreamWriterOutputStreamCharset() throws IOException { + Charset cs = Charset.forName("ascii"); + try { + writer = new OutputStreamWriter(null, cs); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + writer = new OutputStreamWriter(out, (Charset) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + OutputStreamWriter writer2 = new OutputStreamWriter(out, cs); + assertEquals(cs, Charset.forName(writer2.getEncoding())); + writer2.close(); + } + + /* + * Class under test for void OutputStreamWriter(OutputStream, String) + */ + public void testOutputStreamWriterOutputStreamCharsetEncoder() + throws IOException { + Charset cs = Charset.forName("ascii"); + CharsetEncoder enc = cs.newEncoder(); + try { + writer = new OutputStreamWriter(null, enc); + fail(); + } catch (NullPointerException e) { + // Expected + } + try { + writer = new OutputStreamWriter(out, (CharsetEncoder) null); + fail(); + } catch (NullPointerException e) { + // Expected + } + OutputStreamWriter writer2 = new OutputStreamWriter(out, enc); + assertEquals(cs, Charset.forName(writer2.getEncoding())); + writer2.close(); + } + + public void testGetEncoding() { + Charset cs = Charset.forName("utf-8"); + assertEquals(cs, Charset.forName(writer.getEncoding())); + } + + public void testHandleEarlyEOFChar_1() throws IOException { + String str = "All work and no play makes Jack a dull boy\n"; //$NON-NLS-1$ + int NUMBER = 2048; + int j = 0; + int len = str.length() * NUMBER; + char[] strChars = new char[len]; + for (int i = 0; i < NUMBER; ++i) { + for (int k = 0; k < str.length(); ++k) { + strChars[j++] = str.charAt(k); + } + } + + File f = File.createTempFile("one", "by_one"); + f.deleteOnExit(); + FileWriter fw = new FileWriter(f); + fw.write(strChars); + fw.close(); + FileInputStream fis = new FileInputStream(f); + InputStreamReader in = new InputStreamReader(fis); + for (int offset = 0; offset < strChars.length; ++offset) { + int b = in.read(); + assertFalse("Early EOF at offset", -1 == b); + } + } + + public void testHandleEarlyEOFChar_2() throws IOException { + int capacity = 65536; + byte[] bytes = new byte[capacity]; + byte[] bs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' }; + for (int i = 0; i < bytes.length; i++) { + bytes[i] = bs[i / 8192]; + } + String inputStr = new String(bytes); + int len = inputStr.length(); + File f = File.createTempFile("FileWriterBugTest ", null); //$NON-NLS-1$ + f.deleteOnExit(); + FileWriter writer = new FileWriter(f); + writer.write(inputStr); + writer.close(); + long flen = f.length(); + + FileReader reader = new FileReader(f); + char[] outChars = new char[capacity]; + int outCount = reader.read(outChars); + String outStr = new String(outChars, 0, outCount); + + assertEquals(len, flen); + assertEquals(inputStr, outStr); + } + + public void testSingleCharIO() throws Exception { + InputStreamReader isr = null; + for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) { + try { + out = new ByteArrayOutputStream(); + writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]); + + int upper = UPPER; + switch (i) { + case 0: + upper = 128; + break; + case 1: + upper = 256; + break; + } + + for (int c = 0; c < upper; ++c) { + writer.write(c); + } + writer.flush(); + byte[] result = out.toByteArray(); + + isr = new InputStreamReader(new ByteArrayInputStream(result), + MINIMAL_CHARSETS[i]); + for (int expected = 0; expected < upper; ++expected) { + assertEquals("Error when reading bytes in " + + MINIMAL_CHARSETS[i], expected, isr.read()); + } + } finally { + try { + isr.close(); + } catch (Exception e) { + } + try { + writer.close(); + } catch (Exception e) { + } + } + } + } + + public void testBlockIO() throws Exception { + InputStreamReader isr = null; + char[] largeBuffer = new char[BUFFER_SIZE]; + for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) { + try { + out = new ByteArrayOutputStream(); + writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]); + + int upper = UPPER; + switch (i) { + case 0: + upper = 128; + break; + case 1: + upper = 256; + break; + } + + int m = 0; + for (int c = 0; c < upper; ++c) { + largeBuffer[m++] = (char) c; + if (m == BUFFER_SIZE) { + writer.write(largeBuffer); + m = 0; + } + } + writer.write(largeBuffer, 0, m); + writer.flush(); + byte[] result = out.toByteArray(); + + isr = new InputStreamReader(new ByteArrayInputStream(result), + MINIMAL_CHARSETS[i]); + int expected = 0, read = 0, j = 0; + while (expected < upper) { + if (j == read) { + read = isr.read(largeBuffer); + j = 0; + } + assertEquals("Error when reading bytes in " + + MINIMAL_CHARSETS[i], expected++, largeBuffer[j++]); + } + } finally { + try { + isr.close(); + } catch (Exception e) { + } + try { + writer.close(); + } catch (Exception e) { + } + } + } + } + + /** + * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream) + */ + public void test_ConstructorLjava_io_OutputStream() { + assertTrue("Used in tests", true); + } + + /** + * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream, + * java.lang.String) + */ + public void test_ConstructorLjava_io_OutputStreamLjava_lang_String() + throws UnsupportedEncodingException { + osw = new OutputStreamWriter(fos, "8859_1"); + try { + osw = new OutputStreamWriter(fos, "Bogus"); + fail("Failed to throw Unsupported Encoding exception"); } catch (UnsupportedEncodingException e) { - fail("Should not throw UnsupportedEncodingException"); + // Expected } + } + + /** + * @tests java.io.OutputStreamWriter#close() + */ + public void test_close() throws IOException { + osw.close(); + try { - out.close(); + osw.write(testString, 0, testString.length()); + fail("Chars written after close"); } catch (IOException e) { - fail("Should not throw IOException"); + // Expected + } + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try { + OutputStreamWriter writer = new OutputStreamWriter(bout, + "ISO2022JP"); + writer.write(new char[] { 'a' }); + writer.close(); + // the default is ASCII, there should not be any mode changes + String converted = new String(bout.toByteArray(), "ISO8859_1"); + assertTrue("invalid conversion 1: " + converted, converted + .equals("a")); + + bout.reset(); + writer = new OutputStreamWriter(bout, "ISO2022JP"); + writer.write(new char[] { '\u3048' }); + writer.flush(); + // the byte sequence should not switch to ASCII mode until the + // stream is closed + converted = new String(bout.toByteArray(), "ISO8859_1"); + assertTrue("invalid conversion 2: " + converted, converted + .equals("\u001b$B$(")); + writer.close(); + converted = new String(bout.toByteArray(), "ISO8859_1"); + assertTrue("invalid conversion 3: " + converted, converted + .equals("\u001b$B$(\u001b(B")); + + bout.reset(); + writer = new OutputStreamWriter(bout, "ISO2022JP"); + writer.write(new char[] { '\u3048' }); + writer.write(new char[] { '\u3048' }); + writer.close(); + // there should not be a mode switch between writes + assertEquals("invalid conversion 4", "\u001b$B$($(\u001b(B", + new String(bout.toByteArray(), "ISO8859_1")); + } catch (UnsupportedEncodingException e) { + // Can't test missing converter + System.out.println(e); } + } + + /** + * @tests java.io.OutputStreamWriter#flush() + */ + public void test_flush() throws IOException { + char[] buf = new char[testString.length()]; + osw.write(testString, 0, testString.length()); + osw.flush(); + openInputStream(); + isr.read(buf, 0, buf.length); + assertTrue("Chars not flushed", new String(buf, 0, buf.length) + .equals(testString)); + } + + /** + * @tests java.io.OutputStreamWriter#getEncoding() + */ + public void test_getEncoding() throws IOException { + try { + osw = new OutputStreamWriter(fos, "8859_1"); + } catch (UnsupportedEncodingException e) { + assertEquals("Returned incorrect encoding", "8859_1", osw + .getEncoding()); + } + + OutputStreamWriter out = new OutputStreamWriter( + new ByteArrayOutputStream(), "UTF-16BE"); + out.close(); + String result = out.getEncoding(); assertNull(result); - } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getEncoding", - args = {} - ) - public void testGetEncoding_NotHistorical() { - OutputStreamWriter out = null; + out = null; try { out = new OutputStreamWriter(new ByteArrayOutputStream(), "UTF-16BE"); } catch (UnsupportedEncodingException e) { // ok } - String result = out.getEncoding(); + result = out.getEncoding(); assertEquals("UnicodeBigUnmarked", result); } -}
\ No newline at end of file + + /** + * @tests java.io.OutputStreamWriter#write(char[], int, int) + */ + public void test_write$CII() throws IOException { + char[] buf = new char[testString.length()]; + osw.write(testString, 0, testString.length()); + osw.close(); + openInputStream(); + isr.read(buf, 0, buf.length); + assertTrue("Incorrect chars returned", new String(buf, 0, buf.length) + .equals(testString)); + } + + /** + * @tests java.io.OutputStreamWriter#write(int) + */ + public void test_writeI() throws IOException { + osw.write('T'); + osw.close(); + openInputStream(); + int c = isr.read(); + assertEquals("Incorrect char returned", 'T', (char) c); + } + + /** + * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int) + */ + public void test_writeLjava_lang_StringII() throws IOException { + char[] buf = new char[testString.length()]; + osw.write(testString, 0, testString.length()); + osw.close(); + openInputStream(); + isr.read(buf); + assertTrue("Incorrect chars returned", new String(buf, 0, buf.length) + .equals(testString)); + } + + private void openInputStream() { + isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray())); + } +} diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java index 4756c09..67e1fb5 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java @@ -1,51 +1,984 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.io; +import java.io.EOFException; import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; -import junit.framework.TestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -@TestTargetClass(RandomAccessFile.class) -public class RandomAccessFileTest extends TestCase { +import java.nio.channels.FileChannel; +import java.nio.channels.NonWritableChannelException; + +public class RandomAccessFileTest extends junit.framework.TestCase { + + public String fileName; + + public boolean ufile = true; + + java.io.RandomAccessFile raf; + + java.io.File f; + + String unihw = "\u0048\u0065\u006C\u0801\u006C\u006F\u0020\u0057\u0081\u006F\u0072\u006C\u0064"; + + //java.io.FileOutputStream fos; + + public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; /** - * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File, java.lang.String) + * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File, + * java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks functionality.", - method = "RandomAccessFile", - args = {java.io.File.class, java.lang.String.class} - ) - public void test_ConstructorLjava_io_FileLjava_lang_String() throws IOException { + public void test_ConstructorLjava_io_FileLjava_lang_String() + throws Exception { + // Test for method java.io.RandomAccessFile(java.io.File, + // java.lang.String) + RandomAccessFile raf = new java.io.RandomAccessFile(f, "rw"); + raf.write(20); + raf.seek(0); + assertEquals("Incorrect int read/written", 20, raf.read()); + raf.close(); + + raf = new java.io.RandomAccessFile(f, "rwd"); + raf.write(20); + raf.seek(0); + assertEquals("Incorrect int read/written", 20, raf.read()); + raf.close(); + + raf = new java.io.RandomAccessFile(f, "rws"); + raf.write(20); + raf.seek(0); + assertEquals("Incorrect int read/written", 20, raf.read()); + raf.close(); + // Regression for HARMONY-50 File f = File.createTempFile("xxx", "yyy"); f.deleteOnExit(); - RandomAccessFile raf = new RandomAccessFile(f, "rws"); + raf = new RandomAccessFile(f, "rws"); raf.close(); f = File.createTempFile("xxx", "yyy"); f.deleteOnExit(); raf = new RandomAccessFile(f, "rwd"); - raf.close(); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#RandomAccessFile(java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_String() + throws IOException { + // Test for method java.io.RandomAccessFile(java.lang.String, + // java.lang.String) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.write("Test".getBytes(), 0, 4); + raf.close(); + + raf = new java.io.RandomAccessFile(fileName, "rwd"); + raf.write("Test".getBytes(), 0, 4); + raf.close(); + + raf = new java.io.RandomAccessFile(fileName, "rws"); + raf.write("Test".getBytes(), 0, 4); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#close() + */ + public void test_close() { + // Test for method void java.io.RandomAccessFile.close() + try { + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.close(); + raf.write("Test".getBytes(), 0, 4); + fail("Failed to close file properly"); + } catch (IOException e) {} + } + + /** + * @tests java.io.RandomAccessFile#getFD() + */ + public void test_getFD() throws IOException { + // Test for method java.io.FileDescriptor + // java.io.RandomAccessFile.getFD() + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + assertTrue("Returned invalid fd", raf.getFD().valid()); + + raf.close(); + assertFalse("Returned valid fd after close", raf.getFD().valid()); + } + + /** + * @tests java.io.RandomAccessFile#getFilePointer() + */ + public void test_getFilePointer() throws IOException { + // Test for method long java.io.RandomAccessFile.getFilePointer() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.write(fileString.getBytes(), 0, 1000); + assertEquals("Incorrect filePointer returned", 1000, raf + .getFilePointer()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#length() + */ + public void test_length() throws IOException { + // Test for method long java.io.RandomAccessFile.length() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.write(fileString.getBytes()); + assertEquals("Incorrect length returned", fileString.length(), raf + .length()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#read() + */ + public void test_read() throws IOException { + // Test for method int java.io.RandomAccessFile.read() + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes("UTF-8"), 0, fileString.length()); + fos.close(); + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + assertEquals("Incorrect bytes returned from read", + fileString.charAt(0), raf.read()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[]) + */ + public void test_read$B() throws IOException { + // Test for method int java.io.RandomAccessFile.read(byte []) + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes(), 0, fileString.length()); + fos.close(); + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + byte[] rbuf = new byte[4000]; + raf.read(rbuf); + assertEquals("Incorrect bytes returned from read", fileString, + new String(rbuf, 0, fileString.length())); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[], int, int) + */ + public void test_read$BII() throws IOException { + // Test for method int java.io.RandomAccessFile.read(byte [], int, int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + byte[] rbuf = new byte[4000]; + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes(), 0, fileString.length()); + fos.close(); + raf.read(rbuf, 0, fileString.length()); + assertEquals("Incorrect bytes returned from read", fileString, + new String(rbuf, 0, fileString.length())); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readBoolean() + */ + public void test_readBoolean() throws IOException { + // Test for method boolean java.io.RandomAccessFile.readBoolean() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBoolean(true); + raf.seek(0); + assertTrue("Incorrect boolean read/written", raf.readBoolean()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readByte() + */ + public void test_readByte() throws IOException { + // Test for method byte java.io.RandomAccessFile.readByte() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeByte(127); + raf.seek(0); + assertEquals("Incorrect bytes read/written", 127, raf.readByte()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readChar() + */ + public void test_readChar() throws IOException { + // Test for method char java.io.RandomAccessFile.readChar() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeChar('T'); + raf.seek(0); + assertEquals("Incorrect char read/written", 'T', raf.readChar()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readDouble() + */ + public void test_readDouble() throws IOException { + // Test for method double java.io.RandomAccessFile.readDouble() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeDouble(Double.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf + .readDouble(), 0); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readFloat() + */ + public void test_readFloat() throws IOException { + // Test for method float java.io.RandomAccessFile.readFloat() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeFloat(Float.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf + .readFloat(), 0); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readFully(byte[]) + */ + public void test_readFully$B() throws IOException { + // Test for method void java.io.RandomAccessFile.readFully(byte []) + byte[] buf = new byte[10]; + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBytes("HelloWorld"); + raf.seek(0); + raf.readFully(buf); + assertEquals("Incorrect bytes read/written", "HelloWorld", new String( + buf, 0, 10, "UTF-8")); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readFully(byte[], int, int) + */ + public void test_readFully$BII() throws IOException { + // Test for method void java.io.RandomAccessFile.readFully(byte [], int, + // int) + byte[] buf = new byte[10]; + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBytes("HelloWorld"); + raf.seek(0); + raf.readFully(buf, 0, buf.length); + assertEquals("Incorrect bytes read/written", "HelloWorld", new String( + buf, 0, 10, "UTF-8")); + try { + raf.readFully(buf, 0, buf.length); + fail("Reading past end of buffer did not throw EOFException"); + } catch (EOFException e) {} + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readInt() + */ + public void test_readInt() throws IOException { + // Test for method int java.io.RandomAccessFile.readInt() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeInt(Integer.MIN_VALUE); + raf.seek(0); + assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf + .readInt()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readLine() + */ + public void test_readLine() throws IOException { + // Test for method java.lang.String java.io.RandomAccessFile.readLine() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + String s = "Goodbye\nCruel\nWorld\n"; + raf.write(s.getBytes("UTF-8"), 0, s.length()); + raf.seek(0); + + assertEquals("Goodbye", raf.readLine()); + assertEquals("Cruel", raf.readLine()); + assertEquals("World", raf.readLine()); + + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readLong() + */ + public void test_readLong() throws IOException { + // Test for method long java.io.RandomAccessFile.readLong() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeLong(Long.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf + .readLong()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readShort() + */ + public void test_readShort() throws IOException { + // Test for method short java.io.RandomAccessFile.readShort() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeShort(Short.MIN_VALUE); + raf.seek(0); + assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf + .readShort()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readUnsignedByte() + */ + public void test_readUnsignedByte() throws IOException { + // Test for method int java.io.RandomAccessFile.readUnsignedByte() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeByte(-1); + raf.seek(0); + assertEquals("Incorrect byte read/written", 255, raf.readUnsignedByte()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readUnsignedShort() + */ + public void test_readUnsignedShort() throws IOException { + // Test for method int java.io.RandomAccessFile.readUnsignedShort() + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeShort(-1); + raf.seek(0); + assertEquals("Incorrect byte read/written", 65535, raf + .readUnsignedShort()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#readUTF() + */ + public void test_readUTF() throws IOException { + // Test for method java.lang.String java.io.RandomAccessFile.readUTF() + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeUTF(unihw); + raf.seek(0); + assertEquals("Incorrect utf string read", unihw, raf.readUTF()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#seek(long) + */ + public void test_seekJ() throws IOException { + // Test for method void java.io.RandomAccessFile.seek(long) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.write(fileString.getBytes(), 0, fileString.length()); + raf.seek(12); + assertEquals("Seek failed to set filePointer", 12, raf.getFilePointer()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#skipBytes(int) + */ + public void test_skipBytesI() throws IOException { + // Test for method int java.io.RandomAccessFile.skipBytes(int) + byte[] buf = new byte[5]; + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBytes("HelloWorld"); + raf.seek(0); + raf.skipBytes(5); + raf.readFully(buf); + assertEquals("Failed to skip bytes", "World", new String(buf, 0, 5, "UTF-8")); + raf.close(); } + + /** + * @tests java.io.RandomAccessFile#write(byte[]) + */ + public void test_write$B() throws IOException { + // Test for method void java.io.RandomAccessFile.write(byte []) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + + byte[] nullByteArray = null; + try { + raf.write(nullByteArray); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + //expected + } + + byte[] rbuf = new byte[4000]; + raf.write(fileString.getBytes()); + raf.close(); + + try { + raf.write(nullByteArray); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + //expected + } + + //will not throw IOException if array's length is 0 + raf.write(new byte[0]); + + try { + raf.write(fileString.getBytes()); + fail("should throw IOException"); + } catch (IOException e) { + //expected + } + + FileInputStream fis = new java.io.FileInputStream(fileName); + fis.read(rbuf, 0, fileString.length()); + assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0, + fileString.length())); + fis.close(); + } + + /** + * @tests java.io.RandomAccessFile#write(byte[], int, int) + */ + public void test_write$BII() throws IOException { + // Test for method void java.io.RandomAccessFile.write(byte [], int, + // int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + byte[] rbuf = new byte[4000]; + raf.write(fileString.getBytes(), 0, fileString.length()); + raf.close(); + FileInputStream fis = new java.io.FileInputStream(fileName); + fis.read(rbuf, 0, fileString.length()); + assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0, + fileString.length())); + fis.close(); + } + + /** + * @tests java.io.RandomAccessFile#write(byte[], int, int) + */ + public void test_write_$BII_Exception() throws IOException { + raf = new java.io.RandomAccessFile(f, "rw"); + byte[] nullByteArray = null; + byte[] byteArray = new byte[10]; + + try { + raf.write(nullByteArray, -1, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(nullByteArray, 0, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(nullByteArray, 1, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(nullByteArray, 1, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(nullByteArray, 1, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(byteArray, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + raf.write(byteArray, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + raf.write(byteArray, -1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + raf.write(byteArray, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + raf.write(byteArray, 0, 0); + raf.write(byteArray, 0, byteArray.length); + raf.write(byteArray, 1, 0); + raf.write(byteArray, byteArray.length, 0); + + try { + raf.write(byteArray, byteArray.length + 1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + + try { + raf.write(byteArray, byteArray.length + 1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + + raf.close(); + + try { + raf.write(nullByteArray, -1, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + raf.write(byteArray, -1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + raf.write(byteArray, 0, 1); + fail("should throw IOException"); + } catch (IOException e) { + //expected + } + + try { + raf.write(byteArray, 0, byteArray.length); + fail("should throw IOException"); + } catch (IOException e) { + //expected + } + + try { + raf.write(byteArray, 1, 1); + fail("should throw IOException"); + } catch (IOException e) { + //expected + } + + try { + raf.write(byteArray, byteArray.length + 1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + + // will not throw IOException if count = 0 + raf.write(byteArray, 0, 0); + raf.write(byteArray, byteArray.length, 0); + } + + + /** + * @tests java.io.RandomAccessFile#write(int) + */ + public void test_writeI() throws IOException { + // Test for method void java.io.RandomAccessFile.write(int) + byte[] rbuf = new byte[4000]; + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.write('t'); + raf.close(); + FileInputStream fis = new java.io.FileInputStream(fileName); + fis.read(rbuf, 0, 1); + assertEquals("Incorrect byte written", 't', rbuf[0]); + fis.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeBoolean(boolean) + */ + public void test_writeBooleanZ() throws IOException { + // Test for method void java.io.RandomAccessFile.writeBoolean(boolean) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBoolean(true); + raf.seek(0); + assertTrue("Incorrect boolean read/written", raf.readBoolean()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeByte(int) + */ + public void test_writeByteI() throws IOException { + // Test for method void java.io.RandomAccessFile.writeByte(int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeByte(127); + raf.seek(0); + assertEquals("Incorrect byte read/written", 127, raf.readByte()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeBytes(java.lang.String) + */ + public void test_writeBytesLjava_lang_String() throws IOException { + // Test for method void + // java.io.RandomAccessFile.writeBytes(java.lang.String) + byte[] buf = new byte[10]; + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeBytes("HelloWorld"); + raf.seek(0); + raf.readFully(buf); + assertEquals("Incorrect bytes read/written", "HelloWorld", new String( + buf, 0, 10, "UTF-8")); + raf.close(); + + } + + /** + * @tests java.io.RandomAccessFile#writeChar(int) + */ + public void test_writeCharI() throws IOException { + // Test for method void java.io.RandomAccessFile.writeChar(int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeChar('T'); + raf.seek(0); + assertEquals("Incorrect char read/written", 'T', raf.readChar()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeChars(java.lang.String) + */ + public void test_writeCharsLjava_lang_String() throws IOException { + // Test for method void + // java.io.RandomAccessFile.writeChars(java.lang.String) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeChars("HelloWorld"); + char[] hchars = new char[10]; + "HelloWorld".getChars(0, 10, hchars, 0); + raf.seek(0); + for (int i = 0; i < hchars.length; i++) + assertEquals("Incorrect string written", hchars[i], raf.readChar()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeDouble(double) + */ + public void test_writeDoubleD() throws IOException { + // Test for method void java.io.RandomAccessFile.writeDouble(double) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeDouble(Double.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf + .readDouble(), 0); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeFloat(float) + */ + public void test_writeFloatF() throws IOException { + // Test for method void java.io.RandomAccessFile.writeFloat(float) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeFloat(Float.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf + .readFloat(), 0); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeInt(int) + */ + public void test_writeIntI() throws IOException { + // Test for method void java.io.RandomAccessFile.writeInt(int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeInt(Integer.MIN_VALUE); + raf.seek(0); + assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf + .readInt()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeLong(long) + */ + public void test_writeLongJ() throws IOException { + // Test for method void java.io.RandomAccessFile.writeLong(long) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeLong(Long.MAX_VALUE); + raf.seek(0); + assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf + .readLong()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeShort(int) + */ + public void test_writeShortI() throws IOException { + // Test for method void java.io.RandomAccessFile.writeShort(int) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeShort(Short.MIN_VALUE); + raf.seek(0); + assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf + .readShort()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#writeUTF(java.lang.String) + */ + public void test_writeUTFLjava_lang_String() throws IOException { + // Test for method void + // java.io.RandomAccessFile.writeUTF(java.lang.String) + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + raf.writeUTF(unihw); + raf.seek(0); + assertEquals("Incorrect utf string", unihw, raf.readUTF()); + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#seek(long) + * + * Regression for HARMONY-374 + */ + public void test_seekI() throws IOException { + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + try { + raf.seek(-1); + fail("IOException must be thrown if pos < 0"); + } catch (IOException e) { + } + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[], int, int) + * + * Regression for HARMONY-377 + */ + public void test_readBII() throws IOException { + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + try { + raf.read(new byte[1], -1, 1); + fail("IndexOutOfBoundsException must be thrown if off <0"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.read(new byte[1], 0, -1); + fail("IndexOutOfBoundsException must be thrown if len <0"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.read(new byte[1], 0, 5); + fail("IndexOutOfBoundsException must be thrown if off+len > b.length"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.read(new byte[10], Integer.MAX_VALUE, 5); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.read(new byte[10], 5, Integer.MAX_VALUE); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + } + + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[],int,int) + */ + public void test_read_$BII_IndexOutOfBoundsException() throws IOException { + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes(), 0, fileString.length()); + fos.close(); + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + byte[] rbuf = new byte[100]; + raf.close(); + try { + raf.read(rbuf,-1,0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //expected + } + } + + /** + * @tests java.io.RandomAccessFile#read(byte[],int,int) + */ + public void test_read_$BII_IOException() throws IOException { + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes(), 0, fileString.length()); + fos.close(); + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + byte[] rbuf = new byte[100]; + raf.close(); + int read = raf.read(rbuf,0,0); + assertEquals(0,read); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[]) + */ + public void test_read_$B_IOException() throws IOException { + FileOutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(fileString.getBytes(), 0, fileString.length()); + fos.close(); + + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + byte[] rbuf = new byte[0]; + raf.close(); + int read = raf.read(rbuf); + assertEquals(0,read); + } + + /** + * @tests java.io.RandomAccessFile#read(byte[],int,int) + */ + public void test_read_$BII_NullPointerException() throws IOException { + File f = File.createTempFile("tmp", "tmp"); + f.deleteOnExit(); + RandomAccessFile raf = new RandomAccessFile(f, "r"); + byte[] rbuf = null; + try { + raf.read(rbuf, 0, -1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + raf.close(); + } + + /** + * @tests java.io.RandomAccessFile#write(byte[], int, int) + * + * Regression for HARMONY-377 + */ + public void test_writeBII() throws IOException { + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); + try { + raf.write(new byte[1], -1, 1); + fail("IndexOutOfBoundsException must be thrown if off <0"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.write(new byte[1], 0, -1); + fail("IndexOutOfBoundsException must be thrown if len <0"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.write(new byte[1], 0, 5); + fail("IndexOutOfBoundsException must be thrown if off+len > b.length"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.write(new byte[10], Integer.MAX_VALUE, 5); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + } + + try { + raf.write(new byte[10], 5, Integer.MAX_VALUE); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + } + raf.close(); + } + + /** + * Regression for HARMONY-69 + */ + public void testRandomAccessFile_String_String() throws IOException { + f.createNewFile(); + RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r"); + FileChannel fcr = raf.getChannel(); + + try { + fcr.lock(0L, Long.MAX_VALUE, false); + fail("NonWritableChannelException expected!"); + } catch (NonWritableChannelException e) {} + raf.close(); + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() throws Exception { + super.setUp(); + f = File.createTempFile("raf", "tst"); + if (!f.delete()) { + fail("Unable to delete test file : " + f); + } + fileName = f.getAbsolutePath(); + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + * @throws Exception + */ + protected void tearDown() throws Exception { + if (f.exists()) { + f.delete(); + } + super.tearDown(); + } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java index 5bad541..da3185e 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java @@ -4,67 +4,78 @@ * 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 - * + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.io; import java.io.IOException; import java.io.Writer; import junit.framework.TestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -@TestTargetClass(Writer.class) public class WriterTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "Writer", - args = {} - ) - public void test_Writer() { - MockWriter w = new MockWriter(); - assertTrue("Test 1: Lock has not been set correctly.", w.lockSet(w)); + /** + * @tests java.io.Writer#append(char) + */ + public void test_appendChar() throws IOException { + char testChar = ' '; + MockWriter writer = new MockWriter(20); + writer.append(testChar); + assertEquals(String.valueOf(testChar), String.valueOf(writer + .getContents())); + writer.close(); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "Writer", - args = {java.lang.Object.class} - ) - public void test_WriterLjava_lang_Object() { - Object o = new Object(); - MockWriter w; - - try { - w = new MockWriter(null); - fail("Test 1: NullPointerException expected."); - } catch (NullPointerException e) { - // Expected. - } - w = new MockWriter(o); - assertTrue("Test 2: Lock has not been set correctly.", w.lockSet(o)); + + /** + * @tests java.io.Writer#append(CharSequence) + */ + public void test_appendCharSequence() throws IOException { + String testString = "My Test String"; + MockWriter writer = new MockWriter(20); + writer.append(testString); + assertEquals(testString, String.valueOf(writer.getContents())); + writer.close(); + } - class MockWriter extends Writer { + /** + * @tests java.io.Writer#append(CharSequence, int, int) + */ + public void test_appendCharSequenceIntInt() throws IOException { + String testString = "My Test String"; + MockWriter writer = new MockWriter(20); + writer.append(testString, 1, 3); + assertEquals(testString.substring(1, 3), String.valueOf(writer + .getContents())); + writer.close(); + + } + + + + /** + * @tests java.io.Writer#write(String) + */ + public void test_writeLjava_lang_String() throws IOException { + // Regression for HARMONY-51 + Object lock = new Object(); + Writer wr = new MockLockWriter(lock); + wr.write("Some string"); + wr.close(); + } + + class MockLockWriter extends Writer { final Object myLock; - MockWriter() { - super(); - myLock = this; - } - - MockWriter(Object lock) { + MockLockWriter(Object lock) { super(lock); myLock = lock; } @@ -83,9 +94,55 @@ public class WriterTest extends TestCase { public void write(char[] arg0, int arg1, int arg2) throws IOException { assertTrue(Thread.holdsLock(myLock)); } + } - public boolean lockSet(Object o) { - return (lock == o); + + class MockWriter extends Writer { + private char[] contents; + + private int length; + + private int offset; + + MockWriter(int capacity) { + contents = new char[capacity]; + length = capacity; + offset = 0; + } + + public synchronized void close() throws IOException { + flush(); + contents = null; + } + + public synchronized void flush() throws IOException { + // do nothing + } + + public void write(char[] buffer, int offset, int count) + throws IOException { + if (null == contents) { + throw new IOException(); + } + if (offset < 0 || count < 0 || offset >= buffer.length) { + throw new IndexOutOfBoundsException(); + } + count = Math.min(count, buffer.length - offset); + count = Math.min(count, this.length - this.offset); + for (int i = 0; i < count; i++) { + contents[this.offset + i] = buffer[offset + i]; + } + this.offset += count; + + } + + public char[] getContents() { + char[] result = new char[offset]; + for (int i = 0; i < offset; i++) { + result[i] = contents[i]; + } + return result; } } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java index c3679f1..2166716 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java @@ -1,51 +1,62 @@ /* - * Copyright (C) 2007 The Android Open Source Project + * 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 * - * 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - -@TestTargetClass(AbstractMethodError.class) -public class AbstractMethodErrorTest extends TestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AbstractMethodError", - args = {} - ) - public void test_AbstractMethodError() { - AbstractMethodError ame = new AbstractMethodError(); - assertNull(ame.getMessage()); +import org.apache.harmony.testframework.serialization.SerializationTest; + +public class AbstractMethodErrorTest extends junit.framework.TestCase { + + /** + * @tests {@link java.lang.AbstractMethodError#AbstractMethodError()} + */ + public void test_Constructor() { + // Test for method java.lang.AbstractMethodError() + Error error = new AbstractMethodError(); + assertNull(error.getCause()); + assertNull(error.getMessage()); + } + + /** + * @tests {@link java.lang.AbstractMethodError#AbstractMethodError(String)} + */ + public void test_ConstructorLjava_lang_String() { + // Test for method java.lang.AbstractMethodError(java.lang.String) + Error error = new AbstractMethodError(null); + assertNull(error.getMessage()); + assertNull(error.getCause()); + + error = new AbstractMethodError("msg"); + assertEquals("msg", error.getMessage()); + assertNull(error.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AbstractMethodError", - args = {java.lang.String.class} - ) - public void test_AbstractMethodError_String() { - String message = "Test Message"; - AbstractMethodError ame = new AbstractMethodError(message); - assertEquals(message, ame.getMessage()); + /** + * @tests serialization/deserialization. + */ + public void testSerializationSelf() throws Exception { + SerializationTest.verifySelf(new AbstractMethodError()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + SerializationTest.verifyGolden(this, new AbstractMethodError()); } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java index 438e560..d6fb8ab 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java @@ -30,7 +30,7 @@ public class AllTests { } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang"); + TestSuite suite = new TestSuite("Tests for java.lang"); suite.addTestSuite(AbstractMethodErrorTest.class); suite.addTestSuite(ArithmeticExceptionTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java index bce6f5d..f99be20 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(ArithmeticException.class) public class ArithmeticExceptionTest extends TestCase { /** * @tests java.lang.ArithmeticException#ArithmeticException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArithmeticException", - args = {} - ) public void test_Constructor() { ArithmeticException e = new ArithmeticException(); assertNull(e.getMessage()); @@ -45,12 +33,6 @@ public class ArithmeticExceptionTest extends TestCase { /** * @tests java.lang.ArithmeticException#ArithmeticException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArithmeticException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { ArithmeticException e = new ArithmeticException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java index 3117e49..c7537c0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(ArrayIndexOutOfBoundsException.class) public class ArrayIndexOutOfBoundsExceptionTest extends TestCase { - /** + /** * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArrayIndexOutOfBoundsException", - args = {int.class} - ) public void test_ConstructorI() { ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException(-1); assertNotNull(e.getMessage()); @@ -47,12 +35,6 @@ public class ArrayIndexOutOfBoundsExceptionTest extends TestCase { /** * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArrayIndexOutOfBoundsException", - args = {} - ) public void test_Constructor() { ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException(); assertNull(e.getMessage()); @@ -62,12 +44,6 @@ public class ArrayIndexOutOfBoundsExceptionTest extends TestCase { /** * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArrayIndexOutOfBoundsException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java index d2345cb..c8979d0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(ArrayStoreException.class) public class ArrayStoreExceptionTest extends TestCase { /** * @tests java.lang.ArrayStoreException#ArrayStoreException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArrayStoreException", - args = {} - ) public void test_Constructor() { ArrayStoreException e = new ArrayStoreException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class ArrayStoreExceptionTest extends TestCase { /** * @tests java.lang.ArrayStoreException#ArrayStoreException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ArrayStoreException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { ArrayStoreException e = new ArrayStoreException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java index ec0d40f..e5a51cc 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java @@ -17,33 +17,16 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(AssertionError.class) public class AssertionErrorTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {} - ) public void test_Constructor() { AssertionError e = new AssertionError(); assertNull(e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {java.lang.Object.class} - ) + public void test_ConstructorObject() { Object obj = "toString"; AssertionError e = new AssertionError(obj); @@ -55,67 +38,37 @@ public class AssertionErrorTest extends TestCase { assertEquals(npe.toString(), e.getMessage()); assertSame(npe, e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {boolean.class} - ) + public void test_ConstructorBoolean() { AssertionError e = new AssertionError(true); assertEquals("true", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {char.class} - ) + public void test_ConstructorChar() { AssertionError e = new AssertionError('a'); assertEquals("a", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {int.class} - ) + public void test_ConstructorInt() { AssertionError e = new AssertionError(1); assertEquals("1", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {long.class} - ) + public void test_ConstructorLong() { AssertionError e = new AssertionError(1L); assertEquals("1", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {float.class} - ) + public void test_ConstructorFloat() { AssertionError e = new AssertionError(1.0F); assertEquals("1.0", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AssertionError", - args = {double.class} - ) + public void test_ConstructorDouble() { AssertionError e = new AssertionError(1.0D); assertEquals("1.0", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java index 23f9575..4c7c3e4 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java @@ -16,25 +16,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Boolean.class) public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { assertEquals(1231, Boolean.TRUE.hashCode()); assertEquals(1237, Boolean.FALSE.hashCode()); @@ -43,12 +31,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#Boolean(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Boolean", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { assertEquals(Boolean.TRUE, new Boolean("TRUE")); assertEquals(Boolean.TRUE, new Boolean("true")); @@ -61,12 +43,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#Boolean(boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Boolean", - args = {boolean.class} - ) public void test_ConstructorZ() { assertEquals(Boolean.TRUE, new Boolean(true)); assertEquals(Boolean.FALSE, new Boolean(false)); @@ -75,12 +51,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#booleanValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "booleanValue", - args = {} - ) public void test_booleanValue() { assertTrue(Boolean.TRUE.booleanValue()); assertFalse(Boolean.FALSE.booleanValue()); @@ -89,12 +59,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#equals(Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { assertTrue(Boolean.TRUE.equals(Boolean.TRUE)); assertTrue(Boolean.TRUE.equals(new Boolean(true))); @@ -108,12 +72,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#getBoolean(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getBoolean", - args = {java.lang.String.class} - ) public void test_getBooleanLjava_lang_String() { System.setProperty(getClass().getName(), "true"); assertTrue(Boolean.getBoolean(getClass().getName())); @@ -128,12 +86,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { assertEquals("true", Boolean.TRUE.toString()); assertEquals("false", Boolean.FALSE.toString()); @@ -142,12 +94,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#toString(boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {boolean.class} - ) public void test_toStringZ() { assertEquals("true", Boolean.toString(true)); assertEquals("false", Boolean.toString(false)); @@ -156,12 +102,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#valueOf(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String() { assertEquals(Boolean.TRUE, Boolean.valueOf("true")); assertEquals(Boolean.FALSE, Boolean.valueOf("false")); @@ -182,12 +122,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#valueOf(boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {boolean.class} - ) public void test_valueOfZ() { assertEquals(Boolean.TRUE, Boolean.valueOf(true)); assertEquals(Boolean.FALSE, Boolean.valueOf(false)); @@ -196,12 +130,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#parseBoolean(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "parseBoolean", - args = {java.lang.String.class} - ) public void test_parseBooleanLjava_lang_String() { assertTrue(Boolean.parseBoolean("true")); assertTrue(Boolean.parseBoolean("TRUE")); @@ -214,12 +142,6 @@ public class BooleanTest extends TestCase { /** * @tests java.lang.Boolean#compareTo(Boolean) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.lang.Boolean.class} - ) public void test_compareToLjava_lang_Boolean() { assertTrue(Boolean.TRUE.compareTo(Boolean.TRUE) == 0); assertTrue(Boolean.FALSE.compareTo(Boolean.FALSE) == 0); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java index d99223a..c1317cc 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java @@ -16,25 +16,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Byte.class) public class ByteTest extends TestCase { /** * @tests java.lang.Byte#valueOf(byte) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {byte.class} - ) public void test_valueOfB() { assertEquals(new Byte(Byte.MIN_VALUE), Byte.valueOf(Byte.MIN_VALUE)); assertEquals(new Byte(Byte.MAX_VALUE), Byte.valueOf(Byte.MAX_VALUE)); @@ -51,12 +39,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { assertEquals(1, new Byte((byte) 1).hashCode()); assertEquals(2, new Byte((byte) 2).hashCode()); @@ -67,12 +49,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#Byte(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Byte", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { assertEquals(new Byte((byte) 0), new Byte("0")); assertEquals(new Byte((byte) 1), new Byte("1")); @@ -106,12 +82,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#Byte(byte) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Byte", - args = {byte.class} - ) public void test_ConstructorB() { assertEquals(1, new Byte((byte) 1).byteValue()); assertEquals(2, new Byte((byte) 2).byteValue()); @@ -122,13 +92,7 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#byteValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "byteValue", - args = {} - ) - public void test_byteValue1() { + public void test_booleanValue() { assertEquals(1, new Byte((byte) 1).byteValue()); assertEquals(2, new Byte((byte) 2).byteValue()); assertEquals(0, new Byte((byte) 0).byteValue()); @@ -138,12 +102,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#equals(Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { assertEquals(new Byte((byte) 0), Byte.valueOf((byte) 0)); assertEquals(new Byte((byte) 1), Byte.valueOf((byte) 1)); @@ -158,12 +116,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { assertEquals("-1", new Byte((byte) -1).toString()); assertEquals("0", new Byte((byte) 0).toString()); @@ -174,12 +126,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#toString(byte) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {byte.class} - ) public void test_toStringB() { assertEquals("-1", Byte.toString((byte) -1)); assertEquals("0", Byte.toString((byte) 0)); @@ -190,12 +136,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#valueOf(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks only positive functionality.", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String() { assertEquals(new Byte((byte) 0), Byte.valueOf("0")); assertEquals(new Byte((byte) 1), Byte.valueOf("1")); @@ -229,12 +169,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#valueOf(String,int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check boundary values.", - method = "valueOf", - args = {java.lang.String.class, int.class} - ) public void test_valueOfLjava_lang_StringI() { assertEquals(new Byte((byte) 0), Byte.valueOf("0", 10)); assertEquals(new Byte((byte) 1), Byte.valueOf("1", 10)); @@ -272,12 +206,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#parseByte(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "parseByte", - args = {java.lang.String.class} - ) public void test_parseByteLjava_lang_String() { assertEquals(0, Byte.parseByte("0")); assertEquals(1, Byte.parseByte("1")); @@ -311,12 +239,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#parseByte(String,int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check boundary values.", - method = "parseByte", - args = {java.lang.String.class, int.class} - ) public void test_parseByteLjava_lang_StringI() { assertEquals(0, Byte.parseByte("0", 10)); assertEquals(1, Byte.parseByte("1", 10)); @@ -354,12 +276,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#decode(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "decode", - args = {java.lang.String.class} - ) public void test_decodeLjava_lang_String() { assertEquals(new Byte((byte) 0), Byte.decode("0")); assertEquals(new Byte((byte) 1), Byte.decode("1")); @@ -392,12 +308,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#doubleValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "No boundary verification.", - method = "doubleValue", - args = {} - ) public void test_doubleValue() { assertEquals(-1D, new Byte((byte) -1).doubleValue(), 0D); assertEquals(0D, new Byte((byte) 0).doubleValue(), 0D); @@ -407,12 +317,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#floatValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify boundary values.", - method = "floatValue", - args = {} - ) public void test_floatValue() { assertEquals(-1F, new Byte((byte) -1).floatValue(), 0F); assertEquals(0F, new Byte((byte) 0).floatValue(), 0F); @@ -422,12 +326,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#intValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "No boundary verification.", - method = "intValue", - args = {} - ) public void test_intValue() { assertEquals(-1, new Byte((byte) -1).intValue()); assertEquals(0, new Byte((byte) 0).intValue()); @@ -437,12 +335,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#longValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "No boundary verification.", - method = "longValue", - args = {} - ) public void test_longValue() { assertEquals(-1L, new Byte((byte) -1).longValue()); assertEquals(0L, new Byte((byte) 0).longValue()); @@ -452,12 +344,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#shortValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check boundary values.", - method = "shortValue", - args = {} - ) public void test_shortValue() { assertEquals(-1, new Byte((byte) -1).shortValue()); assertEquals(0, new Byte((byte) 0).shortValue()); @@ -467,12 +353,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#compareTo(Byte) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.lang.Byte.class} - ) public void test_compareToLjava_lang_Byte() { final Byte min = new Byte(Byte.MIN_VALUE); final Byte zero = new Byte((byte) 0); @@ -501,12 +381,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#Byte(byte) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary test.", - method = "Byte", - args = {byte.class} - ) public void test_ConstructorB2() { // Test for method java.lang.Byte(byte) @@ -517,12 +391,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#Byte(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Doesn't check empty string or null.", - method = "Byte", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String2() { // Test for method java.lang.Byte(java.lang.String) @@ -536,12 +404,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#byteValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "byteValue", - args = {} - ) public void test_byteValue() { // Test for method byte java.lang.Byte.byteValue() assertTrue("Returned incorrect byte value", @@ -551,12 +413,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#compareTo(java.lang.Byte) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.lang.Byte.class} - ) public void test_compareToLjava_lang_Byte2() { // Test for method int java.lang.Byte.compareTo(java.lang.Byte) assertTrue("Comparison failed", new Byte((byte) 1).compareTo(new Byte((byte) 2)) < 0); @@ -567,12 +423,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#decode(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "decode", - args = {java.lang.String.class} - ) public void test_decodeLjava_lang_String2() { // Test for method java.lang.Byte // java.lang.Byte.decode(java.lang.String) @@ -633,12 +483,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#doubleValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks boundary value.", - method = "doubleValue", - args = {} - ) public void test_doubleValue2() { assertEquals(127D, new Byte((byte) 127).doubleValue(), 0.0); } @@ -646,12 +490,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#equals(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Checks that negative value doesn't equal to positive.", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object2() { // Test for method boolean java.lang.Byte.equals(java.lang.Object) Byte b1 = new Byte((byte) 90); @@ -664,12 +502,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#floatValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "floatValue", - args = {} - ) public void test_floatValue2() { assertEquals(127F, new Byte((byte) 127).floatValue(), 0.0); } @@ -677,12 +509,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#hashCode() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary test.", - method = "hashCode", - args = {} - ) public void test_hashCode2() { // Test for method int java.lang.Byte.hashCode() assertEquals("Incorrect hash returned", 127, new Byte((byte) 127).hashCode()); @@ -691,12 +517,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#intValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "intValue", - args = {} - ) public void test_intValue2() { // Test for method int java.lang.Byte.intValue() assertEquals("Returned incorrect int value", 127, new Byte((byte) 127).intValue()); @@ -705,12 +525,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#longValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies boundary values.", - method = "longValue", - args = {} - ) public void test_longValue2() { // Test for method long java.lang.Byte.longValue() assertEquals("Returned incorrect long value", 127L, new Byte((byte) 127).longValue()); @@ -719,12 +533,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#parseByte(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary verification.", - method = "parseByte", - args = {java.lang.String.class} - ) public void test_parseByteLjava_lang_String2() { assertEquals((byte)127, Byte.parseByte("127")); assertEquals((byte)-128, Byte.parseByte("-128")); @@ -754,12 +562,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#parseByte(java.lang.String, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "parseByte", - args = {java.lang.String.class, int.class} - ) public void test_parseByteLjava_lang_StringI2() { // Test for method byte java.lang.Byte.parseByte(java.lang.String, int) byte b = Byte.parseByte("127", 10); @@ -811,12 +613,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#shortValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "shortValue", - args = {} - ) public void test_shortValue2() { assertEquals((short)127, new Byte((byte)127).shortValue()); } @@ -824,12 +620,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary test.", - method = "toString", - args = {} - ) public void test_toString2() { assertEquals("Returned incorrect String", "127", new Byte((byte) 127).toString()); assertEquals("Returned incorrect String", "-127", new Byte((byte) -127).toString()); @@ -839,12 +629,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#toString(byte) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary test.", - method = "toString", - args = {byte.class} - ) public void test_toStringB2() { assertEquals("Returned incorrect String", "127", Byte.toString((byte) 127)); assertEquals("Returned incorrect String", "-127", Byte.toString((byte) -127)); @@ -854,12 +638,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#valueOf(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Boundary test.", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String2() { assertEquals("Returned incorrect byte", 0, Byte.valueOf("0").byteValue()); assertEquals("Returned incorrect byte", 127, Byte.valueOf("127").byteValue()); @@ -876,12 +654,6 @@ public class ByteTest extends TestCase { /** * @tests java.lang.Byte#valueOf(java.lang.String, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Boundary test.", - method = "valueOf", - args = {java.lang.String.class, int.class} - ) public void test_valueOfLjava_lang_StringI2() { assertEquals("Returned incorrect byte", 10, Byte.valueOf("A", 16).byteValue()); assertEquals("Returned incorrect byte", 127, Byte.valueOf("127", 10).byteValue()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java index 9a10cc4..a81775e 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java @@ -16,23 +16,10 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Character.class) public class CharacterImplTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {char.class} - ) public void test_valueOfC() { // test the cache range // BEGIN android-changed diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java index f99fb86..a44a31d 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java @@ -92,8 +92,4 @@ public class Character_SubsetTest extends TestCase { assertFalse(subset1.hashCode() == subset2.hashCode()); assertFalse(subset1.hashCode() == subset3.hashCode()); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(Character_SubsetTest.class); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java index 0766f28..cd485f2 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java @@ -16,22 +16,10 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Character.UnicodeBlock.class) public class Character_UnicodeBlockTest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "of", - args = {char.class} - ) public void test_ofC() { assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char)0x0)); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char)0x7f)); @@ -270,12 +258,6 @@ public class Character_UnicodeBlockTest extends TestCase { assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char)0xfff0)); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char)0xffff)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check exception.", - method = "of", - args = {int.class} - ) public void test_ofI() { assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x0)); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x7f)); @@ -578,12 +560,7 @@ public class Character_UnicodeBlockTest extends TestCase { assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x100000)); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x10ffff)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks IllegalArgumentException.", - method = "of", - args = {int.class} - ) + public void test_ofIExceptions() { try { Character.UnicodeBlock.of(Character.MAX_CODE_POINT + 1); @@ -591,12 +568,7 @@ public class Character_UnicodeBlockTest extends TestCase { } catch(IllegalArgumentException e) { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check null.", - method = "forName", - args = {java.lang.String.class} - ) + @SuppressWarnings("deprecation") public void test_forNameLjava_lang_String() { assertEquals(Character.UnicodeBlock.SURROGATES_AREA, Character.UnicodeBlock.forName("SURROGATES_AREA")); @@ -891,12 +863,6 @@ public class Character_UnicodeBlockTest extends TestCase { assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-B")); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "forName", - args = {java.lang.String.class} - ) public void test_forNameLjava_lang_StringExceptions() { try { Character.UnicodeBlock.forName(null); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java index 1e61f87..bc56cef 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java @@ -17,44 +17,26 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(ClassCastException.class) public class ClassCastExceptionTest extends TestCase { - /** - * @tests java.lang.ClassCastException#ClassCastException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassCastException", - args = {} - ) - public void test_Constructor() { + /** + * @tests java.lang.ClassCastException#ClassCastException() + */ + public void test_Constructor() { ClassCastException e = new ClassCastException(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); - } + } - /** - * @tests java.lang.ClassCastException#ClassCastException(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassCastException", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { + /** + * @tests java.lang.ClassCastException#ClassCastException(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { ClassCastException e = new ClassCastException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java index 7acf714..b062a8c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java @@ -1,51 +1,39 @@ -/* - * 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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; +import junit.framework.TestCase; // android-changed -@TestTargetClass(ClassCircularityError.class) -public class ClassCircularityErrorTest extends TestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassCircularityError", - args = {} - ) +public class ClassCircularityErrorTest extends TestCase { // android-changed + // Thrown when a circularity has been detected while initializing a class. + /** + * @tests java.lang.ClassCircularityError#ClassCircularityError() + */ public void test_ClassCircularityError() { - ClassCircularityError cce = new ClassCircularityError(); - assertNull(cce.getMessage()); + new ClassCircularityError(); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassCircularityError", - args = {java.lang.String.class} - ) - public void test_ClassCircularityError_String() { - String message = "Test message"; - ClassCircularityError cce = new ClassCircularityError(message); - assertEquals(message, cce.getMessage()); - } + + /** + * @tests java.lang.ClassCircularityError#ClassCircularityError(java.lang.String) + */ + public void test_ClassCircularityError_LString() { + ClassCircularityError e = new ClassCircularityError( + "Some Error message"); + assertEquals("Wrong message", "Some Error message", e.getMessage()); + } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java index 0aeef9b..2fd9aac 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java @@ -1,51 +1,43 @@ -/* - * 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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import junit.framework.TestCase; // android-changed -import junit.framework.TestCase; +public class ClassFormatErrorTest extends TestCase { // android-changed + /** + * Thrown when the Java Virtual Machine attempts to read a class file and + * determines that the file is malformed or otherwise cannot be interpreted + * as a class file. + */ -@TestTargetClass(ClassFormatError.class) -public class ClassFormatErrorTest extends TestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassFormatError", - args = {} - ) + /** + * @tests java.lang.ClassFormatError#ClassFormatError() + */ public void test_ClassFormatError() { - ClassFormatError cfe = new ClassFormatError(); - assertNull(cfe.getMessage()); + new ClassFormatError(); + } + + /** + * @tests java.lang.ClassFormatError#ClassFormatError(java.lang.String) + */ + public void test_ClassFormatError_LString() { + ClassFormatError e = new ClassFormatError("Some Error Message"); + assertEquals("Wrong message", "Some Error Message", e.getMessage()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassFormatError", - args = {java.lang.String.class} - ) - public void test_ClassFormatError_String() { - String message = "Test message"; - ClassFormatError cfe = new ClassFormatError(message); - assertEquals(message, cfe.getMessage()); - } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java index 43a73ed..22f49bb 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java @@ -17,304 +17,41 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.BrokenTest; -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.File; -import java.io.FileInputStream; -import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.ByteBuffer; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Policy; import java.security.ProtectionDomain; -import java.util.Enumeration; -import java.util.NoSuchElementException; - -@TestTargetClass(ClassLoader.class) -public class ClassLoaderTest extends TestCase { - - private static final String SYSTEM_RESOURCE_PATH = "META-INF/MANIFEST.MF"; - public static volatile int flag; +import java.security.SecurityPermission; - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassLoader", - args = {} - ) - public void test_ClassLoader() { - PublicClassLoader pcl = new PublicClassLoader(); - SecurityManager sm = new SecurityManager() { - RuntimePermission rp = new RuntimePermission("getProtectionDomain"); - - public void checkCreateClassLoader() { - throw new SecurityException(); - } - - public void checkPermission(Permission perm) { - if (perm.equals(rp)) { - throw new SecurityException(); - } - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new PublicClassLoader(); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldSm); - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassLoader", - args = {java.lang.ClassLoader.class} - ) - @BrokenTest("Infinite loop in classloader. Actually a known failure.") - public void test_ClassLoaderLClassLoader() { - PublicClassLoader pcl = new PublicClassLoader( - ClassLoader.getSystemClassLoader()); - assertEquals(ClassLoader.getSystemClassLoader(), pcl.getParent()); - - SecurityManager sm = new SecurityManager() { - RuntimePermission rp = new RuntimePermission("getProtectionDomain"); - - public void checkCreateClassLoader() { - throw new SecurityException(); - } - - public void checkPermission(Permission perm) { - if (perm.equals(rp)) { - throw new SecurityException(); - } - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new PublicClassLoader(ClassLoader.getSystemClassLoader()); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldSm); - } - } - - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "", - method = "clearAssertionStatus", - args = {} - ) - @KnownFailure("Android doesn't support assertions to be activated " + - "through the api") - public void test_clearAssertionStatus() { - String className = getClass().getPackage().getName() + ".TestAssertions"; - String className1 = getClass().getPackage().getName() + ".TestAssertions1"; - ClassLoader cl = getClass().getClassLoader(); - cl.setClassAssertionStatus("TestAssertions", true); - cl.setDefaultAssertionStatus(true); - try { - - Class clazz = cl.loadClass(className); - - TestAssertions ta = (TestAssertions) clazz.newInstance(); - try { - ta.test(); - fail("AssertionError should be thrown."); - } catch(AssertionError ae) { - //expected - } - cl.clearAssertionStatus(); - clazz = cl.loadClass(className1); - - TestAssertions1 ta1 = (TestAssertions1) clazz.newInstance(); - try { - ta1.test(); - } catch(AssertionError ae) { - fail("AssertionError should not be thrown."); - } - - } catch(Exception cnfe) { - fail("Unexpected exception: " + cnfe.toString()); - } - } +import junit.framework.TestCase; - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This method is not supported. " + - "UnsupportedOperationException should be thrown.", - method = "defineClass", - args = {byte[].class, int.class, int.class} - ) - @AndroidOnly("define methods re not supported on Android. " + - "UnsupportedOperationException should be thrown.") - public void test_defineClassLbyteArrayLintLint() throws Exception { +public class ClassLoaderTest extends TestCase { - try { - Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_1); - //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName()); - fail("UnsupportedOperationException was not thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_1); - fail("IndexOutOfBoundsException is not thrown."); - } catch(IndexOutOfBoundsException ioobe) { - fail("UnsupportedOperationException should be thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This method is not supported. UnsupportedOperationException should be thrown.", - method = "defineClass", - args = {java.lang.String.class, byte[].class, int.class, int.class, java.security.ProtectionDomain.class} - ) - @AndroidOnly("define methods re not supported on Android. " + - "UnsupportedOperationException should be thrown.") - public void test_defineClassLjava_lang_StringLbyteArrayLintLintLProtectionDomain() - throws Exception { - - try { - Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_2); - //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName()); - //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain()); - fail("UnsupportedOperationException was not thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_2); - fail("IndexOutOfBoundsException is not thrown."); - } catch(IndexOutOfBoundsException ioobe) { - fail("UnsupportedOperationException should be thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - /*try { - ErrorLdr loader = new ErrorLdr(); - - try { - loader.define("WrongFormatClass", Ldr.TEST_CASE_DEFINE_2); - fail("ClassFormatError should be thrown."); - } catch (ClassFormatError le) { - //expected - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - loader.defineWrongName("TestClass", 0); - fail("NoClassDefFoundError should be thrown."); - } catch (NoClassDefFoundError ncdfe) { - //expected - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - Class<?> clazz = loader.defineNullDomain("TestClass", 0); - assertEquals(getClass().getProtectionDomain(), - clazz.getProtectionDomain()); - } catch(UnsupportedOperationException uoe) { - //expected - } - - } catch(Exception e) { - fail("Unexpected exception was thrown: " + e.toString()); - } - */ - } + public static volatile int flag; - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This method is not supported. UnsupportedOperationException should be thrown.", - method = "defineClass", - args = {java.lang.String.class, java.nio.ByteBuffer.class, java.security.ProtectionDomain.class} - ) - @AndroidOnly("define methods re not supported on Android. " + - "UnsupportedOperationException should be thrown.") - public void test_defineClassLjava_lang_StringLByteBufferLProtectionDomain() { - - try { - try { - Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_3); - //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName()); - //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain()); - fail("UnsupportedOperationException was not thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_3); - fail("IndexOutOfBoundsException is not thrown."); - } catch(IndexOutOfBoundsException ioobe) { - fail("UnsupportedOperationException should be thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - } catch(Exception e) { - fail("Unexpected exception was thrown: " + e.toString()); - } - } - /** * Tests that Classloader.defineClass() assigns appropriate * default domains to the defined classes. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This method is not supported. " + - "UnsupportedOperationException should be thrown.", - method = "defineClass", - args = {java.lang.String.class, byte[].class, int.class, int.class} - ) - @AndroidOnly("define methods re not supported on Android. " + - "UnsupportedOperationException should be thrown.") public void test_defineClass_defaultDomain() throws Exception { + // Regression for HARMONY-765 + DynamicPolicy plc = new DynamicPolicy(); + Policy back = Policy.getPolicy(); try { - Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_0); - fail("UnsupportedOperationException was not thrown."); - } catch(UnsupportedOperationException uoe) { - //expected - } - - try { - new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_0); - fail("IndexOutOfBoundsException is not thrown."); - } catch(IndexOutOfBoundsException ioobe) { - fail("UnsupportedOperationException should be thrown."); - } catch(UnsupportedOperationException uoe) { - //expected + Policy.setPolicy(plc); + + Class<?> a = new Ldr().define(); + + Permission p = new SecurityPermission("abc"); + assertFalse("impossible! misconfiguration?", a.getProtectionDomain().implies(p)); + + plc.pc = p.newPermissionCollection(); + plc.pc.add(p); + assertTrue("default domain is not dynamic", a.getProtectionDomain().implies(p)); + } finally { + Policy.setPolicy(back); } } @@ -354,7 +91,8 @@ public class ClassLoaderTest extends TestCase { 0, 1, 0, 1, 0, 8, 0, 0, 0, 2, 0, 9 }; - protected Class findClass(String name) throws ClassNotFoundException { + @Override + protected Class<?> findClass(String name) throws ClassNotFoundException { try { while (flag != 2) { synchronized (lock) { @@ -366,21 +104,21 @@ public class ClassLoaderTest extends TestCase { if (name.equals("TestClass")) { numFindClassCalled++; return defineClass(null, classData, 0, classData.length); - } else { - throw new ClassNotFoundException("Class " + name + " not found."); } + throw new ClassNotFoundException("Class " + name + " not found."); } } static class SyncLoadTestThread extends Thread { volatile boolean started; ClassLoader cl; - Class cls; + Class<?> cls; SyncLoadTestThread(ClassLoader cl) { this.cl = cl; } + @Override public void run() { try { started = true; @@ -397,14 +135,6 @@ public class ClassLoaderTest extends TestCase { * and the same classloader. It is expected that both threads succeed but * class must be defined just once. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test.", - method = "loadClass", - args = {java.lang.String.class} - ) - @BrokenTest("Defining classes not supported, unfortunately the test appears" - + " to succeed, which is not true, so marking it broken.") public void test_loadClass_concurrentLoad() throws Exception { Object lock = new Object(); @@ -430,109 +160,13 @@ public class ClassLoaderTest extends TestCase { assertEquals("Both threads tried to define class", 1, cl.numFindClassCalled); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "loadClass", - args = {java.lang.String.class} - ) - public void test_loadClassLjava_lang_String() { - - String [] classNames = {"org.apache.harmony.luni.tests.java.lang.TestClass1", - "org.apache.harmony.luni.tests.java.lang.TestClass3", - "org.apache.harmony.luni.tests.java.lang.A"}; - - ClassLoader cl = getClass().getClassLoader(); - for(String str:classNames) { - try { - Class<?> clazz = cl.loadClass(str); - assertNotNull(clazz); - assertEquals(str, clazz.getName()); - if(str.endsWith("A")) - clazz.newInstance(); - if(str.endsWith("TestClass1")) { - try { - clazz.newInstance(); - fail("ExceptionInInitializerError was not thrown."); - } catch(ExceptionInInitializerError eiine) { - //expected - } - } - if(str.endsWith("TestClass3")) { - try { - clazz.newInstance(); - fail("IllegalAccessException was not thrown."); - } catch(IllegalAccessException ie) { - //expected - } - } - } catch (ClassNotFoundException e) { - fail("ClassNotFoundException was thrown." + e.getMessage()); - } catch (InstantiationException e) { - fail("InstantiationException was thrown."); - } catch (IllegalAccessException e) { - fail("IllegalAccessException was thrown."); - } - } - - try { - Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass4"); - fail("ClassNotFoundException was not thrown."); - } catch (ClassNotFoundException e) { - //expected - } - - try { - Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass5"); - fail("ClassNotFoundException was not thrown."); - } catch (ClassNotFoundException e) { - //expected - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "loadClass", - args = {java.lang.String.class, boolean.class} - ) - public void test_loadClassLjava_lang_StringLZ() throws - IllegalAccessException, InstantiationException, - ClassNotFoundException { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - String className = getClass().getPackage().getName() + ".A"; - - Class<?> clazz = pcl.loadClass(className, false); - assertEquals(className, clazz.getName()); - assertNotNull(clazz.newInstance()); - - clazz = pcl.loadClass(className, true); - assertEquals(className, clazz.getName()); - assertNotNull(clazz.newInstance()); - - try { - clazz = pcl.loadClass("UnknownClass", false); - assertEquals("TestClass", clazz.getName()); - fail("ClassNotFoundException was not thrown."); - } catch (ClassNotFoundException e) { - //expected - } - } - /** * @tests java.lang.ClassLoader#getResource(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResource", - args = {java.lang.String.class} - ) public void test_getResourceLjava_lang_String() { // Test for method java.net.URL // java.lang.ClassLoader.getResource(java.lang.String) - java.net.URL u = getClass().getClassLoader().getResource("hyts_Foo.c"); + java.net.URL u = ClassLoader.getSystemClassLoader().getResource("hyts_Foo.c"); assertNotNull("Unable to find resource", u); java.io.InputStream is = null; try { @@ -542,577 +176,61 @@ public class ClassLoaderTest extends TestCase { } catch (java.io.IOException e) { fail("IOException getting stream for resource : " + e.getMessage()); } - - - - assertNull(getClass().getClassLoader() - .getResource("not.found.resource")); } /** * @tests java.lang.ClassLoader#getResourceAsStream(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResourceAsStream", - args = {java.lang.String.class} - ) public void test_getResourceAsStreamLjava_lang_String() { // Test for method java.io.InputStream // java.lang.ClassLoader.getResourceAsStream(java.lang.String) // Need better test... java.io.InputStream is = null; - assertNotNull("Failed to find resource: HelloWorld.txt", - (is = getClass().getClassLoader() - .getResourceAsStream("HelloWorld.txt"))); - - byte [] array = new byte[13]; - try { - is.read(array); - } catch(IOException ioe) { - fail("IOException was not thrown."); - } finally { - try { - is.close(); - } catch(IOException ioe) {} - } - - assertEquals("Hello, World.", new String(array)); - - + assertNotNull("Failed to find resource: hyts_Foo.c", (is = ClassLoader + .getSystemClassLoader().getResourceAsStream("hyts_Foo.c"))); try { is.close(); } catch (java.io.IOException e) { fail("Exception during getResourceAsStream: " + e.toString()); } - - assertNull(getClass().getClassLoader(). - getResourceAsStream("unknownResource.txt")); } /** * @tests java.lang.ClassLoader#getSystemClassLoader() */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "", - method = "getSystemClassLoader", - args = {} - ) public void test_getSystemClassLoader() { // Test for method java.lang.ClassLoader // java.lang.ClassLoader.getSystemClassLoader() ClassLoader cl = ClassLoader.getSystemClassLoader(); - - java.io.InputStream is = cl.getResourceAsStream(SYSTEM_RESOURCE_PATH); + java.io.InputStream is = cl.getResourceAsStream("hyts_Foo.c"); assertNotNull("Failed to find resource from system classpath", is); try { is.close(); } catch (java.io.IOException e) { } - SecurityManager sm = new SecurityManager() { - public void checkPermission(Permission perm) { - if(perm.getName().equals("getClassLoader")) { - throw new SecurityException(); - } - } - }; - - SecurityManager oldManager = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - ClassLoader.getSystemClassLoader(); - } catch(SecurityException se) { - //expected - } finally { - System.setSecurityManager(oldManager); - } -/* - * // java.lang.Error is not thrown on RI, but it's specified. - * - * String keyProp = "java.system.class.loader"; - * String oldProp = System.getProperty(keyProp); - * System.setProperty(keyProp, "java.test.UnknownClassLoader"); - * boolean isFailed = false; - * try { - * ClassLoader.getSystemClassLoader(); - * isFailed = true; - * } catch(java.lang.Error e) { - * //expected - * } finally { - * if(oldProp == null) { - * System.clearProperty(keyProp); - * } else { - * System.setProperty(keyProp, oldProp); - * } - * } - * assertFalse("java.lang.Error was not thrown.", isFailed); - */ } /** * @tests java.lang.ClassLoader#getSystemResource(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSystemResource", - args = {java.lang.String.class} - ) - @AndroidOnly("The RI doesn't have a classes.dex as resource in the " - + "core-tests.jar. Also on Android this file is the only one " - + "that is sure to exist.") - public void test_getSystemResourceLjava_lang_String() throws IOException { + public void test_getSystemResourceLjava_lang_String() { + // Test for method java.net.URL // java.lang.ClassLoader.getSystemResource(java.lang.String) // Need better test... - - - //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" + - // getClass().getSimpleName() + ".class"; - //assertNotNull("Failed to find resource: " + classResource, - // ClassLoader.getSystemResource(classResource)); - - URL url = getClass().getClassLoader().getSystemResource(SYSTEM_RESOURCE_PATH); - assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), url); - java.io.InputStream is = url.openStream(); - - assertTrue("System resource not found", is.available() > 0); - assertNull("Doesn't return null for unknown resource.", - getClass().getClassLoader().getSystemResource("NotFound")); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSystemResourceAsStream", - args = {java.lang.String.class} - ) - @AndroidOnly("The RI doesn't have a classes.dex as resource in the " - + "core-tests.jar. Also on Android this file is the only one " - + "that is sure to exist.") - public void test_getSystemResourceAsStreamLjava_lang_String() - throws IOException { - - //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" + - // getClass().getSimpleName() + ".class"; - //assertNotNull("Failed to find resource: " + classResource, - // ClassLoader.getSystemResourceAsStream(classResource)); - - java.io.InputStream is = getClass().getClassLoader() - .getSystemResourceAsStream(SYSTEM_RESOURCE_PATH); - assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), is); - - assertTrue("System resource not found", is.available() > 0); - - assertNull(ClassLoader.getSystemResourceAsStream("NotFoundResource")); + assertNotNull("Failed to find resource: hyts_Foo.c", ClassLoader + .getSystemResource("hyts_Foo.c")); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSystemResources", - args = {java.lang.String.class} - ) - @AndroidOnly("The RI doesn't have a classes.dex as resource in the " - + "core-tests.jar. Also on Android this file is the only one " - + "that is sure to exist.") - public void test_getSystemResources() { - - String textResource = SYSTEM_RESOURCE_PATH; - - try { - Enumeration<URL> urls = ClassLoader.getSystemResources(textResource); - assertNotNull(urls); - assertTrue(urls.nextElement().getPath().endsWith(textResource)); - while (urls.hasMoreElements()) { - assertNotNull(urls.nextElement()); - } - try { - urls.nextElement(); - fail("NoSuchElementException was not thrown."); - } catch(NoSuchElementException nse) { - //expected - } - } catch(IOException ioe) { - fail("IOException was thrown."); - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPackage", - args = {java.lang.String.class} - ) - @KnownFailure("PackageClassLoader.getPackage returns null.") - public void test_getPackageLjava_lang_String() { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - - String [] packageProperties = { "test.package", "title", "1.0", - "Vendor", "Title", "1.1", "implementation vendor"}; - - URL url = null; - try { - url = new URL("file:"); - } catch (MalformedURLException e) { - fail("MalformedURLException was thrown."); - } - pcl.definePackage(packageProperties[0], - packageProperties[1], - packageProperties[2], - packageProperties[3], - packageProperties[4], - packageProperties[5], - packageProperties[6], - url); - - assertNotNull(pcl.getPackage(packageProperties[0])); - - assertEquals("should define current package", getClass().getPackage(), - pcl.getPackage(getClass().getPackage().getName())); - - assertNull(pcl.getPackage("not.found.package")); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPackages", - args = {} - ) - @KnownFailure("The package canot be found. Seems like the cache is not " + - "shared between the class loaders. But this test seems to " + - "expect exactly that. this tests works on the RI.") - public void test_getPackages() { - - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - - String [] packageProperties = { "test.package", "title", "1.0", - "Vendor", "Title", "1.1", "implementation vendor"}; - - URL url = null; - try { - url = new URL("file:"); - } catch (MalformedURLException e) { - fail("MalformedURLException was thrown."); - } - pcl.definePackage(packageProperties[0], - packageProperties[1], - packageProperties[2], - packageProperties[3], - packageProperties[4], - packageProperties[5], - packageProperties[6], - url); - - Package [] packages = pcl.getPackages(); - assertTrue(packages.length != 0); - - pcl = new PackageClassLoader(getClass().getClassLoader()); - packages = pcl.getPackages(); - assertNotNull(packages); - - boolean isThisFound = false; - for(Package p:packages) { - if(p.equals(getClass().getPackage())) { - isThisFound = true; - } - } - assertTrue(isThisFound); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getParent", - args = {} - ) - public void test_getParent() { - PublicClassLoader pcl = new PublicClassLoader(); - assertNotNull(pcl.getParent()); - ClassLoader cl = getClass().getClassLoader().getParent(); - assertNotNull(cl); - - SecurityManager sm = new SecurityManager() { - - final String perName = "getClassLoader"; - - public void checkPermission(Permission perm) { - if (perm.getName().equals(perName)) { - throw new SecurityException(); - } - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - getClass().getClassLoader().getParent(); - fail("Should throw SecurityException"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldSm); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResources", - args = {java.lang.String.class} - ) - public void test_getResourcesLjava_lang_String() { - Enumeration<java.net.URL> urls = null; - FileInputStream fis = null; - try { - urls = getClass().getClassLoader().getResources("HelloWorld.txt"); - URL url = urls.nextElement(); - fis = new FileInputStream(url.getFile()); - byte [] array = new byte[13]; - fis.read(array); - assertEquals("Hello, World.", new String(array)); - } catch (IOException e) { - - } finally { - try { - fis.close(); - } catch(Exception e) {} - } - - assertNull(getClass().getClassLoader() - .getResource("not.found.resource")); - - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "definePackage", - args = {java.lang.String.class, java.lang.String.class, - java.lang.String.class, java.lang.String.class, - java.lang.String.class, java.lang.String.class, - java.lang.String.class, java.net.URL.class } - ) - public void test_definePackage() { - - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - - String [] packageProperties = { "test.package", "title", "1.0", - "Vendor", "Title", "1.1", "implementation vendor"}; - - URL url = null; - try { - url = new URL("file:"); - } catch (MalformedURLException e) { - fail("MalformedURLException was thrown."); - } - pcl.definePackage(packageProperties[0], - packageProperties[1], - packageProperties[2], - packageProperties[3], - packageProperties[4], - packageProperties[5], - packageProperties[6], - url); - - Package pack = pcl.getPackage(packageProperties[0]); - assertEquals(packageProperties[1], pack.getSpecificationTitle()); - assertEquals(packageProperties[2], pack.getSpecificationVersion()); - assertEquals(packageProperties[3], pack.getSpecificationVendor()); - assertEquals(packageProperties[4], pack.getImplementationTitle()); - assertEquals(packageProperties[5], pack.getImplementationVersion()); - assertEquals(packageProperties[6], pack.getImplementationVendor()); - assertTrue(pack.isSealed(url)); - assertTrue(pack.isSealed()); - - try { - pcl.definePackage(packageProperties[0], - packageProperties[1], - packageProperties[2], - packageProperties[3], - packageProperties[4], - packageProperties[5], - packageProperties[6], - null); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - pcl.definePackage("test.package.test", null, null, null, null, - null, null, null); - pack = pcl.getPackage("test.package.test"); - assertNull(pack.getSpecificationTitle()); - assertNull(pack.getSpecificationVersion()); - assertNull(pack.getSpecificationVendor()); - assertNull(pack.getImplementationTitle()); - assertNull(pack.getImplementationVersion()); - assertNull(pack.getImplementationVendor()); - assertFalse(pack.isSealed()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findClass", - args = {java.lang.String.class} - ) - @AndroidOnly("findClass method throws ClassNotFoundException exception.") - public void test_findClass(){ - - try { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - pcl.findClass(getClass().getPackage().getName() + ".A"); - fail("ClassNotFoundException was not thrown."); - } catch(ClassNotFoundException cnfe) { - //expected - } - - try { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - pcl.findClass("TestClass"); - fail("ClassNotFoundException was not thrown."); - } catch(ClassNotFoundException cnfe) { - //expected - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findLibrary", - args = {java.lang.String.class} - ) - @AndroidOnly("findLibrary method is not supported, it returns null.") - public void test_findLibrary() { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - assertNull(pcl.findLibrary("libjvm.so")); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findResource", - args = {java.lang.String.class} - ) - @AndroidOnly("findResource method is not supported, it returns null.") - public void test_findResourceLjava_lang_String() { - assertNull(new PackageClassLoader( - getClass().getClassLoader()).findResource("hyts_Foo.c")); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findResources", - args = {java.lang.String.class} - ) - @AndroidOnly("findResources method is not supported, it returns " + - "empty Enumeration.") - public void test_findResourcesLjava_lang_String() throws IOException { - assertFalse(new PackageClassLoader( - getClass().getClassLoader()).findResources("hyts_Foo.c"). - hasMoreElements()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findSystemClass", - args = {java.lang.String.class} - ) - public void test_findSystemClass() { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - - Class [] classes = { String.class, Integer.class, Object.class, - Object[].class }; - - for(Class clazz:classes) { - try { - String className = clazz.getName(); - assertEquals(clazz, pcl.findSystemClazz(className)); - } catch(ClassNotFoundException cnfe) { - fail("ClassNotFoundException was thrown: " + cnfe.getMessage()); - } - } - try { - pcl.findSystemClazz("unknownClass"); - fail("ClassNotFoundException was not thrown."); - } catch(ClassNotFoundException cnfe) { - //expected - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "findLoadedClass", - args = {java.lang.String.class } - ) - public void test_findLoadedClass() { - PackageClassLoader pcl = new PackageClassLoader( - getClass().getClassLoader()); - - Class [] classes = { A.class, PublicTestClass.class, - TestAnnotation.class, TestClass1.class }; - - for(Class clazz:classes) { - String className = clazz.getName(); - assertNull(pcl.findLoadedClazz(className)); - } - - assertNull(pcl.findLoadedClazz("unknownClass")); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "setClassAssertionStatus is not supported.", - method = "setClassAssertionStatus", - args = {java.lang.String.class, boolean.class} - ), - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "setDefaultAssertionStatus is not supported.", - method = "setDefaultAssertionStatus", - args = {boolean.class} - ), - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "setPackageAssertionStatus is not supported.", - method = "setPackageAssertionStatus", - args = {java.lang.String.class, boolean.class} - ), - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "resolveClass is not supported.", - method = "resolveClass", - args = {java.lang.Class.class} - ), - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "setSigners is not supported.", - method = "setSigners", - args = {java.lang.Class.class, java.lang.Object[].class} - ) - }) - public void test_notSupported() { - getClass().getClassLoader().setClassAssertionStatus(getName(), true); - getClass().getClassLoader().setDefaultAssertionStatus(true); - getClass().getClassLoader().setPackageAssertionStatus( - getClass().getPackage().getName(), true); - } + //Regression Test for JIRA-2047 + public void test_getResourceAsStream_withSharpChar() throws Exception { + InputStream in = this.getClass().getClassLoader().getResourceAsStream( + ClassTest.FILENAME); + assertNotNull(in); + in.close(); + } } class DynamicPolicy extends Policy { @@ -1138,127 +256,14 @@ class A { } class Ldr extends ClassLoader { - - /* - * These bytes are the content of the file - * /org/apache/harmony/luni/tests/java/lang/A.class - */ - byte[] classBytes = new byte[] { -54, -2, -70, -66, 0, 0, 0, 49, 0, 16, 7, - 0, 2, 1, 0, 41, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, - 104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116, - 101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, - 65, 7, 0, 4, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, - 79, 98, 106, 101, 99, 116, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, - 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 10, 0, 3, 0, 9, 12, 0, - 5, 0, 6, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, - 84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114, - 105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105, - 115, 1, 0, 43, 76, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, - 104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116, - 101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, - 65, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, - 0, 20, 67, 108, 97, 115, 115, 76, 111, 97, 100, 101, 114, 84, 101, - 115, 116, 46, 106, 97, 118, 97, 0, 32, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1, - 0, 0, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 47, 0, 1, 0, 1, 0, 0, 0, 5, - 42, -73, 0, 8, -79, 0, 0, 0, 2, 0, 10, 0, 0, 0, 6, 0, 1, 0, 0, 4, - -128, 0, 11, 0, 0, 0, 12, 0, 1, 0, 0, 0, 5, 0, 12, 0, 13, 0, 0, 0, - 1, 0, 14, 0, 0, 0, 2, 0, 15 }; - - public static final int TEST_CASE_DEFINE_0 = 0; - public static final int TEST_CASE_DEFINE_1 = 1; - public static final int TEST_CASE_DEFINE_2 = 2; - public static final int TEST_CASE_DEFINE_3 = 3; - @SuppressWarnings("deprecation") - public Class<?> define(int len, int testCase) throws Exception { - - if(len < 0) len = classBytes.length; - Class<?> clazz = null; - String className = "org.apache.harmony.luni.tests.java.lang.A"; - switch(testCase) { - case TEST_CASE_DEFINE_0: - clazz = defineClass(className, classBytes, 0, len); - break; - case TEST_CASE_DEFINE_1: - clazz = defineClass(classBytes, 0, len); - break; - case TEST_CASE_DEFINE_2: - clazz = defineClass(className, classBytes, 0, len, - getClass().getProtectionDomain()); - break; - case TEST_CASE_DEFINE_3: - ByteBuffer bb = ByteBuffer.wrap(classBytes); - clazz = defineClass(className, - bb, getClass().getProtectionDomain()); - break; - } - return clazz; + public Class<?> define() throws Exception { + Package p = getClass().getPackage(); + // Class loader paths use '/' character as separator + String path = p == null ? "" : p.getName().replace('.', '/') + '/'; + InputStream is = getResourceAsStream(path + "A.class"); + byte[] buf = new byte[512]; + int len = is.read(buf); + return defineClass(buf, 0, len); } - - public Class<?> define(int testCase) throws Exception { - return define(-1, testCase); - } - } - -class PackageClassLoader extends ClassLoader { - public PackageClassLoader() { - super(); - } - - public PackageClassLoader(ClassLoader parent) { - super(parent); - } - - public Package definePackage(String name, - String specTitle, - String specVersion, - String specVendor, - String implTitle, - String implVersion, - String implVendor, - URL sealBase) - throws IllegalArgumentException { - return super.definePackage(name, specTitle, specVersion, - specVendor, implTitle, implVersion, implVendor, sealBase); - } - - public Package getPackage(String name) { - return super.getPackage(name); - } - - public Package[] getPackages() { - return super.getPackages(); - } - - public Class<?> findClass(String name) - throws ClassNotFoundException { - return super.findClass(name); - } - - public String findLibrary(String libname) { - return super.findLibrary(libname); - } - - public Class<?> loadClass(String name, boolean resolve) - throws ClassNotFoundException { - return super.loadClass(name, resolve); - } - - public URL findResource(String name) { - return super.findResource(name); - } - - public Enumeration<URL> findResources(String resName) - throws IOException { - return super.findResources(resName); - } - - public Class<?> findSystemClazz(String name) throws ClassNotFoundException { - return super.findSystemClass(name); - } - - public Class<?> findLoadedClazz(String name) { - return super.findLoadedClass(name); - } -} diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java index b8051cc..3a26a79 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java @@ -17,114 +17,44 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.io.IOException; import junit.framework.TestCase; -@TestTargetClass(ClassNotFoundException.class) public class ClassNotFoundExceptionTest extends TestCase { - /** - * @tests java.lang.ClassNotFoundException#ClassNotFoundException() + * Thrown when an application tries to load in a class through its string + * name using the forName method in class Class. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassNotFoundException", - args = {} - ) - public void test_Constructor() { + + /** + * @tests java.lang.ClassNotFoundException#ClassNotFoundException() + */ + public void test_Constructor() { ClassNotFoundException e = new ClassNotFoundException(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); - } + } - /** - * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassNotFoundException", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { + /** + * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { ClassNotFoundException e = new ClassNotFoundException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); + } + + /** + * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String, java.lang.Throwable) + */ + public void test_ClassNotFoundException_LString_LThrowable() { + IOException in = new IOException(); + ClassNotFoundException e = new ClassNotFoundException("SomeMessage", in); + assertEquals("Wrong Exception", in, e.getException()); + assertEquals("Wrong message", "SomeMessage", e.getMessage()); + assertEquals("Wrong cause", in, e.getCause()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ClassNotFoundException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) - public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() { - String testMessage = "Test Message"; - Throwable thr = new Throwable(); - ClassNotFoundException cnfe = new ClassNotFoundException(testMessage, thr); - assertEquals(testMessage, cnfe.getMessage()); - assertEquals(thr, cnfe.getException()); - - cnfe = new ClassNotFoundException(null, thr); - assertNull(cnfe.getMessage()); - assertEquals(thr, cnfe.getException()); - - cnfe = new ClassNotFoundException(testMessage, null); - assertNull(cnfe.getException()); - assertEquals(testMessage, cnfe.getMessage()); - - cnfe = new ClassNotFoundException(null, null); - assertNull(cnfe.getMessage()); - assertNull(cnfe.getException()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCause", - args = {} - ) - public void test_getCause() { - ClassNotFoundException e = new ClassNotFoundException(); - assertNull(e.getCause()); - - e = new ClassNotFoundException("Message"); - assertNull(e.getCause()); - - NullPointerException cause = new NullPointerException(); - Throwable thr = new Throwable(cause); - e = new ClassNotFoundException("Message", thr); - assertEquals(thr, e.getCause()); - - e = new ClassNotFoundException("Message", null); - assertEquals(null, e.getCause()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getException", - args = {} - ) - public void test_getException() { - ClassNotFoundException e = new ClassNotFoundException(); - assertNull(e.getException()); - - e = new ClassNotFoundException("Message"); - assertNull(e.getException()); - - NullPointerException cause = new NullPointerException(); - Throwable thr = new Throwable(cause); - e = new ClassNotFoundException("Message", thr); - assertEquals(thr, e.getException()); - - e = new ClassNotFoundException("Message", null); - assertEquals(null, e.getException()); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java index 58e86fa..da66da9 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java @@ -17,44 +17,26 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(CloneNotSupportedException.class) public class CloneNotSupportedExceptionTest extends TestCase { - /** - * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "CloneNotSupportedException", - args = {} - ) - public void test_Constructor() { + /** + * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException() + */ + public void test_Constructor() { CloneNotSupportedException e = new CloneNotSupportedException(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); - } + } - /** - * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "CloneNotSupportedException", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { + /** + * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { CloneNotSupportedException e = new CloneNotSupportedException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java index 5c01a36..4793a42 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java @@ -17,117 +17,49 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Compiler.class) public class CompilerTest extends TestCase { /** * @tests java.lang.Compiler#command(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "command", - args = {java.lang.Object.class} - ) public void test_commandLjava_lang_Object() { - - if(System.getProperty("java.compiler") != null) { - try { - assertNull("Incorrect behavior.", Compiler.command(new Object())); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - // NullPointerException is not specified. - Compiler.command(null); - } else { - Compiler.command(""); - } + assertNull("Incorrect behavior.", Compiler.command(new Object())); } /** * @tests java.lang.Compiler#compileClass(java.lang.Class) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compileClass", - args = {java.lang.Class.class} - ) public void test_compileClassLjava_lang_Class() { - try { - // Do not test return value, may return true or false depending on - // if the jit is enabled. Make the call to ensure it doesn't crash. - Compiler.compileClass(Compiler.class); - } catch (Exception e) { - fail("Exception during test."); - } - - // NullPointerException is not specified. - Compiler.compileClass((Class) null); + // Do not test return value, may return true or false depending on + // if the jit is enabled. Make the call to ensure it doesn't crash. + Compiler.compileClass(Compiler.class); } /** * @tests java.lang.Compiler#compileClasses(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compileClasses", - args = {java.lang.String.class} - ) public void test_compileClassesLjava_lang_String() { - try { - // Do not test return value, may return true or false depending on - // if the jit is enabled. Make the call to ensure it doesn't crash. + // Do not test return value, may return true or false depending on + // if the jit is enabled. Make the call to ensure it doesn't crash. Compiler.compileClasses("Compiler"); - } catch (Exception e) { - fail("Exception during test."); - } - - // NullPointerException is not specified. - Compiler.compileClasses((String) null); } /** * @tests java.lang.Compiler#disable() */ - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "Doesn't verify that disable() method causes the Compiler to cease operation.", - method = "disable", - args = {} - ) public void test_disable() { - try { - Compiler.disable(); - Compiler.compileClass(Compiler.class); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } + Compiler.disable(); + Compiler.compileClass(Compiler.class); } /** * @tests java.lang.Compiler#enable() */ - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "Doesn't verify that enable() method causes the Compiler to resume operation.", - method = "enable", - args = {} - ) public void test_enable() { - try { - Compiler.disable(); - Compiler.enable(); - Compiler.compileClass(Compiler.class); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } + Compiler.disable(); + Compiler.enable(); + Compiler.compileClass(Compiler.class); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java index 3b2d405..44039df 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java @@ -541,8 +541,6 @@ public class DoubleTest extends TestCase { method = "parseDouble", args = {java.lang.String.class} ) - @KnownFailure("parseDouble returns different value on Android " + - "for 0x44b52d02c7e14af6L, it returns 1.0e23.") public void test_parseDoubleLjava_lang_String() { assertEquals("Incorrect double returned, expected zero.", 0.0, Double .parseDouble("2.4703282292062327208828439643411e-324"), 0.0); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java index d91584b..2fea1b1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java @@ -16,14 +16,8 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(EnumConstantNotPresentException.class) public class EnumConstantNotPresentExceptionTest extends TestCase { public enum Fixture { @@ -34,20 +28,7 @@ public class EnumConstantNotPresentExceptionTest extends TestCase { * @test java.lang.EnumConstantNotPresentException#EnumConstantNotPresentException(Class<? * extends Enum>, String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "EnumConstantNotPresentException", - args = {java.lang.Class.class, java.lang.String.class} - ) public void test_ConstructorLjava_lang_ClassLjava_lang_String() { - String tm = "Test Message"; - EnumConstantNotPresentException ecnpe = new - EnumConstantNotPresentException(Fixture.class, tm); - - assertEquals("Constant name is incorrect: " + ecnpe.constantName() + - " instead of " + tm, tm, ecnpe.constantName()); - try { new EnumConstantNotPresentException(null, ""); fail("No NPE"); @@ -58,12 +39,6 @@ public class EnumConstantNotPresentExceptionTest extends TestCase { /** * @test java.lang.EnumConstantNotPresentException#enumType() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "enumType", - args = {} - ) public void test_enumType() { EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR"); assertEquals(Fixture.class, e.enumType()); @@ -72,12 +47,6 @@ public class EnumConstantNotPresentExceptionTest extends TestCase { /** * @test java.lang.EnumConstantNotPresentException#constantName() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "constantName", - args = {} - ) public void test_constantName() { EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR"); assertEquals("FOUR", e.constantName()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java index 94b495f..afe1146 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java @@ -16,9 +16,7 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; +import java.util.HashMap; import junit.framework.TestCase; @@ -26,9 +24,6 @@ import org.apache.harmony.testframework.serialization.SerializationTest; import tests.util.SerializationTester; -import java.util.HashMap; - -@TestTargetClass(Enum.class) public class EnumTest extends TestCase { enum Sample { @@ -49,37 +44,18 @@ public class EnumTest extends TestCase { enum Color { Red, Green, Blue {}; } - - - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "Can't be tested, according to the spec this constructor can't be invoked.", - method = "Enum", - args = {java.lang.String.class, int.class} - ) - public void test_EnumLStringLlang() { - //TODO - } - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "Can't be tested, according to the spec.", - method = "clone", - args = {} - ) - public void test_clone() { - //TODO + enum MockCloneEnum { + ONE; + + public void callClone() throws CloneNotSupportedException{ + super.clone(); + } } /** * @tests java.lang.Enum#compareTo(java.lang.Enum) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.lang.Enum.class} - ) public void test_compareToLjava_lang_Enum() { assertTrue(0 < Sample.MOE.compareTo(Sample.LARRY)); assertEquals(0, Sample.MOE.compareTo(Sample.MOE)); @@ -95,12 +71,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#equals(Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { assertFalse(moe.equals("bob")); assertTrue(moe.equals(Sample.MOE)); @@ -112,12 +82,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#getDeclaringClass() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getDeclaringClass", - args = {} - ) public void test_getDeclaringClass() { assertEquals(Sample.class, moe.getDeclaringClass()); } @@ -125,27 +89,13 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { assertEquals (moe.hashCode(), moe.hashCode()); - assertTrue (moe.hashCode() != Sample.LARRY.hashCode()); - } /** * @tests java.lang.Enum#name() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "name", - args = {} - ) public void test_name() { assertEquals("MOE", moe.name()); } @@ -153,12 +103,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#ordinal() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ordinal", - args = {} - ) public void test_ordinal() { assertEquals(0, larry.ordinal()); assertEquals(1, moe.ordinal()); @@ -168,12 +112,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { assertTrue(moe.toString().equals("MOE")); } @@ -181,12 +119,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#valueOf(Class, String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.Class.class, java.lang.String.class} - ) public void test_valueOfLjava_lang_String() { assertSame(Sample.CURLY, Sample.valueOf("CURLY")); assertSame(Sample.LARRY, Sample.valueOf("LARRY")); @@ -248,13 +180,6 @@ public class EnumTest extends TestCase { /** * @tests java.lang.Enum#values */ - @TestTargetNew( - level = TestLevel.TODO, - notes = "Tests the values() method which is not in the API since it is" + - "automatically created by the compiler for enum types", - method = "!values", - args = {} - ) public void test_values() { Sample[] myValues = Sample.values(); assertEquals(3, myValues.length); @@ -265,31 +190,32 @@ public class EnumTest extends TestCase { assertEquals(0, Empty.values().length); } + + /** + * @tests java.lang.Enum#clone() + */ + public void test_clone() { + try { + MockCloneEnum.ONE.callClone(); + fail("Should throw CloneNotSupprotedException"); + } catch (CloneNotSupportedException e1) { + // expected + } + + } /** * @test Serialization/deserilazation compatibility with Harmony. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Serialization/deserilazation compatibility.", - method = "!SerializationGolden", - args = {} - ) public void test_compatibilitySerialization_inClass_Complex_Harmony() throws Exception{ // TODO migrate to the new testing framework assertTrue(SerializationTester.assertCompabilityEquals(new MockEnum2(), - "/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser")); + "serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser")); } /** * @tests serialization/deserialization compatibility. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { // test a map class that has enums. @@ -315,18 +241,11 @@ public class EnumTest extends TestCase { assertEquals(mock2.i, test2.i); assertEquals(mock2.str, test2.str); assertEquals(mock2.samEnum, test2.samEnum); - } /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { // regression test for Harmony-1163 @@ -342,5 +261,4 @@ public class EnumTest extends TestCase { SerializationTest.verifyGolden(this, testCases); } - } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java index 03735c2..32db9b3 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Error.class) public class ErrorTest extends TestCase { - /** - * @tests java.lang.Error#Error() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Error", - args = {} - ) + /** + * @tests java.lang.Error#Error() + */ public void test_Constructor() { Error e = new Error(); assertNull(e.getMessage()); @@ -46,41 +34,9 @@ public class ErrorTest extends TestCase { /** * @tests java.lang.Error#Error(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Error", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { Error e = new Error("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Error", - args = {java.lang.String.class, java.lang.Throwable.class} - ) - public void test_ConstructorLjava_lang_StringLThrowable() { - Throwable thr = new Throwable(); - String message = "Test message"; - Error err = new Error(message, thr); - assertEquals(message, err.getMessage()); - assertEquals(thr, err.getCause()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Error", - args = {java.lang.Throwable.class} - ) - public void test_ConstructorLThrowable() { - Throwable thr = new Throwable(); - Error err = new Error(thr); - assertEquals(thr, err.getCause()); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java index 6614090..83c6cd8 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java @@ -17,31 +17,11 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -@TestTargetClass(ExceptionInInitializerError.class) public class ExceptionInInitializerErrorTest extends junit.framework.TestCase { - /** - * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError() - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ExceptionInInitializerError", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCause", - args = {} - ) - }) + /** + * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError() + */ public void test_Constructor() { ExceptionInInitializerError e = new ExceptionInInitializerError(); assertNull(e.getMessage()); @@ -52,56 +32,22 @@ public class ExceptionInInitializerErrorTest extends junit.framework.TestCase { /** * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError(java.lang.String) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ExceptionInInitializerError", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCause", - args = {} - ) - }) public void test_ConstructorLjava_lang_String() { ExceptionInInitializerError e = new ExceptionInInitializerError("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } - /** - * @tests java.lang.ExceptionInInitializerExceptionInInitializerError#ExceptionInInitializerError(java.lang.Throwable) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ExceptionInInitializerError", - args = {java.lang.Throwable.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCause", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getException", - args = {} - ) - }) - public void test_ConstructorLjava_lang_Throwable() { - NullPointerException npe = new NullPointerException("fixture"); + /** + * @tests java.lang.ExceptionInInitializerExceptionInInitializerError#ExceptionInInitializerError(java.lang.Throwable) + */ + public void test_ConstructorLjava_lang_Throwable() { + NullPointerException npe = new NullPointerException("fixture"); ExceptionInInitializerError e = new ExceptionInInitializerError(npe); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertSame(npe, e.getException()); assertSame(npe, e.getCause()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java index 9057269..88cc2e4 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Exception.class) public class ExceptionTest extends TestCase { - /** - * @tests java.lang.Exception#Exception() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Exception", - args = {} - ) + /** + * @tests java.lang.Exception#Exception() + */ public void test_Constructor() { Exception e = new Exception(); assertNull(e.getMessage()); @@ -46,42 +34,9 @@ public class ExceptionTest extends TestCase { /** * @tests java.lang.Exception#Exception(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Exception", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { Exception e = new Exception("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Exception", - args = {java.lang.String.class, java.lang.Throwable.class} - ) - public void test_ConstructorLjava_lang_StringLThrowable() { - Throwable thr = new Throwable(); - String message = "Test message"; - Exception err = new Exception(message, thr); - assertEquals(message, err.getMessage()); - assertEquals(thr, err.getCause()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Exception", - args = {java.lang.Throwable.class} - ) - public void test_ConstructorLThrowable() { - Throwable thr = new Throwable(); - Exception err = new Exception(thr); - assertEquals(thr, err.getCause()); - } - } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java index caec351..5b032e1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IllegalAccessError.class) public class IllegalAccessErrorTest extends TestCase { - /** - * @tests java.lang.IllegalAccessError#IllegalAccessError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalAccessError", - args = {} - ) + /** + * @tests java.lang.IllegalAccessError#IllegalAccessError() + */ public void test_Constructor() { IllegalAccessError e = new IllegalAccessError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IllegalAccessErrorTest extends TestCase { /** * @tests java.lang.IllegalAccessError#IllegalAccessError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalAccessError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IllegalAccessError e = new IllegalAccessError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java index a14ae66..2a984cb 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IllegalAccessException.class) public class IllegalAccessExceptionTest extends TestCase { - /** - * @tests java.lang.IllegalAccessException#IllegalAccessException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalAccessException", - args = {} - ) + /** + * @tests java.lang.IllegalAccessException#IllegalAccessException() + */ public void test_Constructor() { IllegalAccessException e = new IllegalAccessException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IllegalAccessExceptionTest extends TestCase { /** * @tests java.lang.IllegalAccessException#IllegalAccessException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalAccessException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IllegalAccessException e = new IllegalAccessException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java index 3acc8e4..9acf54c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java @@ -17,57 +17,51 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(IllegalArgumentException.class) public class IllegalArgumentExceptionTest extends TestCase { - /** - * @tests java.lang.IllegalArgumentException#IllegalArgumentException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalArgumentException", - args = {} - ) - public void test_Constructor() { - IllegalArgumentException e = new IllegalArgumentException(); + /** + * @tests java.lang.IllegalArgumentException#IllegalArgumentException() + */ + public void test_Constructor() { + IllegalArgumentException e = new IllegalArgumentException(); assertNull(e.getMessage()); assertNull(e.getLocalizedMessage()); assertNull(e.getCause()); - } + } - /** - * @tests java.lang.IllegalArgumentException#IllegalArgumentException(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalArgumentException", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { + /** + * @tests java.lang.IllegalArgumentException#IllegalArgumentException(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { IllegalArgumentException e = new IllegalArgumentException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); + } + + /** + * @tests {@link java.lang.IllegalArgumentException#IllegalArgumentException(Throwable)} + */ + public void test_ConstructorLjava_lang_Throwable() { + Throwable emptyThrowable = new Exception(); + IllegalArgumentException emptyException = new IllegalArgumentException(emptyThrowable); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString()); + + Throwable exception = new Exception("msg"); + IllegalArgumentException e = new IllegalArgumentException(exception); + assertEquals(exception.getClass().getName() + ": " + "msg", e.getMessage()); + assertEquals(exception.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(exception.getClass().getName(), emptyException.getCause().toString()); } /** * @tests java.lang.IllegalArgumentException#IllegalArgumentException(String,Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalArgumentException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) @SuppressWarnings("nls") public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() { NullPointerException npe = new NullPointerException(); @@ -77,27 +71,9 @@ public class IllegalArgumentExceptionTest extends TestCase { assertSame(npe, e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalArgumentException", - args = {java.lang.Throwable.class} - ) - public void test_ConstructorLjava_lang_Throwable() { - NullPointerException npe = new NullPointerException(); - IllegalArgumentException e = new IllegalArgumentException(npe); - assertSame(npe, e.getCause()); - } - /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new IllegalArgumentException()); } @@ -105,12 +81,6 @@ public class IllegalArgumentExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new IllegalArgumentException()); } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java index adc155f..37ce9c3 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IllegalMonitorStateException.class) public class IllegalMonitorStateExceptionTest extends TestCase { /** * @tests java.lang.IllegalMonitorStateException#IllegalMonitorStateException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalMonitorStateException", - args = {} - ) public void test_Constructor() { IllegalMonitorStateException e = new IllegalMonitorStateException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IllegalMonitorStateExceptionTest extends TestCase { /** * @tests java.lang.IllegalMonitorStateException#IllegalMonitorStateException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalMonitorStateException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IllegalMonitorStateException e = new IllegalMonitorStateException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java index 03acac6..2d55d6c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java @@ -17,26 +17,15 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(IllegalStateException.class) public class IllegalStateExceptionTest extends TestCase { - /** - * @tests java.lang.IllegalStateException#IllegalStateException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalStateException", - args = {} - ) + /** + * @tests java.lang.IllegalStateException#IllegalStateException() + */ public void test_Constructor() { IllegalStateException e = new IllegalStateException(); assertNull(e.getMessage()); @@ -47,60 +36,50 @@ public class IllegalStateExceptionTest extends TestCase { /** * @tests java.lang.IllegalStateException#IllegalStateException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalStateException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IllegalStateException e = new IllegalStateException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } + + /** + * @tests {@link java.land.IllegalStateException#IllIllegalStateException(java.lang.Throwable)} + */ + public void test_ConstructorLjava_lang_Throwable() { + Throwable emptyThrowable = new Exception(); + IllegalStateException emptyException = new IllegalStateException(emptyThrowable); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString()); - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalStateException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) - public void test_ConstructorLjava_lang_StringLThrowable() { - String message = "Test message"; - NullPointerException npe = new NullPointerException(); - IllegalStateException e = new IllegalStateException(message, npe); - assertEquals(message, e.getMessage()); - assertEquals(npe, e.getCause()); - - e = new IllegalStateException(message, null); - assertEquals(message, e.getMessage()); - assertNull(e.getCause()); + Throwable throwable = new Exception("msg"); + IllegalStateException exception = new IllegalStateException(throwable); + assertEquals(throwable.getClass().getName() + ": " + "msg", exception.getMessage()); + assertEquals(throwable.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(throwable.getClass().getName(), emptyException.getCause().toString()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalStateException", - args = {java.lang.Throwable.class} - ) - public void test_ConstructorLThrowable() { - NullPointerException npe = new NullPointerException(); - IllegalStateException e = new IllegalStateException(npe); - assertEquals(npe, e.getCause()); - - e = new IllegalStateException((Throwable)null); - assertNull(e.getCause()); + /** + * @tests {@link java.land.IllegalStateException#IllIllegalStateException(java.lang.String, java.lang.Throwable)} + */ + public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() { + Throwable emptyThrowable = new Exception(); + IllegalStateException emptyException = new IllegalStateException("msg", emptyThrowable); + assertEquals("msg", emptyException.getMessage()); + assertEquals("msg", emptyException.getLocalizedMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString()); + + Throwable throwable = new Exception("msg_exception"); + IllegalStateException exception = new IllegalStateException("msg", throwable); + assertEquals("msg", exception.getMessage()); + assertEquals("msg", exception.getLocalizedMessage()); + assertEquals(throwable.getClass().getName() + ": " + throwable.getMessage(), exception + .getCause().toString()); } - + /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new IllegalStateException()); @@ -109,12 +88,6 @@ public class IllegalStateExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new IllegalStateException()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java index 1b3a03d..475f6bb 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IllegalThreadStateException.class) public class IllegalThreadStateExceptionTest extends TestCase { - /** + /** * @tests java.lang.IllegalThreadStateException#IllegalThreadStateException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalThreadStateException", - args = {} - ) public void test_Constructor() { IllegalThreadStateException e = new IllegalThreadStateException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IllegalThreadStateExceptionTest extends TestCase { /** * @tests java.lang.IllegalThreadStateException#IllegalThreadStateException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalThreadStateException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IllegalThreadStateException e = new IllegalThreadStateException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java index 7893b29..b6a8d6a 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IncompatibleClassChangeError.class) public class IncompatibleClassChangeErrorTest extends TestCase { - /** - * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IncompatibleClassChangeError", - args = {} - ) + /** + * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError() + */ public void test_Constructor() { IncompatibleClassChangeError e = new IncompatibleClassChangeError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IncompatibleClassChangeErrorTest extends TestCase { /** * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IncompatibleClassChangeError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IncompatibleClassChangeError e = new IncompatibleClassChangeError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java index d897e47..617c71c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(IndexOutOfBoundsException.class) public class IndexOutOfBoundsExceptionTest extends TestCase { - /** - * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IndexOutOfBoundsException", - args = {} - ) + /** + * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException() + */ public void test_Constructor() { IndexOutOfBoundsException e = new IndexOutOfBoundsException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class IndexOutOfBoundsExceptionTest extends TestCase { /** * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IndexOutOfBoundsException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { IndexOutOfBoundsException e = new IndexOutOfBoundsException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java index 5601755..1d9722c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(InstantiationError.class) public class InstantiationErrorTest extends TestCase { - /** - * @tests java.lang.InstantiationError#InstantiationError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InstantiationError", - args = {} - ) + /** + * @tests java.lang.InstantiationError#InstantiationError() + */ public void test_Constructor() { InstantiationError e = new InstantiationError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class InstantiationErrorTest extends TestCase { /** * @tests java.lang.InstantiationError#InstantiationError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InstantiationError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { InstantiationError e = new InstantiationError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java index febeee2..5f636d5 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(InstantiationException.class) public class InstantiationExceptionTest extends TestCase { - /** - * @tests java.lang.InstantiationException#InstantiationException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InstantiationException", - args = {} - ) + /** + * @tests java.lang.InstantiationException#InstantiationException() + */ public void test_Constructor() { InstantiationException e = new InstantiationException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class InstantiationExceptionTest extends TestCase { /** * @tests java.lang.InstantiationException#InstantiationException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InstantiationException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { InstantiationException e = new InstantiationException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java index 4b93777..3ff4711 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(InternalError.class) public class InternalErrorTest extends TestCase { - /** - * @tests java.lang.InternalError#InternalError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InternalError", - args = {} - ) + /** + * @tests java.lang.InternalError#InternalError() + */ public void test_Constructor() { InternalError e = new InternalError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class InternalErrorTest extends TestCase { /** * @tests java.lang.InternalError#InternalError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InternalError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { InternalError e = new InternalError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java index 4faa301..96c85e6 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(InterruptedException.class) public class InterruptedExceptionTest extends TestCase { - /** - * @tests java.lang.InterruptedException#InterruptedException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InterruptedException", - args = {} - ) + /** + * @tests java.lang.InterruptedException#InterruptedException() + */ public void test_Constructor() { InterruptedException e = new InterruptedException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class InterruptedExceptionTest extends TestCase { /** * @tests java.lang.InterruptedException#InterruptedException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InterruptedException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { InterruptedException e = new InterruptedException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java index c856705..9c1adcb 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(LinkageError.class) public class LinkageErrorTest extends TestCase { - /** - * @tests java.lang.LinkageError#LinkageError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LinkageError", - args = {} - ) + /** + * @tests java.lang.LinkageError#LinkageError() + */ public void test_Constructor() { LinkageError e = new LinkageError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class LinkageErrorTest extends TestCase { /** * @tests java.lang.LinkageError#LinkageError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LinkageError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { LinkageError e = new LinkageError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java index ef1c9a6..93b6dbd 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NegativeArraySizeException.class) public class NegativeArraySizeExceptionTest extends TestCase { - /** - * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NegativeArraySizeException", - args = {} - ) + /** + * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException() + */ public void test_Constructor() { NegativeArraySizeException e = new NegativeArraySizeException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NegativeArraySizeExceptionTest extends TestCase { /** * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NegativeArraySizeException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NegativeArraySizeException e = new NegativeArraySizeException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java index 9c76a56..db7dced 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NoClassDefFoundError.class) public class NoClassDefFoundErrorTest extends TestCase { - /** - * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoClassDefFoundError", - args = {} - ) + /** + * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError() + */ public void test_Constructor() { NoClassDefFoundError e = new NoClassDefFoundError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NoClassDefFoundErrorTest extends TestCase { /** * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoClassDefFoundError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NoClassDefFoundError e = new NoClassDefFoundError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java index 0ca4f41..88889e5 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NoSuchFieldError.class) public class NoSuchFieldErrorTest extends TestCase { - /** - * @tests java.lang.NoSuchFieldError#NoSuchFieldError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchFieldError", - args = {} - ) + /** + * @tests java.lang.NoSuchFieldError#NoSuchFieldError() + */ public void test_Constructor() { NoSuchFieldError e = new NoSuchFieldError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NoSuchFieldErrorTest extends TestCase { /** * @tests java.lang.NoSuchFieldError#NoSuchFieldError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchFieldError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NoSuchFieldError e = new NoSuchFieldError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java index 135fdb5..5902d86 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NoSuchFieldException.class) public class NoSuchFieldExceptionTest extends TestCase { - /** - * @tests java.lang.NoSuchFieldException#NoSuchFieldException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchFieldException", - args = {} - ) + /** + * @tests java.lang.NoSuchFieldException#NoSuchFieldException() + */ public void test_Constructor() { NoSuchFieldException e = new NoSuchFieldException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NoSuchFieldExceptionTest extends TestCase { /** * @tests java.lang.NoSuchFieldException#NoSuchFieldException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchFieldException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NoSuchFieldException e = new NoSuchFieldException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java index 5c8a462..b7e711b 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NoSuchMethodError.class) public class NoSuchMethodErrorTest extends TestCase { - /** - * @tests java.lang.NoSuchMethodError#NoSuchMethodError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchMethodError", - args = {} - ) + /** + * @tests java.lang.NoSuchMethodError#NoSuchMethodError() + */ public void test_Constructor() { NoSuchMethodError e = new NoSuchMethodError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NoSuchMethodErrorTest extends TestCase { /** * @tests java.lang.NoSuchMethodError#NoSuchMethodError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchMethodError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NoSuchMethodError e = new NoSuchMethodError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java index 8e01984..68d46a2 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NoSuchMethodException.class) public class NoSuchMethodExceptionTest extends TestCase { - /** - * @tests java.lang.NoSuchMethodException#NoSuchMethodException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchMethodException", - args = {} - ) + /** + * @tests java.lang.NoSuchMethodException#NoSuchMethodException() + */ public void test_Constructor() { NoSuchMethodException e = new NoSuchMethodException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NoSuchMethodExceptionTest extends TestCase { /** * @tests java.lang.NoSuchMethodException#NoSuchMethodException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NoSuchMethodException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NoSuchMethodException e = new NoSuchMethodException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java index f1c870d..a3df668 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java @@ -16,25 +16,13 @@ */ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NullPointerException.class) public class NullPointerExceptionTest extends TestCase { - /** - * @tests java.lang.NullPointerException#NullPointerException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NullPointerException", - args = {} - ) + /** + * @tests java.lang.NullPointerException#NullPointerException() + */ public void test_Constructor() { NullPointerException e = new NullPointerException(); assertNull(e.getMessage()); @@ -45,12 +33,6 @@ public class NullPointerExceptionTest extends TestCase { /** * @tests java.lang.NullPointerException#NullPointerException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NullPointerException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NullPointerException e = new NullPointerException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java index 579b0b9..3cdf445 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(NumberFormatException.class) public class NumberFormatExceptionTest extends TestCase { - /** - * @tests java.lang.NumberFormatException#NumberFormatException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NumberFormatException", - args = {} - ) + /** + * @tests java.lang.NumberFormatException#NumberFormatException() + */ public void test_Constructor() { NumberFormatException e = new NumberFormatException(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class NumberFormatExceptionTest extends TestCase { /** * @tests java.lang.NumberFormatException#NumberFormatException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NumberFormatException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { NumberFormatException e = new NumberFormatException("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java index d1caf92..5b7d7f7 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java @@ -17,108 +17,50 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -@TestTargetClass(Number.class) public class NumberTest extends junit.framework.TestCase { - - class MockNumber extends Number { - - @Override - public double doubleValue() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public float floatValue() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int intValue() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public long longValue() { - // TODO Auto-generated method stub - return 0; - } - - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Number", - args = {} - ) - public void test_Number() { - MockNumber number = new MockNumber(); - assertEquals(0, number.longValue()); - assertEquals(0, number.shortValue()); - } - - /** - * @tests java.lang.Number#byteValue() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "byteValue", - args = {} - ) - public void test_byteValue() { - int number = 1231243; - assertTrue("Incorrect byte returned for: " + number, - ((byte) new Integer(number).intValue()) == new Integer(number) - .byteValue()); - number = 0; - assertTrue("Incorrect byte returned for: " + number, - ((byte) new Integer(number).intValue()) == new Integer(number) - .byteValue()); - number = -1; - assertTrue("Incorrect byte returned for: " + number, - ((byte) new Integer(number).intValue()) == new Integer(number) - .byteValue()); - number = -84109328; - assertTrue("Incorrect byte returned for: " + number, - ((byte) new Integer(number).intValue()) == new Integer(number) - .byteValue()); - } + /** + * @tests java.lang.Number#byteValue() + */ + public void test_byteValue() { + int number = 1231243; + assertTrue("Incorrect byte returned for: " + number, + ((byte) new Integer(number).intValue()) == new Integer(number) + .byteValue()); + number = 0; + assertTrue("Incorrect byte returned for: " + number, + ((byte) new Integer(number).intValue()) == new Integer(number) + .byteValue()); + number = -1; + assertTrue("Incorrect byte returned for: " + number, + ((byte) new Integer(number).intValue()) == new Integer(number) + .byteValue()); + number = -84109328; + assertTrue("Incorrect byte returned for: " + number, + ((byte) new Integer(number).intValue()) == new Integer(number) + .byteValue()); + } - /** - * @tests java.lang.Number#shortValue() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "shortValue", - args = {} - ) - public void test_shortValue() { - int number = 1231243; - assertTrue("Incorrect byte returned for: " + number, - ((short) new Integer(number).intValue()) == new Integer(number) - .shortValue()); - number = 0; - assertTrue("Incorrect byte returned for: " + number, - ((short) new Integer(number).intValue()) == new Integer(number) - .shortValue()); - number = -1; - assertTrue("Incorrect byte returned for: " + number, - ((short) new Integer(number).intValue()) == new Integer(number) - .shortValue()); - number = -84109328; - assertTrue("Incorrect byte returned for: " + number, - ((short) new Integer(number).intValue()) == new Integer(number) - .shortValue()); + /** + * @tests java.lang.Number#shortValue() + */ + public void test_shortValue() { + int number = 1231243; + assertTrue("Incorrect byte returned for: " + number, + ((short) new Integer(number).intValue()) == new Integer(number) + .shortValue()); + number = 0; + assertTrue("Incorrect byte returned for: " + number, + ((short) new Integer(number).intValue()) == new Integer(number) + .shortValue()); + number = -1; + assertTrue("Incorrect byte returned for: " + number, + ((short) new Integer(number).intValue()) == new Integer(number) + .shortValue()); + number = -84109328; + assertTrue("Incorrect byte returned for: " + number, + ((short) new Integer(number).intValue()) == new Integer(number) + .shortValue()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java index 4782f1e..a23789b 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java @@ -17,48 +17,30 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -@TestTargetClass(OutOfMemoryError.class) public class OutOfMemoryErrorTest extends junit.framework.TestCase { - /** - * @tests java.lang.OutOfMemoryError#OutOfMemoryError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "OutOfMemoryError", - args = {} - ) - public void test_Constructor() { - // Test for method java.lang.OutOfMemoryError() - Error e = new OutOfMemoryError(); + /** + * @tests java.lang.OutOfMemoryError#OutOfMemoryError() + */ + public void test_Constructor() { + // Test for method java.lang.OutOfMemoryError() + Error e = new OutOfMemoryError(); assertNull(e.getCause()); assertNull(e.getMessage()); - } + } - /** - * @tests java.lang.OutOfMemoryError#OutOfMemoryError(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "OutOfMemoryError", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { - // Test for method java.lang.OutOfMemoryError(java.lang.String) - Error e = new OutOfMemoryError(null); + /** + * @tests java.lang.OutOfMemoryError#OutOfMemoryError(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + // Test for method java.lang.OutOfMemoryError(java.lang.String) + Error e = new OutOfMemoryError(null); assertNull(e.getMessage()); assertNull(e.getCause()); e= new OutOfMemoryError("msg"); assertEquals("msg", e.getMessage()); assertNull(e.getCause()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java index 283c1db..61dab9a 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java @@ -16,48 +16,27 @@ */ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.File; +import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; -import java.lang.annotation.Annotation; - -import java.lang.annotation.Annotation; -import tests.support.Support_ClassLoader; import tests.support.resource.Support_Resources; -@TestTargetClass(Package.class) public class PackageTest extends junit.framework.TestCase { private File resources; private String resPath; - - Class clazz; Package getTestPackage(String resourceJar, String className) throws Exception { - - if ("Dalvik".equals(System.getProperty("java.vm.name"))) { - resourceJar = resourceJar.substring(0, resourceJar.indexOf(".")) + - "_dex.jar"; - } Support_Resources.copyFile(resources, "Package", resourceJar); URL resourceURL = new URL("file:/" + resPath + "/Package/" + resourceJar); - ClassLoader cl = Support_ClassLoader.getInstance(resourceURL, - getClass().getClassLoader()); - - clazz = cl.loadClass(className); - return clazz.getPackage(); + URLClassLoader ucl = new URLClassLoader(new URL[] { resourceURL }, null); + return Class.forName(className, true, ucl).getPackage(); } @Override @@ -82,45 +61,6 @@ public class PackageTest extends junit.framework.TestCase { * @tests java.lang.Package#getSpecificationVersion() * @tests java.lang.Package#getImplementationTitle() */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getImplementationTitle", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getImplementationVendor", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getImplementationVersion", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSpecificationTitle", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSpecificationVendor", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSpecificationVersion", - args = {} - ) - }) - @KnownFailure("get methods don't work.") public void test_helper_Attributes() throws Exception { Package p = getTestPackage("hyts_all_attributes.jar", "p.C"); @@ -231,13 +171,6 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#getName() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getName", - args = {} - ) - @BrokenTest("Different behavior between cts host and run-core-test") public void test_getName() throws Exception { Package p = getTestPackage("hyts_pq.jar", "p.q.C"); assertEquals("Package getName returns a wrong string", "p.q", p @@ -247,34 +180,17 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#getPackage(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPackage", - args = {java.lang.String.class} - ) - @KnownFailure("Real package information missing on android.") - public void test_getPackageLjava_lang_String() throws Exception { + public void test_getPackageLjava_lang_String() { assertSame("Package getPackage failed for java.lang", Package .getPackage("java.lang"), Package.getPackage("java.lang")); assertSame("Package getPackage failed for java.lang", Package .getPackage("java.lang"), Object.class.getPackage()); - - Package p = getTestPackage("hyts_package.jar", "C"); - assertNull("getPackage should return null.", p); } /** * @tests java.lang.Package#getPackages() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPackages", - args = {} - ) - @KnownFailure("Package information missing on android") public void test_getPackages() throws Exception { Package[] pckgs = Package.getPackages(); boolean found = false; @@ -290,12 +206,6 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { Package p1 = Package.getPackage("java.lang"); if (p1 != null) { @@ -306,13 +216,6 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#isCompatibleWith(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isCompatibleWith", - args = {java.lang.String.class} - ) - @KnownFailure("Dalvik packages are always version '0.0'.") public void test_isCompatibleWithLjava_lang_String() throws Exception { Package p = getTestPackage("hyts_c.jar", "p.C"); @@ -363,31 +266,14 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#isSealed() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isSealed", - args = {} - ) - @KnownFailure("isSealed method returns false for sealed package.") public void test_isSealed() throws Exception { Package p = getTestPackage("hyts_pq.jar", "p.q.C"); assertTrue("Package isSealed returns wrong boolean", p.isSealed()); - - p = String.class.getPackage(); - assertFalse("Package isSealed returns wrong boolean", p.isSealed()); } /** * @tests java.lang.Package#isSealed(java.net.URL) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isSealed", - args = {java.net.URL.class} - ) - @KnownFailure("isSealed method returns false for sealed package.") public void test_isSealedLjava_net_URL() throws Exception { Package p = getTestPackage("hyts_c.jar", "p.C"); assertFalse("Package isSealed returns wrong boolean (1)", p @@ -399,91 +285,106 @@ public class PackageTest extends junit.framework.TestCase { /** * @tests java.lang.Package#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - @BrokenTest("Different behavior between cts host and run-core-test") public void test_toString() throws Exception { Package p = getTestPackage("hyts_c.jar", "p.C"); assertTrue("Package toString returns wrong string", p.toString() .length() > 0); } - @SuppressWarnings("unchecked") - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAnnotation", - args = {java.lang.Class.class} - ) - @KnownFailure("Class loader can't retrieve information about annotations.") - public void test_getAnnotation() throws Exception { - String annotationName = "a.b.PackageAnnotation"; - Package p = getTestPackage("hyts_package.jar", annotationName); - assertEquals(annotationName, - p.getAnnotation(clazz).annotationType().getName()); - assertNull(String.class.getPackage().getAnnotation(Deprecated.class)); - assertNull(ExtendTestClass.class.getPackage(). - getAnnotation(Deprecated.class)); + public void test_SealedPackage_forName() throws Exception { + Support_Resources.copyFile(resources, "Package", "hyts_c.jar"); + Support_Resources.copyFile(resources, "Package", "hyts_d.jar"); + Support_Resources.copyFile(resources, "Package", "hyts_d1.jar"); + Support_Resources.copyFile(resources, "Package", "hyts_d2.jar"); + + URL resourceURL1 = new URL("file:/" + resPath + "/Package/hyts_c.jar"); + URL resourceURL2 = new URL("file:/" + resPath + "/Package/hyts_d.jar"); + URL resourceURL3 = new URL("file:/" + resPath + "/Package/hyts_d1.jar"); + URL resourceURL4 = new URL("file:/" + resPath + "/Package/hyts_d2.jar"); + URL resourceURL5 = new URL("file:/" + resPath + "/"); + + URLClassLoader uclClassLoader; + // load from the sealed jar, then an unsealed jar with no manifest + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL2 }, null); + Class.forName("p.C", true, uclClassLoader); + try { + Class.forName("p.D", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // setup for next test + Support_Resources.copyFile(resources, "p", ""); + InputStream in = uclClassLoader.getResourceAsStream("p/D.class"); + Support_Resources.copyLocalFileto(new File(resources.toString(), + "p/D.class"), in); + + // load from a sealed jar, then the directory + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL5 }, null); + Class.forName("p.C", true, uclClassLoader); + try { + Class.forName("p.D", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // load from a directory, then the sealed jar + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL5 }, null); + Class.forName("p.D", true, uclClassLoader); + try { + Class.forName("p.C", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // load from an unsealed jar with no manifest, then the sealed jar + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL2 }, null); + Class.forName("p.D", true, uclClassLoader); + try { + Class.forName("p.C", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // load from an unsealed jar with a manifest, then the sealed jar + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL3 }, null); + Class.forName("p.C", true, uclClassLoader); + try { + Class.forName("p.D", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // load from an sealed jar, then the unsealed jar with a manifest + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL3 }, null); + Class.forName("p.D", true, uclClassLoader); + try { + Class.forName("p.C", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } + + // load from the sealed jar, then another sealed jar + uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1, + resourceURL4 }, null); + Class.forName("p.C", true, uclClassLoader); + try { + Class.forName("p.D", true, uclClassLoader); + fail("should throw SecurityException"); + } catch (SecurityException e) { + // Expected + } } - - @SuppressWarnings("unchecked") - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAnnotations", - args = {} - ) - @KnownFailure("Class loader can't retrieve information about annotations.") - public void test_getAnnotations() throws Exception { - String annotationName = "a.b.PackageAnnotation"; - Package p = getTestPackage("hyts_package.jar", annotationName); - - Annotation [] annotations = p.getAnnotations(); - assertEquals(1, annotations.length); - - p = String.class.getPackage(); - assertEquals(0, p.getAnnotations().length); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getDeclaredAnnotations", - args = {} - ) - @KnownFailure("Class loader can't retrieve information about annotations.") - public void test_getDeclaredAnnotations() throws Exception { - String annotationName = "a.b.PackageAnnotation"; - Package p = getTestPackage("hyts_package.jar", annotationName); - - Annotation [] annotations = p.getDeclaredAnnotations(); - assertEquals(1, annotations.length); - - p = String.class.getPackage(); - assertEquals(0, p.getDeclaredAnnotations().length); - } - - @SuppressWarnings("unchecked") - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isAnnotationPresent", - args = {java.lang.Class.class} - ) - @KnownFailure("Class loader can't retrieve information about annotations.") - public void test_isAnnotationPresent() throws Exception { - String annotationName = "a.b.PackageAnnotation"; - Package p = getTestPackage("hyts_package.jar", annotationName); - - assertTrue(p.isAnnotationPresent(clazz)); - assertFalse(p.isAnnotationPresent(Deprecated.class)); - - p = String.class.getPackage(); - assertFalse(p.isAnnotationPresent(clazz)); - assertFalse(p.isAnnotationPresent(Deprecated.class)); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java index cc5145e..ebe3a40 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java @@ -17,46 +17,28 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -@TestTargetClass(RuntimePermission.class) public class RuntimePermissionTest extends junit.framework.TestCase { - /** - * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "RuntimePermission", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { - // Test for method java.lang.RuntimePermission(java.lang.String) - RuntimePermission r = new RuntimePermission("createClassLoader"); - assertEquals("Returned incorrect name", - "createClassLoader", r.getName()); + /** + * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + // Test for method java.lang.RuntimePermission(java.lang.String) + RuntimePermission r = new RuntimePermission("createClassLoader"); + assertEquals("Returned incorrect name", + "createClassLoader", r.getName()); - } + } - /** - * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String, - * java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "RuntimePermission", - args = {java.lang.String.class, java.lang.String.class} - ) - public void test_ConstructorLjava_lang_StringLjava_lang_String() { - // Test for method java.lang.RuntimePermission(java.lang.String, - // java.lang.String) - RuntimePermission r = new RuntimePermission("createClassLoader", null); - assertEquals("Returned incorrect name", - "createClassLoader", r.getName()); - } + /** + * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_String() { + // Test for method java.lang.RuntimePermission(java.lang.String, + // java.lang.String) + RuntimePermission r = new RuntimePermission("createClassLoader", null); + assertEquals("Returned incorrect name", + "createClassLoader", r.getName()); + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java index 407d6f9..94c7dc2 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java @@ -17,26 +17,15 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(SecurityException.class) public class SecurityExceptionTest extends TestCase { - - /** - * @tests java.lang.SecurityException#SecurityException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SecurityException", - args = {} - ) + + /** + * @tests java.lang.SecurityException#SecurityException() + */ public void test_Constructor() { SecurityException e = new SecurityException(); assertNull(e.getMessage()); @@ -47,12 +36,6 @@ public class SecurityExceptionTest extends TestCase { /** * @tests java.lang.SecurityException#SecurityException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SecurityException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { SecurityException e = new SecurityException("fixture"); assertEquals("fixture", e.getMessage()); @@ -62,12 +45,6 @@ public class SecurityExceptionTest extends TestCase { /** * @tests java.lang.SecurityException#SecurityException(String, Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SecurityException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) @SuppressWarnings("nls") public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() { NullPointerException npe = new NullPointerException(); @@ -79,12 +56,6 @@ public class SecurityExceptionTest extends TestCase { /** * @tests java.lang.SecurityException#SecurityException(Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SecurityException", - args = {java.lang.Throwable.class} - ) @SuppressWarnings("nls") public void test_ConstructorLjava_lang_Throwable() { NullPointerException npe = new NullPointerException(); @@ -95,12 +66,6 @@ public class SecurityExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new SecurityException()); @@ -109,12 +74,6 @@ public class SecurityExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new SecurityException()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java index 0bd0c1f..d8c3751 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java @@ -4,9 +4,9 @@ * 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. @@ -16,19 +16,10 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import junit.framework.TestCase; - +import java.io.File; import java.io.FileDescriptor; import java.io.FilePermission; -import java.io.IOException; -import java.lang.reflect.Member; import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; import java.net.SocketPermission; import java.net.UnknownHostException; import java.security.AccessControlContext; @@ -36,20 +27,13 @@ import java.security.AllPermission; import java.security.Permission; import java.security.ProtectionDomain; import java.security.Security; -import java.security.SecurityPermission; + +import junit.framework.TestCase; +import tests.support.Support_Exec; /** * Test case for java.lang.SecurityManager */ -@TestTargetClass(value = SecurityManager.class, - untestedMethods = { - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "AWTPermission class is not supported.", - method = "checkSystemClipboardAccess", - args = {} - ) -}) public class SecurityManagerTest extends TestCase { MutableSecurityManager mutableSM = null; @@ -57,50 +41,9 @@ public class SecurityManagerTest extends TestCase { SecurityManager originalSM = null; - String deletedFile = "/"; - String readedFile = "/"; - String writedFile = "/"; - - /** - * @tests java.lang.SecurityManager#SecurityManager() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "SecurityManager", - args = {} - ) - public void test_Constructor() { - SecurityManager localManager = null; - try { - localManager = new MockSecurityManager(); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - - try { - assertNotNull("Incorrect SecurityManager", localManager); - System.setSecurityManager(localManager); - try { - new MockSecurityManager(); - fail("SecurityException was not thrown"); - } catch (SecurityException se) { - // expected - } - } finally { - System.setSecurityManager(null); - } - } - /** * @tests java.lang.SecurityManager#checkPackageAccess(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPackageAccess", - args = {java.lang.String.class} - ) public void test_checkPackageAccessLjava_lang_String() { final String old = Security.getProperty("package.access"); Security.setProperty("package.access", "a.,bbb, c.d."); @@ -149,12 +92,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests java.lang.SecurityManager#checkPackageDefinition(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPackageDefinition", - args = {java.lang.String.class} - ) public void test_checkPackageDefinitionLjava_lang_String() { final String old = Security.getProperty("package.definition"); Security.setProperty("package.definition", "a.,bbb, c.d."); @@ -203,17 +140,11 @@ public class SecurityManagerTest extends TestCase { /** * @tests java.lang.SecurityManager#checkMemberAccess(java.lang.Class, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkMemberAccess", - args = {java.lang.Class.class, int.class} - ) public void test_checkMemberAccessLjava_lang_ClassI() { // enable all but one check mutableSM.addPermission(new AllPermission()); - mutableSM.denyPermission( - new RuntimePermission("accessDeclaredMembers")); + mutableSM + .denyPermission(new RuntimePermission("accessDeclaredMembers")); System.setSecurityManager(mutableSM); try { getClass().getDeclaredFields(); @@ -223,80 +154,37 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException."); } catch (SecurityException e) { } - - try { - delegateCallToCheckMemberAccess2(Object.class, Member.DECLARED); - fail("SecurityException was not thrown."); - } catch(SecurityException se) { - //expected - } - - try { - delegateCallToCheckMemberAccess2(null, Member.PUBLIC); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } + } finally { System.setSecurityManager(null); } } /** - * Don't call checkMemberAccess directly, since we're checking our caller - * (and not ourselves). This is necessary for unit tests, since JUnit's - * TestCase is usually in the boot classpath for dalvik. This delegating - * method corresponds to Class.getDeclared*(); - */ - private void delegateCallToCheckMemberAccess2(Class<Object> cls, int type) { - delegateCallToCheckMemberAccess1(cls, type); - } - - /** - * This delegating method corresponds to Class.checkMemberAccess(). - */ - private void delegateCallToCheckMemberAccess1(Class<Object> cls, int type) { - mutableSM.checkMemberAccess(cls, type); - } - - /** * @tests java.lang.SecurityManager#checkPermission(java.security.Permission) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPermission", - args = {java.security.Permission.class} - ) + /* BEGIN android-removed: we don't have Support_Exec.execJava. public void test_checkPermissionLjava_security_Permission() throws Exception { // tmp user home to avoid presence of ${user.home}/.java.policy - //String tmpUserHome = System.getProperty("java.io.tmpdir") - // + File.separatorChar + "tmpUserHomeForSecurityManagerTest"; - //File dir = new File(tmpUserHome); - //if (!dir.exists()) { - // dir.mkdirs(); - // dir.deleteOnExit(); - //} - //String javaPolycy = tmpUserHome + File.separatorChar + ".java.policy"; - //assertFalse("There should be no java policy file: " + javaPolycy, - // new File(javaPolycy).exists()); - // - //String[] arg = new String[] { "-Duser.home=" + tmpUserHome, - // checkPermissionLjava_security_PermissionTesting.class.getName() }; - // - //Support_Exec.execJava(arg, null, true); - - checkPermissionLjava_security_PermissionTesting.class.getName(); - - try { - mutableSM.checkPermission(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected + String tmpUserHome = System.getProperty("java.io.tmpdir") + + File.separatorChar + "tmpUserHomeForSecurityManagerTest"; + File dir = new File(tmpUserHome); + if (!dir.exists()) { + dir.mkdirs(); + dir.deleteOnExit(); } + String javaPolycy = tmpUserHome + File.separatorChar + ".java.policy"; + assertFalse("There should be no java policy file: " + javaPolycy, + new File(javaPolycy).exists()); + + String[] arg = new String[] { "-Duser.home=" + tmpUserHome, + checkPermissionLjava_security_PermissionTesting.class.getName() }; + + Support_Exec.execJava(arg, null, true); } + */ private static class checkPermissionLjava_security_PermissionTesting { public static void main(String[] args) { @@ -310,12 +198,6 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException"); } catch (SecurityException e) { } - - try { - sm.checkPermission(new SecurityPermission("setSystemScope")); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } } finally { System.setSecurityManager(null); } @@ -325,259 +207,39 @@ public class SecurityManagerTest extends TestCase { /** * @tests java.lang.SecurityManager#checkAccess(java.lang.Thread) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkAccess", - args = {java.lang.Thread.class} - ) public void test_checkAccessLjava_lang_Thread() throws InterruptedException { // Regression for HARMONY-66 Thread t = new Thread() { @Override public void run() { - } + }; }; t.start(); t.join(); new SecurityManager().checkAccess(t); - - mutableSM.addPermission(new AllPermission()); - mutableSM.denyPermission( new RuntimePermission("modifyThread")); - System.setSecurityManager(mutableSM); - - try { - try { - mutableSM.checkAccess(t); - // should not throw SecurityException for not system thread. - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } - - try { - ThreadGroup initialThreadGroup = Thread.currentThread().getThreadGroup(); - - while (initialThreadGroup.getParent() != null) { - initialThreadGroup = initialThreadGroup.getParent(); - } - Thread [] systemThread = new Thread[1]; - initialThreadGroup.enumerate(systemThread); - mutableSM.checkAccess(systemThread[0]); - fail("SecurityException was not thrown."); - } catch(SecurityException se) { - // expected - } - - - } finally { - System.setSecurityManager(null); - } - - try { - mutableSM.checkAccess((Thread) null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - try { - new SecurityManager().checkAccess((Thread)null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe){ - //expected - } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkAccess", - args = {java.lang.ThreadGroup.class} - ) - public void test_checkAccessLjava_lang_ThreadGroup() { - - ThreadGroup tg = new ThreadGroup("name"); - - RuntimePermission rp = new RuntimePermission("modifyThreadGroup"); - mutableSM.addPermission(new AllPermission()); - - mutableSM.denyPermission(rp); - SecurityManager sm = System.getSecurityManager(); - System.setSecurityManager(mutableSM); - - try { - try { - mutableSM.checkAccess(tg); - - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } - - try { - ThreadGroup initialThreadGroup = Thread.currentThread().getThreadGroup(); - - while (initialThreadGroup.getParent() != null) { - initialThreadGroup = initialThreadGroup.getParent(); - } - mutableSM.checkAccess(initialThreadGroup); - } catch(SecurityException se) { - - } - } finally { - System.setSecurityManager(sm); - } - - try { - mutableSM.checkAccess((ThreadGroup) null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } /** * @tests {@link java.lang.SecurityManager#checkAccept(String, int)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkAccept", - args = {java.lang.String.class, int.class} - ) @SuppressWarnings("nls") public void test_checkAcceptLjava_lang_String_int() { // enable all but one check mutableSM.addPermission(new AllPermission()); - System.setSecurityManager(mutableSM); - try { - assertFalse(startServerSocket()); - assertTrue(mutableSM.isCheckAcceptCalled); - - mutableSM.denyPermission(new SocketPermission("localhost:1024-", - "accept, connect, listen")); - assertTrue(startServerSocket()); - assertTrue(mutableSM.isCheckAcceptCalled); - - try { - mutableSM.checkAccept(null, 0); - fail("NullPointerException is not thrown."); - } catch(NullPointerException npe) { - //expected - } - } finally { - System.setSecurityManager(null); - } - } - - boolean startServerSocket() { - boolean isSecurityExceptionThrown = false; - ServerSocket ss = null; - try { - ss = new ServerSocket(3132); - Thread thr = new Thread() { - Socket s = null; - - public void run() { - try { - s = new Socket(InetAddress.getLocalHost().getHostName(), 3132); - Thread.sleep(1); - } catch(InterruptedException ie) { - fail("InterruptedException was thrown."); - } catch(UnknownHostException uhe) { - fail("UnknownHostException was thrown."); - } catch(IOException ioe) { - fail("IOException was thrown."); - } finally { - try { - s.close(); - } catch(Exception e) {} - } - } - }; - thr.start(); - ss.accept(); - ss.close(); - } catch(IOException ioe) { - fail("IOException was thrown."); - } catch(SecurityException se) { - isSecurityExceptionThrown = true; - } finally { - try { - if(!ss.isClosed()) - ss.close(); - } catch(Exception e) { - } - - } - return isSecurityExceptionThrown; - } - - /** - * @tests {@link java.lang.SecurityManager#checkConnect(String, int)} - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkConnect", - args = {java.lang.String.class, int.class} - ) - public void test_checkConnectLjava_lang_StringI() { - String hostName = "localhost"; - int port = 1024; - - // enable all but one check - mutableSM.addPermission(new AllPermission()); mutableSM.denyPermission(new SocketPermission("localhost:1024-", "accept, connect, listen")); System.setSecurityManager(mutableSM); try { - try { - mutableSM.checkConnect(hostName, port); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - assertTrue(createSocketAddress(hostName, port)); - - try { - mutableSM.checkConnect(hostName, -1); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - try { - mutableSM.checkConnect(null, 1024); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } finally { - System.setSecurityManager(null); + mutableSM.checkAccept("localhost", 1024); + fail("This should throw a SecurityException."); + } catch (SecurityException e) { + // expected } - - assertFalse(createSocketAddress(hostName, port)); } - - boolean createSocketAddress(String hostname, int port) { - try { - new InetSocketAddress(hostname, port); - } catch(SecurityException se) { - return true; - } - return false; - } - /** * @tests {@link java.lang.SecurityManager#checkConnect(String, int, Object)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkConnect", - args = {java.lang.String.class, int.class, java.lang.Object.class} - ) @SuppressWarnings("nls") public void test_checkConnectLjava_lang_String_int_Ljava_lang_Object() { // enable all but one check @@ -585,133 +247,20 @@ public class SecurityManagerTest extends TestCase { mutableSM.denyPermission(new SocketPermission("localhost:1024-", "accept, connect, listen")); System.setSecurityManager(mutableSM); + ProtectionDomain pDomain = this.getClass().getProtectionDomain(); + ProtectionDomain[] pd = { pDomain }; + AccessControlContext acc = new AccessControlContext(pd); try { - ProtectionDomain pDomain = this.getClass().getProtectionDomain(); - ProtectionDomain[] pd = { pDomain }; - AccessControlContext acc = new AccessControlContext(pd); - try { - mutableSM.checkConnect("localhost", 1024, acc); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - try { - mutableSM.checkConnect("localhost", -1, acc); - // The action "resolve" is implicitely in the denied Permission - // that was added to the denied permissions at the beginning of - // this test. So this throws a security Exception on the RI and - // also on android. - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - assertTrue(createSocketAddress("localhost", 1024)); - - try { - mutableSM.checkConnect(null, 1024, acc); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - System.setSecurityManager(null); - try { - mutableSM.checkConnect("localhost", 1024, null); - fail("SecurityException was not thrown."); - } catch(SecurityException se) { - //expected - } - } finally { - System.setSecurityManager(null); - } - assertFalse(createSocketAddress("localhost", 1024)); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkCreateClassLoader", - args = {} - ) - public void test_checkCreateClassLoader() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - System.setSecurityManager(mutableSM); - try { - mutableSM.checkCreateClassLoader(); + mutableSM.checkConnect("localhost", 1024, acc); + fail("This should throw a SecurityException."); } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } - - SecurityManager localManager = new MockSecurityManager(); - try { - System.setSecurityManager(localManager); - try { - localManager.checkCreateClassLoader(); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - } finally { - System.setSecurityManager(null); - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkDelete", - args = {java.lang.String.class} - ) - public void test_checkDeleteLjava_lang_String() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - mutableSM - .denyPermission(new FilePermission("<<ALL FILES>>", "delete")); - try { - System.setSecurityManager(mutableSM); - - try { - mutableSM.checkDelete("new.file"); - fail("SecurityException was not thrown"); - } catch (SecurityException npe) { - // expected - } - - try { - mutableSM.checkDelete(null); - fail("NullPointerException was not thrown"); - } catch (NullPointerException npe) { - // expected - } - } finally { - System.setSecurityManager(null); - } - - SecurityManager localManager = new MockSecurityManager(); - try { - System.setSecurityManager(localManager); - try { - localManager.checkDelete(deletedFile); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - } finally { - System.setSecurityManager(null); + // expected } } /** * @tests {@link java.lang.SecurityManager#checkExec(String)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkExec", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_checkExecLjava_lang_String() { // enable all but one check @@ -724,36 +273,16 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException."); } catch (SecurityException e) { // expected - } finally { - System.setSecurityManager(null); - } - - try { - mutableSM.checkExec(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected } } /** * @tests {@link java.lang.SecurityManager#checkExit(int)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkExit", - args = {int.class} - ) @SuppressWarnings("nls") public void test_checkExit_int() { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkExit(0); - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } mutableSM.denyPermission(new RuntimePermission("exitVM")); System.setSecurityManager(mutableSM); try { @@ -761,20 +290,12 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException."); } catch (SecurityException e) { // expected - } finally { - System.setSecurityManager(null); } } /** * @tests {@link java.lang.SecurityManager#checkLink(String)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkLink", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_checkLinkLjava_lang_String() { // enable all but one check @@ -782,42 +303,20 @@ public class SecurityManagerTest extends TestCase { mutableSM.denyPermission(new RuntimePermission("loadLibrary.harmony")); System.setSecurityManager(mutableSM); try { - try { - mutableSM.checkLink("harmony"); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - try { - mutableSM.checkLink(null); - fail("NullPointerException is not thrown."); - } catch(NullPointerException npe) { - //expected - } - } finally { - System.setSecurityManager(null); + mutableSM.checkLink("harmony"); + fail("This should throw a SecurityException."); + } catch (SecurityException e) { + // expected } } /** * @tests {@link java.lang.SecurityManager#checkListen(int)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkListen", - args = {int.class} - ) @SuppressWarnings("nls") public void test_checkListen_int() { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkListen(80); - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } mutableSM .denyPermission(new SocketPermission("localhost:80", "listen")); System.setSecurityManager(mutableSM); @@ -844,22 +343,11 @@ public class SecurityManagerTest extends TestCase { * @throws UnknownHostException * @tests {@link java.lang.SecurityManager#checkMulticast(java.net.InetAddress)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies SecurityException.", - method = "checkMulticast", - args = {java.net.InetAddress.class} - ) @SuppressWarnings("nls") public void test_checkMulticastLjava_net_InetAddress() throws UnknownHostException { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkMulticast(InetAddress.getByName("localhost")); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } mutableSM.denyPermission(new SocketPermission(InetAddress.getByName( "localhost").getHostAddress(), "accept,connect")); System.setSecurityManager(mutableSM); @@ -868,73 +356,35 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException."); } catch (SecurityException e) { // expected - } finally { - System.setSecurityManager(null); } - - try { - mutableSM.checkMulticast(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException e) { - //expected - } } /** * @throws UnknownHostException * @tests {@link java.lang.SecurityManager#checkMulticast(java.net.InetAddress,byte)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkMulticast", - args = {java.net.InetAddress.class, byte.class} - ) @SuppressWarnings( { "nls", "deprecation" }) public void test_checkMulticastLjava_net_InetAddress_int() throws UnknownHostException { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkMulticast( - InetAddress.getByName("localhost"), (byte) 0); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } mutableSM.denyPermission(new SocketPermission(InetAddress.getByName( "localhost").getHostAddress(), "accept,connect")); System.setSecurityManager(mutableSM); try { - try { - // the second parameter is the TTL(time to live) - mutableSM.checkMulticast(InetAddress.getByName("localhost"), - (byte) 0); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - try { - mutableSM.checkMulticast(null, (byte) 0); - fail("NullPointerException is not thrown."); - } catch(NullPointerException ne) { - //expected - } - } finally { - System.setSecurityManager(null); + // the second parameter is the TTL(time to live) + mutableSM.checkMulticast(InetAddress.getByName("localhost"), + (byte) 0); + fail("This should throw a SecurityException."); + } catch (SecurityException e) { + // expected } } /** - * + * * @tests {@link java.lang.SecurityManager#checkPermission(Permission, Object)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPermission", - args = {java.security.Permission.class, java.lang.Object.class} - ) @SuppressWarnings("nls") public void test_checkPermissionLjava_security_PermissionLjava_lang_Object() { // enable all but one check @@ -951,43 +401,16 @@ public class SecurityManagerTest extends TestCase { fail("This should throw a SecurityException."); } catch (SecurityException e) { // expected - } finally { - System.setSecurityManager(null); } - - try { - mutableSM.checkPermission(null, acc); - fail("NullPointerException was not thrown."); - } catch (NullPointerException npe) { - // expected - } - - try { - mutableSM.checkPermission(denyp, null); - fail("SecurityException was not thrown."); - } catch (SecurityException se) { - // expected - } } /** * @tests {@link java.lang.SecurityManager#checkPrintJobAccess()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPrintJobAccess", - args = {} - ) @SuppressWarnings("nls") public void test_checkPrintJobAccess() { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkPrintJobAccess(); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } mutableSM.denyPermission(new RuntimePermission("queuePrintJob")); System.setSecurityManager(mutableSM); try { @@ -997,99 +420,14 @@ public class SecurityManagerTest extends TestCase { // expected } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPropertiesAccess", - args = {} - ) - public void test_checkPropertiesAccess() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - System.setSecurityManager(mutableSM); - try { - mutableSM.checkPropertiesAccess(); - } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } finally { - System.setSecurityManager(null); - } - - SecurityManager localManager = new MockSecurityManager(); - try { - System.setSecurityManager(localManager); - try { - localManager.checkPropertiesAccess(); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - } finally { - System.setSecurityManager(null); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkPropertyAccess", - args = {java.lang.String.class} - ) - public void test_checkPropertyAccessLjava_lang_String() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - System.setSecurityManager(mutableSM); - try { - mutableSM.checkPropertyAccess("key"); - } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } finally { - System.setSecurityManager(null); - } - - SecurityManager localManager = new MockSecurityManager(); - try { - System.setSecurityManager(localManager); - try { - localManager.checkPropertyAccess("key"); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - try { - localManager.checkPropertyAccess(""); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - try { - localManager.checkPropertyAccess(null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } finally { - System.setSecurityManager(null); - } - } /** * @tests {@link java.lang.SecurityManager#checkRead(FileDescriptor)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkRead", - args = {java.io.FileDescriptor.class} - ) @SuppressWarnings("nls") public void test_checkReadLjava_io_FileDescriptor() { // enable all but one check mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkRead(new FileDescriptor()); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } mutableSM.denyPermission(new RuntimePermission("readFileDescriptor")); System.setSecurityManager(mutableSM); try { @@ -1099,314 +437,47 @@ public class SecurityManagerTest extends TestCase { // expected } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkRead", - args = {java.lang.String.class} - ) - public void test_checkReadLjava_lang_String() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkRead(readedFile); - } catch(SecurityException se) { - fail("SecurityException is thrown."); - } - mutableSM.denyPermission(new RuntimePermission("readFileDescriptor")); - System.setSecurityManager(mutableSM); - try { - try { - mutableSM.checkRead(readedFile); - } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } - - SecurityManager localManager = new MockSecurityManager(); - System.setSecurityManager(localManager); - try { - localManager.checkRead(readedFile); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - - try { - localManager.checkRead((String) null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } finally { - System.setSecurityManager(null); - } - } /** * @tests {@link java.lang.SecurityManager#checkRead(String,Object)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies SecurityException.", - method = "checkRead", - args = {java.lang.String.class, java.lang.Object.class} - ) @SuppressWarnings("nls") public void test_checkReadLjava_lang_StringLjava_lang_Object() { // enable all but one check mutableSM.addPermission(new AllPermission()); + mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read")); ProtectionDomain pDomain = this.getClass().getProtectionDomain(); ProtectionDomain[] pd = { pDomain }; - AccessControlContext acc = new AccessControlContext(pd); - mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read")); - System.setSecurityManager(mutableSM); - try { - try { - mutableSM.checkRead("aa", acc); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - try { - mutableSM.checkRead(null, acc); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } finally { - System.setSecurityManager(null); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkSecurityAccess", - args = {java.lang.String.class} - ) - public void test_checkSecurityAccessLjava_lang_String() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); + AccessControlContext acc = new AccessControlContext(pd); System.setSecurityManager(mutableSM); try { - mutableSM.checkSecurityAccess("getPolicy"); + mutableSM.checkRead("aa", acc); + fail("This should throw a SecurityException."); } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } finally { - System.setSecurityManager(null); - } - - SecurityManager localManager = new MockSecurityManager(); - try { - System.setSecurityManager(localManager); - try { - localManager.checkSecurityAccess("getPolicy"); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - try { - localManager.checkSecurityAccess(""); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - try { - localManager.checkSecurityAccess(null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } finally { - System.setSecurityManager(null); + // expected } } /** * @tests {@link java.lang.SecurityManager#checkSetFactory()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkSetFactory", - args = {} - ) @SuppressWarnings("nls") public void test_checkSetFactory() { // enable all but one check mutableSM.addPermission(new AllPermission()); - assertFalse(setFactory()); mutableSM.denyPermission(new RuntimePermission("setFactory")); System.setSecurityManager(mutableSM); try { - try { - mutableSM.checkSetFactory(); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - assertTrue(setFactory()); - } finally { - System.setSecurityManager(null); - } - } - - boolean setFactory() { - try { - ServerSocket.setSocketFactory(null); - } catch(IOException ioe) { - fail("IOException was thrown."); - } catch(SecurityException se) { - return true; - } - return false; - } - - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "Mark this method not feasable: AWTPermission doesn't exist", - method = "checkAwtEventQueueAccess", - args = {} - ) - public void test_checkAwtEventQueueAccess() { - mutableSM.addPermission(new AllPermission()); - // TODO AWTPermission class is unavailable - //mutableSM.denyPermission(new AWTPermission("accessEventQueue")); - //System.setSecurityManager(mutableSM); - //try { - // try { - // mutableSM.checkAwtEventQueueAccess(); - // fail("This should throw a SecurityException."); - // } catch (SecurityException e) { - // expected - // } - //} finally { - // System.setSecurityManager(null); - //} - } - - @TestTargetNew( - level = TestLevel.NOT_NECESSARY, - notes = "Mark this method not feasable: AWTPermission doesn't exist", - method = "checkTopLevelWindow", - args = {java.lang.Object.class} - ) - public void test_checkTopLevelWindowLjava_lang_Object() { - // assertFalse("Calling thread isn't trusted to bring up the top-level window", - // mutableSM.checkTopLevelWindow(this)); - - try { - SecurityManager localManager = new MockSecurityManager(); - System.setSecurityManager(localManager); - assertTrue("Calling thread is trusted to bring up the top-level window", - localManager.checkTopLevelWindow(this)); - try { - localManager.checkTopLevelWindow(null); - fail("Expected NullPointerexception was not thrown"); - } catch (NullPointerException e) { - // expected - } - } finally { - System.setSecurityManager(null); - } - //TODO AWTPermission class is unavailable - //mutableSM.addPermission(new AllPermission()); - //assertTrue(mutableSM.checkTopLevelWindow(new Object())); - //mutableSM.denyPermission(new AWTPermission("showWindowWithoutWarningBanner")); - //System.setSecurityManager(mutableSM); - //try { - // assertFalse(mutableSM.checkTopLevelWindow(new Object())); - //} finally { - // System.setSecurityManager(null); - //} - - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkWrite", - args = {java.io.FileDescriptor.class} - ) - public void test_checkWriteLjava_io_FileDescriptor() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkWrite(new FileDescriptor()); - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } - mutableSM.denyPermission(new RuntimePermission("writeFileDescriptor")); - System.setSecurityManager(mutableSM); - try { - mutableSM.checkWrite(new FileDescriptor()); + mutableSM.checkSetFactory(); fail("This should throw a SecurityException."); } catch (SecurityException e) { // expected - } finally { - System.setSecurityManager(null); - } - - try { - mutableSM.checkWrite((FileDescriptor) null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "checkWrite", - args = {java.lang.String.class} - ) - public void test_checkWriteLjava_lang_String() { - // enable all but one check - mutableSM.addPermission(new AllPermission()); - try { - mutableSM.checkWrite(writedFile); - } catch(SecurityException se) { - fail("SecurityException was thrown."); - } - mutableSM.denyPermission(new RuntimePermission("writeFileDescriptor")); - System.setSecurityManager(mutableSM); - try { - mutableSM.checkWrite(writedFile); - } catch (SecurityException e) { - fail("Unexpected SecurityException " + e.toString()); - } finally { - System.setSecurityManager(null); - } - - try { - SecurityManager localManager = new MockSecurityManager(); - System.setSecurityManager(localManager); - try { - localManager.checkWrite(writedFile); - fail("Expected SecurityException was not thrown"); - } catch (SecurityException e) { - // expected - } - } finally { - System.setSecurityManager(null); - } - - try { - mutableSM.checkWrite((String) null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected } } /** * @tests {@link java.lang.SecurityManager#getInCheck()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getInCheck", - args = {} - ) public void test_getIncheck() { mockSM.setInCheck(false); assertFalse(mockSM.getInCheck()); @@ -1417,12 +488,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#getSecurityContext()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSecurityContext", - args = {} - ) @SuppressWarnings("nls") public void test_getSecurityContext() { // enable all but one check @@ -1430,61 +495,16 @@ public class SecurityManagerTest extends TestCase { mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read")); System.setSecurityManager(mutableSM); try { - try { - mutableSM.getSecurityContext(); - } catch(Exception e) { - fail("Unexpected exception was thrown: " + e.toString()); - } - - try { - mutableSM.checkRead("aa", mutableSM.getSecurityContext()); - fail("This should throw a SecurityException."); - } catch (SecurityException e) { - // expected - } - - } finally { - System.setSecurityManager(null); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getThreadGroup", - args = {} - ) - public void test_getThreadGroup() throws InterruptedException { - final ThreadGroup tgroup = new ThreadGroup(mutableSM.getThreadGroup(), - "groupName"); - assertNotNull("Incorrect thread group", tgroup); - class MyThread extends Thread{ - public int newCount; - - public MyThread() { - super(tgroup, "threadName"); - } - - @Override - public void run() { - super.run(); - newCount = tgroup.activeCount(); - } + mutableSM.checkRead("aa", mutableSM.getSecurityContext()); + fail("This should throw a SecurityException."); + } catch (SecurityException e) { + // expected } - MyThread t = new MyThread(); - t.start(); - t.join(); - assertEquals("Incorrect active count value", 1, t.newCount); } /** * @tests {@link java.lang.SecurityManager#classDepth(String)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = ".", - method = "classDepth", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_classDepthLjava_lang_String() { assertEquals(-1, mockSM.classDepth("nothing")); @@ -1493,12 +513,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#classLoaderDepth()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "classLoaderDepth", - args = {} - ) public void test_classLoaderDepth() { assertEquals(-1, mockSM.classLoaderDepth()); } @@ -1506,12 +520,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#currentClassLoader()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "currentClassLoader", - args = {} - ) public void test_currentClassLoader() { assertNull(mockSM.currentClassLoader()); } @@ -1519,12 +527,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#currentLoadedClass()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "currentLoadedClass", - args = {} - ) public void test_currentLoadedClass() { assertNull(mockSM.currentLoadedClass()); } @@ -1532,12 +534,6 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#inClass(String)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "inClass", - args = {java.lang.String.class} - ) @SuppressWarnings("nls") public void test_inClassLjava_lang_String() { assertFalse(mockSM.inClass("nothing")); @@ -1547,43 +543,60 @@ public class SecurityManagerTest extends TestCase { /** * @tests {@link java.lang.SecurityManager#inClassLoader()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "inClassLoader", - args = {} - ) public void test_inClassLoader() { assertFalse(mockSM.inClassLoader()); } /** - * @tests {@link java.lang.SecurityManager#getClassContext()} + * @tests {@link java.lang.SecurityManager#inClassLoader()} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getClassContext", - args = {} - ) public void test_getClassContext() { - - Class [] stack = {MockSecurityManager.class, - getClass(), TestCase.class}; - - Class [] returnedStack = mockSM.getClassContext(); - - assertNotNull(returnedStack); - assertTrue(returnedStack.length > stack.length); - for(int i = 0; i < stack.length; i++) { - assertEquals(stack[i].getName() + " class should have " + i + - " position in the classes stack, but there is " + - returnedStack[i].getName(), - stack[i], returnedStack[i]); - } + assertEquals("MockSecurityManager should be the first in the classes stack", + mockSM.getClassContext()[0], MockSecurityManager.class); } // set some protected method to public for testing + class MockSecurityManager extends SecurityManager { + + public void setInCheck(boolean inCheck) { + super.inCheck = inCheck; + } + + @Override + public int classDepth(String name) { + return super.classDepth(name); + } + + @Override + public int classLoaderDepth() { + return super.classLoaderDepth(); + } + + @Override + public ClassLoader currentClassLoader() { + return super.currentClassLoader(); + } + + @Override + public Class<?> currentLoadedClass() { + return super.currentLoadedClass(); + } + + @Override + public Class[] getClassContext() { + return super.getClassContext(); + } + + @Override + public boolean inClass(String name) { + return super.inClass(name); + } + + @Override + public boolean inClassLoader() { + return super.inClassLoader(); + } + } @Override protected void setUp() throws Exception { diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java index 34f9958..30c9ea7 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java @@ -16,14 +16,8 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(Short.class) public class ShortTest extends TestCase { private Short sp = new Short((short) 18000); private Short sn = new Short((short) -19000); @@ -31,12 +25,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#byteValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks boundary values.", - method = "byteValue", - args = {} - ) public void test_byteValue() { // Test for method byte java.lang.Short.byteValue() assertEquals("Returned incorrect byte value", 0, new Short(Short.MIN_VALUE) @@ -48,12 +36,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#compareTo(java.lang.Short) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.lang.Short.class} - ) public void test_compareToLjava_lang_Short() { // Test for method int java.lang.Short.compareTo(java.lang.Short) Short s = new Short((short) 1); @@ -79,12 +61,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#decode(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Doesn't check that no whitespace characters are permitted in the String. ", - method = "decode", - args = {java.lang.String.class} - ) public void test_decodeLjava_lang_String2() { // Test for method java.lang.Short // java.lang.Short.decode(java.lang.String) @@ -153,12 +129,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#parseShort(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "parseShort", - args = {java.lang.String.class} - ) public void test_parseShortLjava_lang_String2() { // Test for method short java.lang.Short.parseShort(java.lang.String) short sp = Short.parseShort("32746"); @@ -194,12 +164,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#parseShort(java.lang.String, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "parseShort", - args = {java.lang.String.class, int.class} - ) public void test_parseShortLjava_lang_StringI2() { // Test for method short java.lang.Short.parseShort(java.lang.String, // int) @@ -293,12 +257,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString2() { // Test for method java.lang.String java.lang.Short.toString() assertTrue("Invalid string returned", sp.toString().equals("18000") @@ -314,12 +272,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#toString(short) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "toString", - args = {short.class} - ) public void test_toStringS2() { // Test for method java.lang.String java.lang.Short.toString(short) assertEquals("Returned incorrect string", "32767", Short.toString((short) 32767) @@ -333,12 +285,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#valueOf(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks boundary values.", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String2() { // Test for method java.lang.Short // java.lang.Short.valueOf(java.lang.String) @@ -351,12 +297,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#valueOf(java.lang.String, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class, int.class} - ) public void test_valueOfLjava_lang_StringI2() { // Test for method java.lang.Short // java.lang.Short.valueOf(java.lang.String, int) @@ -400,37 +340,25 @@ public class ShortTest extends TestCase { fail( "Failed to throw exception when passed string larger than 16 bits"); } - /** - * @tests java.lang.Short#valueOf(short) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {short.class} - ) - public void test_valueOfS() { - assertEquals(new Short(Short.MIN_VALUE), Short.valueOf(Short.MIN_VALUE)); - assertEquals(new Short(Short.MAX_VALUE), Short.valueOf(Short.MAX_VALUE)); - assertEquals(new Short((short) 0), Short.valueOf((short) 0)); - - short s = -128; - while (s < 128) { - assertEquals(new Short(s), Short.valueOf(s)); - assertSame(Short.valueOf(s), Short.valueOf(s)); - s++; - } - } + /** + * @tests java.lang.Short#valueOf(byte) + */ + public void test_valueOfS() { + assertEquals(new Short(Short.MIN_VALUE), Short.valueOf(Short.MIN_VALUE)); + assertEquals(new Short(Short.MAX_VALUE), Short.valueOf(Short.MAX_VALUE)); + assertEquals(new Short((short) 0), Short.valueOf((short) 0)); + + short s = -128; + while (s < 128) { + assertEquals(new Short(s), Short.valueOf(s)); + assertSame(Short.valueOf(s), Short.valueOf(s)); + s++; + } + } /** * @tests java.lang.Short#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { assertEquals(1, new Short((short)1).hashCode()); assertEquals(2, new Short((short)2).hashCode()); @@ -441,12 +369,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#Short(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Short", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { assertEquals(new Short((short)0), new Short("0")); assertEquals(new Short((short)1), new Short("1")); @@ -476,12 +398,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#Short(short) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "Short", - args = {short.class} - ) public void test_ConstructorS() { assertEquals(1, new Short((short)1).shortValue()); assertEquals(2, new Short((short)2).shortValue()); @@ -492,13 +408,7 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#byteValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check boundary values.", - method = "byteValue", - args = {} - ) - public void test_byteValue1() { + public void test_booleanValue() { assertEquals(1, new Short((short)1).byteValue()); assertEquals(2, new Short((short)2).byteValue()); assertEquals(0, new Short((short)0).byteValue()); @@ -508,12 +418,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#equals(Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { assertEquals(new Short((short)0), Short.valueOf((short)0)); assertEquals(new Short((short)1), Short.valueOf((short)1)); @@ -528,12 +432,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { assertEquals("-1", new Short((short)-1).toString()); assertEquals("0", new Short((short)0).toString()); @@ -544,12 +442,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#toString(short) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "toString", - args = {short.class} - ) public void test_toStringS() { assertEquals("-1", Short.toString((short)-1)); assertEquals("0", Short.toString((short)0)); @@ -560,12 +452,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#valueOf(String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't check boundary values.", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String() { assertEquals(new Short((short)0), Short.valueOf("0")); assertEquals(new Short((short)1), Short.valueOf("1")); @@ -595,12 +481,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#valueOf(String,int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class, int.class} - ) public void test_valueOfLjava_lang_StringI() { assertEquals(new Short((short)0), Short.valueOf("0", 10)); assertEquals(new Short((short)1), Short.valueOf("1", 10)); @@ -634,12 +514,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#parseShort(String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Doesn't check boundary values, unicodes.", - method = "parseShort", - args = {java.lang.String.class} - ) public void test_parseShortLjava_lang_String() { assertEquals(0, Short.parseShort("0")); assertEquals(1, Short.parseShort("1")); @@ -669,12 +543,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#parseShort(String,int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Doesn't check boundary values.", - method = "parseShort", - args = {java.lang.String.class, int.class} - ) public void test_parseShortLjava_lang_StringI() { assertEquals(0, Short.parseShort("0", 10)); assertEquals(1, Short.parseShort("1", 10)); @@ -708,12 +576,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#decode(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "decode", - args = {java.lang.String.class} - ) public void test_decodeLjava_lang_String() { assertEquals(new Short((short)0), Short.decode("0")); assertEquals(new Short((short)1), Short.decode("1")); @@ -724,13 +586,6 @@ public class ShortTest extends TestCase { assertEquals(new Short((short)07), Short.decode("07")); try { - Short.decode(" 0 "); - fail("NumberFormatException is not thrown."); - } catch(NumberFormatException nfe) { - //expected - } - - try { Short.decode("9.2"); fail("Expected NumberFormatException with floating point string."); } catch (NumberFormatException e) {} @@ -750,12 +605,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#doubleValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "doubleValue", - args = {} - ) public void test_doubleValue() { assertEquals(-1D, new Short((short)-1).doubleValue(), 0D); assertEquals(0D, new Short((short)0).doubleValue(), 0D); @@ -765,12 +614,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#floatValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "floatValue", - args = {} - ) public void test_floatValue() { assertEquals(-1F, new Short((short)-1).floatValue(), 0F); assertEquals(0F, new Short((short)0).floatValue(), 0F); @@ -780,12 +623,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#intValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "intValue", - args = {} - ) public void test_intValue() { assertEquals(-1, new Short((short)-1).intValue()); assertEquals(0, new Short((short)0).intValue()); @@ -795,12 +632,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#longValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "longValue", - args = {} - ) public void test_longValue() { assertEquals(-1L, new Short((short)-1).longValue()); assertEquals(0L, new Short((short)0).longValue()); @@ -810,12 +641,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#shortValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "shortValue", - args = {} - ) public void test_shortValue() { assertEquals(-1, new Short((short)-1).shortValue()); assertEquals(0, new Short((short)0).shortValue()); @@ -825,12 +650,6 @@ public class ShortTest extends TestCase { /** * @tests java.lang.Short#reverseBytes(short) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reverseBytes", - args = {short.class} - ) public void test_reverseBytesS() { assertEquals((short)0xABCD, Short.reverseBytes((short)0xCDAB)); assertEquals((short)0x1234, Short.reverseBytes((short)0x3412)); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java index 009349f..b4e928f 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(StackOverflowError.class) public class StackOverflowErrorTest extends TestCase { - /** - * @tests java.lang.StackOverflowError#StackOverflowError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StackOverflowError", - args = {} - ) + /** + * @tests java.lang.StackOverflowError#StackOverflowError() + */ public void test_Constructor() { StackOverflowError e = new StackOverflowError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class StackOverflowErrorTest extends TestCase { /** * @tests java.lang.StackOverflowError#StackOverflowError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StackOverflowError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { StackOverflowError e = new StackOverflowError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java index 79b87fc..1f5de93 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java @@ -16,30 +16,18 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.io.Serializable; import junit.framework.TestCase; -import java.io.Serializable; - import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(StringBuffer.class) public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer#setLength(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IndexOutOfBoundsException.", - method = "setLength", - args = {int.class} - ) public void test_setLengthI() { // Regression for HARMONY-90 StringBuffer buffer = new StringBuffer("abcde"); @@ -49,22 +37,81 @@ public class StringBufferTest extends TestCase { } catch (IndexOutOfBoundsException e) { // expected } + + assertEquals("abcde", buffer.toString()); + buffer.setLength(1); + buffer.append('f'); + assertEquals("af", buffer.toString()); + + buffer = new StringBuffer("abcde"); + assertEquals("cde", buffer.substring(2)); + buffer.setLength(3); + buffer.append('f'); + assertEquals("abcf", buffer.toString()); + + buffer = new StringBuffer("abcde"); + buffer.setLength(2); + try { + buffer.charAt(3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + buffer = new StringBuffer(); + buffer.append("abcdefg"); + buffer.setLength(2); + buffer.setLength(5); + for (int i = 2; i < 5; i++) { + assertEquals(0, buffer.charAt(i)); + } + + buffer = new StringBuffer(); + buffer.append("abcdefg"); + buffer.delete(2, 4); + buffer.setLength(7); + assertEquals('a', buffer.charAt(0)); + assertEquals('b', buffer.charAt(1)); + assertEquals('e', buffer.charAt(2)); + assertEquals('f', buffer.charAt(3)); + assertEquals('g', buffer.charAt(4)); + for (int i = 5; i < 7; i++) { + assertEquals(0, buffer.charAt(i)); + } + + buffer = new StringBuffer(); + buffer.append("abcdefg"); + buffer.replace(2, 5, "z"); + buffer.setLength(7); + for (int i = 5; i < 7; i++) { + assertEquals(0, buffer.charAt(i)); + } } - + + /** + * @tests java.lang.StringBuffer#toString() + */ + public void test_toString() throws Exception { + StringBuffer buffer = new StringBuffer(); + assertEquals("", buffer.toString()); + + buffer.append("abcde"); + assertEquals("abcde", buffer.toString()); + buffer.setLength(1000); + byte[] bytes = buffer.toString().getBytes("GB18030"); + for (int i = 5; i < bytes.length; i++) { + assertEquals(0, bytes[i]); + } + + buffer.setLength(5); + buffer.append("fghij"); + assertEquals("abcdefghij", buffer.toString()); + } + /** * @tests StringBuffer.StringBuffer(CharSequence); */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringBuffer", - args = {java.lang.CharSequence.class} - ) public void test_constructorLjava_lang_CharSequence() { - String str = "Test string"; - StringBuffer sb = new StringBuffer((CharSequence) str); - assertEquals(str.length(), sb.length()); - try { new StringBuffer((CharSequence) null); fail("Assert 0: NPE must be thrown."); @@ -72,12 +119,7 @@ public class StringBufferTest extends TestCase { assertEquals("Assert 1: must equal 'abc'.", "abc", new StringBuffer((CharSequence)"abc").toString()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "trimToSize", - args = {} - ) + public void test_trimToSize() { StringBuffer buffer = new StringBuffer(25); buffer.append("abc"); @@ -92,12 +134,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.append(CharSequence) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.CharSequence.class} - ) public void test_appendLjava_lang_CharSequence() { StringBuffer sb = new StringBuffer(); assertSame(sb, sb.append((CharSequence) "ab")); @@ -109,35 +145,10 @@ public class StringBufferTest extends TestCase { assertSame(sb, sb.append((CharSequence) null)); assertEquals("null", sb.toString()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.StringBuffer.class} - ) - public void test_appendLStringBuffer() { - StringBuffer originalSB = new StringBuffer(); - StringBuffer sb1 = new StringBuffer("append1"); - StringBuffer sb2 = new StringBuffer("append2"); - originalSB.append(sb1); - assertEquals(sb1.toString(), originalSB.toString()); - originalSB.append(sb2); - assertEquals(sb1.toString() + sb2.toString(), originalSB.toString()); - originalSB.append((StringBuffer) null); - assertEquals(sb1.toString() + sb2.toString() + "null", - originalSB.toString()); - } /** * @tests java.lang.StringBuffer.append(CharSequence, int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.CharSequence.class, int.class, int.class} - ) @SuppressWarnings("cast") public void test_appendLjava_lang_CharSequenceII() { StringBuffer sb = new StringBuffer(); @@ -155,24 +166,11 @@ public class StringBufferTest extends TestCase { sb.setLength(0); assertSame(sb, sb.append((CharSequence) null, 0, 2)); assertEquals("nu", sb.toString()); - - try { - sb.append((CharSequence) "abcd", -1, 2); - fail("IndexOutOfBoundsException was thrown."); - } catch(IndexOutOfBoundsException e) { - //expected - } } /** * @tests java.lang.StringBuffer.append(char[], int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ArrayIndexOutOfBoundsException.", - method = "append", - args = {char[].class, int.class, int.class} - ) public void test_append$CII_2() { StringBuffer obj = new StringBuffer(); try { @@ -186,12 +184,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.append(char[], int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "append", - args = {char[].class, int.class, int.class} - ) public void test_append$CII_3() throws Exception { StringBuffer obj = new StringBuffer(); try { @@ -205,12 +197,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.insert(int, CharSequence) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.CharSequence.class} - ) public void test_insertILjava_lang_CharSequence() { final String fixture = "0000"; StringBuffer sb = new StringBuffer(fixture); @@ -253,12 +239,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.insert(int, CharSequence, int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.CharSequence.class, int.class, int.class} - ) @SuppressWarnings("cast") public void test_insertILjava_lang_CharSequenceII() { final String fixture = "0000"; @@ -341,12 +321,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.insert(int, char) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ArrayIndexOutOfBoundsException.", - method = "insert", - args = {int.class, char.class} - ) public void test_insertIC() { StringBuffer obj = new StringBuffer(); try { @@ -360,12 +334,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.appendCodePoint(int)' */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "appendCodePoint", - args = {int.class} - ) public void test_appendCodePointI() { StringBuffer sb = new StringBuffer(); sb.appendCodePoint(0x10000); @@ -379,12 +347,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.codePointAt(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointAt", - args = {int.class} - ) public void test_codePointAtI() { StringBuffer sb = new StringBuffer("abc"); assertEquals('a', sb.codePointAt(0)); @@ -420,12 +382,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.codePointBefore(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointBefore", - args = {int.class} - ) public void test_codePointBeforeI() { StringBuffer sb = new StringBuffer("abc"); assertEquals('a', sb.codePointBefore(1)); @@ -461,12 +417,6 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.codePointCount(int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointCount", - args = {int.class, int.class} - ) public void test_codePointCountII() { assertEquals(1, new StringBuffer("\uD800\uDC00").codePointCount(0, 2)); assertEquals(1, new StringBuffer("\uD800\uDC01").codePointCount(0, 2)); @@ -502,41 +452,19 @@ public class StringBufferTest extends TestCase { /** * @tests java.lang.StringBuffer.getChars(int, int, char[], int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IndexOutOfBoundsException, NullPointerException.", - method = "getChars", - args = {int.class, int.class, char[].class, int.class} - ) public void test_getCharsII$CI() { StringBuffer obj = new StringBuffer(); try { obj.getChars(0, 0, new char[0], -1); -// TODO(Fixed) According to spec this should be IndexOutOfBoundsException. -// fail("ArrayIndexOutOfBoundsException expected"); -// } catch (ArrayIndexOutOfBoundsException e) { - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { + fail("ArrayIndexOutOfBoundsException expected"); + } catch (ArrayIndexOutOfBoundsException e) { // expected } - - try { - obj.getChars(0, 0, null, -1); - fail("NullPointerException is not thrown."); - } catch(NullPointerException npe) { - //expected - } } /** * @tests java.lang.StringBuffer.offsetByCodePoints(int, int)' */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "offsetByCodePoints", - args = {int.class, int.class} - ) public void test_offsetByCodePointsII() { int result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(0, 2); assertEquals(3, result); @@ -602,12 +530,6 @@ public class StringBufferTest extends TestCase { /** * @tests {@link java.lang.StringBuffer#indexOf(String, int)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "indexOf", - args = {java.lang.String.class, int.class} - ) @SuppressWarnings("nls") public void test_IndexOfStringInt() { final String fixture = "0123456789"; @@ -638,12 +560,6 @@ public class StringBufferTest extends TestCase { /** * @tests {@link java.lang.StringBuffer#lastIndexOf(String, int)} */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "lastIndexOf", - args = {java.lang.String.class, int.class} - ) @SuppressWarnings("nls") public void test_lastIndexOfLjava_lang_StringI() { final String fixture = "0123456789"; @@ -689,12 +605,6 @@ public class StringBufferTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new StringBuffer("0123456789"), @@ -704,12 +614,6 @@ public class StringBufferTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new StringBuffer("0123456789"), diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java index 0243fdb..596453d 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java @@ -17,565 +17,412 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.Arrays; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(StringBuilder.class) public class StringBuilderTest extends TestCase { - /** - * @tests java.lang.StringBuilder.StringBuilder() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringBuilder", - args = {} - ) - public void test_Constructor() { - StringBuilder sb = new StringBuilder(); - assertNotNull(sb); - assertEquals(16, sb.capacity()); - } - - /** - * @tests java.lang.StringBuilder.StringBuilder(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringBuilder", - args = {int.class} - ) - public void test_ConstructorI() { - StringBuilder sb = new StringBuilder(24); - assertNotNull(sb); - assertEquals(24, sb.capacity()); - - try { - new StringBuilder(-1); - fail("no exception"); - } catch (NegativeArraySizeException e) { - // Expected - } - - assertNotNull(new StringBuilder(0)); - } - - /** - * @tests java.lang.StringBuilder.StringBuilder(CharSequence) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringBuilder", - args = {java.lang.CharSequence.class} - ) - @SuppressWarnings("cast") + /** + * @tests java.lang.StringBuilder.StringBuilder() + */ + public void test_Constructor() { + StringBuilder sb = new StringBuilder(); + assertNotNull(sb); + assertEquals(16, sb.capacity()); + } + + /** + * @tests java.lang.StringBuilder.StringBuilder(int) + */ + public void test_ConstructorI() { + StringBuilder sb = new StringBuilder(24); + assertNotNull(sb); + assertEquals(24, sb.capacity()); + + try { + new StringBuilder(-1); + fail("no exception"); + } catch (NegativeArraySizeException e) { + // Expected + } + + assertNotNull(new StringBuilder(0)); + } + + /** + * @tests java.lang.StringBuilder.StringBuilder(CharSequence) + */ + @SuppressWarnings("cast") public void test_ConstructorLjava_lang_CharSequence() { - StringBuilder sb = new StringBuilder((CharSequence) "fixture"); - assertEquals("fixture", sb.toString()); - assertEquals("fixture".length() + 16, sb.capacity()); - - sb = new StringBuilder((CharSequence) new StringBuffer("fixture")); - assertEquals("fixture", sb.toString()); - assertEquals("fixture".length() + 16, sb.capacity()); - - try { - new StringBuilder((CharSequence) null); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.StringBuilder(String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringBuilder", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { - StringBuilder sb = new StringBuilder("fixture"); - assertEquals("fixture", sb.toString()); - assertEquals("fixture".length() + 16, sb.capacity()); - - try { - new StringBuilder((String) null); - fail("no NPE"); - } catch (NullPointerException e) { - } - } - - /** - * @tests java.lang.StringBuilder.append(boolean) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {boolean.class} - ) - public void test_appendZ() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(true)); - assertEquals("true", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(false)); - assertEquals("false", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(char) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {char.class} - ) - public void test_appendC() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append('a')); - assertEquals("a", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append('b')); - assertEquals("b", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(char[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {char[].class} - ) - public void test_append$C() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(new char[] { 'a', 'b' })); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(new char[] { 'c', 'd' })); - assertEquals("cd", sb.toString()); - try { - sb.append((char[]) null); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.append(char[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {char[].class, int.class, int.class} - ) - public void test_append$CII() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(new char[] { 'a', 'b' }, 0, 2)); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(new char[] { 'c', 'd' }, 0, 2)); - assertEquals("cd", sb.toString()); - - sb.setLength(0); - assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, 2)); - assertEquals("ab", sb.toString()); - - sb.setLength(0); - assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 2)); - assertEquals("cd", sb.toString()); - - sb.setLength(0); - assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 0)); - assertEquals("", sb.toString()); - - try { - sb.append((char[]) null, 0, 2); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - - try { - sb.append(new char[] { 'a', 'b', 'c', 'd' }, -1, 2); - fail("no IOOBE, negative offset"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, -1); - fail("no IOOBE, negative length"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 3); - fail("no IOOBE, offset and length overflow"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.append(CharSequence) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.CharSequence.class} - ) - public void test_appendLjava_lang_CharSequence() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append((CharSequence) "ab")); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) "cd")); - assertEquals("cd", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) null)); - assertEquals("null", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(CharSequence, int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.CharSequence.class, int.class, int.class} - ) - @SuppressWarnings("cast") + StringBuilder sb = new StringBuilder((CharSequence) "fixture"); + assertEquals("fixture", sb.toString()); + assertEquals("fixture".length() + 16, sb.capacity()); + + sb = new StringBuilder((CharSequence) new StringBuffer("fixture")); + assertEquals("fixture", sb.toString()); + assertEquals("fixture".length() + 16, sb.capacity()); + + try { + new StringBuilder((CharSequence) null); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.StringBuilder(String) + */ + public void test_ConstructorLjava_lang_String() { + StringBuilder sb = new StringBuilder("fixture"); + assertEquals("fixture", sb.toString()); + assertEquals("fixture".length() + 16, sb.capacity()); + + try { + new StringBuilder((String) null); + fail("no NPE"); + } catch (NullPointerException e) { + } + } + + /** + * @tests java.lang.StringBuilder.append(boolean) + */ + public void test_appendZ() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(true)); + assertEquals("true", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(false)); + assertEquals("false", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(char) + */ + public void test_appendC() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append('a')); + assertEquals("a", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append('b')); + assertEquals("b", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(char[]) + */ + public void test_append$C() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(new char[] { 'a', 'b' })); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(new char[] { 'c', 'd' })); + assertEquals("cd", sb.toString()); + try { + sb.append((char[]) null); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.append(char[], int, int) + */ + public void test_append$CII() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(new char[] { 'a', 'b' }, 0, 2)); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(new char[] { 'c', 'd' }, 0, 2)); + assertEquals("cd", sb.toString()); + + sb.setLength(0); + assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, 2)); + assertEquals("ab", sb.toString()); + + sb.setLength(0); + assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 2)); + assertEquals("cd", sb.toString()); + + sb.setLength(0); + assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 0)); + assertEquals("", sb.toString()); + + try { + sb.append((char[]) null, 0, 2); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + sb.append(new char[] { 'a', 'b', 'c', 'd' }, -1, 2); + fail("no IOOBE, negative offset"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, -1); + fail("no IOOBE, negative length"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 3); + fail("no IOOBE, offset and length overflow"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.append(CharSequence) + */ + public void test_appendLjava_lang_CharSequence() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append((CharSequence) "ab")); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) "cd")); + assertEquals("cd", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) null)); + assertEquals("null", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(CharSequence, int, int) + */ + @SuppressWarnings("cast") public void test_appendLjava_lang_CharSequenceII() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append((CharSequence) "ab", 0, 2)); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) "cd", 0, 2)); - assertEquals("cd", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) "abcd", 0, 2)); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) "abcd", 2, 4)); - assertEquals("cd", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((CharSequence) null, 0, 2)); - assertEquals("nu", sb.toString()); - - try { - sb.append((CharSequence) "abcd", -1, 2); - fail("IndexOutOfBoundsException was thrown."); - } catch(IndexOutOfBoundsException e) { - //expected - } - - try { - sb.append((CharSequence) "abcd", 0, 5); - fail("IndexOutOfBoundsException was thrown."); - } catch(IndexOutOfBoundsException e) { - //expected - } - - try { - sb.append((CharSequence) "abcd", 2, 1); - fail("IndexOutOfBoundsException was thrown."); - } catch(IndexOutOfBoundsException e) { - //expected - } - } - - /** - * @tests java.lang.StringBuilder.append(double) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {double.class} - ) - public void test_appendD() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(1D)); - assertEquals(String.valueOf(1D), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(0D)); - assertEquals(String.valueOf(0D), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(-1D)); - assertEquals(String.valueOf(-1D), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Double.NaN)); - assertEquals(String.valueOf(Double.NaN), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Double.NEGATIVE_INFINITY)); - assertEquals(String.valueOf(Double.NEGATIVE_INFINITY), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Double.POSITIVE_INFINITY)); - assertEquals(String.valueOf(Double.POSITIVE_INFINITY), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Double.MIN_VALUE)); - assertEquals(String.valueOf(Double.MIN_VALUE), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Double.MAX_VALUE)); - assertEquals(String.valueOf(Double.MAX_VALUE), sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(float) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {float.class} - ) - public void test_appendF() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(1F)); - assertEquals(String.valueOf(1F), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(0F)); - assertEquals(String.valueOf(0F), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(-1F)); - assertEquals(String.valueOf(-1F), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Float.NaN)); - assertEquals(String.valueOf(Float.NaN), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Float.NEGATIVE_INFINITY)); - assertEquals(String.valueOf(Float.NEGATIVE_INFINITY), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Float.POSITIVE_INFINITY)); - assertEquals(String.valueOf(Float.POSITIVE_INFINITY), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Float.MIN_VALUE)); - assertEquals(String.valueOf(Float.MIN_VALUE), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Float.MAX_VALUE)); - assertEquals(String.valueOf(Float.MAX_VALUE), sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {int.class} - ) - public void test_appendI() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(1)); - assertEquals(String.valueOf(1), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(0)); - assertEquals(String.valueOf(0), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(-1)); - assertEquals(String.valueOf(-1), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Integer.MIN_VALUE)); - assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Integer.MAX_VALUE)); - assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {long.class} - ) - public void test_appendL() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(1L)); - assertEquals(String.valueOf(1L), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(0L)); - assertEquals(String.valueOf(0L), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(-1L)); - assertEquals(String.valueOf(-1L), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Integer.MIN_VALUE)); - assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(Integer.MAX_VALUE)); - assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(Object)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.Object.class} - ) - public void test_appendLjava_lang_Object() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(Fixture.INSTANCE)); - assertEquals(Fixture.INSTANCE.toString(), sb.toString()); - - sb.setLength(0); - assertSame(sb, sb.append((Object) null)); - assertEquals("null", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.String.class} - ) - public void test_appendLjava_lang_String() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append("ab")); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append("cd")); - assertEquals("cd", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((String) null)); - assertEquals("null", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.append(StringBuffer) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "append", - args = {java.lang.StringBuffer.class} - ) - public void test_appendLjava_lang_StringBuffer() { - StringBuilder sb = new StringBuilder(); - assertSame(sb, sb.append(new StringBuffer("ab"))); - assertEquals("ab", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append(new StringBuffer("cd"))); - assertEquals("cd", sb.toString()); - sb.setLength(0); - assertSame(sb, sb.append((StringBuffer) null)); - assertEquals("null", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.appendCodePoint(int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "appendCodePoint", - args = {int.class} - ) - public void test_appendCodePointI() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append((CharSequence) "ab", 0, 2)); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) "cd", 0, 2)); + assertEquals("cd", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) "abcd", 0, 2)); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) "abcd", 2, 4)); + assertEquals("cd", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((CharSequence) null, 0, 2)); + assertEquals("nu", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(double) + */ + public void test_appendD() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(1D)); + assertEquals(String.valueOf(1D), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(0D)); + assertEquals(String.valueOf(0D), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(-1D)); + assertEquals(String.valueOf(-1D), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Double.NaN)); + assertEquals(String.valueOf(Double.NaN), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Double.NEGATIVE_INFINITY)); + assertEquals(String.valueOf(Double.NEGATIVE_INFINITY), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Double.POSITIVE_INFINITY)); + assertEquals(String.valueOf(Double.POSITIVE_INFINITY), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Double.MIN_VALUE)); + assertEquals(String.valueOf(Double.MIN_VALUE), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Double.MAX_VALUE)); + assertEquals(String.valueOf(Double.MAX_VALUE), sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(float) + */ + public void test_appendF() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(1F)); + assertEquals(String.valueOf(1F), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(0F)); + assertEquals(String.valueOf(0F), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(-1F)); + assertEquals(String.valueOf(-1F), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Float.NaN)); + assertEquals(String.valueOf(Float.NaN), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Float.NEGATIVE_INFINITY)); + assertEquals(String.valueOf(Float.NEGATIVE_INFINITY), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Float.POSITIVE_INFINITY)); + assertEquals(String.valueOf(Float.POSITIVE_INFINITY), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Float.MIN_VALUE)); + assertEquals(String.valueOf(Float.MIN_VALUE), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Float.MAX_VALUE)); + assertEquals(String.valueOf(Float.MAX_VALUE), sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(int) + */ + public void test_appendI() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(1)); + assertEquals(String.valueOf(1), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(0)); + assertEquals(String.valueOf(0), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(-1)); + assertEquals(String.valueOf(-1), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Integer.MIN_VALUE)); + assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Integer.MAX_VALUE)); + assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(long) + */ + public void test_appendL() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(1L)); + assertEquals(String.valueOf(1L), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(0L)); + assertEquals(String.valueOf(0L), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(-1L)); + assertEquals(String.valueOf(-1L), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Integer.MIN_VALUE)); + assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(Integer.MAX_VALUE)); + assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(Object)' + */ + public void test_appendLjava_lang_Object() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(Fixture.INSTANCE)); + assertEquals(Fixture.INSTANCE.toString(), sb.toString()); + + sb.setLength(0); + assertSame(sb, sb.append((Object) null)); + assertEquals("null", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(String) + */ + public void test_appendLjava_lang_String() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append("ab")); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append("cd")); + assertEquals("cd", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((String) null)); + assertEquals("null", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.append(StringBuffer) + */ + public void test_appendLjava_lang_StringBuffer() { + StringBuilder sb = new StringBuilder(); + assertSame(sb, sb.append(new StringBuffer("ab"))); + assertEquals("ab", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append(new StringBuffer("cd"))); + assertEquals("cd", sb.toString()); + sb.setLength(0); + assertSame(sb, sb.append((StringBuffer) null)); + assertEquals("null", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.appendCodePoint(int)' + */ + public void test_appendCodePointI() { + StringBuilder sb = new StringBuilder(); sb.appendCodePoint(0x10000); assertEquals("\uD800\uDC00", sb.toString()); sb.append("fixture"); assertEquals("\uD800\uDC00fixture", sb.toString()); sb.appendCodePoint(0x00010FFFF); assertEquals("\uD800\uDC00fixture\uDBFF\uDFFF", sb.toString()); - } - - /** - * @tests java.lang.StringBuilder.capacity()' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "capacity", - args = {} - ) - public void test_capacity() { - StringBuilder sb = new StringBuilder(); - assertEquals(16, sb.capacity()); - sb.append("0123456789ABCDEF0123456789ABCDEF"); - assertTrue(sb.capacity() > 16); - } - - /** - * @tests java.lang.StringBuilder.charAt(int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "charAt", - args = {int.class} - ) - public void test_charAtI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - for (int i = 0; i < fixture.length(); i++) { - assertEquals((char) ('0' + i), sb.charAt(i)); - } - - try { - sb.charAt(-1); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.charAt(fixture.length()); - fail("no IOOBE, equal to length"); - } catch (IndexOutOfBoundsException e) { - } - - try { - sb.charAt(fixture.length() + 1); - fail("no IOOBE, greater than length"); - } catch (IndexOutOfBoundsException e) { - } - } - - /** - * @tests java.lang.StringBuilder.codePointAt(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointAt", - args = {int.class} - ) - public void test_codePointAtI() { + } + + /** + * @tests java.lang.StringBuilder.capacity()' + */ + public void test_capacity() { + StringBuilder sb = new StringBuilder(); + assertEquals(16, sb.capacity()); + sb.append("0123456789ABCDEF0123456789ABCDEF"); + assertTrue(sb.capacity() > 16); + } + + /** + * @tests java.lang.StringBuilder.charAt(int)' + */ + public void test_charAtI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + for (int i = 0; i < fixture.length(); i++) { + assertEquals((char) ('0' + i), sb.charAt(i)); + } + + try { + sb.charAt(-1); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.charAt(fixture.length()); + fail("no IOOBE, equal to length"); + } catch (IndexOutOfBoundsException e) { + } + + try { + sb.charAt(fixture.length() + 1); + fail("no IOOBE, greater than length"); + } catch (IndexOutOfBoundsException e) { + } + } + + /** + * @tests java.lang.StringBuilder.codePointAt(int) + */ + public void test_codePointAtI() { StringBuilder sb = new StringBuilder("abc"); assertEquals('a', sb.codePointAt(0)); assertEquals('b', sb.codePointAt(1)); @@ -607,18 +454,12 @@ public class StringBuilderTest extends TestCase { } catch (IndexOutOfBoundsException e) { } - } + } - /** - * @tests java.lang.StringBuilder.codePointBefore(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointBefore", - args = {int.class} - ) - public void test_codePointBeforeI() { + /** + * @tests java.lang.StringBuilder.codePointBefore(int) + */ + public void test_codePointBeforeI() { StringBuilder sb = new StringBuilder("abc"); assertEquals('a', sb.codePointBefore(1)); assertEquals('b', sb.codePointBefore(2)); @@ -651,18 +492,12 @@ public class StringBuilderTest extends TestCase { } catch (IndexOutOfBoundsException e) { } - } + } - /** - * @tests java.lang.StringBuilder.codePointCount(int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "codePointCount", - args = {int.class, int.class} - ) - public void test_codePointCountII() { + /** + * @tests java.lang.StringBuilder.codePointCount(int, int) + */ + public void test_codePointCountII() { assertEquals(1, new StringBuilder("\uD800\uDC00").codePointCount(0, 2)); assertEquals(1, new StringBuilder("\uD800\uDC01").codePointCount(0, 2)); assertEquals(1, new StringBuilder("\uD801\uDC01").codePointCount(0, 2)); @@ -693,371 +528,326 @@ public class StringBuilderTest extends TestCase { } catch (IndexOutOfBoundsException e) { } - } - - /** - * @tests java.lang.StringBuilder.delete(int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "delete", - args = {int.class, int.class} - ) - public void test_deleteII() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.delete(0, 0)); - assertEquals(fixture, sb.toString()); - assertSame(sb, sb.delete(5, 5)); - assertEquals(fixture, sb.toString()); - assertSame(sb, sb.delete(0, 1)); - assertEquals("123456789", sb.toString()); - assertEquals(9, sb.length()); - assertSame(sb, sb.delete(0, sb.length())); - assertEquals("", sb.toString()); - assertEquals(0, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.delete(0, 11)); - assertEquals("", sb.toString()); - assertEquals(0, sb.length()); - - try { - new StringBuilder(fixture).delete(-1, 2); - fail("no SIOOBE, negative start"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - new StringBuilder(fixture).delete(11, 12); - fail("no SIOOBE, start too far"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - new StringBuilder(fixture).delete(13, 12); - fail("no SIOOBE, start larger than end"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.deleteCharAt(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "deleteCharAt", - args = {int.class} - ) - public void test_deleteCharAtI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.deleteCharAt(0)); - assertEquals("123456789", sb.toString()); - assertEquals(9, sb.length()); - sb = new StringBuilder(fixture); - assertSame(sb, sb.deleteCharAt(5)); - assertEquals("012346789", sb.toString()); - assertEquals(9, sb.length()); - sb = new StringBuilder(fixture); - assertSame(sb, sb.deleteCharAt(9)); - assertEquals("012345678", sb.toString()); - assertEquals(9, sb.length()); - - try { - new StringBuilder(fixture).deleteCharAt(-1); - fail("no SIOOBE, negative index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - new StringBuilder(fixture).deleteCharAt(fixture.length()); - fail("no SIOOBE, index equals length"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - new StringBuilder(fixture).deleteCharAt(fixture.length() + 1); - fail("no SIOOBE, index exceeds length"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.ensureCapacity(int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ensureCapacity", - args = {int.class} - ) - public void test_ensureCapacityI() { - StringBuilder sb = new StringBuilder(5); - assertEquals(5, sb.capacity()); - sb.ensureCapacity(10); - assertEquals(12, sb.capacity()); - sb.ensureCapacity(26); - assertEquals(26, sb.capacity()); - sb.ensureCapacity(55); - assertEquals(55, sb.capacity()); - } - - /** - * @tests java.lang.StringBuilder.getChars(int, int, char[], int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getChars", - args = {int.class, int.class, char[].class, int.class} - ) - public void test_getCharsII$CI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - char[] dst = new char[10]; - sb.getChars(0, 10, dst, 0); - assertTrue(Arrays.equals(fixture.toCharArray(), dst)); - - Arrays.fill(dst, '\0'); - sb.getChars(0, 5, dst, 0); - char[] fixtureChars = new char[10]; - fixture.getChars(0, 5, fixtureChars, 0); - assertTrue(Arrays.equals(fixtureChars, dst)); - - Arrays.fill(dst, '\0'); - Arrays.fill(fixtureChars, '\0'); - sb.getChars(0, 5, dst, 5); - fixture.getChars(0, 5, fixtureChars, 5); - assertTrue(Arrays.equals(fixtureChars, dst)); - - Arrays.fill(dst, '\0'); - Arrays.fill(fixtureChars, '\0'); - sb.getChars(5, 10, dst, 1); - fixture.getChars(5, 10, fixtureChars, 1); - assertTrue(Arrays.equals(fixtureChars, dst)); - - try { - sb.getChars(0, 10, null, 0); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - - try { - sb.getChars(-1, 10, dst, 0); - fail("no IOOBE, srcBegin negative"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.getChars(0, 10, dst, -1); - fail("no IOOBE, dstBegin negative"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.getChars(5, 4, dst, 0); - fail("no IOOBE, srcBegin > srcEnd"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.getChars(0, 11, dst, 0); - fail("no IOOBE, srcEnd > length"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb.getChars(0, 10, dst, 5); - fail("no IOOBE, dstBegin and src size too large for what's left in dst"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.indexOf(String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "indexOf", - args = {java.lang.String.class} - ) - public void test_indexOfLjava_lang_String() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertEquals(0, sb.indexOf("0")); - assertEquals(0, sb.indexOf("012")); - assertEquals(-1, sb.indexOf("02")); - assertEquals(8, sb.indexOf("89")); - - try { - sb.indexOf(null); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.indexOf(String, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "indexOf", - args = {java.lang.String.class, int.class} - ) - public void test_IndexOfStringInt() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertEquals(0, sb.indexOf("0")); - assertEquals(0, sb.indexOf("012")); - assertEquals(-1, sb.indexOf("02")); - assertEquals(8, sb.indexOf("89")); - - assertEquals(0, sb.indexOf("0"), 0); - assertEquals(0, sb.indexOf("012"), 0); - assertEquals(-1, sb.indexOf("02"), 0); - assertEquals(8, sb.indexOf("89"), 0); - - assertEquals(-1, sb.indexOf("0"), 5); - assertEquals(-1, sb.indexOf("012"), 5); - assertEquals(-1, sb.indexOf("02"), 0); - assertEquals(8, sb.indexOf("89"), 5); - - try { - sb.indexOf(null, 0); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, boolean) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, boolean.class} - ) - public void test_insertIZ() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, true)); - assertEquals("true0000", sb.toString()); - assertEquals(8, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, false)); - assertEquals("false0000", sb.toString()); - assertEquals(9, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, false)); - assertEquals("00false00", sb.toString()); - assertEquals(9, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, false)); - assertEquals("0000false", sb.toString()); - assertEquals(9, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, false); - fail("no SIOOBE, negative index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, false); - fail("no SIOOBE, index too large index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } + } + + /** + * @tests java.lang.StringBuilder.delete(int, int) + */ + public void test_deleteII() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.delete(0, 0)); + assertEquals(fixture, sb.toString()); + assertSame(sb, sb.delete(5, 5)); + assertEquals(fixture, sb.toString()); + assertSame(sb, sb.delete(0, 1)); + assertEquals("123456789", sb.toString()); + assertEquals(9, sb.length()); + assertSame(sb, sb.delete(0, sb.length())); + assertEquals("", sb.toString()); + assertEquals(0, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.delete(0, 11)); + assertEquals("", sb.toString()); + assertEquals(0, sb.length()); + + try { + new StringBuilder(fixture).delete(-1, 2); + fail("no SIOOBE, negative start"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + new StringBuilder(fixture).delete(11, 12); + fail("no SIOOBE, start too far"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + new StringBuilder(fixture).delete(13, 12); + fail("no SIOOBE, start larger than end"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + // HARMONY 6212 + sb = new StringBuilder(); + sb.append("abcde"); + String str = sb.toString(); + sb.delete(0, sb.length()); + sb.append("YY"); + assertEquals("abcde", str); + assertEquals("YY", sb.toString()); + } + + /** + * @tests java.lang.StringBuilder.deleteCharAt(int) + */ + public void test_deleteCharAtI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.deleteCharAt(0)); + assertEquals("123456789", sb.toString()); + assertEquals(9, sb.length()); + sb = new StringBuilder(fixture); + assertSame(sb, sb.deleteCharAt(5)); + assertEquals("012346789", sb.toString()); + assertEquals(9, sb.length()); + sb = new StringBuilder(fixture); + assertSame(sb, sb.deleteCharAt(9)); + assertEquals("012345678", sb.toString()); + assertEquals(9, sb.length()); + + try { + new StringBuilder(fixture).deleteCharAt(-1); + fail("no SIOOBE, negative index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + new StringBuilder(fixture).deleteCharAt(fixture.length()); + fail("no SIOOBE, index equals length"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + new StringBuilder(fixture).deleteCharAt(fixture.length() + 1); + fail("no SIOOBE, index exceeds length"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.ensureCapacity(int)' + */ + public void test_ensureCapacityI() { + StringBuilder sb = new StringBuilder(5); + assertEquals(5, sb.capacity()); + sb.ensureCapacity(10); + assertEquals(12, sb.capacity()); + sb.ensureCapacity(26); + assertEquals(26, sb.capacity()); + sb.ensureCapacity(55); + assertEquals(55, sb.capacity()); + } + + /** + * @tests java.lang.StringBuilder.getChars(int, int, char[], int)' + */ + public void test_getCharsII$CI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + char[] dst = new char[10]; + sb.getChars(0, 10, dst, 0); + assertTrue(Arrays.equals(fixture.toCharArray(), dst)); + + Arrays.fill(dst, '\0'); + sb.getChars(0, 5, dst, 0); + char[] fixtureChars = new char[10]; + fixture.getChars(0, 5, fixtureChars, 0); + assertTrue(Arrays.equals(fixtureChars, dst)); + + Arrays.fill(dst, '\0'); + Arrays.fill(fixtureChars, '\0'); + sb.getChars(0, 5, dst, 5); + fixture.getChars(0, 5, fixtureChars, 5); + assertTrue(Arrays.equals(fixtureChars, dst)); + + Arrays.fill(dst, '\0'); + Arrays.fill(fixtureChars, '\0'); + sb.getChars(5, 10, dst, 1); + fixture.getChars(5, 10, fixtureChars, 1); + assertTrue(Arrays.equals(fixtureChars, dst)); + + try { + sb.getChars(0, 10, null, 0); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + sb.getChars(-1, 10, dst, 0); + fail("no IOOBE, srcBegin negative"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.getChars(0, 10, dst, -1); + fail("no IOOBE, dstBegin negative"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.getChars(5, 4, dst, 0); + fail("no IOOBE, srcBegin > srcEnd"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.getChars(0, 11, dst, 0); + fail("no IOOBE, srcEnd > length"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.getChars(0, 10, dst, 5); + fail("no IOOBE, dstBegin and src size too large for what's left in dst"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.indexOf(String) + */ + public void test_indexOfLjava_lang_String() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertEquals(0, sb.indexOf("0")); + assertEquals(0, sb.indexOf("012")); + assertEquals(-1, sb.indexOf("02")); + assertEquals(8, sb.indexOf("89")); + + try { + sb.indexOf(null); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.indexOf(String, int) + */ + public void test_IndexOfStringInt() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertEquals(0, sb.indexOf("0")); + assertEquals(0, sb.indexOf("012")); + assertEquals(-1, sb.indexOf("02")); + assertEquals(8, sb.indexOf("89")); + + assertEquals(0, sb.indexOf("0"), 0); + assertEquals(0, sb.indexOf("012"), 0); + assertEquals(-1, sb.indexOf("02"), 0); + assertEquals(8, sb.indexOf("89"), 0); + + assertEquals(-1, sb.indexOf("0"), 5); + assertEquals(-1, sb.indexOf("012"), 5); + assertEquals(-1, sb.indexOf("02"), 0); + assertEquals(8, sb.indexOf("89"), 5); + + try { + sb.indexOf(null, 0); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, boolean) + */ + public void test_insertIZ() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, true)); + assertEquals("true0000", sb.toString()); + assertEquals(8, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, false)); + assertEquals("false0000", sb.toString()); + assertEquals(9, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, false)); + assertEquals("00false00", sb.toString()); + assertEquals(9, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, false)); + assertEquals("0000false", sb.toString()); + assertEquals(9, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, false); + fail("no SIOOBE, negative index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, false); + fail("no SIOOBE, index too large index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, char) + */ + public void test_insertIC() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 'a')); + assertEquals("a0000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 'b')); + assertEquals("b0000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, 'b')); + assertEquals("00b00", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, 'b')); + assertEquals("0000b", sb.toString()); + assertEquals(5, sb.length()); + + // FIXME this fails on Sun JRE 5.0_5 +// try { +// sb = new StringBuilder(fixture); +// sb.insert(-1, 'a'); +// fail("no SIOOBE, negative index"); +// } catch (StringIndexOutOfBoundsException e) { +// // Expected +// } + + /* + * FIXME This fails on Sun JRE 5.0_5, but that seems like a bug, since + * the 'insert(int, char[]) behaves this way. + */ +// try { +// sb = new StringBuilder(fixture); +// sb.insert(5, 'a'); +// fail("no SIOOBE, index too large index"); +// } catch (StringIndexOutOfBoundsException e) { +// // Expected +// } + } /** * @tests java.lang.StringBuilder.insert(int, char) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IndexOutOfBoundsException is not verified.", - method = "insert", - args = {int.class, char.class} - ) - public void test_insertIC() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 'a')); - assertEquals("a0000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 'b')); - assertEquals("b0000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, 'b')); - assertEquals("00b00", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, 'b')); - assertEquals("0000b", sb.toString()); - assertEquals(5, sb.length()); - - // FIXME this fails on Sun JRE 5.0_5 -// try { -// sb = new StringBuilder(fixture); -// sb.insert(-1, 'a'); -// fail("no SIOOBE, negative index"); -// } catch (StringIndexOutOfBoundsException e) { -// // Expected -// } - - /* - * FIXME This fails on Sun JRE 5.0_5, but that seems like a bug, since - * the 'insert(int, char[]) behaves this way. - */ -// try { -// sb = new StringBuilder(fixture); -// sb.insert(5, 'a'); -// fail("no SIOOBE, index too large index"); -// } catch (StringIndexOutOfBoundsException e) { -// // Expected -// } - } - - /** - * @tests java.lang.StringBuilder.insert(int, char) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ArrayIndexOutOfBoundsException.", - method = "insert", - args = {int.class, char.class} - ) public void test_insertIC_2() { StringBuilder obj = new StringBuilder(); try { @@ -1069,668 +859,584 @@ public class StringBuilderTest extends TestCase { } /** - * @tests java.lang.StringBuilder.insert(int, char[])' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, char[].class} - ) - public void test_insertI$C() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, new char[] { 'a', 'b' })); - assertEquals("ab0000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, new char[] { 'a', 'b' })); - assertEquals("00ab00", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, new char[] { 'a', 'b' })); - assertEquals("0000ab", sb.toString()); - assertEquals(6, sb.length()); - - /* - * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's - * undocumented. The assumption is that this method behaves like - * String.valueOf(char[]), which does throw a NPE too, but that is also - * undocumented. - */ - - try { - sb.insert(0, (char[]) null); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, new char[] { 'a', 'b' }); - fail("no SIOOBE, negative index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }); - fail("no SIOOBE, index too large index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, char[], int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, char[].class, int.class, int.class} - ) - public void test_insertI$CII() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 2)); - assertEquals("ab0000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 1)); - assertEquals("a0000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 2)); - assertEquals("00ab00", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 1)); - assertEquals("00a00", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 2)); - assertEquals("0000ab", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 1)); - assertEquals("0000a", sb.toString()); - assertEquals(5, sb.length()); - - /* - * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's - * undocumented. The assumption is that this method behaves like - * String.valueOf(char[]), which does throw a NPE too, but that is also - * undocumented. - */ - - try { - sb.insert(0, (char[]) null, 0, 2); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, new char[] { 'a', 'b' }, 0, 2); - fail("no SIOOBE, negative index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, 0, 2); - fail("no SIOOBE, index too large index"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, -1, 2); - fail("no SIOOBE, negative offset"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, 0, -1); - fail("no SIOOBE, negative length"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, 0, 3); - fail("no SIOOBE, too long"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, CharSequence) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.CharSequence.class} - ) - public void test_insertILjava_lang_CharSequence() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, (CharSequence) "ab")); - assertEquals("ab0000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, (CharSequence) "ab")); - assertEquals("00ab00", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (CharSequence) "ab")); - assertEquals("0000ab", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (CharSequence) null)); - assertEquals("0000null", sb.toString()); - assertEquals(8, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, (CharSequence) "ab"); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, (CharSequence) "ab"); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, CharSequence, int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.CharSequence.class, int.class, int.class} - ) - @SuppressWarnings("cast") + * @tests java.lang.StringBuilder.insert(int, char[])' + */ + public void test_insertI$C() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, new char[] { 'a', 'b' })); + assertEquals("ab0000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, new char[] { 'a', 'b' })); + assertEquals("00ab00", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, new char[] { 'a', 'b' })); + assertEquals("0000ab", sb.toString()); + assertEquals(6, sb.length()); + + /* + * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's + * undocumented. The assumption is that this method behaves like + * String.valueOf(char[]), which does throw a NPE too, but that is also + * undocumented. + */ + + try { + sb.insert(0, (char[]) null); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, new char[] { 'a', 'b' }); + fail("no SIOOBE, negative index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }); + fail("no SIOOBE, index too large index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, char[], int, int) + */ + public void test_insertI$CII() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 2)); + assertEquals("ab0000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 1)); + assertEquals("a0000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 2)); + assertEquals("00ab00", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 1)); + assertEquals("00a00", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 2)); + assertEquals("0000ab", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 1)); + assertEquals("0000a", sb.toString()); + assertEquals(5, sb.length()); + + /* + * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's + * undocumented. The assumption is that this method behaves like + * String.valueOf(char[]), which does throw a NPE too, but that is also + * undocumented. + */ + + try { + sb.insert(0, (char[]) null, 0, 2); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, new char[] { 'a', 'b' }, 0, 2); + fail("no SIOOBE, negative index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, 0, 2); + fail("no SIOOBE, index too large index"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, -1, 2); + fail("no SIOOBE, negative offset"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, 0, -1); + fail("no SIOOBE, negative length"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, 0, 3); + fail("no SIOOBE, too long"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, CharSequence) + */ + public void test_insertILjava_lang_CharSequence() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, (CharSequence) "ab")); + assertEquals("ab0000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, (CharSequence) "ab")); + assertEquals("00ab00", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (CharSequence) "ab")); + assertEquals("0000ab", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (CharSequence) null)); + assertEquals("0000null", sb.toString()); + assertEquals(8, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, (CharSequence) "ab"); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, (CharSequence) "ab"); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, CharSequence, int, int) + */ + @SuppressWarnings("cast") public void test_insertILjava_lang_CharSequenceII() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 2)); - assertEquals("ab0000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 1)); - assertEquals("a0000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 2)); - assertEquals("00ab00", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 1)); - assertEquals("00a00", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 2)); - assertEquals("0000ab", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 1)); - assertEquals("0000a", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (CharSequence) null, 0, 2)); - assertEquals("0000nu", sb.toString()); - assertEquals(6, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, (CharSequence) "ab", 0, 2); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, (CharSequence) "ab", 0, 2); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, (CharSequence) "ab", -1, 2); - fail("no IOOBE, negative offset"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, 0, -1); - fail("no IOOBE, negative length"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, new char[] { 'a', 'b' }, 0, 3); - fail("no IOOBE, too long"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, double) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, double.class} - ) - public void test_insertID() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, -1D)); - assertEquals("-1.00000", sb.toString()); - assertEquals(8, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 0D)); - assertEquals("0.00000", sb.toString()); - assertEquals(7, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, 1D)); - assertEquals("001.000", sb.toString()); - assertEquals(7, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, 2D)); - assertEquals("00002.0", sb.toString()); - assertEquals(7, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, 1D); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, 1D); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, float) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, float.class} - ) - public void test_insertIF() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, -1F)); - assertEquals("-1.00000", sb.toString()); - assertEquals(8, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 0F)); - assertEquals("0.00000", sb.toString()); - assertEquals(7, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, 1F)); - assertEquals("001.000", sb.toString()); - assertEquals(7, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, 2F)); - assertEquals("00002.0", sb.toString()); - assertEquals(7, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, 1F); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, 1F); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, int.class} - ) - public void test_insertII() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, -1)); - assertEquals("-10000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 0)); - assertEquals("00000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, 1)); - assertEquals("00100", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, 2)); - assertEquals("00002", sb.toString()); - assertEquals(5, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, 1); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, 1); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, long) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, long.class} - ) - public void test_insertIJ() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, -1L)); - assertEquals("-10000", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, 0L)); - assertEquals("00000", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, 1L)); - assertEquals("00100", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, 2L)); - assertEquals("00002", sb.toString()); - assertEquals(5, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, 1L); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, 1L); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, Object) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.Object.class} - ) - public void test_insertILjava_lang_Object() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, Fixture.INSTANCE)); - assertEquals("fixture0000", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, Fixture.INSTANCE)); - assertEquals("00fixture00", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, Fixture.INSTANCE)); - assertEquals("0000fixture", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (Object) null)); - assertEquals("0000null", sb.toString()); - assertEquals(8, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, Fixture.INSTANCE); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, Fixture.INSTANCE); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.insert(int, String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "insert", - args = {int.class, java.lang.String.class} - ) - public void test_insertILjava_lang_String() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(0, "fixture")); - assertEquals("fixture0000", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(2, "fixture")); - assertEquals("00fixture00", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, "fixture")); - assertEquals("0000fixture", sb.toString()); - assertEquals(11, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.insert(4, (Object) null)); - assertEquals("0000null", sb.toString()); - assertEquals(8, sb.length()); - - try { - sb = new StringBuilder(fixture); - sb.insert(-1, "fixture"); - fail("no IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.insert(5, "fixture"); - fail("no IOOBE, index too large index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.lastIndexOf(String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "lastIndexOf", - args = {java.lang.String.class} - ) - public void test_lastIndexOfLjava_lang_String() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertEquals(0, sb.lastIndexOf("0")); - assertEquals(0, sb.lastIndexOf("012")); - assertEquals(-1, sb.lastIndexOf("02")); - assertEquals(8, sb.lastIndexOf("89")); - - try { - sb.lastIndexOf(null); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.lastIndexOf(String, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "lastIndexOf", - args = {java.lang.String.class, int.class} - ) - public void test_lastIndexOfLjava_lang_StringI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertEquals(0, sb.lastIndexOf("0")); - assertEquals(0, sb.lastIndexOf("012")); - assertEquals(-1, sb.lastIndexOf("02")); - assertEquals(8, sb.lastIndexOf("89")); - - assertEquals(0, sb.lastIndexOf("0"), 0); - assertEquals(0, sb.lastIndexOf("012"), 0); - assertEquals(-1, sb.lastIndexOf("02"), 0); - assertEquals(8, sb.lastIndexOf("89"), 0); - - assertEquals(-1, sb.lastIndexOf("0"), 5); - assertEquals(-1, sb.lastIndexOf("012"), 5); - assertEquals(-1, sb.lastIndexOf("02"), 0); - assertEquals(8, sb.lastIndexOf("89"), 5); - - try { - sb.lastIndexOf(null, 0); - fail("no NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * @tests java.lang.StringBuilder.length() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "length", - args = {} - ) - public void test_length() { - StringBuilder sb = new StringBuilder(); - assertEquals(0, sb.length()); - sb.append("0000"); - assertEquals(4, sb.length()); - } - - /** - * @tests java.lang.StringBuilder.offsetByCodePoints(int, int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "offsetByCodePoints", - args = {int.class, int.class} - ) - public void test_offsetByCodePointsII() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 2)); + assertEquals("ab0000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 1)); + assertEquals("a0000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 2)); + assertEquals("00ab00", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 1)); + assertEquals("00a00", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 2)); + assertEquals("0000ab", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 1)); + assertEquals("0000a", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (CharSequence) null, 0, 2)); + assertEquals("0000nu", sb.toString()); + assertEquals(6, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, (CharSequence) "ab", 0, 2); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, (CharSequence) "ab", 0, 2); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, (CharSequence) "ab", -1, 2); + fail("no IOOBE, negative offset"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, 0, -1); + fail("no IOOBE, negative length"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, new char[] { 'a', 'b' }, 0, 3); + fail("no IOOBE, too long"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, double) + */ + public void test_insertID() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, -1D)); + assertEquals("-1.00000", sb.toString()); + assertEquals(8, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 0D)); + assertEquals("0.00000", sb.toString()); + assertEquals(7, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, 1D)); + assertEquals("001.000", sb.toString()); + assertEquals(7, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, 2D)); + assertEquals("00002.0", sb.toString()); + assertEquals(7, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, 1D); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, 1D); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, float) + */ + public void test_insertIF() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, -1F)); + assertEquals("-1.00000", sb.toString()); + assertEquals(8, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 0F)); + assertEquals("0.00000", sb.toString()); + assertEquals(7, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, 1F)); + assertEquals("001.000", sb.toString()); + assertEquals(7, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, 2F)); + assertEquals("00002.0", sb.toString()); + assertEquals(7, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, 1F); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, 1F); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, int) + */ + public void test_insertII() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, -1)); + assertEquals("-10000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 0)); + assertEquals("00000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, 1)); + assertEquals("00100", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, 2)); + assertEquals("00002", sb.toString()); + assertEquals(5, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, 1); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, 1); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, long) + */ + public void test_insertIJ() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, -1L)); + assertEquals("-10000", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, 0L)); + assertEquals("00000", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, 1L)); + assertEquals("00100", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, 2L)); + assertEquals("00002", sb.toString()); + assertEquals(5, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, 1L); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, 1L); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, Object) + */ + public void test_insertILjava_lang_Object() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, Fixture.INSTANCE)); + assertEquals("fixture0000", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, Fixture.INSTANCE)); + assertEquals("00fixture00", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, Fixture.INSTANCE)); + assertEquals("0000fixture", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (Object) null)); + assertEquals("0000null", sb.toString()); + assertEquals(8, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, Fixture.INSTANCE); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, Fixture.INSTANCE); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.insert(int, String) + */ + public void test_insertILjava_lang_String() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(0, "fixture")); + assertEquals("fixture0000", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(2, "fixture")); + assertEquals("00fixture00", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, "fixture")); + assertEquals("0000fixture", sb.toString()); + assertEquals(11, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.insert(4, (Object) null)); + assertEquals("0000null", sb.toString()); + assertEquals(8, sb.length()); + + try { + sb = new StringBuilder(fixture); + sb.insert(-1, "fixture"); + fail("no IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.insert(5, "fixture"); + fail("no IOOBE, index too large index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.lastIndexOf(String) + */ + public void test_lastIndexOfLjava_lang_String() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertEquals(0, sb.lastIndexOf("0")); + assertEquals(0, sb.lastIndexOf("012")); + assertEquals(-1, sb.lastIndexOf("02")); + assertEquals(8, sb.lastIndexOf("89")); + + try { + sb.lastIndexOf(null); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.lastIndexOf(String, int) + */ + public void test_lastIndexOfLjava_lang_StringI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertEquals(0, sb.lastIndexOf("0")); + assertEquals(0, sb.lastIndexOf("012")); + assertEquals(-1, sb.lastIndexOf("02")); + assertEquals(8, sb.lastIndexOf("89")); + + assertEquals(0, sb.lastIndexOf("0"), 0); + assertEquals(0, sb.lastIndexOf("012"), 0); + assertEquals(-1, sb.lastIndexOf("02"), 0); + assertEquals(8, sb.lastIndexOf("89"), 0); + + assertEquals(-1, sb.lastIndexOf("0"), 5); + assertEquals(-1, sb.lastIndexOf("012"), 5); + assertEquals(-1, sb.lastIndexOf("02"), 0); + assertEquals(8, sb.lastIndexOf("89"), 5); + + try { + sb.lastIndexOf(null, 0); + fail("no NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.length() + */ + public void test_length() { + StringBuilder sb = new StringBuilder(); + assertEquals(0, sb.length()); + sb.append("0000"); + assertEquals(4, sb.length()); + } + + /** + * @tests java.lang.StringBuilder.offsetByCodePoints(int, int)' + */ + public void test_offsetByCodePointsII() { int result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 2); assertEquals(3, result); @@ -1791,87 +1497,102 @@ public class StringBuilderTest extends TestCase { } catch (IndexOutOfBoundsException e) { } + } + + /** + * @tests java.lang.StringBuilder.replace(int, int, String)' + */ + public void test_replaceIILjava_lang_String() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + assertSame(sb, sb.replace(1, 3, "11")); + assertEquals("0110", sb.toString()); + assertEquals(4, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.replace(1, 2, "11")); + assertEquals("01100", sb.toString()); + assertEquals(5, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.replace(4, 5, "11")); + assertEquals("000011", sb.toString()); + assertEquals(6, sb.length()); + + sb = new StringBuilder(fixture); + assertSame(sb, sb.replace(4, 6, "11")); + assertEquals("000011", sb.toString()); + assertEquals(6, sb.length()); + + // FIXME Undocumented NPE in Sun's JRE 5.0_5 + try { + sb.replace(1, 2, null); + fail("No NPE"); + } catch (NullPointerException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.replace(-1, 2, "11"); + fail("No SIOOBE, negative start"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.replace(5, 2, "11"); + fail("No SIOOBE, start > length"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb = new StringBuilder(fixture); + sb.replace(3, 2, "11"); + fail("No SIOOBE, start > end"); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + // Regression for HARMONY-348 + StringBuilder buffer = new StringBuilder("1234567"); + buffer.replace(2, 6, "XXX"); + assertEquals("12XXX7",buffer.toString()); + } + + private void reverseTest(String org, String rev, String back) { + // create non-shared StringBuilder + StringBuilder sb = new StringBuilder(org); + sb.reverse(); + String reversed = sb.toString(); + assertEquals(rev, reversed); + // create non-shared StringBuilder + sb = new StringBuilder(reversed); + sb.reverse(); + reversed = sb.toString(); + assertEquals(back, reversed); + + // test algorithm when StringBuilder is shared + sb = new StringBuilder(org); + String copy = sb.toString(); + assertEquals(org, copy); + sb.reverse(); + reversed = sb.toString(); + assertEquals(rev, reversed); + sb = new StringBuilder(reversed); + copy = sb.toString(); + assertEquals(rev, copy); + sb.reverse(); + reversed = sb.toString(); + assertEquals(back, reversed); } - /** - * @tests java.lang.StringBuilder.replace(int, int, String)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "replace", - args = {int.class, int.class, java.lang.String.class} - ) - public void test_replaceIILjava_lang_String() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - assertSame(sb, sb.replace(1, 3, "11")); - assertEquals("0110", sb.toString()); - assertEquals(4, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.replace(1, 2, "11")); - assertEquals("01100", sb.toString()); - assertEquals(5, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.replace(4, 5, "11")); - assertEquals("000011", sb.toString()); - assertEquals(6, sb.length()); - - sb = new StringBuilder(fixture); - assertSame(sb, sb.replace(4, 6, "11")); - assertEquals("000011", sb.toString()); - assertEquals(6, sb.length()); - - // FIXME Undocumented NPE in Sun's JRE 5.0_5 - try { - sb.replace(1, 2, null); - fail("No NPE"); - } catch (NullPointerException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.replace(-1, 2, "11"); - fail("No SIOOBE, negative start"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.replace(5, 2, "11"); - fail("No SIOOBE, start > length"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - try { - sb = new StringBuilder(fixture); - sb.replace(3, 2, "11"); - fail("No SIOOBE, start > end"); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - - // Regression for HARMONY-348 - StringBuilder buffer = new StringBuilder("1234567"); - buffer.replace(2, 6, "XXX"); - assertEquals("12XXX7",buffer.toString()); - } - - /** - * @tests java.lang.StringBuilder.reverse() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "reverse", - args = {} - ) - public void test_reverse() { + /** + * @tests java.lang.StringBuilder.reverse() + */ + public void test_reverse() { final String fixture = "0123456789"; StringBuilder sb = new StringBuilder(fixture); assertSame(sb, sb.reverse()); @@ -1888,252 +1609,336 @@ public class StringBuilderTest extends TestCase { sb.setLength(0); assertSame(sb, sb.reverse()); assertEquals("", sb.toString()); - } - /** - * @tests java.lang.StringBuilder.setCharAt(int, char) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setCharAt", - args = {int.class, char.class} - ) - public void test_setCharAtIC() { - final String fixture = "0000"; - StringBuilder sb = new StringBuilder(fixture); - sb.setCharAt(0, 'A'); - assertEquals("A000", sb.toString()); - sb.setCharAt(1, 'B'); - assertEquals("AB00", sb.toString()); - sb.setCharAt(2, 'C'); - assertEquals("ABC0", sb.toString()); - sb.setCharAt(3, 'D'); - assertEquals("ABCD", sb.toString()); + String str; + str = "a"; + reverseTest(str, str, str); - try { - sb.setCharAt(-1, 'A'); - fail("No IOOBE, negative index"); - } catch (IndexOutOfBoundsException e) { - // Expected - } + str = "ab"; + reverseTest(str, "ba", str); - try { - sb.setCharAt(4, 'A'); - fail("No IOOBE, index == length"); - } catch (IndexOutOfBoundsException e) { - // Expected - } + str = "abcdef"; + reverseTest(str, "fedcba", str); - try { - sb.setCharAt(5, 'A'); - fail("No IOOBE, index > length"); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } + str = "abcdefg"; + reverseTest(str, "gfedcba", str); - /** - * @tests java.lang.StringBuilder.setLength(int)' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setLength", - args = {int.class} - ) - public void test_setLengthI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - sb.setLength(5); - assertEquals(5, sb.length()); - assertEquals("01234", sb.toString()); - sb.setLength(6); - assertEquals(6, sb.length()); - assertEquals("01234\0", sb.toString()); - sb.setLength(0); - assertEquals(0, sb.length()); - assertEquals("", sb.toString()); + str = "\ud800\udc00"; + reverseTest(str, str, str); - try { - sb.setLength(-1); - fail("No IOOBE, negative length."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } + str = "\udc00\ud800"; + reverseTest(str, "\ud800\udc00", "\ud800\udc00"); - /** - * @tests java.lang.StringBuilder.subSequence(int, int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "subSequence", - args = {int.class, int.class} - ) - public void test_subSequenceII() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - CharSequence ss = sb.subSequence(0, 5); - assertEquals("01234", ss.toString()); + str = "a\ud800\udc00"; + reverseTest(str, "\ud800\udc00a", str); - ss = sb.subSequence(0, 0); - assertEquals("", ss.toString()); + str = "ab\ud800\udc00"; + reverseTest(str, "\ud800\udc00ba", str); - try { - sb.subSequence(-1, 1); - fail("No IOOBE, negative start."); - } catch (IndexOutOfBoundsException e) { - // Expected - } + str = "abc\ud800\udc00"; + reverseTest(str, "\ud800\udc00cba", str); - try { - sb.subSequence(0, -1); - fail("No IOOBE, negative end."); - } catch (IndexOutOfBoundsException e) { - // Expected - } + str = "\ud800\udc00\udc01\ud801\ud802\udc02"; + reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00", + "\ud800\udc00\ud801\udc01\ud802\udc02"); - try { - sb.subSequence(0, fixture.length() + 1); - fail("No IOOBE, end > length."); - } catch (IndexOutOfBoundsException e) { - // Expected - } + str = "\ud800\udc00\ud801\udc01\ud802\udc02"; + reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00", str); - try { - sb.subSequence(3, 2); - fail("No IOOBE, start > end."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } + str = "\ud800\udc00\udc01\ud801a"; + reverseTest(str, "a\ud801\udc01\ud800\udc00", + "\ud800\udc00\ud801\udc01a"); - /** - * @tests java.lang.StringBuilder.substring(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "substring", - args = {int.class} - ) - public void test_substringI() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - String ss = sb.substring(0); - assertEquals(fixture, ss); + str = "a\ud800\udc00\ud801\udc01"; + reverseTest(str, "\ud801\udc01\ud800\udc00a", str); - ss = sb.substring(10); - assertEquals("", ss); + str = "\ud800\udc00\udc01\ud801ab"; + reverseTest(str, "ba\ud801\udc01\ud800\udc00", + "\ud800\udc00\ud801\udc01ab"); - try { - sb.substring(-1); - fail("No SIOOBE, negative start."); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } + str = "ab\ud800\udc00\ud801\udc01"; + reverseTest(str, "\ud801\udc01\ud800\udc00ba", str); - try { - sb.substring(0, -1); - fail("No SIOOBE, negative end."); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } + str = "\ud800\udc00\ud801\udc01"; + reverseTest(str, "\ud801\udc01\ud800\udc00", str); - try { - sb.substring(fixture.length() + 1); - fail("No SIOOBE, start > length."); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } + str = "a\ud800\udc00z\ud801\udc01"; + reverseTest(str, "\ud801\udc01z\ud800\udc00a", str); + + str = "a\ud800\udc00bz\ud801\udc01"; + reverseTest(str, "\ud801\udc01zb\ud800\udc00a", str); + + str = "abc\ud802\udc02\ud801\udc01\ud800\udc00"; + reverseTest(str, "\ud800\udc00\ud801\udc01\ud802\udc02cba", str); + + str = "abcd\ud802\udc02\ud801\udc01\ud800\udc00"; + reverseTest(str, "\ud800\udc00\ud801\udc01\ud802\udc02dcba", str); } - /** - * @tests java.lang.StringBuilder.substring(int, int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "substring", - args = {int.class, int.class} - ) - public void test_substringII() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - String ss = sb.substring(0, 5); - assertEquals("01234", ss); + /** + * @tests java.lang.StringBuilder.setCharAt(int, char) + */ + public void test_setCharAtIC() { + final String fixture = "0000"; + StringBuilder sb = new StringBuilder(fixture); + sb.setCharAt(0, 'A'); + assertEquals("A000", sb.toString()); + sb.setCharAt(1, 'B'); + assertEquals("AB00", sb.toString()); + sb.setCharAt(2, 'C'); + assertEquals("ABC0", sb.toString()); + sb.setCharAt(3, 'D'); + assertEquals("ABCD", sb.toString()); + + try { + sb.setCharAt(-1, 'A'); + fail("No IOOBE, negative index"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.setCharAt(4, 'A'); + fail("No IOOBE, index == length"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.setCharAt(5, 'A'); + fail("No IOOBE, index > length"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.setLength(int)' + */ + public void test_setLengthI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + sb.setLength(5); + assertEquals(5, sb.length()); + assertEquals("01234", sb.toString()); + sb.setLength(6); + assertEquals(6, sb.length()); + assertEquals("01234\0", sb.toString()); + sb.setLength(0); + assertEquals(0, sb.length()); + assertEquals("", sb.toString()); + + try { + sb.setLength(-1); + fail("No IOOBE, negative length."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + sb = new StringBuilder("abcde"); + assertEquals("abcde", sb.toString()); + sb.setLength(1); + sb.append('g'); + assertEquals("ag", sb.toString()); - ss = sb.substring(0, 0); - assertEquals("", ss); + sb = new StringBuilder("abcde"); + sb.setLength(3); + sb.append('g'); + assertEquals("abcg", sb.toString()); + sb = new StringBuilder("abcde"); + sb.setLength(2); try { - sb.substring(-1, 1); - fail("No SIOOBE, negative start."); - } catch (StringIndexOutOfBoundsException e) { + sb.charAt(3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { // Expected } - try { - sb.substring(0, -1); - fail("No SIOOBE, negative end."); - } catch (StringIndexOutOfBoundsException e) { - // Expected + sb = new StringBuilder(); + sb.append("abcdefg"); + sb.setLength(2); + sb.setLength(5); + for (int i = 2; i < 5; i++) { + assertEquals(0, sb.charAt(i)); } - try { - sb.substring(0, fixture.length() + 1); - fail("No SIOOBE, end > length."); - } catch (StringIndexOutOfBoundsException e) { - // Expected + sb = new StringBuilder(); + sb.append("abcdefg"); + sb.delete(2, 4); + sb.setLength(7); + assertEquals('a', sb.charAt(0)); + assertEquals('b', sb.charAt(1)); + assertEquals('e', sb.charAt(2)); + assertEquals('f', sb.charAt(3)); + assertEquals('g', sb.charAt(4)); + for (int i = 5; i < 7; i++) { + assertEquals(0, sb.charAt(i)); } - try { - sb.substring(3, 2); - fail("No SIOOBE, start > end."); - } catch (StringIndexOutOfBoundsException e) { - // Expected - } - } + sb = new StringBuilder(); + sb.append("abcdefg"); + sb.replace(2, 5, "z"); + sb.setLength(7); + for (int i = 5; i < 7; i++) { + assertEquals(0, sb.charAt(i)); + } + } + + /** + * @tests java.lang.StringBuilder.subSequence(int, int) + */ + public void test_subSequenceII() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + CharSequence ss = sb.subSequence(0, 5); + assertEquals("01234", ss.toString()); + + ss = sb.subSequence(0, 0); + assertEquals("", ss.toString()); + + try { + sb.subSequence(-1, 1); + fail("No IOOBE, negative start."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.subSequence(0, -1); + fail("No IOOBE, negative end."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.subSequence(0, fixture.length() + 1); + fail("No IOOBE, end > length."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + sb.subSequence(3, 2); + fail("No IOOBE, start > end."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.substring(int) + */ + public void test_substringI() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + String ss = sb.substring(0); + assertEquals(fixture, ss); + + ss = sb.substring(10); + assertEquals("", ss); + + try { + sb.substring(-1); + fail("No SIOOBE, negative start."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb.substring(0, -1); + fail("No SIOOBE, negative end."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb.substring(fixture.length() + 1); + fail("No SIOOBE, start > length."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } + + /** + * @tests java.lang.StringBuilder.substring(int, int) + */ + public void test_substringII() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + String ss = sb.substring(0, 5); + assertEquals("01234", ss); + + ss = sb.substring(0, 0); + assertEquals("", ss); + + try { + sb.substring(-1, 1); + fail("No SIOOBE, negative start."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb.substring(0, -1); + fail("No SIOOBE, negative end."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb.substring(0, fixture.length() + 1); + fail("No SIOOBE, end > length."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + + try { + sb.substring(3, 2); + fail("No SIOOBE, start > end."); + } catch (StringIndexOutOfBoundsException e) { + // Expected + } + } /** * @tests java.lang.StringBuilder.toString()' */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - public void test_toString() { + public void test_toString() throws Exception { final String fixture = "0123456789"; StringBuilder sb = new StringBuilder(fixture); assertEquals(fixture, sb.toString()); - } - /** - * @tests java.lang.StringBuilder.trimToSize()' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "trimToSize", - args = {} - ) - public void test_trimToSize() { - final String fixture = "0123456789"; - StringBuilder sb = new StringBuilder(fixture); - assertTrue(sb.capacity() > fixture.length()); - assertEquals(fixture.length(), sb.length()); - assertEquals(fixture, sb.toString()); - int prevCapacity = sb.capacity(); - sb.trimToSize(); - assertTrue(prevCapacity > sb.capacity()); - assertEquals(fixture.length(), sb.length()); - assertEquals(fixture, sb.toString()); + sb.setLength(0); + sb.append("abcde"); + assertEquals("abcde", sb.toString()); + sb.setLength(1000); + byte[] bytes = sb.toString().getBytes("GB18030"); + for (int i = 5; i < bytes.length; i++) { + assertEquals(0, bytes[i]); + } + + sb.setLength(5); + sb.append("fghij"); + assertEquals("abcdefghij", sb.toString()); } + /** + * @tests java.lang.StringBuilder.trimToSize()' + */ + public void test_trimToSize() { + final String fixture = "0123456789"; + StringBuilder sb = new StringBuilder(fixture); + assertTrue(sb.capacity() > fixture.length()); + assertEquals(fixture.length(), sb.length()); + assertEquals(fixture, sb.toString()); + int prevCapacity = sb.capacity(); + sb.trimToSize(); + assertTrue(prevCapacity > sb.capacity()); + assertEquals(fixture.length(), sb.length()); + assertEquals(fixture, sb.toString()); + } + // comparator for StringBuilder objects private static final SerializableAssert STRING_BILDER_COMPARATOR = new SerializableAssert() { public void assertDeserialized(Serializable initial, @@ -2149,12 +1954,6 @@ public class StringBuilderTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new StringBuilder("0123456789"), @@ -2164,28 +1963,22 @@ public class StringBuilderTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new StringBuilder("0123456789"), STRING_BILDER_COMPARATOR); } - private static final class Fixture { - static final Fixture INSTANCE = new Fixture(); + private static final class Fixture { + static final Fixture INSTANCE = new Fixture(); - private Fixture() { - super(); - } + private Fixture() { + super(); + } - @Override + @Override public String toString() { - return "fixture"; - } - } + return "fixture"; + } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java index 2adf610..8ffeb3a 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(StringIndexOutOfBoundsException.class) public class StringIndexOutOfBoundsExceptionTest extends TestCase { /** * @tests java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringIndexOutOfBoundsException", - args = {} - ) public void test_Constructor() { StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException(); assertNull(e.getMessage()); @@ -46,26 +34,9 @@ public class StringIndexOutOfBoundsExceptionTest extends TestCase { /** * @tests java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringIndexOutOfBoundsException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "StringIndexOutOfBoundsException", - args = {int.class} - ) - public void test_ConstructorLint() { - StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException(0); - assertTrue(e.getMessage().contains("0")); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java index abb52c1..c40e0b0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java @@ -17,26 +17,14 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -@TestTargetClass(ThreadDeath.class) public class ThreadDeathTest extends junit.framework.TestCase { - /** - * @tests java.lang.ThreadDeath#ThreadDeath() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ThreadDeath", - args = {} - ) - public void test_Constructor() { - ThreadDeath td = new ThreadDeath(); + /** + * @tests java.lang.ThreadDeath#ThreadDeath() + */ + public void test_Constructor() { + ThreadDeath td = new ThreadDeath(); assertNull(td.getCause()); assertNull(td.getMessage()); - } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java index 4b01a98..1f86648 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java @@ -16,25 +16,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(TypeNotPresentException.class) public class TypeNotPresentExceptionTest extends TestCase { /** * @tests java.lang.TypeNotPresentException.TypeNotPresentException(String, Throwable) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "TypeNotPresentException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) public void test_constructorLjava_lang_StringLjava_lang_Throwable() { TypeNotPresentException e = new TypeNotPresentException(null, null); assertNotNull(e); @@ -55,12 +43,6 @@ public class TypeNotPresentExceptionTest extends TestCase { /** * @tests java.lang.TypeNotPresentException.typeName() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "typeName", - args = {} - ) public void test_typeName() { TypeNotPresentException e = new TypeNotPresentException(null, null); assertNull(e.typeName()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java index a894d7e..15f264b 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(UnknownError.class) public class UnknownErrorTest extends TestCase { - /** - * @tests java.lang.UnknownError#UnknownError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnknownError", - args = {} - ) + /** + * @tests java.lang.UnknownError#UnknownError() + */ public void test_Constructor() { UnknownError e = new UnknownError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class UnknownErrorTest extends TestCase { /** * @tests java.lang.UnknownError#UnknownError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnknownError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { UnknownError e = new UnknownError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java index 39a8855..84229d8 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(UnsatisfiedLinkError.class) public class UnsatisfiedLinkErrorTest extends TestCase { - /** - * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsatisfiedLinkError", - args = {} - ) + /** + * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError() + */ public void test_Constructor() { UnsatisfiedLinkError e = new UnsatisfiedLinkError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class UnsatisfiedLinkErrorTest extends TestCase { /** * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsatisfiedLinkError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { UnsatisfiedLinkError e = new UnsatisfiedLinkError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java index c1f3ee9..e9757f1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java @@ -1,55 +1,46 @@ -/* - * 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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import junit.framework.TestCase; // android-changed -import junit.framework.TestCase; +public class UnsupportedClassVersionErrorTest extends TestCase { // android-changed + /** + * Thrown when the Java Virtual Machine attempts to read a class file and + * determines that the major and minor version numbers in the file are not + * supported. + */ -@TestTargetClass(UnsupportedClassVersionError.class) -public class UnsupportedClassVersionErrorTest extends TestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedClassVersionError", - args = {} - ) - public void test_Constructor() { - UnsupportedClassVersionError ucve = new UnsupportedClassVersionError(); - assertNull(ucve.getMessage()); - assertNull(ucve.getCause()); + /** + * @tests java.lang.UnsupportedClassVersionError#UnsupportedClassVersionError() + */ + public void test_UnsupportedClassVersionError() { + UnsupportedClassVersionError error = new UnsupportedClassVersionError(); + assertNotNull(error); + assertNull(error.getMessage()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedClassVersionError", - args = {java.lang.String.class} - ) - public void test_ConstructorLString() { - String message = "Test message"; - UnsupportedClassVersionError ucve = new UnsupportedClassVersionError( - message); - assertEquals(message, ucve.getMessage()); - ucve = new UnsupportedClassVersionError(null); - assertNull(ucve.getMessage()); + + /** + *@tests java.lang.UnsupportedClassVersionError#UnsupportedClassVersionError(java.lang.String) + */ + public void test_UnsupportedClassVersionError_LString() { + UnsupportedClassVersionError e = new UnsupportedClassVersionError( + "Some Error Message"); + assertEquals("Wrong message", "Some Error Message", e.getMessage()); } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java index 73176bb..0458012 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java @@ -17,26 +17,15 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(UnsupportedOperationException.class) public class UnsupportedOperationExceptionTest extends TestCase { - /** - * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedOperationException", - args = {} - ) + /** + * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException() + */ public void test_Constructor() { UnsupportedOperationException e = new UnsupportedOperationException(); assertNull(e.getMessage()); @@ -47,55 +36,54 @@ public class UnsupportedOperationExceptionTest extends TestCase { /** * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedOperationException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { UnsupportedOperationException e = new UnsupportedOperationException("fixture"); assertEquals("fixture", e.getMessage()); assertNull(e.getCause()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedOperationException", - args = {java.lang.String.class, java.lang.Throwable.class} - ) - public void test_ConstructorLStringLThrowable() { - String message = "Test message"; - NullPointerException npe = new NullPointerException(); - UnsupportedOperationException uoe = new UnsupportedOperationException(message, npe); - assertEquals(message, uoe.getMessage()); - assertEquals(npe, uoe.getCause()); + /** + * @tests {@link java.land.UnsupportedOperationException#UnsupportedOperationException(java.lang.Throwable)} + */ + public void test_ConstructorLjava_lang_Throwable() { + Throwable emptyThrowable = new Exception(); + UnsupportedOperationException emptyException = new UnsupportedOperationException( + emptyThrowable); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString()); + + Throwable throwable = new Exception("msg"); + UnsupportedOperationException exception = new UnsupportedOperationException(throwable); + assertEquals(throwable.getClass().getName() + ": " + "msg", exception.getMessage()); + assertEquals(throwable.getClass().getName(), emptyException.getLocalizedMessage()); + assertEquals(throwable.getClass().getName(), emptyException.getCause().toString()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnsupportedOperationException", - args = {java.lang.Throwable.class} - ) - public void test_ConstructorLThrowable(){ - NullPointerException npe = new NullPointerException(); - UnsupportedOperationException uoe = new UnsupportedOperationException(npe); - assertEquals(npe, uoe.getCause()); - uoe = new UnsupportedOperationException((Throwable) null); - assertNull("The cause is not null.", uoe.getCause()); + + /** + * @tests {@link java.land.UnsupportedOperationException#UnsupportedOperationException(java.lang.String, java.lang.Throwable)} + */ + public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() { + Throwable emptyThrowable = new Exception(); + UnsupportedOperationException emptyException = new UnsupportedOperationException( + "msg", emptyThrowable); + assertEquals("msg", emptyException.getMessage()); + assertEquals("msg", emptyException.getLocalizedMessage()); + assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString()); + + Throwable throwable = new Exception("msg_exception"); + UnsupportedOperationException exception = new UnsupportedOperationException( + "msg", throwable); + assertEquals("msg", exception.getMessage()); + assertEquals("msg", exception.getLocalizedMessage()); + assertEquals(throwable.getClass().getName() + ": " + throwable.getMessage(), exception + .getCause().toString()); } + /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new UnsupportedOperationException()); @@ -104,12 +92,6 @@ public class UnsupportedOperationExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java index 3115698..7bd2581 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java @@ -17,25 +17,13 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; -@TestTargetClass(VerifyError.class) public class VerifyErrorTest extends TestCase { - /** - * @tests java.lang.VerifyError#VerifyError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "VerifyError", - args = {} - ) + /** + * @tests java.lang.VerifyError#VerifyError() + */ public void test_Constructor() { VerifyError e = new VerifyError(); assertNull(e.getMessage()); @@ -46,12 +34,6 @@ public class VerifyErrorTest extends TestCase { /** * @tests java.lang.VerifyError#VerifyError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "VerifyError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { VerifyError e = new VerifyError("fixture"); assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java index b998b98..c8ce58c 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java @@ -17,26 +17,14 @@ package org.apache.harmony.luni.tests.java.lang; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; @SuppressWarnings("serial") -@TestTargetClass(VirtualMachineError.class) public class VirtualMachineErrorTest extends TestCase { - /** - * @tests java.lang.VirtualMachineError#VirtualMachineError() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "VirtualMachineError", - args = {} - ) + /** + * @tests java.lang.VirtualMachineError#VirtualMachineError() + */ public void test_Constructor() { VirtualMachineError e = new VirtualMachineError() {}; assertNull(e.getMessage()); @@ -47,12 +35,6 @@ public class VirtualMachineErrorTest extends TestCase { /** * @tests java.lang.VirtualMachineError#VirtualMachineError(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "VirtualMachineError", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { VirtualMachineError e = new VirtualMachineError("fixture") {}; assertEquals("fixture", e.getMessage()); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java index 91ca3a4..ef60ac3 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java @@ -30,7 +30,7 @@ public class AllTests { } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net"); + TestSuite suite = new TestSuite("Tests for java.net"); // add net testsuites here suite.addTestSuite(ContentHandlerTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java index 6b1957a..07a374b 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.luni.tests.java.net; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.IOException; import java.net.ContentHandler; import java.net.URL; @@ -29,19 +24,12 @@ import java.net.URLConnection; import junit.framework.TestCase; -@TestTargetClass(ContentHandler.class) public class ContentHandlerTest extends TestCase { /** * @tests java.net.ContentHandler#getContent(java.net.URLConnection, * java.lang.Class[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getContent", - args = {java.net.URLConnection.class, java.lang.Class[].class} - ) public void test_getContent() throws IOException { URLConnection conn = new URL("http://www.apache.org").openConnection(); Class[] classes = { Foo.class, String.class, }; @@ -49,7 +37,7 @@ public class ContentHandlerTest extends TestCase { ((ContentHandlerImpl) handler).setContent(new Foo()); Object content = handler.getContent(conn, classes); assertEquals("Foo", ((Foo) content).getFoo()); - + ((ContentHandlerImpl) handler).setContent(new FooSub()); content = handler.getContent(conn, classes); assertEquals("FooSub", ((Foo) content).getFoo()); @@ -58,33 +46,6 @@ public class ContentHandlerTest extends TestCase { ((ContentHandlerImpl) handler).setContent(new Foo()); content = handler.getContent(conn, classes2); assertNull(content); - - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getContent", - args = {java.net.URLConnection.class} - ) - public void test_getContentLURLConnection() throws IOException { - URLConnection conn = new URL("http://www.apache.org").openConnection(); - Class[] classes = { Foo.class, String.class, }; - ContentHandler handler = new ContentHandlerImpl(); - ((ContentHandlerImpl) handler).setContent(new Foo()); - Object content = handler.getContent(conn); - assertEquals("Foo", ((Foo) content).getFoo()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ContentHandler", - args = {} - ) - public void test_Constructor() { - ContentHandlerImpl ch = new ContentHandlerImpl(); - ch.setContent(new Object()); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java index 3e3cafe..bc14d6f 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.luni.tests.java.net; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.Serializable; import java.net.HttpRetryException; @@ -30,7 +25,6 @@ import junit.framework.TestCase; import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(HttpRetryException.class) public class HttpRetryExceptionTest extends TestCase { private static final String LOCATION = "Http test"; //$NON-NLS-1$ @@ -54,12 +48,6 @@ public class HttpRetryExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks serialization", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new HttpRetryException(DETAIL, 100, LOCATION), comparator); @@ -68,12 +56,6 @@ public class HttpRetryExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks serialization", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new HttpRetryException(DETAIL, 100, LOCATION), comparator); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java index e290e27..e7be391 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java @@ -1,177 +1,1859 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.net; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - +import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import junit.framework.TestCase; -@TestTargetClass(URI.class) +import org.apache.harmony.testframework.serialization.SerializationTest; + public class URITest extends TestCase { + + private URI[] uris; + + private URI[] getUris() throws URISyntaxException { + if (uris != null) { + return uris; + } + + uris = new URI[] { + // single arg constructor + new URI( + "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag"), + // escaped octets for illegal chars + new URI( + "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g"), + // escaped octets for unicode chars + new URI( + "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g"), + // unicode chars equivalent to = new + // URI("ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g"), + + // multiple arg constructors + new URI("http", "user%60%20info", "host", 80, "/a%20path", //$NON-NLS-4$ + "qu%60%20ery", "fr%5E%20ag"), + // escaped octets for illegal + new URI("http", "user%C3%9F%C2%A3info", "host", -1, + "/a%E2%82%ACpath", "qu%C2%A9%C2%AEery", + "fr%C3%A4%C3%A8g"), + // escaped octets for unicode + new URI("ascheme", "user\u00DF\u00A3info", "host", 80, + "/a\u20ACpath", "qu\u00A9\u00AEery", "fr\u00E4\u00E8g"), + // unicode chars equivalent to = new + // URI("ascheme", "user\u00df\u00a3info", "host", 80, + // "/a\u0080path", "qu\u00a9\u00aeery", "fr\u00e4\u00e8g"), + new URI("http", "user` info", "host", 81, "/a path", "qu` ery", + "fr^ ag"), // illegal chars + new URI("http", "user%info", "host", 0, "/a%path", "que%ry", + "f%rag"), + // % as illegal char, not escaped octet + + // urls with undefined components + new URI("mailto", "user@domain.com", null), + // no host, path, query or fragment + new URI("../adirectory/file.html#"), + // relative path with empty fragment; + new URI("news", "comp.infosystems.www.servers.unix", null), // + new URI(null, null, null, "fragment"), // only fragment + new URI("telnet://server.org"), // only host + new URI("http://reg:istry?query"), + // malformed hostname, therefore registry-based, + // with query + new URI("file:///c:/temp/calculate.pl?"), + // empty authority, non empty path, empty query + }; + return uris; + } + /** - * @tests java.net.URI(java.lang.String) + * @tests java.net.URI#URI(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "NullPointerException checking missed.", - method = "URI", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() throws URISyntaxException { + // tests for public URI(String uri) throws URISyntaxException + + String[] constructorTests = new String[] { + "http://user@www.google.com:45/search?q=helpinfo#somefragment", + // http with authority, query and fragment + "ftp://ftp.is.co.za/rfc/rfc1808.txt", // ftp + "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", // gopher + "mailto:mduerst@ifi.unizh.ch", // mailto + "news:comp.infosystems.www.servers.unix", // news + "telnet://melvyl.ucop.edu/", // telnet + "http://123.24.17.98/test", // IPv4 authority + "http://www.google.com:80/test",// domain name authority + "http://joe@[3ffe:2a00:100:7031::1]:80/test", + // IPv6 authority, with userinfo and port + "/relative", // relative starting with / + "//relative", // relative starting with // + "relative", // relative with no / + "#fragment",// relative just with fragment + "http://user@host:80", // UI, host,port + "http://user@host", // ui, host + "http://host", // host + "http://host:80", // host,port + "http://joe@:80", // ui, port (becomes registry-based) + "file:///foo/bar", // empty authority, non empty path + "ht?tp://hoe@host:80", // miscellaneous tests + "mai/lto:hey?joe#man", "http://host/a%20path#frag", + // path with an escaped octet for space char + "http://host/a%E2%82%ACpath#frag", + // path with escaped octet for unicode char, not USASCII + "http://host/a\u20ACpath#frag", + // path with unicode char, not USASCII equivalent to + // = "http://host/a\u0080path#frag", + "http://host%20name/", // escaped octets in host (becomes + // registry based) + "http://host\u00DFname/", // unicodechar in host (becomes + // registry based) + // equivalent to = "http://host\u00dfname/", + "ht123-+tp://www.google.com:80/test", // legal chars in scheme + }; + + for (int i = 0; i < constructorTests.length; i++) { + try { + new URI(constructorTests[i]); + } catch (URISyntaxException e) { + fail("Failed to construct URI for: " + constructorTests[i] + + " : " + e); + } + } + + String[] constructorTestsInvalid = new String[] { + "http:///a path#frag", // space char in path, not in escaped + // octet form, with no host + "http://host/a[path#frag", // an illegal char, not in escaped + // octet form, should throw an + // exception + "http://host/a%path#frag", // invalid escape sequence in path + "http://host/a%#frag", // incomplete escape sequence in path + + "http://host#a frag", // space char in fragment, not in + // escaped octet form, no path + "http://host/a#fr#ag", // illegal char in fragment + "http:///path#fr%ag", // invalid escape sequence in fragment, + // with no host + "http://host/path#frag%", // incomplete escape sequence in + // fragment + + "http://host/path?a query#frag", // space char in query, not + // in escaped octet form + "http://host?query%ag", // invalid escape sequence in query, no + // path + "http:///path?query%", // incomplete escape sequence in query, + // with no host + + "mailto:user^name@fklkf.com" // invalid char in scheme + // specific part + }; + + int[] constructorTestsInvalidIndices = new int[] { 9, 13, 13, 13, 13, + 16, 15, 21, 18, 17, 18, 11 }; + + for (int i = 0; i < constructorTestsInvalid.length; i++) { + try { + new URI(constructorTestsInvalid[i]); + fail("Failed to throw URISyntaxException for: " + + constructorTestsInvalid[i]); + } catch (URISyntaxException e) { + assertTrue("Wrong index in URISytaxException for: " + + constructorTestsInvalid[i] + " expected: " + + constructorTestsInvalidIndices[i] + ", received: " + + e.getIndex(), + e.getIndex() == constructorTestsInvalidIndices[i]); + } + } + + String invalid2[] = { + // authority validation + "http://user@[3ffe:2x00:100:7031::1]:80/test", // malformed + // IPv6 authority + "http://[ipv6address]/apath#frag", // malformed ipv6 address + "http://[ipv6address/apath#frag", // malformed ipv6 address + "http://ipv6address]/apath#frag", // illegal char in host name + "http://ipv6[address/apath#frag", + "http://ipv6addr]ess/apath#frag", + "http://ipv6address[]/apath#frag", + // illegal char in username... + "http://us[]er@host/path?query#frag", "http://host name/path", // illegal + // char + // in + // authority + "http://host^name#fragment", // illegal char in authority + "telnet://us er@hostname/", // illegal char in authority + // missing components + "//", // Authority expected + "ascheme://", // Authority expected + "ascheme:", // Scheme-specific part expected + // scheme validation + "a scheme://reg/", // illegal char + "1scheme://reg/", // non alpha char as 1st char + "asche\u00dfme:ssp", // unicode char , not USASCII + "asc%20heme:ssp" // escape octets + }; + + for (int i = 0; i < invalid2.length; i++) { + try { + new URI(invalid2[i]); + fail("Failed to throw URISyntaxException for: " + invalid2[i]); + } catch (URISyntaxException e) { + } + } + // Regression test for HARMONY-23 try { new URI("%3"); fail("Assert 0: URI constructor failed to throw exception on invalid input."); } catch (URISyntaxException e) { // Expected - assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex()); + assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e + .getIndex()); } - + // Regression test for HARMONY-25 - // if port value is negative, the authority should be considered registry-based. + // if port value is negative, the authority should be considered + // registry-based. URI uri = new URI("http://host:-8096/path/index.html"); assertEquals("Assert 2: returned wrong port value,", -1, uri.getPort()); assertNull("Assert 3: returned wrong host value,", uri.getHost()); try { uri.parseServerAuthority(); fail("Assert 4: Expected URISyntaxException"); - } catch (URISyntaxException e){ + } catch (URISyntaxException e) { // Expected } - - uri = new URI("http","//myhost:-8096", null); + + uri = new URI("http", "//myhost:-8096", null); assertEquals("Assert 5: returned wrong port value,", -1, uri.getPort()); assertNull("Assert 6: returned wrong host value,", uri.getHost()); try { uri.parseServerAuthority(); fail("Assert 7: Expected URISyntaxException"); - } catch (URISyntaxException e){ + } catch (URISyntaxException e) { // Expected } } - + /** - * @tests java.net.URI(java.lang.String, java.lang.String, java.lang.String) + * @tests java.net.URI#URI(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exceptions checked only.", - method = "URI", - args = {java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) - public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() { - // scheme can not be empty string + public void test_URI_String() { try { - new URI("","//authority/path", "fragment"); - fail ("Assert 0: Expected URISyntaxException with empty URI scheme"); - } catch(URISyntaxException e) { + URI myUri = new URI(":abc@mymail.com"); + fail("TestA, URISyntaxException expected, but not received."); + } catch (URISyntaxException e) { + assertEquals("TestA, Wrong URISyntaxException index, ", 0, e + .getIndex()); + } + + try { + URI uri = new URI("path[one"); + fail("TestB, URISyntaxException expected, but not received."); + } catch (URISyntaxException e1) { + assertEquals("TestB, Wrong URISyntaxException index, ", 4, e1 + .getIndex()); + } + + try { + URI uri = new URI(" "); + fail("TestC, URISyntaxException expected, but not received."); + } catch (URISyntaxException e2) { + assertEquals("TestC, Wrong URISyntaxException index, ", 0, e2 + .getIndex()); + } + } + + /** + * @tests java.net.URI#URI(java.lang.String, java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() + throws URISyntaxException { + URI uri = new URI("mailto", "mduerst@ifi.unizh.ch", null); + assertNull("wrong userinfo", uri.getUserInfo()); + assertNull("wrong hostname", uri.getHost()); + assertNull("wrong authority", uri.getAuthority()); + assertEquals("wrong port number", -1, uri.getPort()); + assertNull("wrong path", uri.getPath()); + assertNull("wrong query", uri.getQuery()); + assertNull("wrong fragment", uri.getFragment()); + assertEquals("wrong SchemeSpecificPart", "mduerst@ifi.unizh.ch", uri + .getSchemeSpecificPart()); + + // scheme specific part can not be null + try { + uri = new URI("mailto", null, null); + fail("Expected URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + + // scheme needs to start with an alpha char + try { + uri = new URI("3scheme", "//authority/path", "fragment"); + fail("Expected URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + + // scheme can not be empty string + try { + uri = new URI("", "//authority/path", "fragment"); + fail("Expected URISyntaxException"); + } catch (URISyntaxException e) { // Expected - assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex()); } } - + + /** + * @tests java.net.URI#URI(java.lang.String, java.lang.String, + * java.lang.String, int, java.lang.String, java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_lang_StringLjava_lang_String() { + // check for URISyntaxException for invalid Server Authority + construct1("http", "user", "host\u00DFname", -1, "/file", "query", + "fragment"); // unicode chars in host name + // equivalent to construct1("http", "user", "host\u00dfname", -1, + // "/file", "query", "fragment"); + construct1("http", "user", "host%20name", -1, "/file", "query", + "fragment"); // escaped octets in host name + construct1("http", "user", "host name", -1, "/file", "query", + "fragment"); // illegal char in host name + construct1("http", "user", "host]name", -1, "/file", "query", + "fragment"); // illegal char in host name + + // missing host name + construct1("http", "user", "", 80, "/file", "query", "fragment"); + + // missing host name + construct1("http", "user", "", -1, "/file", "query", "fragment"); + + // malformed ipv4 address + construct1("telnet", null, "256.197.221.200", -1, null, null, null); + + // malformed ipv4 address + construct1("ftp", null, "198.256.221.200", -1, null, null, null); + + // These tests fail on other implementations... + // construct1("http", "user", null, 80, "/file", "query", "fragment"); + // //missing host name + // construct1("http", "user", null, -1, "/file", "query", "fragment"); + // //missing host name + + // check for URISyntaxException for invalid scheme + construct1("ht\u00DFtp", "user", "hostname", -1, "/file", "query", + "fragment"); // unicode chars in scheme + // equivalent to construct1("ht\u00dftp", "user", "hostname", -1, + // "/file", + // "query", "fragment"); + + construct1("ht%20tp", "user", "hostname", -1, "/file", "query", + "fragment"); // escaped octets in scheme + construct1("ht tp", "user", "hostname", -1, "/file", "query", + "fragment"); // illegal char in scheme + construct1("ht]tp", "user", "hostname", -1, "/file", "query", + "fragment"); // illegal char in scheme + + // relative path with scheme + construct1("http", "user", "hostname", -1, "relative", "query", + "fragment"); // unicode chars in scheme + + // functional test + URI uri; + try { + uri = new URI("http", "us:e@r", "hostname", 85, "/file/dir#/qu?e/", + "qu?er#y", "frag#me?nt"); + assertEquals("wrong userinfo", "us:e@r", uri.getUserInfo()); + assertEquals("wrong hostname", "hostname", uri.getHost()); + assertEquals("wrong port number", 85, uri.getPort()); + assertEquals("wrong path", "/file/dir#/qu?e/", uri.getPath()); + assertEquals("wrong query", "qu?er#y", uri.getQuery()); + assertEquals("wrong fragment", "frag#me?nt", uri.getFragment()); + assertEquals("wrong SchemeSpecificPart", + "//us:e@r@hostname:85/file/dir#/qu?e/?qu?er#y", uri + .getSchemeSpecificPart()); + } catch (URISyntaxException e) { + fail("Unexpected Exception: " + e); + } + } + + /* + * helper method checking if the 7 arg constructor throws URISyntaxException + * for a given set of parameters + */ + private void construct1(String scheme, String userinfo, String host, + int port, String path, String query, String fragment) { + try { + URI uri = new URI(scheme, userinfo, host, port, path, query, + fragment); + fail("Expected URISyntaxException not thrown for URI: " + + uri.toString()); + } catch (URISyntaxException e) { + // this constructor throws URISyntaxException for malformed server + // based authorities + } + } + + /** + * @throws URISyntaxException + * @tests java.net.URI#URI(java.lang.String, java.lang.String, + * java.lang.String, java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String() + throws URISyntaxException { + // relative path + try { + URI myUri = new URI("http", "www.joe.com", "relative", "jimmy"); + fail("URISyntaxException expected but not received."); + } catch (URISyntaxException e) { + // Expected + } + + // valid parameters for this constructor + URI uri; + + uri = new URI("http", "www.joe.com", "/path", "jimmy"); + + // illegal char in path + uri = new URI("http", "www.host.com", "/path?q", "somefragment"); + + // empty fragment + uri = new URI("ftp", "ftp.is.co.za", "/rfc/rfc1808.txt", ""); + + // path with escaped octet for unicode char, not USASCII + uri = new URI("http", "host", "/a%E2%82%ACpath", "frag"); + + // frag with unicode char, not USASCII + // equivalent to = uri = new URI("http", "host", "/apath", + // "\u0080frag"); + uri = new URI("http", "host", "/apath", "\u20ACfrag"); + + // Regression test for Harmony-1693 + new URI(null, null, null, null); + + // regression for Harmony-1346 + try { + uri = new URI("http", ":2:3:4:5:6:7:8", "/apath", "\u20ACfrag"); + fail("Should throw URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + } + + /** + * @throws URISyntaxException + * @tests java.net.URI#URI(java.lang.String, java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String() + throws URISyntaxException { + // URISyntaxException on relative path + try { + URI myUri = new URI("http", "www.joe.com", "relative", "query", + "jimmy"); + fail("URISyntaxException expected but not received."); + } catch (URISyntaxException e) { + // Expected + } + + // test if empty authority is parsed into undefined host, userinfo and + // port and if unicode chars and escaped octets in components are + // preserved, illegal chars are quoted + URI uri = new URI("ht12-3+tp", "", "/p#a%E2%82%ACth", "q^u%25ery", + "f/r\u00DFag"); + + assertEquals("wrong scheme", "ht12-3+tp", uri.getScheme()); + assertNull("wrong authority", uri.getUserInfo()); + assertNull("wrong userinfo", uri.getUserInfo()); + assertNull("wrong hostname", uri.getHost()); + assertEquals("wrong port number", -1, uri.getPort()); + assertEquals("wrong path", "/p#a%E2%82%ACth", uri.getPath()); + assertEquals("wrong query", "q^u%25ery", uri.getQuery()); + assertEquals("wrong fragment", "f/r\u00DFag", uri.getFragment()); + // equivalent to = assertTrue("wrong fragment", + // uri.getFragment().equals("f/r\u00dfag")); + assertEquals("wrong SchemeSpecificPart", "///p#a%E2%82%ACth?q^u%25ery", + uri.getSchemeSpecificPart()); + assertEquals("wrong RawSchemeSpecificPart", + "///p%23a%25E2%2582%25ACth?q%5Eu%2525ery", uri + .getRawSchemeSpecificPart()); + assertEquals( + "incorrect toString()", + "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r\u00dfag", + uri.toString()); + assertEquals("incorrect toASCIIString()", + + "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r%C3%9Fag", uri + .toASCIIString()); + } + + /** + * @throws URISyntaxException + * @tests java.net.URI#URI(java.lang.String, java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) + */ + public void test_fiveArgConstructor() throws URISyntaxException { + // accept [] as part of valid ipv6 host name + URI uri = new URI("ftp", "[0001:1234::0001]", "/dir1/dir2", "query", + "frag"); + assertEquals("Returned incorrect host", "[0001:1234::0001]", uri + .getHost()); + + // do not accept [] as part of invalid ipv6 address + try { + uri = new URI("ftp", "[www.abc.com]", "/dir1/dir2", "query", "frag"); + fail("Expected URISyntaxException for invalid ipv6 address"); + } catch (URISyntaxException e) { + // Expected + } + + // do not accept [] as part of user info + try { + uri = new URI("ftp", "[user]@host", "/dir1/dir2", "query", "frag"); + fail("Expected URISyntaxException invalid user info"); + } catch (URISyntaxException e) { + // Expected + } + } + + /** + * @tests java.net.URI#compareTo(java.lang.Object) + */ + public void test_compareToLjava_lang_Object() throws Exception { + // compareTo tests + + String[][] compareToData = new String[][] { + // scheme tests + { "http:test", "" }, // scheme null, scheme not null + { "", "http:test" }, // reverse + { "http:test", "ftp:test" }, // schemes different + { "/test", "/test" }, // schemes null + { "http://joe", "http://joe" }, // schemes same + { "http://joe", "hTTp://joe" }, // schemes same ignoring case + + // opacity : one opaque, the other not + { "http:opaque", "http://nonopaque" }, + { "http://nonopaque", "http:opaque" }, + { "mailto:abc", "mailto:abc" }, // same ssp + { "mailto:abC", "mailto:Abc" }, // different, by case + { "mailto:abc", "mailto:def" }, // different by letter + { "mailto:abc#ABC", "mailto:abc#DEF" }, + { "mailto:abc#ABC", "mailto:abc#ABC" }, + { "mailto:abc#DEF", "mailto:abc#ABC" }, + + // hierarchical tests.. + + // different authorities + { "//www.test.com/test", "//www.test2.com/test" }, + + { "/nullauth", "//nonnullauth/test" }, // one null authority + { "//nonnull", "/null" }, + { "/hello", "/hello" }, // both authorities null + // different userinfo + { "http://joe@test.com:80", "http://test.com" }, + { "http://jim@test.com", "http://james@test.com" }, + // different hostnames + { "http://test.com", "http://toast.com" }, + { "http://test.com:80", "test.com:87" }, // different ports + { "http://test.com", "http://test.com:80" }, + // different paths + { "http://test.com:91/dir1", "http://test.com:91/dir2" }, + // one null host + { "http:/hostless", "http://hostfilled.com/hostless" }, + + // queries + { "http://test.com/dir?query", "http://test.com/dir?koory" }, + { "/test?query", "/test" }, + { "/test", "/test?query" }, + { "/test", "/test" }, + + // fragments + { "ftp://test.com/path?query#frag", "ftp://test.com/path?query" }, + { "ftp://test.com/path?query", "ftp://test.com/path?query#frag" }, + { "#frag", "#frag" }, { "p", "" }, + + { "http://www.google.com", "#test" } // miscellaneous + }; + + int[] compareToResults = { 1, -1, 2, 0, 0, 0, 1, -1, 0, 32, -3, -3, 0, + 3, -4, -1, 1, 0, 1, 8, -10, -12, -81, -1, -1, 6, 1, -1, 0, 1, + -1, 0, 1, 1, }; + + // test compareTo functionality + for (int i = 0; i < compareToResults.length; i++) { + URI b = new URI(compareToData[i][0]); + URI r = new URI(compareToData[i][1]); + if (b.compareTo(r) != compareToResults[i]) { + fail("Test " + i + ": " + compareToData[i][0] + " compared to " + + compareToData[i][1] + " -> " + b.compareTo(r) + + " rather than " + compareToResults[i]); + } + } + } + + /** + * @throws URISyntaxException + * @tests java.net.URI#compareTo(java.lang.Object) + */ + public void test_compareTo2() throws URISyntaxException { + URI uri, uri2; + + // test URIs with host names with different casing + uri = new URI("http://AbC.cOm/root/news"); + uri2 = new URI("http://aBc.CoM/root/news"); + assertEquals("TestA", 0, uri.compareTo(uri2)); + assertEquals("TestB", 0, uri.compareTo(uri2)); + + // test URIs with one undefined component + uri = new URI("http://abc.com:80/root/news"); + uri2 = new URI("http://abc.com/root/news"); + assertTrue("TestC", uri.compareTo(uri2) > 0); + assertTrue("TestD", uri2.compareTo(uri) < 0); + + // test URIs with one undefined component + uri = new URI("http://user@abc.com/root/news"); + uri2 = new URI("http://abc.com/root/news"); + assertTrue("TestE", uri.compareTo(uri2) > 0); + assertTrue("TestF", uri2.compareTo(uri) < 0); + } + + /** + * @tests java.net.URI#create(java.lang.String) + */ + public void test_createLjava_lang_String() { + try { + URI myUri = URI.create("a scheme://reg/"); + fail("IllegalArgumentException expected but not received."); + } catch (IllegalArgumentException e) { + // Expected + } + } + + /** + * @tests java.net.URI#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() throws Exception { + String[][] equalsData = new String[][] { + { "", "" }, // null frags + { "/path", "/path#frag" }, + { "#frag", "#frag2" }, + { "#frag", "#FRag" }, + + // case insensitive on hex escapes + { "#fr%4F", "#fr%4f" }, + + { "scheme:test", "scheme2:test" }, // scheme stuff + { "test", "http:test" }, + { "http:test", "test" }, + { "SCheme:test", "schEMe:test" }, + + // hierarchical/opaque mismatch + { "mailto:jim", "mailto://jim" }, + { "mailto://test", "mailto:test" }, + + // opaque + { "mailto:name", "mailto:name" }, + { "mailtO:john", "mailto:jim" }, + + // test hex case insensitivity on ssp + { "mailto:te%4Fst", "mailto:te%4fst" }, + + { "mailto:john#frag", "mailto:john#frag2" }, + + // hierarchical + { "/test", "/test" }, // paths + { "/te%F4st", "/te%f4st" }, + { "/TEst", "/teSt" }, + { "", "/test" }, + + // registry based because they don't resolve properly to + // server-based add more tests here + { "//host.com:80err", "//host.com:80e" }, + { "//host.com:81e%Abrr", "//host.com:81e%abrr" }, + + { "/test", "//auth.com/test" }, + { "//test.com", "/test" }, + + { "//test.com", "//test.com" }, // hosts + + // case insensitivity for hosts + { "//HoSt.coM/", "//hOsT.cOm/" }, + { "//te%ae.com", "//te%aE.com" }, + { "//test.com:80", "//test.com:81" }, + { "//joe@test.com:80", "//test.com:80" }, + { "//jo%3E@test.com:82", "//jo%3E@test.com:82" }, + { "//test@test.com:85", "//test@test.com" }, }; + + boolean[] equalsResults = new boolean[] { true, false, false, false, + true, false, false, false, true, false, false, true, false, + true, false, true, true, false, false, false, true, false, + false, true, true, true, false, false, true, false, }; + + // test equals functionality + for (int i = 0; i < equalsResults.length; i++) { + URI b = new URI(equalsData[i][0]); + URI r = new URI(equalsData[i][1]); + if (b.equals(r) != equalsResults[i]) { + fail("Error: " + equalsData[i][0] + " == " + equalsData[i][1] + + "? -> " + b.equals(r) + " expected " + + equalsResults[i]); + } + } + + } + + /** + * @throws URISyntaxException + * @tests java.net.URI#equals(java.lang.Object) + */ + public void test_equals2() throws URISyntaxException { + // test URIs with empty string authority + URI uri = new URI("http:///~/dictionary"); + URI uri2 = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), + uri.getQuery(), uri.getFragment()); + assertTrue(uri2.equals(uri)); + + // test URIs with port number + uri = new URI("http://abc.com%E2%82%AC:88/root/news"); + uri2 = new URI("http://abc.com%E2%82%AC/root/news"); + assertFalse(uri.equals(uri2)); + assertFalse(uri2.equals(uri)); + + // test URIs with host names with different casing + uri = new URI("http://AbC.cOm/root/news"); + uri2 = new URI("http://aBc.CoM/root/news"); + assertTrue(uri.equals(uri2)); + assertTrue(uri2.equals(uri)); + } + + /** + * @tests java.net.URI#getAuthority() + */ + public void test_getAuthority() throws Exception { + URI[] uris = getUris(); + + String[] getAuthorityResults = { + "user` info@host", + "user\u00DF\u00A3info@host:80", // = + // "user\u00df\u00a3info@host:80", + "user\u00DF\u00A3info@host:0", // = + // "user\u00df\u00a3info@host:0", + "user%60%20info@host:80", + "user%C3%9F%C2%A3info@host", + "user\u00DF\u00A3info@host:80", // = + // "user\u00df\u00a3info@host:80", + "user` info@host:81", "user%info@host:0", null, null, null, + null, "server.org", "reg:istry", null, }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getAuthority(); + if (getAuthorityResults[i] != result + && !getAuthorityResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getAuthority() returned: " + result + + ", expected: " + getAuthorityResults[i]); + } + } + // regression test for HARMONY-1119 + assertNull(new URI(null, null, null, 127, null, null, null) + .getAuthority()); + } + + /** + * @tests java.net.URI#getAuthority() + */ + public void test_getAuthority2() throws Exception { + // tests for URIs with empty string authority component + + URI uri = new URI("file:///tmp/"); + assertNull("Authority not null for URI: " + uri, uri.getAuthority()); + assertNull("Host not null for URI " + uri, uri.getHost()); + assertEquals("testA, toString() returned incorrect value", + "file:///tmp/", uri.toString()); + + uri = new URI("file", "", "/tmp", "frag"); + assertNull("Authority not null for URI: " + uri, uri.getAuthority()); + assertNull("Host not null for URI " + uri, uri.getHost()); + assertEquals("testB, toString() returned incorrect value", + "file:///tmp#frag", uri.toString()); + + uri = new URI("file", "", "/tmp", "query", "frag"); + assertNull("Authority not null for URI: " + uri, uri.getAuthority()); + assertNull("Host not null for URI " + uri, uri.getHost()); + assertEquals("test C, toString() returned incorrect value", + "file:///tmp?query#frag", uri.toString()); + + // after normalization the host string info may be lost since the + // uri string is reconstructed + uri = new URI("file", "", "/tmp/a/../b/c", "query", "frag"); + URI uri2 = uri.normalize(); + assertNull("Authority not null for URI: " + uri2, uri.getAuthority()); + assertNull("Host not null for URI " + uri2, uri.getHost()); + assertEquals("test D, toString() returned incorrect value", + "file:///tmp/a/../b/c?query#frag", uri.toString()); + assertEquals("test E, toString() returned incorrect value", + "file:/tmp/b/c?query#frag", uri2.toString()); + + // the empty string host will give URISyntaxException + // for the 7 arg constructor + try { + uri = new URI("file", "user", "", 80, "/path", "query", "frag"); + fail("Expected URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + } + + /** + * @tests java.net.URI#getFragment() + */ + public void test_getFragment() throws Exception { + URI[] uris = getUris(); + + String[] getFragmentResults = { "fr^ ag", "fr\u00E4\u00E8g", // = + // "fr\u00e4\u00e8g", + "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g", + "fr%5E%20ag", "fr%C3%A4%C3%A8g", "fr\u00E4\u00E8g", // = + // "fr\u00e4\u00e8g", + "fr^ ag", "f%rag", null, "", null, "fragment", null, null, null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getFragment(); + if (getFragmentResults[i] != result + && !getFragmentResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getFragment() returned: " + result + + ", expected: " + getFragmentResults[i]); + } + } + } + + /** + * @tests java.net.URI#getHost() + */ + public void test_getHost() throws Exception { + URI[] uris = getUris(); + + String[] getHostResults = { "host", "host", "host", "host", "host", + "host", "host", "host", null, null, null, null, "server.org", + null, null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getHost(); + if (getHostResults[i] != result + && !getHostResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getHost() returned: " + result + ", expected: " + + getHostResults[i]); + } + } + } + + /** + * @tests java.net.URI#getPath() + */ + public void test_getPath() throws Exception { + URI[] uris = getUris(); + + String[] getPathResults = { "/a path", + "/a\u20ACpath", // = "/a\u0080path", + "/a\u20ACpath", // = "/a\u0080path", + "/a%20path", "/a%E2%82%ACpath", + "/a\u20ACpath", // = "/a\u0080path", + "/a path", "/a%path", null, "../adirectory/file.html", null, + "", "", "", "/c:/temp/calculate.pl" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getPath(); + if (getPathResults[i] != result + && !getPathResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getPath() returned: " + result + ", expected: " + + getPathResults[i]); + } + } + } + + /** + * @tests java.net.URI#getPort() + */ + public void test_getPort() throws Exception { + URI[] uris = getUris(); + + int[] getPortResults = { -1, 80, 0, 80, -1, 80, 81, 0, -1, -1, -1, -1, + -1, -1, -1 }; + + for (int i = 0; i < uris.length; i++) { + int result = uris[i].getPort(); + assertTrue("Error: For URI \"" + uris[i].toString() + + "\", getPort() returned: " + result + ", expected: " + + getPortResults[i], result == getPortResults[i]); + } + } + + /** + * @tests java.net.URI#getPort() + */ + public void test_getPort2() throws Exception { + // if port value is negative, the authority should be + // consider registry based. + + URI uri = new URI("http://myhost:-8096/site/index.html"); + assertEquals("TestA, returned wrong port value,", -1, uri.getPort()); + assertNull("TestA, returned wrong host value,", uri.getHost()); + try { + uri.parseServerAuthority(); + fail("TestA, Expected URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + + uri = new URI("http", "//myhost:-8096", null); + assertEquals("TestB returned wrong port value,", -1, uri.getPort()); + assertNull("TestB returned wrong host value,", uri.getHost()); + try { + uri.parseServerAuthority(); + fail("TestB, Expected URISyntaxException"); + } catch (URISyntaxException e) { + // Expected + } + } + + /** + * @tests java.net.URI#getQuery() + */ + public void test_getQuery() throws Exception { + URI[] uris = getUris(); + + String[] getQueryResults = { "qu` ery", "qu\u00A9\u00AEery", // = + // "qu\u00a9\u00aeery", + "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery", + "qu%60%20ery", "qu%C2%A9%C2%AEery", "qu\u00A9\u00AEery", // = + // "qu\u00a9\u00aeery", + "qu` ery", "que%ry", null, null, null, null, null, "query", "" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getQuery(); + if (getQueryResults[i] != result + && !getQueryResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getQuery() returned: " + result + ", expected: " + + getQueryResults[i]); + } + } + } + + /** + * @tests java.net.URI#getRawAuthority() + */ + public void test_getRawAuthority() throws Exception { + URI[] uris = getUris(); + + String[] getRawAuthorityResults = { + "user%60%20info@host", + "user%C3%9F%C2%A3info@host:80", + "user\u00DF\u00A3info@host:0", // = + // "user\u00df\u00a3info@host:0", + "user%2560%2520info@host:80", + "user%25C3%259F%25C2%25A3info@host", + "user\u00DF\u00A3info@host:80", // = + // "user\u00df\u00a3info@host:80", + "user%60%20info@host:81", "user%25info@host:0", null, null, + null, null, "server.org", "reg:istry", null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawAuthority(); + if (getRawAuthorityResults[i] != result + && !getRawAuthorityResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawAuthority() returned: " + result + + ", expected: " + getRawAuthorityResults[i]); + } + } + } + + /** + * @tests java.net.URI#getRawFragment() + */ + public void test_getRawFragment() throws Exception { + URI[] uris = getUris(); + + String[] getRawFragmentResults = { "fr%5E%20ag", + "fr%C3%A4%C3%A8g", + "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g", + "fr%255E%2520ag", "fr%25C3%25A4%25C3%25A8g", + "fr\u00E4\u00E8g", // = + // "fr\u00e4\u00e8g", + "fr%5E%20ag", "f%25rag", null, "", null, "fragment", null, + null, null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawFragment(); + if (getRawFragmentResults[i] != result + && !getRawFragmentResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawFragment() returned: " + result + + ", expected: " + getRawFragmentResults[i]); + } + } + } + + /** + * @tests java.net.URI#getRawPath() + */ + public void test_getRawPath() throws Exception { + URI[] uris = getUris(); + + String[] getRawPathResults = { "/a%20path", + "/a%E2%82%ACpath", + "/a\u20ACpath", // = "/a\u0080path", + "/a%2520path", "/a%25E2%2582%25ACpath", + "/a\u20ACpath", // = + // "/a\u0080path", + "/a%20path", "/a%25path", null, "../adirectory/file.html", + null, "", "", "", "/c:/temp/calculate.pl" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawPath(); + if (getRawPathResults[i] != result + && !getRawPathResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawPath() returned: " + result + + ", expected: " + getRawPathResults[i]); + } + } + } + + /** + * @tests java.net.URI#getRawQuery() + */ + public void test_getRawQuery() throws Exception { + URI[] uris = getUris(); + + String[] getRawQueryResults = { + "qu%60%20ery", + "qu%C2%A9%C2%AEery", + "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery", + "qu%2560%2520ery", + "qu%25C2%25A9%25C2%25AEery", + "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery", + "qu%60%20ery", "que%25ry", null, null, null, null, null, + "query", "" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawQuery(); + if (getRawQueryResults[i] != result + && !getRawQueryResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawQuery() returned: " + result + + ", expected: " + getRawQueryResults[i]); + } + } + + } + + /** + * @tests java.net.URI#getRawSchemeSpecificPart() + */ + public void test_getRawSchemeSpecificPart() throws Exception { + URI[] uris = getUris(); + + String[] getRawSspResults = { + "//user%60%20info@host/a%20path?qu%60%20ery", + "//user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery", + "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // = + // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery" + "//user%2560%2520info@host:80/a%2520path?qu%2560%2520ery", + "//user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery", + "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // = + // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery" + "//user%60%20info@host:81/a%20path?qu%60%20ery", + "//user%25info@host:0/a%25path?que%25ry", "user@domain.com", + "../adirectory/file.html", "comp.infosystems.www.servers.unix", + "", "//server.org", "//reg:istry?query", + "///c:/temp/calculate.pl?" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawSchemeSpecificPart(); + if (!getRawSspResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawSchemeSpecificPart() returned: " + result + + ", expected: " + getRawSspResults[i]); + } + } + } + + /** + * @tests java.net.URI#getRawUserInfo() + */ + public void test_getRawUserInfo() throws URISyntaxException { + URI[] uris = getUris(); + + String[] getRawUserInfoResults = { + "user%60%20info", + "user%C3%9F%C2%A3info", + "user\u00DF\u00A3info", // = "user\u00df\u00a3info", + "user%2560%2520info", + "user%25C3%259F%25C2%25A3info", + "user\u00DF\u00A3info", // = "user\u00df\u00a3info", + "user%60%20info", "user%25info", null, null, null, null, null, + null, null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getRawUserInfo(); + if (getRawUserInfoResults[i] != result + && !getRawUserInfoResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getRawUserInfo() returned: " + result + + ", expected: " + getRawUserInfoResults[i]); + } + } + } + + /** + * @tests java.net.URI#getScheme() + */ + public void test_getScheme() throws Exception { + URI[] uris = getUris(); + + String[] getSchemeResults = { "http", "http", "ascheme", "http", + "http", "ascheme", "http", "http", "mailto", null, "news", + null, "telnet", "http", "file" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getScheme(); + if (getSchemeResults[i] != result + && !getSchemeResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getScheme() returned: " + result + + ", expected: " + getSchemeResults[i]); + } + } + } + + /** + * @tests java.net.URI#getSchemeSpecificPart() + */ + public void test_getSchemeSpecificPart() throws Exception { + URI[] uris = getUris(); + + String[] getSspResults = { + "//user` info@host/a path?qu` ery", + "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // = + // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery", + "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // = + // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery", + "//user%60%20info@host:80/a%20path?qu%60%20ery", + "//user%C3%9F%C2%A3info@host/a%E2%82%ACpath?qu%C2%A9%C2%AEery", + "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // = + // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery", + "//user` info@host:81/a path?qu` ery", + "//user%info@host:0/a%path?que%ry", "user@domain.com", + "../adirectory/file.html", "comp.infosystems.www.servers.unix", + "", "//server.org", "//reg:istry?query", + "///c:/temp/calculate.pl?" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getSchemeSpecificPart(); + if (!getSspResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getSchemeSpecificPart() returned: " + result + + ", expected: " + getSspResults[i]); + } + } + + } + + /** + * @tests java.net.URI#getUserInfo() + */ + public void test_getUserInfo() throws Exception { + URI[] uris = getUris(); + + String[] getUserInfoResults = { + "user` info", + "user\u00DF\u00A3info", // = + // "user\u00df\u00a3info", + "user\u00DF\u00A3info", // = "user\u00df\u00a3info", + "user%60%20info", + "user%C3%9F%C2%A3info", + "user\u00DF\u00A3info", // = "user\u00df\u00a3info", + "user` info", "user%info", null, null, null, null, null, null, + null }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].getUserInfo(); + if (getUserInfoResults[i] != result + && !getUserInfoResults[i].equals(result)) { + fail("Error: For URI \"" + uris[i].toString() + + "\", getUserInfo() returned: " + result + + ", expected: " + getUserInfoResults[i]); + } + } + } + + /** + * @tests java.net.URI#hashCode() + */ + public void test_hashCode() throws Exception { + String[][] hashCodeData = new String[][] { + { "", "" }, // null frags + { "/path", "/path#frag" }, + { "#frag", "#frag2" }, + { "#frag", "#FRag" }, + + { "#fr%4F", "#fr%4F" }, // case insensitive on hex escapes + + { "scheme:test", "scheme2:test" }, // scheme + { "test", "http:test" }, + { "http:test", "test" }, + + // case insensitivity for scheme + { "SCheme:test", "schEMe:test" }, + + // hierarchical/opaque mismatch + { "mailto:jim", "mailto://jim" }, + { "mailto://test", "mailto:test" }, + + // opaque + { "mailto:name", "mailto:name" }, + { "mailtO:john", "mailto:jim" }, + { "mailto:te%4Fst", "mailto:te%4Fst" }, + { "mailto:john#frag", "mailto:john#frag2" }, + + // hierarchical + { "/test/", "/test/" }, // paths + { "/te%F4st", "/te%F4st" }, + { "/TEst", "/teSt" }, + { "", "/test" }, + + // registry based because they don't resolve properly to + // server-based + // add more tests here + { "//host.com:80err", "//host.com:80e" }, + { "//host.com:81e%Abrr", "//host.com:81e%Abrr" }, + { "//Host.com:80e", "//hoSt.com:80e" }, + + { "/test", "//auth.com/test" }, + { "//test.com", "/test" }, + + { "//test.com", "//test.com" }, // server based + + // case insensitivity for host + { "//HoSt.coM/", "//hOsT.cOm/" }, + { "//te%aE.com", "//te%aE.com" }, + { "//test.com:80", "//test.com:81" }, + { "//joe@test.com:80", "//test.com:80" }, + { "//jo%3E@test.com:82", "//jo%3E@test.com:82" }, + { "//test@test.com:85", "//test@test.com" }, }; + + boolean[] hashCodeResults = new boolean[] { true, false, false, false, + true, false, false, false, true, false, false, true, false, + true, false, true, true, false, false, false, true, false, + false, false, true, true, true, false, false, true, false, }; + + for (int i = 0; i < hashCodeResults.length; i++) { + URI b = new URI(hashCodeData[i][0]); + URI r = new URI(hashCodeData[i][1]); + assertEquals("Error in hashcode equals results for" + b.toString() + + " " + r.toString(), hashCodeResults[i], b.hashCode() == r + .hashCode()); + } + + } + + /** + * @tests java.net.URI#isAbsolute() + */ + public void test_isAbsolute() throws URISyntaxException { + String[] isAbsoluteData = new String[] { "mailto:user@ca.ibm.com", + "urn:isbn:123498989h", "news:software.ibm.com", + "http://www.amazon.ca", "file:///d:/temp/results.txt", + "scheme:ssp", "calculate.pl?isbn=123498989h", + "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top", + "//pc1/", "//user@host/path/file" }; + + boolean results[] = new boolean[] { true, true, true, true, true, true, + false, false, false, false, false, false, false }; + + for (int i = 0; i < isAbsoluteData.length; i++) { + boolean result = new URI(isAbsoluteData[i]).isAbsolute(); + assertEquals("new URI(" + isAbsoluteData[i] + ").isAbsolute()", + results[i], result); + } + } + + /** + * @tests java.net.URI#isOpaque() + */ + public void test_isOpaque() throws URISyntaxException { + String[] isOpaqueData = new String[] { "mailto:user@ca.ibm.com", + "urn:isbn:123498989h", "news:software.ibm.com", + "http://www.amazon.ca", "file:///d:/temp/results.txt", + "scheme:ssp", "calculate.pl?isbn=123498989h", + "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top", + "//pc1/", "//user@host/path/file" }; + + boolean results[] = new boolean[] { true, true, true, false, false, + true, false, false, false, false, false, false, false }; + + for (int i = 0; i < isOpaqueData.length; i++) { + boolean result = new URI(isOpaqueData[i]).isOpaque(); + assertEquals("new URI(" + isOpaqueData[i] + ").isOpaque()", + results[i], result); + } + } + + /** + * @tests java.net.URI#normalize() + */ + public void test_normalize() throws Exception { + + String[] normalizeData = new String[] { + // normal + "/", + "/a", + "/a/b", + "/a/b/c", + // single, '.' + "/.", "/./", "/./.", "/././", + "/./a", + "/./a/", + "/././a", + "/././a/", + "/a/.", + "/a/./", + "/a/./.", + "/a/./b", + // double, '..' + "/a/..", "/a/../", "/a/../b", "/a/../b/..", "/a/../b/../", + "/a/../b/../c", "/..", "/../", "/../..", "/../../", "/../a", + "/../a/", "/../../a", "/../../a/", "/a/b/../../c", + "/a/b/../..", + "/a/b/../../", + "/a/b/../../c", + "/a/b/c/../../../d", + "/a/b/..", + "/a/b/../", + "/a/b/../c", + // miscellaneous + "/a/b/.././../../c/./d/../e", + "/a/../../.c././../././c/d/../g/..", + // '.' in the middle of segments + "/a./b", "/.a/b", "/a.b/c", "/a/b../c", + "/a/..b/c", + "/a/b..c/d", + // no leading slash, miscellaneous + "", "a", "a/b", "a/b/c", "../", ".", "..", "../g", + "g/a/../../b/c/./g", "a/b/.././../../c/./d/../e", + "a/../../.c././../././c/d/../g/..", }; + + String[] normalizeResults = new String[] { "/", "/a", "/a/b", "/a/b/c", + "/", "/", "/", "/", "/a", "/a/", "/a", "/a/", "/a/", "/a/", + "/a/", "/a/b", "/", "/", "/b", "/", "/", "/c", "/..", "/../", + "/../..", "/../../", "/../a", "/../a/", "/../../a", + "/../../a/", "/c", "/", "/", "/c", "/d", "/a/", "/a/", "/a/c", + "/../c/e", "/../c/", "/a./b", "/.a/b", "/a.b/c", "/a/b../c", + "/a/..b/c", "/a/b..c/d", "", "a", "a/b", "a/b/c", "../", "", + "..", "../g", "b/c/g", "../c/e", "../c/", }; + + for (int i = 0; i < normalizeData.length; i++) { + URI test = new URI(normalizeData[i]); + String result = test.normalize().toString(); + assertEquals("Normalized incorrectly, ", normalizeResults[i], + result.toString()); + } + } + + /** + * @tests java.net.URI#normalize() + */ + public void test_normalize2() throws URISyntaxException { + URI uri1 = null, uri2 = null; + uri1 = new URI("file:/D:/one/two/../../three"); + uri2 = uri1.normalize(); + + assertEquals("Normalized to incorrect URI", "file:/D:/three", uri2 + .toString()); + assertTrue("Resolved URI is not absolute", uri2.isAbsolute()); + assertFalse("Resolved URI is opaque", uri2.isOpaque()); + assertEquals("Resolved URI has incorrect scheme specific part", + "/D:/three", uri2.getRawSchemeSpecificPart()); + } + + /** + * @tests java.net.URI#normalize() + */ + public void test_normalize3() throws URISyntaxException { + // return same URI if it has a normalized path already + URI uri1 = null, uri2 = null; + uri1 = new URI("http://host/D:/one/two/three"); + uri2 = uri1.normalize(); + assertSame("Failed to return same URI after normalization", uri1, uri2); + + // try with empty path + uri1 = new URI("http", "host", null, "fragment"); + uri2 = uri1.normalize(); + assertSame("Failed to return same URI after normalization", uri1, uri2); + } + + /** + * @tests java.net.URI#parseServerAuthority() + */ + public void test_parseServerAuthority() throws URISyntaxException { + // registry based uris + URI[] uris = null; + uris = new URI[] { + // port number not digits + new URI("http://foo:bar/file#fragment"), + new URI("http", "//foo:bar/file", "fragment"), + + // unicode char in the hostname = new + // URI("http://host\u00dfname/") + new URI("http://host\u00DFname/"), + + new URI("http", "//host\u00DFname/", null), + // = new URI("http://host\u00dfname/", null), + + // escaped octets in host name + new URI("http://host%20name/"), + new URI("http", "//host%20name/", null), + + // missing host name, port number + new URI("http://joe@:80"), + + // missing host name, no port number + new URI("http://user@/file?query#fragment"), + + new URI("//host.com:80err"), // malformed port number + new URI("//host.com:81e%Abrr"), + + // malformed ipv4 address + new URI("telnet", "//256.197.221.200", null), + + new URI("telnet://198.256.221.200"), + new URI("//te%ae.com"), // misc .. + new URI("//:port"), new URI("//:80"), + + // last label has to start with alpha char + new URI("//fgj234fkgj.jhj.123."), + + new URI("//fgj234fkgj.jhj.123"), + + // '-' cannot be first or last character in a label + new URI("//-domain.name"), new URI("//domain.name-"), + new URI("//domain-"), + + // illegal char in host name + new URI("//doma*in"), + + // host expected + new URI("http://:80/"), new URI("http://user@/"), + + // ipv6 address not enclosed in "[]" + new URI("http://3ffe:2a00:100:7031:22:1:80:89/"), + + // expected ipv6 addresses to be enclosed in "[]" + new URI("http", "34::56:78", "/path", "query", "fragment"), + + // expected host + new URI("http", "user@", "/path", "query", "fragment") }; + // these URIs do not have valid server based authorities, + // but single arg, 3 and 5 arg constructors + // parse them as valid registry based authorities + + // exception should occur when parseServerAuthority is + // requested on these uris + for (int i = 0; i < uris.length; i++) { + try { + URI uri = uris[i].parseServerAuthority(); + fail("URISyntaxException expected but not received for URI: " + + uris[i].toString()); + } catch (URISyntaxException e) { + // Expected + } + } + + // valid Server based authorities + new URI("http", "3ffe:2a00:100:7031:2e:1:80:80", "/path", "fragment") + .parseServerAuthority(); + new URI("http", "host:80", "/path", "query", "fragment") + .parseServerAuthority(); + new URI("http://[::3abc:4abc]:80/").parseServerAuthority(); + new URI("http", "34::56:78", "/path", "fragment") + .parseServerAuthority(); + new URI("http", "[34:56::78]:80", "/path", "fragment") + .parseServerAuthority(); + + // invalid authorities (neither server nor registry) + try { + URI uri = new URI("http://us[er@host:80/"); + fail("Expected URISyntaxException for URI " + uri.toString()); + } catch (URISyntaxException e) { + // Expected + } + + try { + URI uri = new URI("http://[ddd::hgghh]/"); + fail("Expected URISyntaxException for URI " + uri.toString()); + } catch (URISyntaxException e) { + // Expected + } + + try { + URI uri = new URI("http", "[3ffe:2a00:100:7031:2e:1:80:80]a:80", + "/path", "fragment"); + fail("Expected URISyntaxException for URI " + uri.toString()); + } catch (URISyntaxException e) { + // Expected + } + + try { + URI uri = new URI("http", "host:80", "/path", "fragment"); + fail("Expected URISyntaxException for URI " + uri.toString()); + } catch (URISyntaxException e) { + // Expected + } + + // regression test for HARMONY-1126 + assertNotNull(URI.create("file://C:/1.txt").parseServerAuthority()); + } + /** * @tests java.net.URI#relativize(java.net.URI) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "NullPointerException checking missed.", - method = "relativize", - args = {java.net.URI.class} - ) - public void test_relativizeLjava_net_URI() throws URISyntaxException{ + public void test_relativizeLjava_net_URI() throws URISyntaxException { + // relativization tests + String[][] relativizeData = new String[][] { + // first is base, second is the one to relativize + { "http://www.google.com/dir1/dir2", "mailto:test" }, // rel = + // opaque + { "mailto:test", "http://www.google.com" }, // base = opaque + + // different authority + { "http://www.eclipse.org/dir1", + "http://www.google.com/dir1/dir2" }, + + // different scheme + { "http://www.google.com", "ftp://www.google.com" }, + + { "http://www.google.com/dir1/dir2/", + "http://www.google.com/dir3/dir4/file.txt" }, + { "http://www.google.com/dir1/", + "http://www.google.com/dir1/dir2/file.txt" }, + { "./dir1/", "./dir1/hi" }, + { "/dir1/./dir2", "/dir1/./dir2/hi" }, + { "/dir1/dir2/..", "/dir1/dir2/../hi" }, + { "/dir1/dir2/..", "/dir1/dir2/hi" }, + { "/dir1/dir2/", "/dir1/dir3/../dir2/text" }, + { "//www.google.com", "//www.google.com/dir1/file" }, + { "/dir1", "/dir1/hi" }, { "/dir1/", "/dir1/hi" }, }; + + // expected results + String[] relativizeResults = new String[] { "mailto:test", + "http://www.google.com", "http://www.google.com/dir1/dir2", + "ftp://www.google.com", + "http://www.google.com/dir3/dir4/file.txt", "dir2/file.txt", + "hi", "hi", "hi", "dir2/hi", "text", "dir1/file", "hi", "hi", }; + + for (int i = 0; i < relativizeData.length; i++) { + try { + URI b = new URI(relativizeData[i][0]); + URI r = new URI(relativizeData[i][1]); + if (!b.relativize(r).toString().equals(relativizeResults[i])) { + fail("Error: relativize, " + relativizeData[i][0] + ", " + + relativizeData[i][1] + " returned: " + + b.relativize(r) + ", expected:" + + relativizeResults[i]); + } + } catch (URISyntaxException e) { + fail("Exception on relativize test on data " + + relativizeData[i][0] + ", " + relativizeData[i][1] + + ": " + e); + } + } + URI a = new URI("http://host/dir"); - URI b = new URI("http://host/dir/file?query"); - assertEquals("Assert 0: URI relativized incorrectly,", - new URI("file?query"), a.relativize(b)); - + URI b = new URI("http://host/dir/file?query"); + assertEquals("Assert 0: URI relativized incorrectly,", new URI( + "file?query"), a.relativize(b)); + // One URI with empty host a = new URI("file:///~/first"); b = new URI("file://tools/~/first"); - assertEquals("Assert 1: URI relativized incorrectly,", - new URI("file://tools/~/first"), a.relativize(b)); - assertEquals("Assert 2: URI relativized incorrectly,", - new URI("file:///~/first"), b.relativize(a)); + assertEquals("Assert 1: URI relativized incorrectly,", new URI( + "file://tools/~/first"), a.relativize(b)); + assertEquals("Assert 2: URI relativized incorrectly,", new URI( + "file:///~/first"), b.relativize(a)); // Both URIs with empty hosts b = new URI("file:///~/second"); - assertEquals("Assert 3: URI relativized incorrectly,", - new URI("file:///~/second"), a.relativize(b)); - assertEquals("Assert 4: URI relativized incorrectly,", - new URI("file:///~/first"), b.relativize(a)); + assertEquals("Assert 3: URI relativized incorrectly,", new URI( + "file:///~/second"), a.relativize(b)); + assertEquals("Assert 4: URI relativized incorrectly,", new URI( + "file:///~/first"), b.relativize(a)); } - - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "NullPointerException checking missed.", - method = "relativize", - args = {java.net.URI.class} - ) - public void test_relativizeBasedOneEclipseCoreResources() throws URISyntaxException { + + // Regression test for HARMONY-6075 + public void test_relativize3() throws Exception { + URI uri = new URI("file", null, "/test/location", null); + + URI base = new URI("file", null, "/test", null); + + URI relative = base.relativize(uri); + assertEquals("location", relative.getSchemeSpecificPart()); + assertNull(relative.getScheme()); + } + + /** + * @tests java.net.URI#relativize(java.net.URI) + */ + public void test_relativize2() throws URISyntaxException { + URI a = new URI("http://host/dir"); + URI b = new URI("http://host/dir/file?query"); + assertEquals("relativized incorrectly,", new URI("file?query"), a + .relativize(b)); + + // one URI with empty host + a = new URI("file:///~/dictionary"); + b = new URI("file://tools/~/dictionary"); + assertEquals("relativized incorrectly,", new URI( + "file://tools/~/dictionary"), a.relativize(b)); + assertEquals("relativized incorrectly,", + new URI("file:///~/dictionary"), b.relativize(a)); + + // two URIs with empty hosts + b = new URI("file:///~/therasus"); + assertEquals("relativized incorrectly,", new URI("file:///~/therasus"), + a.relativize(b)); + assertEquals("relativized incorrectly,", + new URI("file:///~/dictionary"), b.relativize(a)); + URI one = new URI("file:/C:/test/ws"); URI two = new URI("file:/C:/test/ws"); - + URI empty = new URI(""); assertEquals(empty, one.relativize(two)); - + one = new URI("file:/C:/test/ws"); two = new URI("file:/C:/test/ws/p1"); URI result = new URI("p1"); assertEquals(result, one.relativize(two)); - + one = new URI("file:/C:/test/ws/"); assertEquals(result, one.relativize(two)); } + + /** + * @tests java.net.URI#resolve(java.net.URI) + */ + public void test_resolve() throws URISyntaxException { + URI uri1 = null, uri2 = null; + uri1 = new URI("file:/D:/one/two/three"); + uri2 = uri1.resolve(new URI("..")); + + assertEquals("Resolved to incorrect URI", "file:/D:/one/", uri2 + .toString()); + assertTrue("Resolved URI is not absolute", uri2.isAbsolute()); + assertFalse("Resolved URI is opaque", uri2.isOpaque()); + assertEquals("Resolved URI has incorrect scheme specific part", + "/D:/one/", uri2.getRawSchemeSpecificPart()); + } + + /** + * @tests java.net.URI#resolve(java.net.URI) + */ + public void test_resolveLjava_net_URI() { + // resolution tests + String[][] resolveData = new String[][] { + // authority in given URI + { "http://www.test.com/dir", + "//www.test.com/hello?query#fragment" }, + // no authority, absolute path + { "http://www.test.com/dir", "/abspath/file.txt" }, + // no authority, relative paths + { "/", "dir1/file.txt" }, { "/dir1", "dir2/file.txt" }, + { "/dir1/", "dir2/file.txt" }, { "", "dir1/file.txt" }, + { "dir1", "dir2/file.txt" }, { "dir1/", "dir2/file.txt" }, + // normalization required + { "/dir1/dir2/../dir3/./", "dir4/./file.txt" }, + // allow a standalone fragment to be resolved + { "http://www.google.com/hey/joe?query#fragment", "#frag2" }, + // return given when base is opaque + { "mailto:idontexist@uk.ibm.com", "dir1/dir2" }, + // return given when given is absolute + { "http://www.google.com/hi/joe", "http://www.oogle.com" }, }; + + // expected results + String[] resolveResults = new String[] { + "http://www.test.com/hello?query#fragment", + "http://www.test.com/abspath/file.txt", "/dir1/file.txt", + "/dir2/file.txt", "/dir1/dir2/file.txt", "dir1/file.txt", + "dir2/file.txt", "dir1/dir2/file.txt", + "/dir1/dir3/dir4/file.txt", + "http://www.google.com/hey/joe?query#frag2", "dir1/dir2", + "http://www.oogle.com", }; + + for (int i = 0; i < resolveResults.length; i++) { + try { + URI b = new URI(resolveData[i][0]); + URI r = new URI(resolveData[i][1]); + URI result = b.resolve(r); + if (!result.toString().equals(resolveResults[i])) { + fail("Error: resolve, " + resolveData[i][0] + ", " + + resolveData[i][1] + " returned: " + b.resolve(r) + + ", expected:" + resolveResults[i]); + } + if (!b.isOpaque()) { + assertEquals(b + " and " + result + + " incorrectly differ in absoluteness", b + .isAbsolute(), result.isAbsolute()); + } + } catch (URISyntaxException e) { + fail("Exception on resolve test on data " + resolveData[i][0] + + ", " + resolveData[i][1] + ": " + e); + } + } + } + + /** + * @tests java.net.URI#toASCIIString() + */ + public void test_toASCIIString() throws Exception { + URI[] uris = getUris(); + + String[] toASCIIStringResults0 = new String[] { + "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag", + "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g", + "ascheme://user%C3%9F%C2%A3info@host:0/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g", + "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag", + "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g", + "ascheme://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g", + "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag", + "http://user%25info@host:0/a%25path?que%25ry#f%25rag", + "mailto:user@domain.com", "../adirectory/file.html#", + "news:comp.infosystems.www.servers.unix", "#fragment", + "telnet://server.org", "http://reg:istry?query", + "file:///c:/temp/calculate.pl?" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].toASCIIString(); + assertTrue("Error: For URI \"" + uris[i].toString() + + "\", toASCIIString() returned: " + result + + ", expected: " + toASCIIStringResults0[i], result + .equals(toASCIIStringResults0[i])); + } + + String[] toASCIIStringData = new String[] { + "http://www.test.com/\u00DF/dir/", + "http://www.test.com/\u20AC/dir", "http://www.\u20AC.com/dir", + "http://www.test.com/\u20AC/dir/file#fragment", + "mailto://user@domain.com", "mailto://user\u00DF@domain.com", }; + + String[] toASCIIStringResults = new String[] { + "http://www.test.com/%C3%9F/dir/", + "http://www.test.com/%E2%82%AC/dir", + "http://www.%E2%82%AC.com/dir", + "http://www.test.com/%E2%82%AC/dir/file#fragment", + "mailto://user@domain.com", "mailto://user%C3%9F@domain.com", }; + + for (int i = 0; i < toASCIIStringData.length; i++) { + URI test = new URI(toASCIIStringData[i]); + String result = test.toASCIIString(); + assertTrue("Error: new URI(\"" + toASCIIStringData[i] + + "\").toASCIIString() returned: " + result + + ", expected: " + toASCIIStringResults[i], result + .equals(toASCIIStringResults[i])); + } + } + + /** + * @tests java.net.URI#toString() + */ + public void test_toString() throws Exception { + URI[] uris = getUris(); + + String[] toStringResults = { + "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag", + "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g", + "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g", + // = + // "ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g", + "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag", + "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g", + "ascheme://user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g", + // = + // "ascheme://user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g", + "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag", + "http://user%25info@host:0/a%25path?que%25ry#f%25rag", + "mailto:user@domain.com", "../adirectory/file.html#", + "news:comp.infosystems.www.servers.unix", "#fragment", + "telnet://server.org", "http://reg:istry?query", + "file:///c:/temp/calculate.pl?" }; + + for (int i = 0; i < uris.length; i++) { + String result = uris[i].toString(); + assertTrue("Error: For URI \"" + uris[i].toString() + + "\", toString() returned: " + result + ", expected: " + + toStringResults[i], result.equals(toStringResults[i])); + } + } + + /** + * @tests java.net.URI#toURL() + */ + public void test_toURL() throws Exception { + String absoluteuris[] = new String[] { "mailto:noreply@apache.org", + "urn:isbn:123498989h", "news:software.ibm.com", + "http://www.apache.org", "file:///d:/temp/results.txt", + "scheme:ssp", }; + + String relativeuris[] = new String[] { "calculate.pl?isbn=123498989h", + "?isbn=123498989h", "//www.apache.org", "a.html", "#top", + "//pc1/", "//user@host/path/file" }; + + for (int i = 0; i < absoluteuris.length; i++) { + try { + new URI(absoluteuris[i]).toURL(); + } catch (MalformedURLException e) { + // not all the URIs can be translated into valid URLs + } + } + + for (int i = 0; i < relativeuris.length; i++) { + try { + new URI(relativeuris[i]).toURL(); + fail("Expected IllegalArgumentException not thrown"); + } catch (IllegalArgumentException e) { + // Expected + } + } + } /** - * @tests java.net.URI#compareTo(java.net.URI) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "compareTo", - args = {java.net.URI.class} - ) - public void test_compareToLjava_net_URI() throws URISyntaxException{ - URI uri1, uri2; - - // URIs whose host names have different casing - uri1 = new URI("http://MixedCaseHost/path/resource"); - uri2 = new URI("http://mixedcasehost/path/resource"); - assertEquals("Assert 0: host name equality failure", 0, uri1.compareTo(uri2)); - assertEquals("Assert 1: host name equality failure", 0, uri1.compareTo(uri2)); - - // URIs with one undefined component (port) - uri1 = new URI("http://anyhost:80/path/resource"); - uri2 = new URI("http://anyhost/path/resource"); - assertTrue("Assert 2: comparison failure", uri1.compareTo(uri2) > 0); - assertTrue("Assert 3: comparison failure", uri2.compareTo(uri1) < 0); - - // URIs with one undefined component (user-info) - uri1 = new URI("http://user-info@anyhost/path/resource"); - uri2 = new URI("http://anyhost/path/resource"); - assertTrue("Assert 4: comparison failure", uri1.compareTo(uri2) > 0); - assertTrue("Assert 5: comparison failure", uri2.compareTo(uri1) < 0); - + * @tests serialization/deserialization. + */ + public void testSerializationSelf() throws Exception { + URI uri = new URI("http://harmony.apache.org/"); + + SerializationTest.verifySelf(uri); } } 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 52fdf4a..67a81cf 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 @@ -1,57 +1,67 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.net; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; import java.net.URLEncoder; import junit.framework.TestCase; +import tests.support.Support_Configuration; -@TestTargetClass(URLEncoder.class) public class URLEncoderTest extends TestCase { - + + /** + * @tests java.net.URLEncoder#encode(java.lang.String) + */ + @SuppressWarnings("deprecation") + public void test_encodeLjava_lang_String() { + final String URL = "http://" + Support_Configuration.HomeAddress; + final String URL2 = "telnet://justWantToHaveFun.com:400"; + final String URL3 = "file://myServer.org/a file with spaces.jpg"; + + assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode( + URLEncoder.encode(URL)).equals(URL)); + assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode( + URLEncoder.encode(URL2)).equals(URL2)); + assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode( + URLEncoder.encode(URL3)).equals(URL3)); + } + /** * @tests URLEncoder#encode(String, String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test. Checks UnsupportedEncodingException & NullPointerException", - method = "encode", - args = {java.lang.String.class, java.lang.String.class} - ) - public void test_encodeLjava_lang_StringLjava_lang_String() throws Exception { + public void test_encodeLjava_lang_StringLjava_lang_String() + throws Exception { // Regression for HARMONY-24 try { - URLEncoder.encode("str","unknown_enc"); + URLEncoder.encode("str", "unknown_enc"); fail("Assert 0: Should throw UEE for invalid encoding"); } catch (UnsupportedEncodingException e) { // expected - } - //Regression for HARMONY-1233 + } + + // Regression for HARMONY-1233 try { URLEncoder.encode(null, "harmony"); fail("NullPointerException expected"); } catch (NullPointerException e) { - //expected + // expected } } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java index 801727c..6021c32 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java @@ -17,29 +17,17 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import junit.framework.TestCase; -@TestTargetClass(java.util.AbstractCollection.class) public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#add(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "add", - args = {java.lang.Object.class} - ) public void test_addLjava_lang_Object() { AbstractCollection<Object> ac = new AbstractCollection<Object>() { @@ -65,12 +53,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#addAll(java.util.Collection) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "addAll", - args = {java.util.Collection.class} - ) public void test_addAllLjava_util_Collection() { final Collection<String> fixtures = Arrays.asList("0", "1", "2"); AbstractCollection<String> ac = new AbstractCollection<String>() { @@ -100,12 +82,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#containsAll(java.util.Collection) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "containsAll", - args = {java.util.Collection.class} - ) public void test_containsAllLjava_util_Collection() { final Collection<String> fixtures = Arrays.asList("0", "1", "2"); AbstractCollection<String> ac = new AbstractCollection<String>() { @@ -135,12 +111,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#isEmpty() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "isEmpty", - args = {} - ) public void test_isEmpty() { final boolean[] sizeCalled = new boolean[1]; AbstractCollection<Object> ac = new AbstractCollection<Object>(){ @@ -162,12 +132,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#removeAll(java.util.Collection) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "removeAll", - args = {java.util.Collection.class} - ) public void test_removeAllLjava_util_Collection() { final String[] removed = new String[3]; AbstractCollection<String> ac = new AbstractCollection<String>() { @@ -210,12 +174,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#retainAll(java.util.Collection) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "retainAll", - args = {java.util.Collection.class} - ) public void test_retainAllLjava_util_Collection() { final String[] removed = new String[1]; AbstractCollection<String> ac = new AbstractCollection<String>() { @@ -254,12 +212,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#toArray() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toArray", - args = {} - ) public void test_toArray() { AbstractCollection<String> ac = new AbstractCollection<String>() { @Override @@ -300,12 +252,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#toArray(java.lang.Object[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toArray", - args = {java.lang.Object[].class} - ) public void test_toArray$Ljava_lang_Object() { AbstractCollection<String> ac = new AbstractCollection<String>() { @Override @@ -365,12 +311,6 @@ public class AbstractCollectionTest extends TestCase { /** * @tests java.util.AbstractCollection#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "toString", - args = {} - ) public void test_toString() { // see HARMONY-1522 // collection that returns null iterator(this is against the spec.) @@ -396,128 +336,4 @@ public class AbstractCollectionTest extends TestCase { } catch (NullPointerException e) { } } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "AbstractCollection", - args = {} - ) - public void test_Constructor() { - AbstractCollection<?> ac = new AbstractCollection<Object>() { - @Override - public Iterator<Object> iterator() { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - assertNotNull(ac); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "clear", - args = {} - ) - public void test_clear() { - AbstractCollection<?> ac = new AbstractCollection<Object>() { - @Override - public Iterator<Object> iterator() { - return new Iterator<Object>() { - - public boolean hasNext() { - return false; - } - - public Object next() { - return null; - } - - public void remove() { - } - }; - } - - @Override - public int size() { - return 0; - } - }; - - ac.clear(); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "contains", - args = {java.lang.Object.class} - ) - public void test_containsLjava_lang_Object() { - AbstractCollection<?> ac = new AbstractCollection<Object>() { - @Override - public Iterator<Object> iterator() { - return new Iterator<Object>() { - - public boolean hasNext() { - return false; - } - - public Object next() { - return null; - } - - public void remove() { - } - }; - } - - @Override - public int size() { - return 0; - } - }; - - assertFalse(ac.contains(this)); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.", - method = "remove", - args = {java.lang.Object.class} - ) - public void test_removeLjava_lang_Object() { - AbstractCollection<?> ac = new AbstractCollection<Object>() { - @Override - public Iterator<Object> iterator() { - return new Iterator<Object>() { - - public boolean hasNext() { - return false; - } - - public Object next() { - return null; - } - - public void remove() { - } - }; - } - - @Override - public int size() { - return 0; - } - }; - - assertFalse(ac.remove(this)); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java index 2bfc7bf..88c4fad 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java @@ -30,7 +30,7 @@ public class AllTests { } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util"); + TestSuite suite = new TestSuite("Tests for java.util"); suite.addTestSuite(AbstractCollectionTest.class); suite.addTestSuite(AbstractMapTest.class); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java index ab29579..7c58d45 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java @@ -1,24 +1,343 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import tests.support.Support_ListTest; + +public class ArrayListTest extends junit.framework.TestCase { + + List alist; + + static Object[] objArray; + { + objArray = new Object[100]; + for (int i = 0; i < objArray.length; i++) + objArray[i] = new Integer(i); + } + + /** + * @tests java.util.ArrayList#ArrayList() + */ + public void test_Constructor() { + // Test for method java.util.ArrayList() + new Support_ListTest("", alist).runTest(); + + ArrayList subList = new ArrayList(); + for (int i = -50; i < 150; i++) + subList.add(new Integer(i)); + new Support_ListTest("", subList.subList(50, 150)).runTest(); + } + + /** + * @tests java.util.ArrayList#ArrayList(int) + */ + public void test_ConstructorI() { + // Test for method java.util.ArrayList(int) + ArrayList al = new ArrayList(5); + assertEquals("Incorrect arrayList created", 0, al.size()); + + al = new ArrayList(0); + assertEquals("Incorrect arrayList created", 0, al.size()); + + try { + al = new ArrayList(-1); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // Excepted + } + } + + /** + * @tests java.util.ArrayList#ArrayList(java.util.Collection) + */ + public void test_ConstructorLjava_util_Collection() { + // Test for method java.util.ArrayList(java.util.Collection) + ArrayList al = new ArrayList(Arrays.asList(objArray)); + assertTrue("arrayList created from collection has incorrect size", al + .size() == objArray.length); + for (int counter = 0; counter < objArray.length; counter++) + assertTrue( + "arrayList created from collection has incorrect elements", + al.get(counter) == objArray[counter]); + + } + + public void testConstructorWithConcurrentCollection() { + Collection<String> collection = shrinksOnSize("A", "B", "C", "D"); + ArrayList<String> list = new ArrayList<String>(collection); + assertFalse(list.contains(null)); + } + + /** + * @tests java.util.ArrayList#add(int, java.lang.Object) + */ + public void test_addILjava_lang_Object() { + // Test for method void java.util.ArrayList.add(int, java.lang.Object) + Object o; + alist.add(50, o = new Object()); + assertTrue("Failed to add Object", alist.get(50) == o); + assertTrue("Failed to fix up list after insert", + alist.get(51) == objArray[50] + && (alist.get(52) == objArray[51])); + Object oldItem = alist.get(25); + alist.add(25, null); + assertNull("Should have returned null", alist.get(25)); + assertTrue("Should have returned the old item from slot 25", alist + .get(26) == oldItem); + + alist.add(0, o = new Object()); + assertEquals("Failed to add Object", alist.get(0), o); + assertEquals(alist.get(1), objArray[0]); + assertEquals(alist.get(2), objArray[1]); + + oldItem = alist.get(0); + alist.add(0, null); + assertNull("Should have returned null", alist.get(0)); + assertEquals("Should have returned the old item from slot 0", alist + .get(1), oldItem); + + try { + alist.add(-1, new Object()); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.add(-1, null); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.add(alist.size() + 1, new Object()); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.add(alist.size() + 1, null); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } + + /** + * @tests java.util.ArrayList#add(int, java.lang.Object) + */ + public void test_addILjava_lang_Object_2() { + Object o = new Object(); + int size = alist.size(); + alist.add(size, o); + assertEquals("Failed to add Object", alist.get(size), o); + assertEquals(alist.get(size - 2), objArray[size - 2]); + assertEquals(alist.get(size - 1), objArray[size - 1]); + + alist.remove(size); + + size = alist.size(); + alist.add(size, null); + assertNull("Should have returned null", alist.get(size)); + assertEquals(alist.get(size - 2), objArray[size - 2]); + assertEquals(alist.get(size - 1), objArray[size - 1]); + } + + /** + * @tests java.util.ArrayList#add(java.lang.Object) + */ + public void test_addLjava_lang_Object() { + // Test for method boolean java.util.ArrayList.add(java.lang.Object) + Object o = new Object(); + alist.add(o); + assertTrue("Failed to add Object", alist.get(alist.size() - 1) == o); + alist.add(null); + assertNull("Failed to add null", alist.get(alist.size() - 1)); + } + + /** + * @tests java.util.ArrayList#addAll(int, java.util.Collection) + */ + public void test_addAllILjava_util_Collection() { + // Test for method boolean java.util.ArrayList.addAll(int, + // java.util.Collection) + alist.addAll(50, alist); + assertEquals("Returned incorrect size after adding to existing list", + 200, alist.size()); + for (int i = 0; i < 50; i++) + assertTrue("Manipulated elements < index", + alist.get(i) == objArray[i]); + for (int i = 0; i >= 50 && (i < 150); i++) + assertTrue("Failed to ad elements properly", + alist.get(i) == objArray[i - 50]); + for (int i = 0; i >= 150 && (i < 200); i++) + assertTrue("Failed to ad elements properly", + alist.get(i) == objArray[i - 100]); + ArrayList listWithNulls = new ArrayList(); + listWithNulls.add(null); + listWithNulls.add(null); + listWithNulls.add("yoink"); + listWithNulls.add("kazoo"); + listWithNulls.add(null); + alist.addAll(100, listWithNulls); + assertTrue("Incorrect size: " + alist.size(), alist.size() == 205); + assertNull("Item at slot 100 should be null", alist.get(100)); + assertNull("Item at slot 101 should be null", alist.get(101)); + assertEquals("Item at slot 102 should be 'yoink'", "yoink", alist + .get(102)); + assertEquals("Item at slot 103 should be 'kazoo'", "kazoo", alist + .get(103)); + assertNull("Item at slot 104 should be null", alist.get(104)); + alist.addAll(205, listWithNulls); + assertTrue("Incorrect size2: " + alist.size(), alist.size() == 210); + } + + /** + * @tests java.util.ArrayList#addAll(int, java.util.Collection) + */ + @SuppressWarnings("unchecked") + public void test_addAllILjava_util_Collection_2() { + // Regression for HARMONY-467 + ArrayList obj = new ArrayList(); + try { + obj.addAll((int) -1, (Collection) null); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + // Regression for HARMONY-5705 + String[] data = new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }; + ArrayList list1 = new ArrayList(); + ArrayList list2 = new ArrayList(); + for (String d : data) { + list1.add(d); + list2.add(d); + list2.add(d); + } + while (list1.size() > 0) + list1.remove(0); + list1.addAll(list2); + assertTrue("The object list is not the same as original list", list1 + .containsAll(list2) + && list2.containsAll(list1)); + + obj = new ArrayList(); + for (int i = 0; i < 100; i++) { + if (list1.size() > 0) { + obj.removeAll(list1); + obj.addAll(list1); + } + } + assertTrue("The object list is not the same as original list", obj + .containsAll(list1) + && list1.containsAll(obj)); -@TestTargetClass(ArrayList.class) -public class ArrayListTest extends TestCase { + // Regression for Harmony-5799 + list1 = new ArrayList(); + list2 = new ArrayList(); + int location = 2; + + String[] strings = { "0", "1", "2", "3", "4", "5", "6" }; + int[] integers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + for (int i = 0; i < 7; i++) { + list1.add(strings[i]); + } + for (int i = 0; i < 10; i++) { + list2.add(integers[i]); + } + list1.remove(location); + list1.addAll(location, list2); + + // Inserted elements should be equal to integers array + for (int i = 0; i < integers.length; i++) { + assertEquals(integers[i], list1.get(location + i)); + } + // Elements after inserted location should + // be equals to related elements in strings array + for (int i = location + 1; i < strings.length; i++) { + assertEquals(strings[i], list1.get(i + integers.length - 1)); + } + } + + /** + * @tests java.util.ArrayList#addAll(int, java.util.Collection) + */ + public void test_addAllILjava_util_Collection_3() { + ArrayList obj = new ArrayList(); + obj.addAll(0, obj); + obj.addAll(obj.size(), obj); + try { + obj.addAll(-1, obj); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + obj.addAll(obj.size() + 1, obj); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + obj.addAll(0, null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // Excepted + } + + try { + obj.addAll(obj.size() + 1, null); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + obj.addAll((int) -1, (Collection) null); + fail("IndexOutOfBoundsException expected"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Regression test.", - method = "add", - args = {java.lang.Object.class} - ) public void test_addAllCollectionOfQextendsE() { // Regression for HARMONY-539 // https://issues.apache.org/jira/browse/HARMONY-539 @@ -35,23 +354,652 @@ public class ArrayListTest extends TestCase { assertEquals("d", blist.get(2)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test.", - method = "addAll", - args = {java.util.Collection.class} - ) - public void test_growForInsert() { - ArrayList<Integer> arrayList = new ArrayList<Integer>(); - arrayList.addAll(0, Arrays.asList(1, 2)); - arrayList.addAll(2, Arrays.asList(13)); - arrayList.addAll(0, Arrays.asList(0)); - arrayList.addAll(3, Arrays.asList(11, 12)); - arrayList.addAll(6, Arrays.asList(22, 23, 24, 25, 26, 27, 28, 29)); - arrayList.addAll(6, Arrays.asList(14, 15, 16, 17, 18, 19, 20, 21)); - arrayList.addAll(3, Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10)); - assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29), - arrayList); - } -}
\ No newline at end of file + /** + * @tests java.util.ArrayList#addAll(java.util.Collection) + */ + public void test_addAllLjava_util_Collection() { + // Test for method boolean + // java.util.ArrayList.addAll(java.util.Collection) + List l = new ArrayList(); + l.addAll(alist); + for (int i = 0; i < alist.size(); i++) + assertTrue("Failed to add elements properly", l.get(i).equals( + alist.get(i))); + alist.addAll(alist); + assertEquals("Returned incorrect size after adding to existing list", + 200, alist.size()); + for (int i = 0; i < 100; i++) { + assertTrue("Added to list in incorrect order", alist.get(i).equals( + l.get(i))); + assertTrue("Failed to add to existing list", alist.get(i + 100) + .equals(l.get(i))); + } + Set setWithNulls = new HashSet(); + setWithNulls.add(null); + setWithNulls.add(null); + setWithNulls.add("yoink"); + setWithNulls.add("kazoo"); + setWithNulls.add(null); + alist.addAll(100, setWithNulls); + Iterator i = setWithNulls.iterator(); + assertTrue("Item at slot 100 is wrong: " + alist.get(100), alist + .get(100) == i.next()); + assertTrue("Item at slot 101 is wrong: " + alist.get(101), alist + .get(101) == i.next()); + assertTrue("Item at slot 103 is wrong: " + alist.get(102), alist + .get(102) == i.next()); + + try { + alist.addAll(null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // Excepted + } + + // Regression test for Harmony-3481 + ArrayList<Integer> originalList = new ArrayList<Integer>(12); + for (int j = 0; j < 12; j++) { + originalList.add(j); + } + + originalList.remove(0); + originalList.remove(0); + + ArrayList<Integer> additionalList = new ArrayList<Integer>(11); + for (int j = 0; j < 11; j++) { + additionalList.add(j); + } + assertTrue(originalList.addAll(additionalList)); + assertEquals(21, originalList.size()); + + } + + public void test_ArrayList_addAll_scenario1() { + ArrayList arrayListA = new ArrayList(); + arrayListA.add(1); + ArrayList arrayListB = new ArrayList(); + arrayListB.add(1); + arrayListA.addAll(1, arrayListB); + int size = arrayListA.size(); + assertEquals(2, size); + for (int index = 0; index < size; index++) { + assertEquals(1, arrayListA.get(index)); + } + } + + public void test_ArrayList_addAll_scenario2() { + ArrayList arrayList = new ArrayList(); + arrayList.add(1); + arrayList.addAll(1, arrayList); + int size = arrayList.size(); + assertEquals(2, size); + for (int index = 0; index < size; index++) { + assertEquals(1, arrayList.get(index)); + } + } + + // Regression test for HARMONY-5839 + public void testaddAllHarmony5839() { + Collection coll = Arrays.asList(new String[] { "1", "2" }); + List list = new ArrayList(); + list.add("a"); + list.add(0, "b"); + list.add(0, "c"); + list.add(0, "d"); + list.add(0, "e"); + list.add(0, "f"); + list.add(0, "g"); + list.add(0, "h"); + list.add(0, "i"); + + list.addAll(6, coll); + + assertEquals(11, list.size()); + assertFalse(list.contains(null)); + } + + /** + * @tests java.util.ArrayList#clear() + */ + public void test_clear() { + // Test for method void java.util.ArrayList.clear() + alist.clear(); + assertEquals("List did not clear", 0, alist.size()); + alist.add(null); + alist.add(null); + alist.add(null); + alist.add("bam"); + alist.clear(); + assertEquals("List with nulls did not clear", 0, alist.size()); + /* + * for (int i = 0; i < alist.size(); i++) assertNull("Failed to clear + * list", alist.get(i)); + */ + + } + + /** + * @tests java.util.ArrayList#clone() + */ + public void test_clone() { + // Test for method java.lang.Object java.util.ArrayList.clone() + ArrayList x = (ArrayList) (((ArrayList) (alist)).clone()); + assertTrue("Cloned list was inequal to original", x.equals(alist)); + for (int i = 0; i < alist.size(); i++) + assertTrue("Cloned list contains incorrect elements", + alist.get(i) == x.get(i)); + + alist.add(null); + alist.add(25, null); + x = (ArrayList) (((ArrayList) (alist)).clone()); + assertTrue("nulls test - Cloned list was inequal to original", x + .equals(alist)); + for (int i = 0; i < alist.size(); i++) + assertTrue("nulls test - Cloned list contains incorrect elements", + alist.get(i) == x.get(i)); + + } + + /** + * @tests java.util.ArrayList#contains(java.lang.Object) + */ + public void test_containsLjava_lang_Object() { + // Test for method boolean + // java.util.ArrayList.contains(java.lang.Object) + assertTrue("Returned false for valid element", alist + .contains(objArray[99])); + assertTrue("Returned false for equal element", alist + .contains(new Integer(8))); + assertTrue("Returned true for invalid element", !alist + .contains(new Object())); + assertTrue("Returned true for null but should have returned false", + !alist.contains(null)); + alist.add(null); + assertTrue("Returned false for null but should have returned true", + alist.contains(null)); + } + + /** + * @tests java.util.ArrayList#ensureCapacity(int) + */ + public void test_ensureCapacityI() { + // Test for method void java.util.ArrayList.ensureCapacity(int) + // TODO : There is no good way to test this as it only really impacts on + // the private implementation. + + Object testObject = new Object(); + int capacity = 20; + ArrayList al = new ArrayList(capacity); + int i; + for (i = 0; i < capacity / 2; i++) { + al.add(i, new Object()); + } + al.add(i, testObject); + int location = al.indexOf(testObject); + al.ensureCapacity(capacity); + assertTrue("EnsureCapacity moved objects around in array1.", + location == al.indexOf(testObject)); + al.remove(0); + al.ensureCapacity(capacity); + assertTrue("EnsureCapacity moved objects around in array2.", + --location == al.indexOf(testObject)); + al.ensureCapacity(capacity + 2); + assertTrue("EnsureCapacity did not change location.", location == al + .indexOf(testObject)); + } + + /** + * @tests java.util.ArrayList#get(int) + */ + public void test_getI() { + // Test for method java.lang.Object java.util.ArrayList.get(int) + assertTrue("Returned incorrect element", alist.get(22) == objArray[22]); + try { + alist.get(8765); + fail("Failed to throw expected exception for index > size"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } + + /** + * @tests java.util.ArrayList#indexOf(java.lang.Object) + */ + public void test_indexOfLjava_lang_Object() { + // Test for method int java.util.ArrayList.indexOf(java.lang.Object) + assertEquals("Returned incorrect index", 87, alist + .indexOf(objArray[87])); + assertEquals("Returned index for invalid Object", -1, alist + .indexOf(new Object())); + alist.add(25, null); + alist.add(50, null); + assertTrue("Wrong indexOf for null. Wanted 25 got: " + + alist.indexOf(null), alist.indexOf(null) == 25); + } + + /** + * @tests java.util.ArrayList#isEmpty() + */ + public void test_isEmpty() { + // Test for method boolean java.util.ArrayList.isEmpty() + assertTrue("isEmpty returned false for new list", new ArrayList() + .isEmpty()); + assertTrue("Returned true for existing list with elements", !alist + .isEmpty()); + } + + /** + * @tests java.util.ArrayList#lastIndexOf(java.lang.Object) + */ + public void test_lastIndexOfLjava_lang_Object() { + // Test for method int java.util.ArrayList.lastIndexOf(java.lang.Object) + alist.add(new Integer(99)); + assertEquals("Returned incorrect index", 100, alist + .lastIndexOf(objArray[99])); + assertEquals("Returned index for invalid Object", -1, alist + .lastIndexOf(new Object())); + alist.add(25, null); + alist.add(50, null); + assertTrue("Wrong lastIndexOf for null. Wanted 50 got: " + + alist.lastIndexOf(null), alist.lastIndexOf(null) == 50); + } + + /** + * @tests {@link java.util.ArrayList#removeRange(int, int)} + */ + public void test_removeRange() { + MockArrayList mylist = new MockArrayList(); + mylist.removeRange(0, 0); + + try { + mylist.removeRange(0, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + int[] data = { 1, 2, 3 }; + for (int i = 0; i < data.length; i++) { + mylist.add(i, data[i]); + } + + mylist.removeRange(0, 1); + assertEquals(data[1], mylist.get(0)); + assertEquals(data[2], mylist.get(1)); + + try { + mylist.removeRange(-1, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + mylist.removeRange(0, -1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + mylist.removeRange(1, 0); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + mylist.removeRange(2, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } + + /** + * @tests java.util.ArrayList#remove(int) + */ + public void test_removeI() { + // Test for method java.lang.Object java.util.ArrayList.remove(int) + alist.remove(10); + assertEquals("Failed to remove element", -1, alist + .indexOf(objArray[10])); + try { + alist.remove(999); + fail("Failed to throw exception when index out of range"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + ArrayList myList = (ArrayList) (((ArrayList) (alist)).clone()); + alist.add(25, null); + alist.add(50, null); + alist.remove(50); + alist.remove(25); + assertTrue("Removing nulls did not work", alist.equals(myList)); + + List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c", + "d", "e", "f", "g" })); + assertTrue("Removed wrong element 1", list.remove(0) == "a"); + assertTrue("Removed wrong element 2", list.remove(4) == "f"); + String[] result = new String[5]; + list.toArray(result); + assertTrue("Removed wrong element 3", Arrays.equals(result, + new String[] { "b", "c", "d", "e", "g" })); + + List l = new ArrayList(0); + l.add(new Object()); + l.add(new Object()); + l.remove(0); + l.remove(0); + try { + l.remove(-1); + fail("-1 should cause exception"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + try { + l.remove(0); + fail("0 should case exception"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } + + /** + * @tests java.util.ArrayList#set(int, java.lang.Object) + */ + public void test_setILjava_lang_Object() { + // Test for method java.lang.Object java.util.ArrayList.set(int, + // java.lang.Object) + Object obj; + alist.set(65, obj = new Object()); + assertTrue("Failed to set object", alist.get(65) == obj); + alist.set(50, null); + assertNull("Setting to null did not work", alist.get(50)); + assertTrue("Setting increased the list's size to: " + alist.size(), + alist.size() == 100); + + obj = new Object(); + alist.set(0, obj); + assertTrue("Failed to set object", alist.get(0) == obj); + + try { + alist.set(-1, obj); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.set(alist.size(), obj); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.set(-1, null); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + + try { + alist.set(alist.size(), null); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + assertNotNull(e.getMessage()); + } + } + + /** + * @tests java.util.ArrayList#size() + */ + public void test_size() { + // Test for method int java.util.ArrayList.size() + assertEquals("Returned incorrect size for exiting list", 100, alist + .size()); + assertEquals("Returned incorrect size for new list", 0, new ArrayList() + .size()); + } + + /** + * @tests java.util.AbstractCollection#toString() + */ + public void test_toString() { + ArrayList l = new ArrayList(1); + l.add(l); + String result = l.toString(); + assertTrue("should contain self ref", result.indexOf("(this") > -1); + } + + /** + * @tests java.util.ArrayList#toArray() + */ + public void test_toArray() { + // Test for method java.lang.Object [] java.util.ArrayList.toArray() + alist.set(25, null); + alist.set(75, null); + Object[] obj = alist.toArray(); + assertEquals("Returned array of incorrect size", objArray.length, + obj.length); + + for (int i = 0; i < obj.length; i++) { + if ((i == 25) || (i == 75)) + assertNull("Should be null at: " + i + " but instead got: " + + obj[i], obj[i]); + else + assertTrue("Returned incorrect array: " + i, + obj[i] == objArray[i]); + } + + } + + /** + * @tests java.util.ArrayList#toArray(java.lang.Object[]) + */ + public void test_toArray$Ljava_lang_Object() { + // Test for method java.lang.Object [] + // java.util.ArrayList.toArray(java.lang.Object []) + alist.set(25, null); + alist.set(75, null); + Integer[] argArray = new Integer[100]; + Object[] retArray; + retArray = alist.toArray(argArray); + assertTrue("Returned different array than passed", retArray == argArray); + argArray = new Integer[1000]; + retArray = alist.toArray(argArray); + assertNull("Failed to set first extra element to null", argArray[alist + .size()]); + for (int i = 0; i < 100; i++) { + if ((i == 25) || (i == 75)) + assertNull("Should be null: " + i, retArray[i]); + else + assertTrue("Returned incorrect array: " + i, + retArray[i] == objArray[i]); + } + } + + /** + * @tests java.util.ArrayList#trimToSize() + */ + public void test_trimToSize() { + // Test for method void java.util.ArrayList.trimToSize() + for (int i = 99; i > 24; i--) + alist.remove(i); + ((ArrayList) alist).trimToSize(); + assertEquals("Returned incorrect size after trim", 25, alist.size()); + for (int i = 0; i < alist.size(); i++) + assertTrue("Trimmed list contained incorrect elements", alist + .get(i) == objArray[i]); + Vector v = new Vector(); + v.add("a"); + ArrayList al = new ArrayList(v); + Iterator it = al.iterator(); + al.trimToSize(); + try { + it.next(); + fail("should throw a ConcurrentModificationException"); + } catch (ConcurrentModificationException ioobe) { + // expected + } + } + + /** + * @test java.util.ArrayList#addAll(int, Collection) + */ + public void test_addAll() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + assertEquals(2, list.size()); + + list.remove(0); + assertEquals(1, list.size()); + + ArrayList collection = new ArrayList(); + collection.add("1"); + collection.add("2"); + collection.add("3"); + assertEquals(3, collection.size()); + + list.addAll(0, collection); + assertEquals(4, list.size()); + + list.remove(0); + list.remove(0); + assertEquals(2, list.size()); + + collection.add("4"); + collection.add("5"); + collection.add("6"); + collection.add("7"); + collection.add("8"); + collection.add("9"); + collection.add("10"); + collection.add("11"); + collection.add("12"); + + assertEquals(12, collection.size()); + + list.addAll(0, collection); + assertEquals(14, list.size()); + } + + public void testAddAllWithConcurrentCollection() { + ArrayList<String> list = new ArrayList<String>(); + list.addAll(shrinksOnSize("A", "B", "C", "D")); + assertFalse(list.contains(null)); + } + + public void testAddAllAtPositionWithConcurrentCollection() { + ArrayList<String> list = new ArrayList<String>( + Arrays.asList("A", "B", "C", "D")); + + list.addAll(3, shrinksOnSize("E", "F", "G", "H")); + assertFalse(list.contains(null)); + } + + public void test_override_size() throws Exception { + ArrayList testlist = new MockArrayList(); + // though size is overriden, it should passed without exception + testlist.add("test_0"); + testlist.add("test_1"); + testlist.add("test_2"); + testlist.add(1, "test_3"); + testlist.get(1); + testlist.remove(2); + testlist.set(1, "test_4"); + } + + public static class ArrayListExtend extends ArrayList { + + private int size = 0; + + public ArrayListExtend() { + super(10); + } + + public boolean add(Object o) { + size++; + return super.add(o); + } + + public int size() { + return size; + } + } + + public class MockArrayList extends ArrayList { + public int size() { + return 0; + } + + public void removeRange(int start, int end) { + super.removeRange(start, end); + } + } + + public void test_subclassing() { + ArrayListExtend a = new ArrayListExtend(); + /* + * Regression test for subclasses that override size() (which used to + * cause an exception when growing 'a'). + */ + for (int i = 0; i < 100; i++) { + a.add(new Object()); + } + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() throws Exception { + super.setUp(); + alist = new ArrayList(); + for (int i = 0; i < objArray.length; i++) + alist.add(objArray[i]); + } + + /** + * Returns a collection that emulates another thread calling remove() each + * time the current thread calls size(). + */ + private <T> Collection<T> shrinksOnSize(T... elements) { + return new HashSet<T>(Arrays.asList(elements)) { + boolean shrink = true; + + @Override + public int size() { + int result = super.size(); + if (shrink) { + Iterator<T> i = iterator(); + i.next(); + i.remove(); + } + return result; + } + + @Override + public Object[] toArray() { + shrink = false; + return super.toArray(); + } + }; + } +} diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java index b26dd43..54f51f0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java @@ -1,621 +1,1853 @@ /* - * 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. + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ - package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - -import java.io.Serializable; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Comparator; +import java.util.LinkedList; import java.util.List; -import java.util.RandomAccess; -import org.apache.harmony.testframework.serialization.SerializationTest; +import tests.support.Support_UnmodifiableCollectionTest; -@TestTargetClass(Arrays.class) -public class ArraysTest extends TestCase { +public class ArraysTest extends junit.framework.TestCase { - /** - * @tests java.util.Arrays#binarySearch(double[], double) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "binarySearch", - args = {double[].class, double.class} - ) - public void test_binarySearch$DD() { - double[] specials = new double[] { Double.NEGATIVE_INFINITY, - -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d, - Double.MIN_VALUE, 2d, Double.MAX_VALUE, - Double.POSITIVE_INFINITY, Double.NaN }; - - for (int i = 0; i < specials.length; i++) { - int result = Arrays.binarySearch(specials, specials[i]); - assertTrue("Assert 0: " + specials[i] + " invalid: " + result, - result == i); + public static class ReversedIntegerComparator implements Comparator { + public int compare(Object o1, Object o2) { + return -(((Integer) o1).compareTo((Integer) o2)); + } + + public boolean equals(Object o1, Object o2) { + return ((Integer) o1).compareTo((Integer) o2) == 0; + } + } + + static class MockComparable implements Comparable{ + public int compareTo(Object o) { + return 0; } - assertEquals("Assert 1: Invalid search index for -1d", - -4, Arrays.binarySearch(specials, -1d)); - assertEquals("Assert 2: Invalid search index for 1d", - -8, Arrays.binarySearch(specials, 1d)); } + final static int arraySize = 100; + + static Object[] objArray; + + static boolean[] booleanArray; + + static byte[] byteArray; + + static char[] charArray; + + static double[] doubleArray; + + static float[] floatArray; + + static int[] intArray; + + static long[] longArray; + + static Object[] objectArray; + + static short[] shortArray; + { + objArray = new Object[arraySize]; + for (int i = 0; i < objArray.length; i++) + objArray[i] = new Integer(i); + } + + /** + * @tests java.util.Arrays#asList(java.lang.Object[]) + */ + public void test_asList$Ljava_lang_Object() { + // Test for method java.util.List + // java.util.Arrays.asList(java.lang.Object []) + List convertedList = Arrays.asList(objectArray); + for (int counter = 0; counter < arraySize; counter++) { + assertTrue( + "Array and List converted from array do not contain identical elements", + convertedList.get(counter) == objectArray[counter]); + } + convertedList.set(50, new Integer(1000)); + assertTrue("set/get did not work on coverted list", convertedList.get( + 50).equals(new Integer(1000))); + convertedList.set(50, new Integer(50)); + new Support_UnmodifiableCollectionTest("", convertedList).runTest(); + + Object[] myArray = (Object[]) (objectArray.clone()); + myArray[30] = null; + myArray[60] = null; + convertedList = Arrays.asList(myArray); + for (int counter = 0; counter < arraySize; counter++) { + assertTrue( + "Array and List converted from array do not contain identical elements", + convertedList.get(counter) == myArray[counter]); + } + + try { + Arrays.asList((Object[])null); + fail("asList with null arg didn't throw NPE"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @tests java.util.Arrays#binarySearch(byte[], byte) + */ + public void test_binarySearch$BB() { + // Test for method int java.util.Arrays.binarySearch(byte [], byte) + for (byte counter = 0; counter < arraySize; counter++) + assertTrue("Binary search on byte[] answered incorrect position", + Arrays.binarySearch(byteArray, counter) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(intArray, (byte) -1)); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(intArray, (byte) arraySize) == -(arraySize + 1)); + for (byte counter = 0; counter < arraySize; counter++) + byteArray[counter] -= 50; + for (byte counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on byte[] involving negative numbers answered incorrect position", + Arrays.binarySearch(byteArray, (byte) (counter - 50)) == counter); + } + + /** + * @tests java.util.Arrays#binarySearch(char[], char) + */ + public void test_binarySearch$CC() { + // Test for method int java.util.Arrays.binarySearch(char [], char) + for (char counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on char[] answered incorrect position", + Arrays.binarySearch(charArray, (char) (counter + 1)) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(charArray, '\u0000')); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(charArray, (char) (arraySize + 1)) == -(arraySize + 1)); + } + + /** + * @tests java.util.Arrays#binarySearch(double[], double) + */ + public void test_binarySearch$DD() { + // Test for method int java.util.Arrays.binarySearch(double [], double) + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on double[] answered incorrect position", + Arrays.binarySearch(doubleArray, (double) counter) == (double) counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(doubleArray, (double) -1)); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(doubleArray, (double) arraySize) == -(arraySize + 1)); + for (int counter = 0; counter < arraySize; counter++) + doubleArray[counter] -= (double) 50; + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on double[] involving negative numbers answered incorrect position", + Arrays.binarySearch(doubleArray, (double) (counter - 50)) == (double) counter); + + double[] specials = new double[] { Double.NEGATIVE_INFINITY, + -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d, + Double.MIN_VALUE, 2d, Double.MAX_VALUE, + Double.POSITIVE_INFINITY, Double.NaN }; + for (int i = 0; i < specials.length; i++) { + int result = Arrays.binarySearch(specials, specials[i]); + assertTrue(specials[i] + " invalid: " + result, result == i); + } + assertEquals("-1d", -4, Arrays.binarySearch(specials, -1d)); + assertEquals("1d", -8, Arrays.binarySearch(specials, 1d)); + + } + + /** + * @tests java.util.Arrays#binarySearch(float[], float) + */ + public void test_binarySearch$FF() { + // Test for method int java.util.Arrays.binarySearch(float [], float) + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on float[] answered incorrect position", + Arrays.binarySearch(floatArray, (float) counter) == (float) counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(floatArray, (float) -1)); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(floatArray, (float) arraySize) == -(arraySize + 1)); + for (int counter = 0; counter < arraySize; counter++) + floatArray[counter] -= (float) 50; + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on float[] involving negative numbers answered incorrect position", + Arrays.binarySearch(floatArray, (float) counter - 50) == (float) counter); + + float[] specials = new float[] { Float.NEGATIVE_INFINITY, + -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f, + Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY, + Float.NaN }; + for (int i = 0; i < specials.length; i++) { + int result = Arrays.binarySearch(specials, specials[i]); + assertTrue(specials[i] + " invalid: " + result, result == i); + } + assertEquals("-1f", -4, Arrays.binarySearch(specials, -1f)); + assertEquals("1f", -8, Arrays.binarySearch(specials, 1f)); + } + + /** + * @tests java.util.Arrays#binarySearch(int[], int) + */ + public void test_binarySearch$II() { + // Test for method int java.util.Arrays.binarySearch(int [], int) + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Binary search on int[] answered incorrect position", + Arrays.binarySearch(intArray, counter) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(intArray, -1)); + assertTrue("Binary search succeeded for value not present in array 2", + Arrays.binarySearch(intArray, arraySize) == -(arraySize + 1)); + for (int counter = 0; counter < arraySize; counter++) + intArray[counter] -= 50; + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on int[] involving negative numbers answered incorrect position", + Arrays.binarySearch(intArray, counter - 50) == counter); + } + + /** + * @tests java.util.Arrays#binarySearch(long[], long) + */ + public void test_binarySearch$JJ() { + // Test for method int java.util.Arrays.binarySearch(long [], long) + for (long counter = 0; counter < arraySize; counter++) + assertTrue("Binary search on long[] answered incorrect position", + Arrays.binarySearch(longArray, counter) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(longArray, (long) -1)); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(longArray, (long) arraySize) == -(arraySize + 1)); + for (long counter = 0; counter < arraySize; counter++) + longArray[(int) counter] -= (long) 50; + for (long counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on long[] involving negative numbers answered incorrect position", + Arrays.binarySearch(longArray, counter - (long) 50) == counter); + } + + /** + * @tests java.util.Arrays#binarySearch(java.lang.Object[], + * java.lang.Object) + */ + public void test_binarySearch$Ljava_lang_ObjectLjava_lang_Object() { + // Test for method int java.util.Arrays.binarySearch(java.lang.Object + // [], java.lang.Object) + assertEquals( + "Binary search succeeded for non-comparable value in empty array", + -1, Arrays.binarySearch(new Object[] {}, new Object())); + assertEquals( + "Binary search succeeded for comparable value in empty array", + -1, Arrays.binarySearch(new Object[] {}, new Integer(-1))); + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on Object[] answered incorrect position", + Arrays.binarySearch(objectArray, objArray[counter]) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(objectArray, new Integer(-1))); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(objectArray, new Integer(arraySize)) == -(arraySize + 1)); + + Object object = new Object(); + Object[] objects = new MockComparable[] { new MockComparable() }; + assertEquals("Should always return 0", 0, Arrays.binarySearch(objects, object)); + + Object[] string_objects = new String[] { "one" }; + try { + Arrays.binarySearch(string_objects, object); + fail("No expected ClassCastException"); + } catch (ClassCastException e) { + // Expected + } + } + + /** + * @tests java.util.Arrays#binarySearch(java.lang.Object[], + * java.lang.Object, java.util.Comparator) + */ + public void test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator() { + // Test for method int java.util.Arrays.binarySearch(java.lang.Object + // [], java.lang.Object, java.util.Comparator) + Comparator comp = new ReversedIntegerComparator(); + for (int counter = 0; counter < arraySize; counter++) + objectArray[counter] = objArray[arraySize - counter - 1]; + assertTrue( + "Binary search succeeded for value not present in array 1", + Arrays.binarySearch(objectArray, new Integer(-1), comp) == -(arraySize + 1)); + assertEquals("Binary search succeeded for value not present in array 2", + -1, Arrays.binarySearch(objectArray, new Integer(arraySize), comp)); + for (int counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on Object[] with custom comparator answered incorrect position", + Arrays.binarySearch(objectArray, objArray[counter], comp) == arraySize + - counter - 1); + } + + /** + * @tests java.util.Arrays#binarySearch(short[], short) + */ + public void test_binarySearch$SS() { + // Test for method int java.util.Arrays.binarySearch(short [], short) + for (short counter = 0; counter < arraySize; counter++) + assertTrue("Binary search on short[] answered incorrect position", + Arrays.binarySearch(shortArray, counter) == counter); + assertEquals("Binary search succeeded for value not present in array 1", + -1, Arrays.binarySearch(intArray, (short) -1)); + assertTrue( + "Binary search succeeded for value not present in array 2", + Arrays.binarySearch(intArray, (short) arraySize) == -(arraySize + 1)); + for (short counter = 0; counter < arraySize; counter++) + shortArray[counter] -= 50; + for (short counter = 0; counter < arraySize; counter++) + assertTrue( + "Binary search on short[] involving negative numbers answered incorrect position", + Arrays.binarySearch(shortArray, (short) (counter - 50)) == counter); + } + + /** + * @tests java.util.Arrays#fill(byte[], byte) + */ + public void test_fill$BB() { + // Test for method void java.util.Arrays.fill(byte [], byte) + + byte d[] = new byte[1000]; + Arrays.fill(d, Byte.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill byte array correctly", + d[i] == Byte.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(byte[], int, int, byte) + */ + public void test_fill$BIIB() { + // Test for method void java.util.Arrays.fill(byte [], int, int, byte) + byte val = Byte.MAX_VALUE; + byte d[] = new byte[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill byte array correctly", d[i] == val); + + int result; + try { + Arrays.fill(new byte[2], 2, 1, (byte) 27); + result = 0; + } catch (ArrayIndexOutOfBoundsException e) { + result = 1; + } catch (IllegalArgumentException e) { + result = 2; + } + assertEquals("Wrong exception1", 2, result); + try { + Arrays.fill(new byte[2], -1, 1, (byte) 27); + result = 0; + } catch (ArrayIndexOutOfBoundsException e) { + result = 1; + } catch (IllegalArgumentException e) { + result = 2; + } + assertEquals("Wrong exception2", 1, result); + try { + Arrays.fill(new byte[2], 1, 4, (byte) 27); + result = 0; + } catch (ArrayIndexOutOfBoundsException e) { + result = 1; + } catch (IllegalArgumentException e) { + result = 2; + } + assertEquals("Wrong exception", 1, result); + } + + /** + * @tests java.util.Arrays#fill(short[], short) + */ + public void test_fill$SS() { + // Test for method void java.util.Arrays.fill(short [], short) + + short d[] = new short[1000]; + Arrays.fill(d, Short.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill short array correctly", + d[i] == Short.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(short[], int, int, short) + */ + public void test_fill$SIIS() { + // Test for method void java.util.Arrays.fill(short [], int, int, short) + short val = Short.MAX_VALUE; + short d[] = new short[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill short array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(char[], char) + */ + public void test_fill$CC() { + // Test for method void java.util.Arrays.fill(char [], char) + + char d[] = new char[1000]; + Arrays.fill(d, 'V'); + for (int i = 0; i < d.length; i++) + assertEquals("Failed to fill char array correctly", 'V', d[i]); + } + + /** + * @tests java.util.Arrays#fill(char[], int, int, char) + */ + public void test_fill$CIIC() { + // Test for method void java.util.Arrays.fill(char [], int, int, char) + char val = 'T'; + char d[] = new char[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill char array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(int[], int) + */ + public void test_fill$II() { + // Test for method void java.util.Arrays.fill(int [], int) + + int d[] = new int[1000]; + Arrays.fill(d, Integer.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill int array correctly", + d[i] == Integer.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(int[], int, int, int) + */ + public void test_fill$IIII() { + // Test for method void java.util.Arrays.fill(int [], int, int, int) + int val = Integer.MAX_VALUE; + int d[] = new int[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill int array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(long[], long) + */ + public void test_fill$JJ() { + // Test for method void java.util.Arrays.fill(long [], long) + + long d[] = new long[1000]; + Arrays.fill(d, Long.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill long array correctly", + d[i] == Long.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(long[], int, int, long) + */ + public void test_fill$JIIJ() { + // Test for method void java.util.Arrays.fill(long [], int, int, long) + long d[] = new long[1000]; + Arrays.fill(d, 400, d.length, Long.MAX_VALUE); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == Long.MAX_VALUE)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill long array correctly", + d[i] == Long.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(float[], float) + */ + public void test_fill$FF() { + // Test for method void java.util.Arrays.fill(float [], float) + float d[] = new float[1000]; + Arrays.fill(d, Float.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill float array correctly", + d[i] == Float.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(float[], int, int, float) + */ + public void test_fill$FIIF() { + // Test for method void java.util.Arrays.fill(float [], int, int, float) + float val = Float.MAX_VALUE; + float d[] = new float[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill float array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(double[], double) + */ + public void test_fill$DD() { + // Test for method void java.util.Arrays.fill(double [], double) + + double d[] = new double[1000]; + Arrays.fill(d, Double.MAX_VALUE); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill double array correctly", + d[i] == Double.MAX_VALUE); + } + + /** + * @tests java.util.Arrays#fill(double[], int, int, double) + */ + public void test_fill$DIID() { + // Test for method void java.util.Arrays.fill(double [], int, int, + // double) + double val = Double.MAX_VALUE; + double d[] = new double[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill double array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(boolean[], boolean) + */ + public void test_fill$ZZ() { + // Test for method void java.util.Arrays.fill(boolean [], boolean) + + boolean d[] = new boolean[1000]; + Arrays.fill(d, true); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill boolean array correctly", d[i]); + } + + /** + * @tests java.util.Arrays#fill(boolean[], int, int, boolean) + */ + public void test_fill$ZIIZ() { + // Test for method void java.util.Arrays.fill(boolean [], int, int, + // boolean) + boolean val = true; + boolean d[] = new boolean[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill boolean array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(java.lang.Object[], java.lang.Object) + */ + public void test_fill$Ljava_lang_ObjectLjava_lang_Object() { + // Test for method void java.util.Arrays.fill(java.lang.Object [], + // java.lang.Object) + Object val = new Object(); + Object d[] = new Object[1000]; + Arrays.fill(d, 0, d.length, val); + for (int i = 0; i < d.length; i++) + assertTrue("Failed to fill Object array correctly", d[i] == val); + } + + /** + * @tests java.util.Arrays#fill(java.lang.Object[], int, int, + * java.lang.Object) + */ + public void test_fill$Ljava_lang_ObjectIILjava_lang_Object() { + // Test for method void java.util.Arrays.fill(java.lang.Object [], int, + // int, java.lang.Object) + Object val = new Object(); + Object d[] = new Object[1000]; + Arrays.fill(d, 400, d.length, val); + for (int i = 0; i < 400; i++) + assertTrue("Filled elements not in range", !(d[i] == val)); + for (int i = 400; i < d.length; i++) + assertTrue("Failed to fill Object array correctly", d[i] == val); + + Arrays.fill(d, 400, d.length, null); + for (int i = 400; i < d.length; i++) + assertNull("Failed to fill Object array correctly with nulls", + d[i]); + } + + /** + * @tests java.util.Arrays#equals(byte[], byte[]) + */ + public void test_equals$B$B() { + // Test for method boolean java.util.Arrays.equals(byte [], byte []) + byte d[] = new byte[1000]; + byte x[] = new byte[1000]; + Arrays.fill(d, Byte.MAX_VALUE); + Arrays.fill(x, Byte.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Byte.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + } + + /** + * @tests java.util.Arrays#equals(short[], short[]) + */ + public void test_equals$S$S() { + // Test for method boolean java.util.Arrays.equals(short [], short []) + short d[] = new short[1000]; + short x[] = new short[1000]; + Arrays.fill(d, Short.MAX_VALUE); + Arrays.fill(x, Short.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Short.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + } + + /** + * @tests java.util.Arrays#equals(char[], char[]) + */ + public void test_equals$C$C() { + // Test for method boolean java.util.Arrays.equals(char [], char []) + char d[] = new char[1000]; + char x[] = new char[1000]; + char c = 'T'; + Arrays.fill(d, c); + Arrays.fill(x, 'L'); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, c); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + } + + /** + * @tests java.util.Arrays#equals(int[], int[]) + */ + public void test_equals$I$I() { + // Test for method boolean java.util.Arrays.equals(int [], int []) + int d[] = new int[1000]; + int x[] = new int[1000]; + Arrays.fill(d, Integer.MAX_VALUE); + Arrays.fill(x, Integer.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Integer.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + + assertTrue("wrong result for null array1", !Arrays.equals(new int[2], + null)); + assertTrue("wrong result for null array2", !Arrays.equals(null, + new int[2])); + } + + /** + * @tests java.util.Arrays#equals(long[], long[]) + */ + public void test_equals$J$J() { + // Test for method boolean java.util.Arrays.equals(long [], long []) + long d[] = new long[1000]; + long x[] = new long[1000]; + Arrays.fill(d, Long.MAX_VALUE); + Arrays.fill(x, Long.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Long.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + + assertTrue("should be false", !Arrays.equals( + new long[] { 0x100000000L }, new long[] { 0x200000000L })); + + } + + /** + * @tests java.util.Arrays#equals(float[], float[]) + */ + public void test_equals$F$F() { + // Test for method boolean java.util.Arrays.equals(float [], float []) + float d[] = new float[1000]; + float x[] = new float[1000]; + Arrays.fill(d, Float.MAX_VALUE); + Arrays.fill(x, Float.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Float.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + + assertTrue("NaN not equals", Arrays.equals(new float[] { Float.NaN }, + new float[] { Float.NaN })); + assertTrue("0f equals -0f", !Arrays.equals(new float[] { 0f }, + new float[] { -0f })); + } + + /** + * @tests java.util.Arrays#equals(double[], double[]) + */ + public void test_equals$D$D() { + // Test for method boolean java.util.Arrays.equals(double [], double []) + double d[] = new double[1000]; + double x[] = new double[1000]; + Arrays.fill(d, Double.MAX_VALUE); + Arrays.fill(x, Double.MIN_VALUE); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, Double.MAX_VALUE); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + + assertTrue("should be false", !Arrays.equals(new double[] { 1.0 }, + new double[] { 2.0 })); + + assertTrue("NaN not equals", Arrays.equals(new double[] { Double.NaN }, + new double[] { Double.NaN })); + assertTrue("0d equals -0d", !Arrays.equals(new double[] { 0d }, + new double[] { -0d })); + } + + /** + * @tests java.util.Arrays#equals(boolean[], boolean[]) + */ + public void test_equals$Z$Z() { + // Test for method boolean java.util.Arrays.equals(boolean [], boolean + // []) + boolean d[] = new boolean[1000]; + boolean x[] = new boolean[1000]; + Arrays.fill(d, true); + Arrays.fill(x, false); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, true); + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + } + + /** + * @tests java.util.Arrays#equals(java.lang.Object[], java.lang.Object[]) + */ + public void test_equals$Ljava_lang_Object$Ljava_lang_Object() { + // Test for method boolean java.util.Arrays.equals(java.lang.Object [], + // java.lang.Object []) + Object d[] = new Object[1000]; + Object x[] = new Object[1000]; + Object o = new Object(); + Arrays.fill(d, o); + Arrays.fill(x, new Object()); + assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); + Arrays.fill(x, o); + d[50] = null; + x[50] = null; + assertTrue("equal arrays returned false", Arrays.equals(d, x)); + } + + /** + * @tests java.util.Arrays#sort(byte[]) + */ + public void test_sort$B() { + // Test for method void java.util.Arrays.sort(byte []) + byte[] reversedArray = new byte[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (byte) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (byte) counter); + } + + /** + * @tests java.util.Arrays#sort(byte[], int, int) + */ + public void test_sort$BII() { + // Test for method void java.util.Arrays.sort(byte [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + byte[] reversedArray = new byte[arraySize]; + byte[] originalReversedArray = new byte[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (byte) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new byte[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(char[]) + */ + public void test_sort$C() { + // Test for method void java.util.Arrays.sort(char []) + char[] reversedArray = new char[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (char) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (char) counter); + + } + + /** + * @tests java.util.Arrays#sort(char[], int, int) + */ + public void test_sort$CII() { + // Test for method void java.util.Arrays.sort(char [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + char[] reversedArray = new char[arraySize]; + char[] originalReversedArray = new char[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (char) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new char[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(double[]) + */ + public void test_sort$D() { + // Test for method void java.util.Arrays.sort(double []) + double[] reversedArray = new double[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (double) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (double) counter); + + double[] specials1 = new double[] { Double.NaN, Double.MAX_VALUE, + Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY }; + double[] specials2 = new double[] { 0d, Double.POSITIVE_INFINITY, -0d, + Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN, + Double.MAX_VALUE }; + double[] specials3 = new double[] { 0.0, Double.NaN, 1.0, 2.0, Double.NaN, + Double.NaN, 1.0, 3.0, -0.0}; + double[] answer = new double[] { Double.NEGATIVE_INFINITY, -0d, 0d, + Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY, + Double.NaN }; + double[] answer3 = new double[] { -0.0, 0.0, 1.0, 1.0, 2.0, 3.0, Double.NaN, + Double.NaN, Double.NaN }; + + Arrays.sort(specials1); + Object[] print1 = new Object[specials1.length]; + for (int i = 0; i < specials1.length; i++) + print1[i] = new Double(specials1[i]); + assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1), + Arrays.equals(specials1, answer)); + + Arrays.sort(specials2); + Object[] print2 = new Object[specials2.length]; + for (int i = 0; i < specials2.length; i++) + print2[i] = new Double(specials2[i]); + assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2), + Arrays.equals(specials2, answer)); + + Arrays.sort(specials3); + Object[] print3 = new Object[specials3.length]; + for (int i = 0; i < specials3.length; i++) + print3[i] = new Double(specials3[i]); + assertTrue("specials sort incorrectly 3: " + Arrays.asList(print3), + Arrays.equals(specials3, answer3)); + } + + /** + * @tests java.util.Arrays#sort(double[], int, int) + */ + public void test_sort$DII() { + // Test for method void java.util.Arrays.sort(double [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + double[] reversedArray = new double[arraySize]; + double[] originalReversedArray = new double[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (double) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new double[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(float[]) + */ + public void test_sort$F() { + // Test for method void java.util.Arrays.sort(float []) + float[] reversedArray = new float[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (float) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (float) counter); + + float[] specials1 = new float[] { Float.NaN, Float.MAX_VALUE, + Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY, + Float.NEGATIVE_INFINITY }; + float[] specials2 = new float[] { 0f, Float.POSITIVE_INFINITY, -0f, + Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN, + Float.MAX_VALUE }; + float[] answer = new float[] { Float.NEGATIVE_INFINITY, -0f, 0f, + Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY, + Float.NaN }; + + Arrays.sort(specials1); + Object[] print1 = new Object[specials1.length]; + for (int i = 0; i < specials1.length; i++) + print1[i] = new Float(specials1[i]); + assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1), + Arrays.equals(specials1, answer)); + + Arrays.sort(specials2); + Object[] print2 = new Object[specials2.length]; + for (int i = 0; i < specials2.length; i++) + print2[i] = new Float(specials2[i]); + assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2), + Arrays.equals(specials2, answer)); + } + + /** + * @tests java.util.Arrays#sort(float[], int, int) + */ + public void test_sort$FII() { + // Test for method void java.util.Arrays.sort(float [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + float[] reversedArray = new float[arraySize]; + float[] originalReversedArray = new float[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (float) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new float[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(int[]) + */ + public void test_sort$I() { + // Test for method void java.util.Arrays.sort(int []) + int[] reversedArray = new int[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = arraySize - counter - 1; + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == counter); + } + + /** + * @tests java.util.Arrays#sort(int[], int, int) + */ + public void test_sort$III() { + // Test for method void java.util.Arrays.sort(int [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + int[] reversedArray = new int[arraySize]; + int[] originalReversedArray = new int[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = arraySize - counter - 1; + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new int[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(long[]) + */ + public void test_sort$J() { + // Test for method void java.util.Arrays.sort(long []) + long[] reversedArray = new long[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (long) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (long) counter); + + } + + /** + * @tests java.util.Arrays#sort(long[], int, int) + */ + public void test_sort$JII() { + // Test for method void java.util.Arrays.sort(long [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + long[] reversedArray = new long[arraySize]; + long[] originalReversedArray = new long[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (long) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new long[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(java.lang.Object[]) + */ + public void test_sort$Ljava_lang_Object() { + // Test for method void java.util.Arrays.sort(java.lang.Object []) + Object[] reversedArray = new Object[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = objectArray[arraySize - counter - 1]; + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == objectArray[counter]); + } + + /** + * @tests java.util.Arrays#sort(java.lang.Object[], int, int) + */ + public void test_sort$Ljava_lang_ObjectII() { + // Test for method void java.util.Arrays.sort(java.lang.Object [], int, + // int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + Object[] reversedArray = new Object[arraySize]; + Object[] originalReversedArray = new Object[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = objectArray[arraySize - counter - 1]; + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + ((Comparable) reversedArray[counter]) + .compareTo(reversedArray[counter + 1]) <= 0); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new Object[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + + /** + * @tests java.util.Arrays#sort(java.lang.Object[], int, int, + * java.util.Comparator) + */ + public void test_sort$Ljava_lang_ObjectIILjava_util_Comparator() { + // Test for method void java.util.Arrays.sort(java.lang.Object [], int, + // int, java.util.Comparator) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + ReversedIntegerComparator comp = new ReversedIntegerComparator(); + Object[] originalArray = new Object[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + originalArray[counter] = objectArray[counter]; + Arrays.sort(objectArray, startIndex, endIndex, comp); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + objectArray[counter] == originalArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", comp.compare( + objectArray[counter], objectArray[counter + 1]) <= 0); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + objectArray[counter] == originalArray[counter]); + } + + /** + * @tests java.util.Arrays#sort(java.lang.Object[], java.util.Comparator) + */ + public void test_sort$Ljava_lang_ObjectLjava_util_Comparator() { + // Test for method void java.util.Arrays.sort(java.lang.Object [], + // java.util.Comparator) + ReversedIntegerComparator comp = new ReversedIntegerComparator(); + Arrays.sort(objectArray, comp); + for (int counter = 0; counter < arraySize - 1; counter++) + assertTrue("Array not sorted correctly with custom comparator", + comp + .compare(objectArray[counter], + objectArray[counter + 1]) <= 0); + } + + // Regression HARMONY-6076 + public void test_sort$Ljava_lang_ObjectLjava_util_Comparator_stable() { + Element[] array = new Element[11]; + array[0] = new Element(122); + array[1] = new Element(146); + array[2] = new Element(178); + array[3] = new Element(208); + array[4] = new Element(117); + array[5] = new Element(146); + array[6] = new Element(173); + array[7] = new Element(203); + array[8] = new Element(56); + array[9] = new Element(208); + array[10] = new Element(96); + + Comparator<Element> comparator = new Comparator<Element>() { + public int compare(Element object1, Element object2) { + return object1.value - object2.value; + } + }; + + Arrays.sort(array, comparator); + + for (int i = 1; i < array.length; i++) { + assertTrue(comparator.compare(array[i - 1], array[i]) <= 0); + if (comparator.compare(array[i - 1], array[i]) == 0) { + assertTrue(array[i - 1].index < array[i].index); + } + } + } + + public static class Element { + public int value; + + public int index; + + private static int count = 0; + + public Element(int value) { + this.value = value; + index = count++; + } + } + + /** + * @tests java.util.Arrays#sort(short[]) + */ + public void test_sort$S() { + // Test for method void java.util.Arrays.sort(short []) + short[] reversedArray = new short[arraySize]; + for (int counter = 0; counter < arraySize; counter++) + reversedArray[counter] = (short) (arraySize - counter - 1); + Arrays.sort(reversedArray); + for (int counter = 0; counter < arraySize; counter++) + assertTrue("Resulting array not sorted", + reversedArray[counter] == (short) counter); + } + + /** + * @tests java.util.Arrays#sort(short[], int, int) + */ + public void test_sort$SII() { + // Test for method void java.util.Arrays.sort(short [], int, int) + int startIndex = arraySize / 4; + int endIndex = 3 * arraySize / 4; + short[] reversedArray = new short[arraySize]; + short[] originalReversedArray = new short[arraySize]; + for (int counter = 0; counter < arraySize; counter++) { + reversedArray[counter] = (short) (arraySize - counter - 1); + originalReversedArray[counter] = reversedArray[counter]; + } + Arrays.sort(reversedArray, startIndex, endIndex); + for (int counter = 0; counter < startIndex; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + for (int counter = startIndex; counter < endIndex - 1; counter++) + assertTrue("Array not sorted within bounds", + reversedArray[counter] <= reversedArray[counter + 1]); + for (int counter = endIndex; counter < arraySize; counter++) + assertTrue("Array modified outside of bounds", + reversedArray[counter] == originalReversedArray[counter]); + + //exception testing + try { + Arrays.sort(reversedArray, startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + + try { + Arrays.sort(reversedArray, -1, startIndex); + fail("ArrayIndexOutOfBoundsException expected (1)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + try { + Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); + fail("ArrayIndexOutOfBoundsException expected (2)"); + } catch (ArrayIndexOutOfBoundsException ignore) { + } + + //exception order testing + try { + Arrays.sort(new short[1], startIndex + 1, startIndex); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException ignore) { + } + } + /** - * @tests java.util.Arrays#binarySearch(float[], float) + * @tests java.util.Arrays#sort(byte[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "binarySearch", - args = {float[].class, float.class} - ) - public void test_binarySearch$FF() { - float[] specials = new float[] { Float.NEGATIVE_INFINITY, - -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f, - Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY, - Float.NaN }; - - for (int i = 0; i < specials.length; i++) { - int result = Arrays.binarySearch(specials, specials[i]); - assertTrue("Assert 0: " + specials[i] + " invalid: " + result, - result == i); + public void test_java_util_Arrays_sort_byte_array_NPE() { + byte[] byte_array_null = null; + try { + java.util.Arrays.sort(byte_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(byte_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - assertEquals("Assert 1: Invalid search index for -1f", - -4, Arrays.binarySearch(specials, -1f)); - assertEquals("Assert 2: Invalid search index for 1f", - -8, Arrays.binarySearch(specials, 1f)); } - + /** - * @tests java.util.Arrays#equals(double[], double[]) + * @tests java.util.Arrays#sort(char[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {double[].class, double[].class} - ) - public void test_equals$D$D() { - double d[] = new double[100]; - double x[] = new double[100]; - Arrays.fill(d, Double.MAX_VALUE); - Arrays.fill(x, Double.MIN_VALUE); - - assertTrue("Assert 0: Inequal arrays returned true", !Arrays.equals(d, x)); - - Arrays.fill(x, Double.MAX_VALUE); - assertTrue("Assert 1: equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("Assert 2: should be false", - !Arrays.equals(new double[] { 1.0 }, new double[] { 2.0 })); - - assertTrue("Assert 3: NaN not equals", - Arrays.equals(new double[] { Double.NaN }, new double[] { Double.NaN })); - assertTrue("Assert 4: 0d equals -0d", - !Arrays.equals(new double[] { 0d }, new double[] { -0d })); + public void test_java_util_Arrays_sort_char_array_NPE() { + char[] char_array_null = null; + try { + java.util.Arrays.sort(char_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(char_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } } - + /** - * @tests java.util.Arrays#equals(float[], float[]) + * @tests java.util.Arrays#sort(double[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {float[].class, float[].class} - ) - public void test_equals$F$F() { - float d[] = new float[100]; - float x[] = new float[100]; - Arrays.fill(d, Float.MAX_VALUE); - Arrays.fill(x, Float.MIN_VALUE); - - assertTrue("Assert 0: Inequal arrays returned true", !Arrays.equals(d, x)); - - Arrays.fill(x, Float.MAX_VALUE); - assertTrue("Assert 1: equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("Assert 2: NaN not equals", - Arrays.equals(new float[] { Float.NaN }, new float[] { Float.NaN })); - assertTrue("Assert 3: 0f equals -0f", - !Arrays.equals(new float[] { 0f }, new float[] { -0f })); + public void test_java_util_Arrays_sort_double_array_NPE() { + double[] double_array_null = null; + try { + java.util.Arrays.sort(double_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(double_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } } - + /** - * @tests java.util.Arrays#sort(double[]) + * @tests java.util.Arrays#sort(float[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "sort", - args = {double[].class} - ) - public void test_sort$D() { - // Test a basic sort - double[] reversedArray = new double[100]; - for (int counter = 0; counter < reversedArray.length; counter ++) { - reversedArray[counter] = (reversedArray.length - counter - 1); + public void test_java_util_Arrays_sort_float_array_NPE() { + float[] float_array_null = null; + try { + java.util.Arrays.sort(float_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - Arrays.sort(reversedArray); - for (int counter = 0; counter < reversedArray.length; counter ++) { - assertTrue("Assert 0: Resulting array not sorted", - reversedArray[counter] == counter); + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(float_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } + } - // These have to sort as per the Double compare ordering - double[] specials1 = new double[]{Double.NaN, Double.MAX_VALUE, Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; - double[] specials2 = new double[]{0d, Double.POSITIVE_INFINITY, -0d, Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN, Double.MAX_VALUE}; - double[] answer = new double[]{Double.NEGATIVE_INFINITY, -0d, 0d, Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN}; - - Arrays.sort(specials1); - Object[] print1 = new Object[specials1.length]; - for (int i = 0; i < specials1.length; i++) { - print1[i] = new Double(specials1[i]); + /** + * @tests java.util.Arrays#sort(int[], int, int) + */ + public void test_java_util_Arrays_sort_int_array_NPE() { + int[] int_array_null = null; + try { + java.util.Arrays.sort(int_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - assertTrue("Assert 1: specials sort incorrectly" + Arrays.asList(print1), - Arrays.equals(specials1, answer)); - - Arrays.sort(specials2); - Object[] print2 = new Object[specials2.length]; - for (int i = 0; i < specials2.length; i++) { - print2[i] = new Double(specials2[i]); + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(int_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - assertTrue("Assert 2: specials sort incorrectly " + Arrays.asList(print2), - Arrays.equals(specials2, answer)); } - + /** - * @tests java.util.Arrays#sort(float[]) + * @tests java.util.Arrays#sort(Object[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "sort", - args = {float[].class} - ) - public void test_sort$F() { - // Test a basic sort - float[] reversedArray = new float[100]; - for (int counter = 0; counter < reversedArray.length; counter ++) { - reversedArray[counter] = (reversedArray.length - counter - 1); + public void test_java_util_Arrays_sort_object_array_NPE() { + Object[] object_array_null = null; + try { + java.util.Arrays.sort(object_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - Arrays.sort(reversedArray); - for (int counter = 0; counter < reversedArray.length; counter ++) { - assertTrue("Assert 0: Resulting array not sorted", - reversedArray[counter] == counter); + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(object_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - - float[] specials1 = new float[]{Float.NaN, Float.MAX_VALUE, Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY}; - float[] specials2 = new float[]{0f, Float.POSITIVE_INFINITY, -0f, Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN, Float.MAX_VALUE}; - float[] answer = new float[]{Float.NEGATIVE_INFINITY, -0f, 0f, Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY, Float.NaN}; - - Arrays.sort(specials1); - Object[] print1 = new Object[specials1.length]; - for (int i = 0; i < specials1.length; i++) { - print1[i] = new Float(specials1[i]); + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(object_array_null, (int) -1, (int) 1, null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - assertTrue("Assert 1: specials sort incorrectly" + Arrays.asList(print1), - Arrays.equals(specials1, answer)); + } - Arrays.sort(specials2); - Object[] print2 = new Object[specials2.length]; - for (int i = 0; i < specials2.length; i++) { - print2[i] = new Float(specials2[i]); + /** + * @tests java.util.Arrays#sort(long[], int, int) + */ + public void test_java_util_Arrays_sort_long_array_NPE() { + long[] long_array_null = null; + try { + java.util.Arrays.sort(long_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(long_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected } - assertTrue("Assert 2: specials sort incorrectly" + Arrays.asList(print2), - Arrays.equals(specials2, answer)); } - + /** - * @tests java.util.Arrays#toString(boolean[]) + * @tests java.util.Arrays#sort(short[], int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {boolean[].class} - ) - public void test_toString$Z() { - assertEquals("null", Arrays.toString((boolean[])null)); - assertEquals("[]", Arrays.toString(new boolean[] {})); - assertEquals("[true]", Arrays.toString(new boolean[] {true})); - assertEquals("[true, false]", Arrays.toString(new boolean[] {true,false})); - assertEquals("[true, false, true]", Arrays.toString(new boolean[] {true,false,true})); + public void test_java_util_Arrays_sort_short_array_NPE() { + short[] short_array_null = null; + try { + java.util.Arrays.sort(short_array_null); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + try { + // Regression for HARMONY-378 + java.util.Arrays.sort(short_array_null, (int) -1, (int) 1); + fail("Should throw java.lang.NullPointerException"); + } catch (NullPointerException e) { + // Expected + } } /** - * @tests java.util.Arrays#toString(byte[]) + * @tests java.util.Arrays#deepEquals(Object[], Object[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {byte[].class} - ) - public void test_toString$B() { - assertEquals("null", Arrays.toString((byte[])null)); - assertEquals("[]", Arrays.toString(new byte[] {})); - assertEquals("[0]", Arrays.toString(new byte[] {0})); - assertEquals("[-1, 0]", Arrays.toString(new byte[] {-1,0})); - assertEquals("[-1, 0, 1]", Arrays.toString(new byte[] {-1,0,1})); + public void test_deepEquals$Ljava_lang_ObjectLjava_lang_Object() { + int [] a1 = {1, 2, 3}; + short [] a2 = {0, 1}; + Object [] a3 = {new Integer(1), a2}; + int [] a4 = {6, 5, 4}; + + int [] b1 = {1, 2, 3}; + short [] b2 = {0, 1}; + Object [] b3 = {new Integer(1), b2}; + + Object a [] = {a1, a2, a3}; + Object b [] = {b1, b2, b3}; + + assertFalse(Arrays.equals(a, b)); + assertTrue(Arrays.deepEquals(a,b)); + + a[2] = a4; + + assertFalse(Arrays.deepEquals(a, b)); } /** - * @tests java.util.Arrays#toString(char[]) + * @tests java.util.Arrays#deepHashCode(Object[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {char[].class} - ) - public void test_toString$C() { - assertEquals("null", Arrays.toString((char[])null)); - assertEquals("[]", Arrays.toString(new char[] {})); - assertEquals("[a]", Arrays.toString(new char[] {'a'})); - assertEquals("[a, b]", Arrays.toString(new char[] {'a','b'})); - assertEquals("[a, b, c]", Arrays.toString(new char[] {'a','b','c'})); - } + public void test_deepHashCode$Ljava_lang_Object() { + int [] a1 = {1, 2, 3}; + short [] a2 = {0, 1}; + Object [] a3 = {new Integer(1), a2}; + + int [] b1 = {1, 2, 3}; + short [] b2 = {0, 1}; + Object [] b3 = {new Integer(1), b2}; + + Object a [] = {a1, a2, a3}; + Object b [] = {b1, b2, b3}; + + int deep_hash_a = Arrays.deepHashCode(a); + int deep_hash_b = Arrays.deepHashCode(b); + + assertEquals(deep_hash_a, deep_hash_b); + } /** - * @tests java.util.Arrays#toString(double[]) + * @tests java.util.Arrays#hashCode(boolean[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {double[].class} - ) - public void test_toString$D() { - assertEquals("null", Arrays.toString((double[])null)); - assertEquals("[]", Arrays.toString(new double[] {})); - assertEquals("[0.0]", Arrays.toString(new double[] {0.0D})); - assertEquals("[-1.0, 0.0]", Arrays.toString(new double[] {-1.0D, 0.0D})); - assertEquals("[-1.0, 0.0, 1.0]", Arrays.toString(new double[] {-1.0D, 0.0D, 1.0D})); + public void test_hashCode$LZ() { + int listHashCode; + int arrayHashCode; + + boolean [] boolArr = {true, false, false, true, false}; + List listOfBoolean = new LinkedList(); + for (int i = 0; i < boolArr.length; i++) { + listOfBoolean.add(new Boolean(boolArr[i])); + } + listHashCode = listOfBoolean.hashCode(); + arrayHashCode = Arrays.hashCode(boolArr); + assertEquals(listHashCode, arrayHashCode); } /** - * @tests java.util.Arrays#toString(float[]) + * @tests java.util.Arrays#hashCode(int[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {float[].class} - ) - public void test_toString$F() { - assertEquals("null", Arrays.toString((float[])null)); - assertEquals("[]", Arrays.toString(new float[] {})); - assertEquals("[0.0]", Arrays.toString(new float[] {0.0F})); - assertEquals("[-1.0, 0.0]", Arrays.toString(new float[] {-1.0F, 0.0F})); - assertEquals("[-1.0, 0.0, 1.0]", Arrays.toString(new float[] {-1.0F, 0.0F, 1.0F})); + public void test_hashCode$LI() { + int listHashCode; + int arrayHashCode; + + int [] intArr = {10, 5, 134, 7, 19}; + List listOfInteger = new LinkedList(); + + for (int i = 0; i < intArr.length; i++) { + listOfInteger.add(new Integer(intArr[i])); + } + listHashCode = listOfInteger.hashCode(); + arrayHashCode = Arrays.hashCode(intArr); + assertEquals(listHashCode, arrayHashCode); + + int [] intArr2 = {10, 5, 134, 7, 19}; + assertEquals(Arrays.hashCode(intArr2), Arrays.hashCode(intArr)); } /** - * @tests java.util.Arrays#toString(int[]) + * @tests java.util.Arrays#hashCode(char[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {int[].class} - ) - public void test_toString$I() { - assertEquals("null", Arrays.toString((int[])null)); - assertEquals("[]", Arrays.toString(new int[] {})); - assertEquals("[0]", Arrays.toString(new int[] {0})); - assertEquals("[-1, 0]", Arrays.toString(new int[] {-1, 0})); - assertEquals("[-1, 0, 1]", Arrays.toString(new int[] {-1, 0, 1})); + public void test_hashCode$LC() { + int listHashCode; + int arrayHashCode; + + char [] charArr = {'a', 'g', 'x', 'c', 'm'}; + List listOfCharacter = new LinkedList(); + for (int i = 0; i < charArr.length; i++) { + listOfCharacter.add(new Character(charArr[i])); + } + listHashCode = listOfCharacter.hashCode(); + arrayHashCode = Arrays.hashCode(charArr); + assertEquals(listHashCode, arrayHashCode); } /** - * @tests java.util.Arrays#toString(long[]) + * @tests java.util.Arrays#hashCode(byte[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {long[].class} - ) - public void test_toString$J() { - assertEquals("null", Arrays.toString((long[])null)); - assertEquals("[]", Arrays.toString(new long[] {})); - assertEquals("[0]", Arrays.toString(new long[] {0})); - assertEquals("[-1, 0]", Arrays.toString(new long[] {-1, 0})); - assertEquals("[-1, 0, 1]", Arrays.toString(new long[] {-1, 0, 1})); + public void test_hashCode$LB() { + int listHashCode; + int arrayHashCode; + + byte [] byteArr = {5, 9, 7, 6, 17}; + List listOfByte = new LinkedList(); + for (int i = 0; i < byteArr.length; i++) { + listOfByte.add(new Byte(byteArr[i])); + } + listHashCode = listOfByte.hashCode(); + arrayHashCode = Arrays.hashCode(byteArr); + assertEquals(listHashCode, arrayHashCode); } /** - * @tests java.util.Arrays#toString(short[]) + * @tests java.util.Arrays#hashCode(long[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {short[].class} - ) - public void test_toString$S() { - assertEquals("null", Arrays.toString((short[])null)); - assertEquals("[]", Arrays.toString(new short[] {})); - assertEquals("[0]", Arrays.toString(new short[] {0})); - assertEquals("[-1, 0]", Arrays.toString(new short[] {-1, 0})); - assertEquals("[-1, 0, 1]", Arrays.toString(new short[] {-1, 0, 1})); + public void test_hashCode$LJ() { + int listHashCode; + int arrayHashCode; + + long [] longArr = {67890234512l, 97587236923425l, 257421912912l, + 6754268100l, 5}; + List listOfLong = new LinkedList(); + for (int i = 0; i < longArr.length; i++) { + listOfLong.add(new Long(longArr[i])); + } + listHashCode = listOfLong.hashCode(); + arrayHashCode = Arrays.hashCode(longArr); + assertEquals(listHashCode, arrayHashCode); } /** - * @tests java.util.Arrays#toString(Object[]) + * @tests java.util.Arrays#hashCode(float[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {java.lang.Object[].class} - ) - public void test_toString$Ljava_lang_Object() { - assertEquals("null", Arrays.toString((Object[])null)); - assertEquals("[]", Arrays.toString(new Object[] {})); - assertEquals("[fixture]", Arrays.toString(new Object[] {"fixture"})); - assertEquals("[fixture, null]", Arrays.toString(new Object[] {"fixture", null})); - assertEquals("[fixture, null, fixture]", Arrays.toString(new Object[] {"fixture", null, "fixture"})); + public void test_hashCode$LF() { + int listHashCode; + int arrayHashCode; + + float [] floatArr = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f}; + List listOfFloat = new LinkedList(); + for (int i = 0; i < floatArr.length; i++) { + listOfFloat.add(new Float(floatArr[i])); + } + listHashCode = listOfFloat.hashCode(); + arrayHashCode = Arrays.hashCode(floatArr); + assertEquals(listHashCode, arrayHashCode); + + float [] floatArr2 = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f}; + assertEquals(Arrays.hashCode(floatArr2), Arrays.hashCode(floatArr)); } /** - * @tests java.util.Arrays#deepToString(Object[]) + * @tests java.util.Arrays#hashCode(double[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "deepToString", - args = {java.lang.Object[].class} - ) - public void test_deepToString$java_lang_Object() { - assertEquals("null", Arrays.deepToString((Object[])null)); - assertEquals("[]", Arrays.deepToString(new Object[] {})); - assertEquals("[fixture]", Arrays.deepToString(new Object[] {"fixture"})); - assertEquals("[fixture, null]", Arrays.deepToString(new Object[] {"fixture", null})); - assertEquals("[fixture, null, fixture]", Arrays.deepToString(new Object[] {"fixture", null, "fixture"})); - - Object[] fixture = new Object[1]; - fixture[0] = fixture; - assertEquals("[[...]]", Arrays.deepToString(fixture)); - - fixture = new Object[2]; - fixture[0] = "fixture"; - fixture[1] = fixture; - assertEquals("[fixture, [...]]", Arrays.deepToString(fixture)); - - fixture = new Object[10]; - fixture[0] = new boolean[] {true, false}; - fixture[1] = new byte[] {0, 1}; - fixture[2] = new char[] {'a', 'b'}; - fixture[3] = new double[] {0.0D, 1.0D}; - fixture[4] = new float[] {0.0F, 1.0F}; - fixture[5] = new int[] {0, 1}; - fixture[6] = new long[] {0L, 1L}; - fixture[7] = new short[] {0, 1}; - fixture[8] = fixture[0]; - fixture[9] = new Object[9]; - ((Object[])fixture[9])[0] = fixture; - ((Object[])fixture[9])[1] = fixture[1]; - ((Object[])fixture[9])[2] = fixture[2]; - ((Object[])fixture[9])[3] = fixture[3]; - ((Object[])fixture[9])[4] = fixture[4]; - ((Object[])fixture[9])[5] = fixture[5]; - ((Object[])fixture[9])[6] = fixture[6]; - ((Object[])fixture[9])[7] = fixture[7]; - Object[] innerFixture = new Object[4]; - innerFixture[0] = "innerFixture0"; - innerFixture[1] = innerFixture; - innerFixture[2] = fixture; - innerFixture[3] = "innerFixture3"; - ((Object[])fixture[9])[8] = innerFixture; + public void test_hashCode$LD() { + int listHashCode; + int arrayHashCode; - String expected = "[[true, false], [0, 1], [a, b], [0.0, 1.0], [0.0, 1.0], [0, 1], [0, 1], [0, 1], [true, false], [[...], [0, 1], [a, b], [0.0, 1.0], [0.0, 1.0], [0, 1], [0, 1], [0, 1], [innerFixture0, [...], [...], innerFixture3]]]"; - - assertEquals(expected, Arrays.deepToString(fixture)); + double [] doubleArr = {0.134945657, 0.0038754, 11e-150, -30e-300, 10e-4}; + List listOfDouble = new LinkedList(); + for (int i = 0; i < doubleArr.length; i++) { + listOfDouble.add(new Double(doubleArr[i])); + } + listHashCode = listOfDouble.hashCode(); + arrayHashCode = Arrays.hashCode(doubleArr); + assertEquals(listHashCode, arrayHashCode); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "asList", - args = {java.lang.Object[].class} - ) - public void test_asListTvararg() throws Exception { - List<String> stringsList = Arrays.asList("0", "1"); - assertEquals(2, stringsList.size()); - assertEquals("0", stringsList.get(0)); - assertEquals("1", stringsList.get(1)); - assertTrue(stringsList instanceof RandomAccess); - assertTrue(stringsList instanceof Serializable); - - assertEquals(stringsList, SerializationTest - .copySerializable((Serializable) stringsList)); - - //test from javadoc - List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); - assertEquals(3, stooges.size()); - assertEquals("Larry", stooges.get(0)); - assertEquals("Moe", stooges.get(1)); - assertEquals("Curly", stooges.get(2)); - - stringsList = Arrays.asList((String)null); - assertEquals(1, stringsList.size()); - assertEquals((String)null, stringsList.get(0)); + + /** + * @tests java.util.Arrays#hashCode(short[] a) + */ + public void test_hashCode$LS() { + int listHashCode; + int arrayHashCode; - try { - Arrays.asList((Object[])null); - fail("No NPE"); - } catch (NullPointerException e) {} + short [] shortArr = {35, 13, 45, 2, 91}; + List listOfShort = new LinkedList(); + for (int i = 0; i < shortArr.length; i++) { + listOfShort.add(new Short(shortArr[i])); + } + listHashCode = listOfShort.hashCode(); + arrayHashCode = Arrays.hashCode(shortArr); + assertEquals(listHashCode, arrayHashCode); } - + /** - * @tests java.util.Arrays#deepToString(Object[]) - * @bug 1452542 + * @tests java.util.Arrays#hashCode(Object[] a) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Tests fix for Android bug 1452542", - method = "deepToString", - args = {java.lang.Object[].class} - ) - public void test_deepToStringNestedEmptyArray() { - Object[][] foo = new Object[1][]; - foo[0] = new Object[0]; - assertEquals("[[]]", Arrays.deepToString(foo)); + public void test_hashCode$Ljava_lang_Object() { + int listHashCode; + int arrayHashCode; + + Object[] objectArr = {new Integer(1), new Float(10e-12f), null}; + List listOfObject= new LinkedList(); + for (int i = 0; i < objectArr.length; i++) { + listOfObject.add(objectArr[i]); + } + listHashCode = listOfObject.hashCode(); + arrayHashCode = Arrays.hashCode(objectArr); + assertEquals(listHashCode, arrayHashCode); } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + booleanArray = new boolean[arraySize]; + byteArray = new byte[arraySize]; + charArray = new char[arraySize]; + doubleArray = new double[arraySize]; + floatArray = new float[arraySize]; + intArray = new int[arraySize]; + longArray = new long[arraySize]; + objectArray = new Object[arraySize]; + shortArray = new short[arraySize]; - /** - * @tests java.util.Arrays#deepToString(Object[]) - * @bug 1452542 + for (int counter = 0; counter < arraySize; counter++) { + byteArray[counter] = (byte) counter; + charArray[counter] = (char) (counter + 1); + doubleArray[counter] = counter; + floatArray[counter] = counter; + intArray[counter] = counter; + longArray[counter] = counter; + objectArray[counter] = objArray[counter]; + shortArray[counter] = (short) counter; + } + for (int counter = 0; counter < arraySize; counter += 2) { + booleanArray[counter] = false; + booleanArray[counter + 1] = true; + } + } + + /** + * @tests java.util.Arrays#swap(int, int, Object[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Tests fix for Android bug 1452542", - method = "deepToString", - args = {java.lang.Object[].class} - ) - public void test_deepToStringNestedNullArray() { - Object[][] foo = new Object[1][]; - assertEquals("[null]", Arrays.deepToString(foo)); + public void test_swap_I_I_$Ljava_lang_Object() throws Exception { + Method m = Arrays.class.getDeclaredMethod("swap", int.class, int.class, Object[].class); + m.setAccessible(true); + Integer[] arr = {new Integer(0), new Integer(1), new Integer(2)}; + m.invoke(null,0, 1, arr); + assertEquals("should be equal to 1",1, arr[0].intValue()); + assertEquals("should be equal to 0",0, arr[1].intValue()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "binarySearch", - args = {java.lang.Object[].class, java.lang.Object.class, java.util.Comparator.class} - ) - public void test_binarySearch$TTLjava_util_ComparatorsuperT() { - String[] strings = new String[] { "a", "B", "c", "D" }; - Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER); - assertEquals(0, Arrays.binarySearch(strings, "a", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(0, Arrays.binarySearch(strings, "A", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(1, Arrays.binarySearch(strings, "b", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(1, Arrays.binarySearch(strings, "B", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(2, Arrays.binarySearch(strings, "c", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(2, Arrays.binarySearch(strings, "C", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(3, Arrays.binarySearch(strings, "d", - String.CASE_INSENSITIVE_ORDER)); - assertEquals(3, Arrays.binarySearch(strings, "D", - String.CASE_INSENSITIVE_ORDER)); - - - assertTrue(Arrays.binarySearch(strings, "e", - String.CASE_INSENSITIVE_ORDER) < 0); - assertTrue(Arrays.binarySearch(strings, "" + ('A' - 1), - String.CASE_INSENSITIVE_ORDER) < 0); - - //test with null comparator, which switches back to Comparable - Arrays.sort(strings, null); - //B, D, a, c - assertEquals(2, Arrays.binarySearch(strings, "a", (Comparator<String>)null)); - assertEquals(-1, Arrays.binarySearch(strings, "A", (Comparator<String>)null)); - assertEquals(-4, Arrays.binarySearch(strings, "b", (Comparator<String>)null)); - assertEquals(0, Arrays.binarySearch(strings, "B", (Comparator<String>)null)); - assertEquals(3, Arrays.binarySearch(strings, "c", (Comparator<String>)null)); - assertEquals(-2, Arrays.binarySearch(strings, "C", (Comparator<String>)null)); - assertEquals(-5, Arrays.binarySearch(strings, "d", (Comparator<String>)null)); - assertEquals(1, Arrays.binarySearch(strings, "D", (Comparator<String>)null)); - - assertTrue(Arrays.binarySearch(strings, "e", null) < 0); - assertTrue(Arrays.binarySearch(strings, "" + ('A' - 1), null) < 0); - - try { - Arrays.binarySearch((String[])null, "A", String.CASE_INSENSITIVE_ORDER); - fail("No NPE"); - } catch (NullPointerException e) {} - - try { - Arrays.binarySearch(strings, (String)null, String.CASE_INSENSITIVE_ORDER); - fail("No NPE"); - } catch (NullPointerException e) {} - - try { - Arrays.binarySearch(strings, (String)null, (Comparator<String>)null); - fail("No NPE"); - } catch (NullPointerException e) {} - - } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "sort", - args = {java.lang.Object[].class, java.util.Comparator.class} - ) - public void test_sort$TLjava_lang_ComparatorsuperT() { - String[] strings = new String[] { "a", "B", "c", "D" }; - Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER); - assertEquals("a", strings[0]); - assertEquals("B", strings[1]); - assertEquals("c", strings[2]); - assertEquals("D", strings[3]); - - //test with null comparator, which switches back to Comparable - Arrays.sort(strings, null); - //B, D, a, c - assertEquals("B", strings[0]); - assertEquals("D", strings[1]); - assertEquals("a", strings[2]); - assertEquals("c", strings[3]); - - try { - Arrays.sort((String[])null, String.CASE_INSENSITIVE_ORDER); - fail("No NPE"); - } catch (NullPointerException e) {} - } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify IllegalArgumentException, ArrayIndexOutOfBoundsException, ClassCastException.", - method = "sort", - args = {java.lang.Object[].class, int.class, int.class} - ) - public void test_sort$TIILjava_lang_ComparatorsuperT() { - String[] strings = new String[] { "a", "B", "c", "D" }; - Arrays.sort(strings, 0, strings.length, String.CASE_INSENSITIVE_ORDER); - assertEquals("a", strings[0]); - assertEquals("B", strings[1]); - assertEquals("c", strings[2]); - assertEquals("D", strings[3]); - - //test with null comparator, which switches back to Comparable - Arrays.sort(strings, 0, strings.length, null); - //B, D, a, c - assertEquals("B", strings[0]); - assertEquals("D", strings[1]); - assertEquals("a", strings[2]); - assertEquals("c", strings[3]); - - try { - Arrays.sort((String[])null, String.CASE_INSENSITIVE_ORDER); - fail("No NPE"); - } catch (NullPointerException e) {} - } + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java index 769e31f..7126321 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java @@ -17,78 +17,1386 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.util.BitSet; import junit.framework.TestCase; -import java.util.BitSet; - -@TestTargetClass(BitSet.class) public class BitSetTest extends TestCase { + BitSet eightbs; + + /** + * @tests java.util.BitSet#BitSet() + */ + public void test_Constructor() { + BitSet bs = new BitSet(); + assertEquals("Create BitSet of incorrect size", 64, bs.size()); + assertEquals("New BitSet had invalid string representation", "{}", + bs.toString()); + } + + /** + * @tests java.util.BitSet#BitSet(int) + */ + public void test_ConstructorI() { + BitSet bs = new BitSet(128); + assertEquals("Create BitSet of incorrect size", 128, bs.size()); + assertEquals("New BitSet had invalid string representation: " + + bs.toString(), "{}", bs.toString()); + // All BitSets are created with elements of multiples of 64 + bs = new BitSet(89); + assertEquals("Failed to round BitSet element size", 128, bs.size()); + + try { + bs = new BitSet(-9); + fail("Failed to throw exception when creating a new BitSet with negative element value"); + } catch (NegativeArraySizeException e) { + // Correct behaviour + } + } + + /** + * tests java.util.BitSet#clone() + */ + public void test_clone() { + BitSet bs; + bs = (BitSet) eightbs.clone(); + assertEquals("clone failed to return equal BitSet", bs, eightbs); + } + + /** + * @tests java.util.BitSet#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + BitSet bs; + bs = (BitSet) eightbs.clone(); + assertEquals("Same BitSet returned false", eightbs, eightbs); + assertEquals("Identical BitSet returned false", bs, eightbs); + bs.clear(6); + assertFalse("Different BitSets returned true", eightbs.equals(bs)); + + bs = (BitSet) eightbs.clone(); + bs.set(128); + assertFalse("Different sized BitSet with higher bit set returned true", + eightbs.equals(bs)); + bs.clear(128); + assertTrue( + "Different sized BitSet with higher bits not set returned false", + eightbs.equals(bs)); + } + + /** + * @tests java.util.BitSet#hashCode() + */ + public void test_hashCode() { + // Test for method int java.util.BitSet.hashCode() + BitSet bs = (BitSet) eightbs.clone(); + bs.clear(2); + bs.clear(6); + assertEquals("BitSet returns wrong hash value", 1129, bs.hashCode()); + bs.set(10); + bs.clear(3); + assertEquals("BitSet returns wrong hash value", 97, bs.hashCode()); + } + + /** + * @tests java.util.BitSet#clear() + */ + public void test_clear() { + eightbs.clear(); + for (int i = 0; i < 8; i++) { + assertFalse("Clear didn't clear bit " + i, eightbs.get(i)); + } + assertEquals("Test1: Wrong length", 0, eightbs.length()); + + BitSet bs = new BitSet(3400); + bs.set(0, bs.size() - 1); // ensure all bits are 1's + bs.set(bs.size() - 1); + bs.clear(); + assertEquals("Test2: Wrong length", 0, bs.length()); + assertTrue("Test2: isEmpty() returned incorrect value", bs.isEmpty()); + assertEquals("Test2: cardinality() returned incorrect value", 0, bs + .cardinality()); + } + + /** + * @tests java.util.BitSet#clear(int) + */ + public void test_clearI() { + // Test for method void java.util.BitSet.clear(int) + + eightbs.clear(7); + assertFalse("Failed to clear bit", eightbs.get(7)); + + // Check to see all other bits are still set + for (int i = 0; i < 7; i++) + assertTrue("Clear cleared incorrect bits", eightbs.get(i)); + + eightbs.clear(165); + assertFalse("Failed to clear bit", eightbs.get(165)); + // Try out of range + try { + eightbs.clear(-1); + fail("Failed to throw out of bounds exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behaviour + } + + BitSet bs = new BitSet(0); + assertEquals("Test1: Wrong length,", 0, bs.length()); + assertEquals("Test1: Wrong size,", 0, bs.size()); + + bs.clear(0); + assertEquals("Test2: Wrong length,", 0, bs.length()); + assertEquals("Test2: Wrong size,", 0, bs.size()); + + bs.clear(60); + assertEquals("Test3: Wrong length,", 0, bs.length()); + assertEquals("Test3: Wrong size,", 0, bs.size()); + + bs.clear(120); + assertEquals("Test4: Wrong size,", 0, bs.size()); + assertEquals("Test4: Wrong length,", 0, bs.length()); + + bs.set(25); + assertEquals("Test5: Wrong size,", 64, bs.size()); + assertEquals("Test5: Wrong length,", 26, bs.length()); + + bs.clear(80); + assertEquals("Test6: Wrong size,", 64, bs.size()); + assertEquals("Test6: Wrong length,", 26, bs.length()); + + bs.clear(25); + assertEquals("Test7: Wrong size,", 64, bs.size()); + assertEquals("Test7: Wrong length,", 0, bs.length()); + } + /** * @tests java.util.BitSet#clear(int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IndexOutOfBoundsException is not verified.", - method = "clear", - args = {int.class, int.class} - ) - public void test_clearII() { + public void test_clearII() throws IndexOutOfBoundsException { // Regression for HARMONY-98 BitSet bitset = new BitSet(); for (int i = 0; i < 20; i++) { bitset.set(i); } bitset.clear(10, 10); + + // Test for method void java.util.BitSet.clear(int, int) + // pos1 and pos2 are in the same bitset element + BitSet bs = new BitSet(16); + int initialSize = bs.size(); + bs.set(0, initialSize); + bs.clear(5); + bs.clear(15); + bs.clear(7, 11); + for (int i = 0; i < 7; i++) { + if (i == 5) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + } + for (int i = 7; i < 11; i++) + assertFalse("Failed to clear bit " + i, bs.get(i)); + + for (int i = 11; i < initialSize; i++) { + if (i == 15) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + } + + for (int i = initialSize; i < bs.size(); i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + + // pos1 and pos2 is in the same bitset element, boundry testing + bs = new BitSet(16); + initialSize = bs.size(); + bs.set(0, initialSize); + bs.clear(7, 64); + assertEquals("Failed to grow BitSet", 64, bs.size()); + for (int i = 0; i < 7; i++) + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + for (int i = 7; i < 64; i++) + assertFalse("Failed to clear bit " + i, bs.get(i)); + for (int i = 64; i < bs.size(); i++) { + assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); + } + // more boundary testing + bs = new BitSet(32); + initialSize = bs.size(); + bs.set(0, initialSize); + bs.clear(0, 64); + for (int i = 0; i < 64; i++) + assertFalse("Failed to clear bit " + i, bs.get(i)); + for (int i = 64; i < bs.size(); i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + + bs = new BitSet(32); + initialSize = bs.size(); + bs.set(0, initialSize); + bs.clear(0, 65); + for (int i = 0; i < 65; i++) + assertFalse("Failed to clear bit " + i, bs.get(i)); + for (int i = 65; i < bs.size(); i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + + // pos1 and pos2 are in two sequential bitset elements + bs = new BitSet(128); + initialSize = bs.size(); + bs.set(0, initialSize); + bs.clear(7); + bs.clear(110); + bs.clear(9, 74); + for (int i = 0; i < 9; i++) { + if (i == 7) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + } + for (int i = 9; i < 74; i++) + assertFalse("Failed to clear bit " + i, bs.get(i)); + for (int i = 74; i < initialSize; i++) { + if (i == 110) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + } + for (int i = initialSize; i < bs.size(); i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + + // pos1 and pos2 are in two non-sequential bitset elements + bs = new BitSet(256); + bs.set(0, 256); + bs.clear(7); + bs.clear(255); + bs.clear(9, 219); + for (int i = 0; i < 9; i++) { + if (i == 7) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + } + + for (int i = 9; i < 219; i++) + assertFalse("failed to clear bit " + i, bs.get(i)); + + for (int i = 219; i < 255; i++) + assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); + + for (int i = 255; i < bs.size(); i++) + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + + // test illegal args + bs = new BitSet(10); + try { + bs.clear(-1, 3); + fail("Test1: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // excepted + } + + try { + bs.clear(2, -1); + fail("Test2: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // excepted + } + + bs.set(2, 4); + bs.clear(2, 2); + assertTrue("Bit got cleared incorrectly ", bs.get(2)); + + try { + bs.clear(4, 2); + fail("Test4: Attempt to flip with illegal args failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // excepted + } + + bs = new BitSet(0); + assertEquals("Test1: Wrong length,", 0, bs.length()); + assertEquals("Test1: Wrong size,", 0, bs.size()); + + bs.clear(0, 2); + assertEquals("Test2: Wrong length,", 0, bs.length()); + assertEquals("Test2: Wrong size,", 0, bs.size()); + + bs.clear(60, 64); + assertEquals("Test3: Wrong length,", 0, bs.length()); + assertEquals("Test3: Wrong size,", 0, bs.size()); + + bs.clear(64, 120); + assertEquals("Test4: Wrong length,", 0, bs.length()); + assertEquals("Test4: Wrong size,", 0, bs.size()); + + bs.set(25); + assertEquals("Test5: Wrong length,", 26, bs.length()); + assertEquals("Test5: Wrong size,", 64, bs.size()); + + bs.clear(60, 64); + assertEquals("Test6: Wrong length,", 26, bs.length()); + assertEquals("Test6: Wrong size,", 64, bs.size()); + + bs.clear(64, 120); + assertEquals("Test7: Wrong size,", 64, bs.size()); + assertEquals("Test7: Wrong length,", 26, bs.length()); + + bs.clear(80); + assertEquals("Test8: Wrong size,", 64, bs.size()); + assertEquals("Test8: Wrong length,", 26, bs.length()); + + bs.clear(25); + assertEquals("Test9: Wrong size,", 64, bs.size()); + assertEquals("Test9: Wrong length,", 0, bs.length()); + } + + /** + * @tests java.util.BitSet#get(int) + */ + public void test_getI() { + // Test for method boolean java.util.BitSet.get(int) + + BitSet bs = new BitSet(); + bs.set(8); + assertFalse("Get returned true for index out of range", eightbs.get(99)); + assertTrue("Get returned false for set value", eightbs.get(3)); + assertFalse("Get returned true for a non set value", bs.get(0)); + + try { + bs.get(-1); + fail("Attempt to get at negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behaviour + } + + bs = new BitSet(1); + assertFalse("Access greater than size", bs.get(64)); + + bs = new BitSet(); + bs.set(63); + assertTrue("Test highest bit", bs.get(63)); + + bs = new BitSet(0); + assertEquals("Test1: Wrong length,", 0, bs.length()); + assertEquals("Test1: Wrong size,", 0, bs.size()); + + bs.get(2); + assertEquals("Test2: Wrong length,", 0, bs.length()); + assertEquals("Test2: Wrong size,", 0, bs.size()); + + bs.get(70); + assertEquals("Test3: Wrong length,", 0, bs.length()); + assertEquals("Test3: Wrong size,", 0, bs.size()); + + } + + /** + * @tests java.util.BitSet#get(int, int) + */ + public void test_getII() { + BitSet bitset = new BitSet(30); + bitset.get(3, 3); + + // Test for method boolean java.util.BitSet.get(int, int) + BitSet bs, resultbs, correctbs; + bs = new BitSet(512); + bs.set(3, 9); + bs.set(10, 20); + bs.set(60, 75); + bs.set(121); + bs.set(130, 140); + + // pos1 and pos2 are in the same bitset element, at index0 + resultbs = bs.get(3, 6); + correctbs = new BitSet(3); + correctbs.set(0, 3); + assertEquals("Test1: Returned incorrect BitSet", correctbs, resultbs); + + // pos1 and pos2 are in the same bitset element, at index 1 + resultbs = bs.get(100, 125); + correctbs = new BitSet(25); + correctbs.set(21); + assertEquals("Test2: Returned incorrect BitSet", correctbs, resultbs); + + // pos1 in bitset element at index 0, and pos2 in bitset element at + // index 1 + resultbs = bs.get(15, 125); + correctbs = new BitSet(25); + correctbs.set(0, 5); + correctbs.set(45, 60); + correctbs.set(121 - 15); + assertEquals("Test3: Returned incorrect BitSet", correctbs, resultbs); + + // pos1 in bitset element at index 1, and pos2 in bitset element at + // index 2 + resultbs = bs.get(70, 145); + correctbs = new BitSet(75); + correctbs.set(0, 5); + correctbs.set(51); + correctbs.set(60, 70); + assertEquals("Test4: Returned incorrect BitSet", correctbs, resultbs); + + // pos1 in bitset element at index 0, and pos2 in bitset element at + // index 2 + resultbs = bs.get(5, 145); + correctbs = new BitSet(140); + correctbs.set(0, 4); + correctbs.set(5, 15); + correctbs.set(55, 70); + correctbs.set(116); + correctbs.set(125, 135); + assertEquals("Test5: Returned incorrect BitSet", correctbs, resultbs); + + // pos1 in bitset element at index 0, and pos2 in bitset element at + // index 3 + resultbs = bs.get(5, 250); + correctbs = new BitSet(200); + correctbs.set(0, 4); + correctbs.set(5, 15); + correctbs.set(55, 70); + correctbs.set(116); + correctbs.set(125, 135); + assertEquals("Test6: Returned incorrect BitSet", correctbs, resultbs); + + assertEquals("equality principle 1 ", bs.get(0, bs.size()), bs); + + // more tests + BitSet bs2 = new BitSet(129); + bs2.set(0, 20); + bs2.set(62, 65); + bs2.set(121, 123); + resultbs = bs2.get(1, 124); + correctbs = new BitSet(129); + correctbs.set(0, 19); + correctbs.set(61, 64); + correctbs.set(120, 122); + assertEquals("Test7: Returned incorrect BitSet", correctbs, resultbs); + + // equality principle with some boundary conditions + bs2 = new BitSet(128); + bs2.set(2, 20); + bs2.set(62); + bs2.set(121, 123); + bs2.set(127); + resultbs = bs2.get(0, bs2.size()); + assertEquals("equality principle 2 ", resultbs, bs2); + + bs2 = new BitSet(128); + bs2.set(2, 20); + bs2.set(62); + bs2.set(121, 123); + bs2.set(127); + bs2.flip(0, 128); + resultbs = bs2.get(0, bs.size()); + assertEquals("equality principle 3 ", resultbs, bs2); + + bs = new BitSet(0); + assertEquals("Test1: Wrong length,", 0, bs.length()); + assertEquals("Test1: Wrong size,", 0, bs.size()); + + bs.get(0, 2); + assertEquals("Test2: Wrong length,", 0, bs.length()); + assertEquals("Test2: Wrong size,", 0, bs.size()); + + bs.get(60, 64); + assertEquals("Test3: Wrong length,", 0, bs.length()); + assertEquals("Test3: Wrong size,", 0, bs.size()); + + bs.get(64, 120); + assertEquals("Test4: Wrong length,", 0, bs.length()); + assertEquals("Test4: Wrong size,", 0, bs.size()); + + bs.set(25); + assertEquals("Test5: Wrong length,", 26, bs.length()); + assertEquals("Test5: Wrong size,", 64, bs.size()); + + bs.get(60, 64); + assertEquals("Test6: Wrong length,", 26, bs.length()); + assertEquals("Test6: Wrong size,", 64, bs.size()); + + bs.get(64, 120); + assertEquals("Test7: Wrong size,", 64, bs.size()); + assertEquals("Test7: Wrong length,", 26, bs.length()); + + bs.get(80); + assertEquals("Test8: Wrong size,", 64, bs.size()); + assertEquals("Test8: Wrong length,", 26, bs.length()); + + bs.get(25); + assertEquals("Test9: Wrong size,", 64, bs.size()); + assertEquals("Test9: Wrong length,", 26, bs.length()); + + } + + /** + * @tests java.util.BitSet#flip(int) + */ + public void test_flipI() { + // Test for method void java.util.BitSet.flip(int) + BitSet bs = new BitSet(); + bs.clear(8); + bs.clear(9); + bs.set(10); + bs.flip(9); + assertFalse("Failed to flip bit", bs.get(8)); + assertTrue("Failed to flip bit", bs.get(9)); + assertTrue("Failed to flip bit", bs.get(10)); + + bs.set(8); + bs.set(9); + bs.clear(10); + bs.flip(9); + assertTrue("Failed to flip bit", bs.get(8)); + assertFalse("Failed to flip bit", bs.get(9)); + assertFalse("Failed to flip bit", bs.get(10)); + + try { + bs.flip(-1); + fail("Attempt to flip at negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behaviour + } + + // Try setting a bit on a 64 boundary + bs.flip(128); + assertEquals("Failed to grow BitSet", 192, bs.size()); + assertTrue("Failed to flip bit", bs.get(128)); + + bs = new BitSet(64); + for (int i = bs.size(); --i >= 0;) { + bs.flip(i); + assertTrue("Test1: Incorrectly flipped bit" + i, bs.get(i)); + assertEquals("Incorrect length", i+1, bs.length()); + for (int j = bs.size(); --j > i;) { + assertTrue("Test2: Incorrectly flipped bit" + j, !bs.get(j)); + } + for (int j = i; --j >= 0;) { + assertTrue("Test3: Incorrectly flipped bit" + j, !bs.get(j)); + } + bs.flip(i); + } + + BitSet bs0 = new BitSet(0); + assertEquals("Test1: Wrong size", 0, bs0.size()); + assertEquals("Test1: Wrong length", 0, bs0.length()); + + bs0.flip(0); + assertEquals("Test2: Wrong size", 64, bs0.size()); + assertEquals("Test2: Wrong length", 1, bs0.length()); + + bs0.flip(63); + assertEquals("Test3: Wrong size", 64, bs0.size()); + assertEquals("Test3: Wrong length", 64, bs0.length()); + + eightbs.flip(7); + assertTrue("Failed to flip bit 7", !eightbs.get(7)); + + // Check to see all other bits are still set + for (int i = 0; i < 7; i++) + assertTrue("Flip flipped incorrect bits", eightbs.get(i)); + + eightbs.flip(127); + assertTrue("Failed to flip bit 127", eightbs.get(127)); + + eightbs.flip(127); + assertTrue("Failed to flip bit 127", !eightbs.get(127)); } /** - * @tests java.util.BitSet#flip(int, int) + * @tests java.util.BitSet#clear(int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IndexOutOfBoundsException is not verified.", - method = "flip", - args = {int.class, int.class} - ) public void test_flipII() { BitSet bitset = new BitSet(); for (int i = 0; i < 20; i++) { bitset.set(i); } bitset.flip(10, 10); + + // Test for method void java.util.BitSet.flip(int, int) + // pos1 and pos2 are in the same bitset element + BitSet bs = new BitSet(16); + bs.set(7); + bs.set(10); + bs.flip(7, 11); + for (int i = 0; i < 7; i++) { + assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); + } + assertFalse("Failed to flip bit 7", bs.get(7)); + assertTrue("Failed to flip bit 8", bs.get(8)); + assertTrue("Failed to flip bit 9", bs.get(9)); + assertFalse("Failed to flip bit 10", bs.get(10)); + for (int i = 11; i < bs.size(); i++) { + assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); + } + + // pos1 and pos2 is in the same bitset element, boundry testing + bs = new BitSet(16); + bs.set(7); + bs.set(10); + bs.flip(7, 64); + assertEquals("Failed to grow BitSet", 64, bs.size()); + for (int i = 0; i < 7; i++) { + assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); + } + assertFalse("Failed to flip bit 7", bs.get(7)); + assertTrue("Failed to flip bit 8", bs.get(8)); + assertTrue("Failed to flip bit 9", bs.get(9)); + assertFalse("Failed to flip bit 10", bs.get(10)); + for (int i = 11; i < 64; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have flipped bit 64", bs.get(64)); + + // more boundary testing + bs = new BitSet(32); + bs.flip(0, 64); + for (int i = 0; i < 64; i++) { + assertTrue("Failed to flip bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have flipped bit 64", bs.get(64)); + + bs = new BitSet(32); + bs.flip(0, 65); + for (int i = 0; i < 65; i++) { + assertTrue("Failed to flip bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have flipped bit 65", bs.get(65)); + + // pos1 and pos2 are in two sequential bitset elements + bs = new BitSet(128); + bs.set(7); + bs.set(10); + bs.set(72); + bs.set(110); + bs.flip(9, 74); + for (int i = 0; i < 7; i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + assertTrue("Shouldn't have flipped bit 7", bs.get(7)); + assertFalse("Shouldn't have flipped bit 8", bs.get(8)); + assertTrue("Failed to flip bit 9", bs.get(9)); + assertFalse("Failed to flip bit 10", bs.get(10)); + for (int i = 11; i < 72; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Failed to flip bit 72", bs.get(72)); + assertTrue("Failed to flip bit 73", bs.get(73)); + for (int i = 74; i < 110; i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + assertTrue("Shouldn't have flipped bit 110", bs.get(110)); + for (int i = 111; i < bs.size(); i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + + // pos1 and pos2 are in two non-sequential bitset elements + bs = new BitSet(256); + bs.set(7); + bs.set(10); + bs.set(72); + bs.set(110); + bs.set(181); + bs.set(220); + bs.flip(9, 219); + for (int i = 0; i < 7; i++) { + assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); + } + assertTrue("Shouldn't have flipped bit 7", bs.get(7)); + assertFalse("Shouldn't have flipped bit 8", bs.get(8)); + assertTrue("Failed to flip bit 9", bs.get(9)); + assertFalse("Failed to flip bit 10", bs.get(10)); + for (int i = 11; i < 72; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Failed to flip bit 72", bs.get(72)); + for (int i = 73; i < 110; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Failed to flip bit 110", bs.get(110)); + for (int i = 111; i < 181; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Failed to flip bit 181", bs.get(181)); + for (int i = 182; i < 219; i++) { + assertTrue("failed to flip bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have flipped bit 219", bs.get(219)); + assertTrue("Shouldn't have flipped bit 220", bs.get(220)); + for (int i = 221; i < bs.size(); i++) { + assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); + } + + // test illegal args + bs = new BitSet(10); + try { + bs.flip(-1, 3); + fail("Test1: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // correct behavior + } + + try { + bs.flip(2, -1); + fail("Test2: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // correct behavior + } + + try { + bs.flip(4, 2); + fail("Test4: Attempt to flip with illegal args failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // correct behavior + } } /** - * @tests java.util.BitSet#get(int, int) + * @tests java.util.BitSet#set(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IndexOutOfBoundsException is not verified.", - method = "get", - args = {int.class, int.class} - ) - public void test_getII() { - BitSet bitset = new BitSet(30); - bitset.get(3, 3); + public void test_setI() { + // Test for method void java.util.BitSet.set(int) + + BitSet bs = new BitSet(); + bs.set(8); + assertTrue("Failed to set bit", bs.get(8)); + + try { + bs.set(-1); + fail("Attempt to set at negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behaviour + } + + // Try setting a bit on a 64 boundary + bs.set(128); + assertEquals("Failed to grow BitSet", 192, bs.size()); + assertTrue("Failed to set bit", bs.get(128)); + + bs = new BitSet(64); + for (int i = bs.size(); --i >= 0;) { + bs.set(i); + assertTrue("Incorrectly set", bs.get(i)); + assertEquals("Incorrect length", i+1, bs.length()); + for (int j = bs.size(); --j > i;) + assertFalse("Incorrectly set bit " + j, bs.get(j)); + for (int j = i; --j >= 0;) + assertFalse("Incorrectly set bit " + j, bs.get(j)); + bs.clear(i); + } + + bs = new BitSet(0); + assertEquals("Test1: Wrong length", 0, bs.length()); + bs.set(0); + assertEquals("Test2: Wrong length", 1, bs.length()); + } + + /** + * @tests java.util.BitSet#set(int, boolean) + */ + public void test_setIZ() { + // Test for method void java.util.BitSet.set(int, boolean) + eightbs.set(5, false); + assertFalse("Should have set bit 5 to true", eightbs.get(5)); + + eightbs.set(5, true); + assertTrue("Should have set bit 5 to false", eightbs.get(5)); } /** * @tests java.util.BitSet#set(int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "IndexOutOfBoundsException is not verified.", - method = "set", - args = {int.class, int.class} - ) - public void test_setII() { + public void test_setII() throws IndexOutOfBoundsException { BitSet bitset = new BitSet(30); bitset.set(29, 29); + + // Test for method void java.util.BitSet.set(int, int) + // pos1 and pos2 are in the same bitset element + BitSet bs = new BitSet(16); + bs.set(5); + bs.set(15); + bs.set(7, 11); + for (int i = 0; i < 7; i++) { + if (i == 5) + assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + for (int i = 7; i < 11; i++) + assertTrue("Failed to set bit " + i, bs.get(i)); + for (int i = 11; i < bs.size(); i++) { + if (i == 15) + assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + + // pos1 and pos2 is in the same bitset element, boundry testing + bs = new BitSet(16); + bs.set(7, 64); + assertEquals("Failed to grow BitSet", 64, bs.size()); + for (int i = 0; i < 7; i++) { + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + for (int i = 7; i < 64; i++) { + assertTrue("Failed to set bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have set bit 64", bs.get(64)); + + // more boundary testing + bs = new BitSet(32); + bs.set(0, 64); + for (int i = 0; i < 64; i++) { + assertTrue("Failed to set bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have set bit 64", bs.get(64)); + + bs = new BitSet(32); + bs.set(0, 65); + for (int i = 0; i < 65; i++) { + assertTrue("Failed to set bit " + i, bs.get(i)); + } + assertFalse("Shouldn't have set bit 65", bs.get(65)); + + // pos1 and pos2 are in two sequential bitset elements + bs = new BitSet(128); + bs.set(7); + bs.set(110); + bs.set(9, 74); + for (int i = 0; i < 9; i++) { + if (i == 7) + assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + for (int i = 9; i < 74; i++) { + assertTrue("Failed to set bit " + i, bs.get(i)); + } + for (int i = 74; i < bs.size(); i++) { + if (i == 110) + assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); + else + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + + // pos1 and pos2 are in two non-sequential bitset elements + bs = new BitSet(256); + bs.set(7); + bs.set(255); + bs.set(9, 219); + for (int i = 0; i < 9; i++) { + if (i == 7) + assertTrue("Shouldn't have set flipped " + i, bs.get(i)); + else + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + + for (int i = 9; i < 219; i++) { + assertTrue("failed to set bit " + i, bs.get(i)); + } + + for (int i = 219; i < 255; i++) { + assertFalse("Shouldn't have set bit " + i, bs.get(i)); + } + + assertTrue("Shouldn't have flipped bit 255", bs.get(255)); + + // test illegal args + bs = new BitSet(10); + try { + bs.set(-1, 3); + fail("Test1: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behavior + } + + try { + bs.set(2, -1); + fail("Test2: Attempt to flip with negative index failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behavior + } + + bs.set(2, 2); + assertFalse("Bit got set incorrectly ", bs.get(2)); + + try { + bs.set(4, 2); + fail("Test4: Attempt to flip with illegal args failed to generate exception"); + } catch (IndexOutOfBoundsException e) { + // Correct behavior + } + } + + /** + * @tests java.util.BitSet#set(int, int, boolean) + */ + public void test_setIIZ() { + // Test for method void java.util.BitSet.set(int, int, boolean) + eightbs.set(3, 6, false); + assertTrue("Should have set bits 3, 4, and 5 to false", !eightbs.get(3) + && !eightbs.get(4) && !eightbs.get(5)); + + eightbs.set(3, 6, true); + assertTrue("Should have set bits 3, 4, and 5 to true", eightbs.get(3) + && eightbs.get(4) && eightbs.get(5)); + + } + + /** + * @tests java.util.BitSet#intersects(java.util.BitSet) + */ + public void test_intersectsLjava_util_BitSet() { + // Test for method boolean java.util.BitSet.intersects(java.util.BitSet) + BitSet bs = new BitSet(500); + bs.set(5); + bs.set(63); + bs.set(64); + bs.set(71, 110); + bs.set(127, 130); + bs.set(192); + bs.set(450); + + BitSet bs2 = new BitSet(8); + assertFalse("Test1: intersects() returned incorrect value", bs + .intersects(bs2)); + assertFalse("Test1: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.set(4); + assertFalse("Test2: intersects() returned incorrect value", bs + .intersects(bs2)); + assertFalse("Test2: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(5); + assertTrue("Test3: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test3: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(63); + assertTrue("Test4: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test4: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(80); + assertTrue("Test5: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test5: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(127); + assertTrue("Test6: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test6: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(192); + assertTrue("Test7: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test7: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(450); + assertTrue("Test8: intersects() returned incorrect value", bs + .intersects(bs2)); + assertTrue("Test8: intersects() returned incorrect value", bs2 + .intersects(bs)); + + bs2.clear(); + bs2.set(500); + assertFalse("Test9: intersects() returned incorrect value", bs + .intersects(bs2)); + assertFalse("Test9: intersects() returned incorrect value", bs2 + .intersects(bs)); + } + + /** + * @tests java.util.BitSet#and(java.util.BitSet) + */ + public void test_andLjava_util_BitSet() { + // Test for method void java.util.BitSet.and(java.util.BitSet) + BitSet bs = new BitSet(128); + // Initialize the bottom half of the BitSet + + for (int i = 64; i < 128; i++) + bs.set(i); + eightbs.and(bs); + assertFalse("AND failed to clear bits", eightbs.equals(bs)); + eightbs.set(3); + bs.set(3); + eightbs.and(bs); + assertTrue("AND failed to maintain set bits", bs.get(3)); + bs.and(eightbs); + for (int i = 64; i < 128; i++) { + assertFalse("Failed to clear extra bits in the receiver BitSet", bs + .get(i)); + } + } + + /** + * @tests java.util.BitSet#andNot(java.util.BitSet) + */ + public void test_andNotLjava_util_BitSet() { + BitSet bs = (BitSet) eightbs.clone(); + bs.clear(5); + BitSet bs2 = new BitSet(); + bs2.set(2); + bs2.set(3); + bs.andNot(bs2); + assertEquals("Incorrect bitset after andNot", + "{0, 1, 4, 6, 7}", bs.toString()); + + bs = new BitSet(0); + bs.andNot(bs2); + assertEquals("Incorrect size", 0, bs.size()); + } + + /** + * @tests java.util.BitSet#or(java.util.BitSet) + */ + public void test_orLjava_util_BitSet() { + // Test for method void java.util.BitSet.or(java.util.BitSet) + BitSet bs = new BitSet(128); + bs.or(eightbs); + for (int i = 0; i < 8; i++) { + assertTrue("OR failed to set bits", bs.get(i)); + } + + bs = new BitSet(0); + bs.or(eightbs); + for (int i = 0; i < 8; i++) { + assertTrue("OR(0) failed to set bits", bs.get(i)); + } + + eightbs.clear(5); + bs = new BitSet(128); + bs.or(eightbs); + assertFalse("OR set a bit which should be off", bs.get(5)); + } + + /** + * @tests java.util.BitSet#xor(java.util.BitSet) + */ + public void test_xorLjava_util_BitSet() { + // Test for method void java.util.BitSet.xor(java.util.BitSet) + + BitSet bs = (BitSet) eightbs.clone(); + bs.xor(eightbs); + for (int i = 0; i < 8; i++) { + assertFalse("XOR failed to clear bits", bs.get(i)); + } + + bs.xor(eightbs); + for (int i = 0; i < 8; i++) { + assertTrue("XOR failed to set bits", bs.get(i)); + } + + bs = new BitSet(0); + bs.xor(eightbs); + for (int i = 0; i < 8; i++) { + assertTrue("XOR(0) failed to set bits", bs.get(i)); + } + + bs = new BitSet(); + bs.set(63); + assertEquals("Test highest bit", "{63}", bs.toString()); + } + + /** + * @tests java.util.BitSet#size() + */ + public void test_size() { + // Test for method int java.util.BitSet.size() + assertEquals("Returned incorrect size", 64, eightbs.size()); + eightbs.set(129); + assertTrue("Returned incorrect size", eightbs.size() >= 129); + + } + + /** + * @tests java.util.BitSet#toString() + */ + public void test_toString() { + // Test for method java.lang.String java.util.BitSet.toString() + assertEquals("Returned incorrect string representation", + "{0, 1, 2, 3, 4, 5, 6, 7}", eightbs.toString()); + eightbs.clear(2); + assertEquals("Returned incorrect string representation", + "{0, 1, 3, 4, 5, 6, 7}", eightbs.toString()); + } + + /** + * @tests java.util.BitSet#length() + */ + public void test_length() { + BitSet bs = new BitSet(); + assertEquals("BitSet returned wrong length", 0, bs.length()); + bs.set(5); + assertEquals("BitSet returned wrong length", 6, bs.length()); + bs.set(10); + assertEquals("BitSet returned wrong length", 11, bs.length()); + bs.set(432); + assertEquals("BitSet returned wrong length", 433, bs.length()); + bs.set(300); + assertEquals("BitSet returned wrong length", 433, bs.length()); + } + + /** + * @tests java.util.BitSet#nextSetBit(int) + */ + public void test_nextSetBitI() { + // Test for method int java.util.BitSet.nextSetBit() + BitSet bs = new BitSet(500); + bs.set(5); + bs.set(32); + bs.set(63); + bs.set(64); + bs.set(71, 110); + bs.set(127, 130); + bs.set(193); + bs.set(450); + try { + bs.nextSetBit(-1); + fail("Expected IndexOutOfBoundsException for negative index"); + } catch (IndexOutOfBoundsException e) { + // correct behavior + } + assertEquals("nextSetBit() returned the wrong value", 5, bs + .nextSetBit(0)); + assertEquals("nextSetBit() returned the wrong value", 5, bs + .nextSetBit(5)); + assertEquals("nextSetBit() returned the wrong value", 32, bs + .nextSetBit(6)); + assertEquals("nextSetBit() returned the wrong value", 32, bs + .nextSetBit(32)); + assertEquals("nextSetBit() returned the wrong value", 63, bs + .nextSetBit(33)); + + // boundary tests + assertEquals("nextSetBit() returned the wrong value", 63, bs + .nextSetBit(63)); + assertEquals("nextSetBit() returned the wrong value", 64, bs + .nextSetBit(64)); + + // at bitset element 1 + assertEquals("nextSetBit() returned the wrong value", 71, bs + .nextSetBit(65)); + assertEquals("nextSetBit() returned the wrong value", 71, bs + .nextSetBit(71)); + assertEquals("nextSetBit() returned the wrong value", 72, bs + .nextSetBit(72)); + assertEquals("nextSetBit() returned the wrong value", 127, bs + .nextSetBit(110)); + + // boundary tests + assertEquals("nextSetBit() returned the wrong value", 127, bs + .nextSetBit(127)); + assertEquals("nextSetBit() returned the wrong value", 128, bs + .nextSetBit(128)); + + // at bitset element 2 + assertEquals("nextSetBit() returned the wrong value", 193, bs + .nextSetBit(130)); + + assertEquals("nextSetBit() returned the wrong value", 193, bs + .nextSetBit(191)); + assertEquals("nextSetBit() returned the wrong value", 193, bs + .nextSetBit(192)); + assertEquals("nextSetBit() returned the wrong value", 193, bs + .nextSetBit(193)); + assertEquals("nextSetBit() returned the wrong value", 450, bs + .nextSetBit(194)); + assertEquals("nextSetBit() returned the wrong value", 450, bs + .nextSetBit(255)); + assertEquals("nextSetBit() returned the wrong value", 450, bs + .nextSetBit(256)); + assertEquals("nextSetBit() returned the wrong value", 450, bs + .nextSetBit(450)); + + assertEquals("nextSetBit() returned the wrong value", -1, bs + .nextSetBit(451)); + assertEquals("nextSetBit() returned the wrong value", -1, bs + .nextSetBit(511)); + assertEquals("nextSetBit() returned the wrong value", -1, bs + .nextSetBit(512)); + assertEquals("nextSetBit() returned the wrong value", -1, bs + .nextSetBit(800)); + } + + /** + * @tests java.util.BitSet#nextClearBit(int) + */ + public void test_nextClearBitI() { + // Test for method int java.util.BitSet.nextSetBit() + BitSet bs = new BitSet(500); + bs.set(0, bs.size() - 1); // ensure all the bits from 0 to bs.size() + // -1 + bs.set(bs.size() - 1); // are set to true + bs.clear(5); + bs.clear(32); + bs.clear(63); + bs.clear(64); + bs.clear(71, 110); + bs.clear(127, 130); + bs.clear(193); + bs.clear(450); + try { + bs.nextClearBit(-1); + fail("Expected IndexOutOfBoundsException for negative index"); + } catch (IndexOutOfBoundsException e) { + // correct behavior + } + assertEquals("nextClearBit() returned the wrong value", 5, bs + .nextClearBit(0)); + assertEquals("nextClearBit() returned the wrong value", 5, bs + .nextClearBit(5)); + assertEquals("nextClearBit() returned the wrong value", 32, bs + .nextClearBit(6)); + assertEquals("nextClearBit() returned the wrong value", 32, bs + .nextClearBit(32)); + assertEquals("nextClearBit() returned the wrong value", 63, bs + .nextClearBit(33)); + + // boundary tests + assertEquals("nextClearBit() returned the wrong value", 63, bs + .nextClearBit(63)); + assertEquals("nextClearBit() returned the wrong value", 64, bs + .nextClearBit(64)); + + // at bitset element 1 + assertEquals("nextClearBit() returned the wrong value", 71, bs + .nextClearBit(65)); + assertEquals("nextClearBit() returned the wrong value", 71, bs + .nextClearBit(71)); + assertEquals("nextClearBit() returned the wrong value", 72, bs + .nextClearBit(72)); + assertEquals("nextClearBit() returned the wrong value", 127, bs + .nextClearBit(110)); + + // boundary tests + assertEquals("nextClearBit() returned the wrong value", 127, bs + .nextClearBit(127)); + assertEquals("nextClearBit() returned the wrong value", 128, bs + .nextClearBit(128)); + + // at bitset element 2 + assertEquals("nextClearBit() returned the wrong value", 193, bs + .nextClearBit(130)); + assertEquals("nextClearBit() returned the wrong value", 193, bs + .nextClearBit(191)); + + assertEquals("nextClearBit() returned the wrong value", 193, bs + .nextClearBit(192)); + assertEquals("nextClearBit() returned the wrong value", 193, bs + .nextClearBit(193)); + assertEquals("nextClearBit() returned the wrong value", 450, bs + .nextClearBit(194)); + assertEquals("nextClearBit() returned the wrong value", 450, bs + .nextClearBit(255)); + assertEquals("nextClearBit() returned the wrong value", 450, bs + .nextClearBit(256)); + assertEquals("nextClearBit() returned the wrong value", 450, bs + .nextClearBit(450)); + + // bitset has 1 still the end of bs.size() -1, but calling nextClearBit + // with any index value + // after the last true bit should return bs.size(), + assertEquals("nextClearBit() returned the wrong value", 512, bs + .nextClearBit(451)); + assertEquals("nextClearBit() returned the wrong value", 512, bs + .nextClearBit(511)); + assertEquals("nextClearBit() returned the wrong value", 512, bs + .nextClearBit(512)); + + // if the index is larger than bs.size(), nextClearBit should return + // index; + assertEquals("nextClearBit() returned the wrong value", 513, bs + .nextClearBit(513)); + assertEquals("nextClearBit() returned the wrong value", 800, bs + .nextClearBit(800)); + } + + /** + * @tests java.util.BitSet#isEmpty() + */ + public void test_isEmpty() { + BitSet bs = new BitSet(500); + assertTrue("Test: isEmpty() returned wrong value", bs.isEmpty()); + + // at bitset element 0 + bs.set(3); + assertFalse("Test0: isEmpty() returned wrong value", bs.isEmpty()); + + // at bitset element 1 + bs.clear(); + bs.set(12); + assertFalse("Test1: isEmpty() returned wrong value", bs.isEmpty()); + + // at bitset element 2 + bs.clear(); + bs.set(128); + assertFalse("Test2: isEmpty() returned wrong value", bs.isEmpty()); + + // boundary testing + bs.clear(); + bs.set(459); + assertFalse("Test3: isEmpty() returned wrong value", bs.isEmpty()); + + bs.clear(); + bs.set(511); + assertFalse("Test4: isEmpty() returned wrong value", bs.isEmpty()); + } + + /** + * @tests java.util.BitSet#cardinality() + */ + public void test_cardinality() { + // test for method int java.util.BitSet.cardinality() + BitSet bs = new BitSet(500); + bs.set(5); + bs.set(32); + bs.set(63); + bs.set(64); + bs.set(71, 110); + bs.set(127, 130); + bs.set(193); + bs.set(450); + assertEquals("cardinality() returned wrong value", 48, bs.cardinality()); + + bs.flip(0, 500); + assertEquals("cardinality() returned wrong value", 452, bs + .cardinality()); + + bs.clear(); + assertEquals("cardinality() returned wrong value", 0, bs.cardinality()); + + bs.set(0, 500); + assertEquals("cardinality() returned wrong value", 500, bs + .cardinality()); + } + + protected void setUp() { + + eightbs = new BitSet(); + + for (int i = 0; i < 8; i++) + eightbs.set(i); } + + protected void tearDown() { + } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java index cb4097b..e11d5a3 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java @@ -1,49 +1,505 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -import junit.framework.TestCase; +public class DateTest extends junit.framework.TestCase { + + static class MockDate extends Date{ + private String holiday; -import java.util.Date; + public MockDate(long theTime) { + super(theTime); + holiday = "Christmas"; + } + + // Constructor should not call this public API, + // since it may be overrided to use variables uninitialized. + public void setTime(long theTime){ + super.setTime(theTime); + holiday.hashCode(); + } + } + + /** + * @tests java.util.Date#Date() + */ + public void test_Constructor() { + // Test for method java.util.Date() + GregorianCalendar gc = new GregorianCalendar(1998, Calendar.OCTOBER, + 13, 19, 9); + long oldTime = gc.getTime().getTime(); + long now = new Date().getTime(); + assertTrue("Created incorrect date: " + oldTime + " now: " + now, + oldTime < now); + } + + /** + * @tests java.util.Date#Date(int, int, int) + */ + public void test_ConstructorIII() { + // Test for method java.util.Date(int, int, int) + Date d1 = new Date(70, 0, 1); // the epoch + local time + + // the epoch + local time + Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000); + + assertTrue("Created incorrect date", d1.equals(d2)); + + Date date = new Date(99, 5, 22); + Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 22); + assertTrue("Wrong time zone", date.equals(cal.getTime())); + } + + /** + * @tests java.util.Date#Date(int, int, int, int, int) + */ + public void test_ConstructorIIIII() { + // Test for method java.util.Date(int, int, int, int, int) + + // the epoch + local time + (1 hour and 1 minute) + Date d1 = new Date(70, 0, 1, 1, 1); + + // the epoch + local time + (1 hour and 1 minute) + Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60 + * 1000 + 60 * 1000); + + assertTrue("Created incorrect date", d1.equals(d2)); + } + + /** + * @tests java.util.Date#Date(int, int, int, int, int, int) + */ + public void test_ConstructorIIIIII() { + // Test for method java.util.Date(int, int, int, int, int, int) + + // the epoch + local time + (1 hour and 1 minute + 1 second) + Date d1 = new Date(70, 0, 1, 1, 1, 1); + + // the epoch + local time + (1 hour and 1 minute + 1 second) + Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60 + * 1000 + 60 * 1000 + 1000); + + assertTrue("Created incorrect date", d1.equals(d2)); + } + + /** + * @tests java.util.Date#Date(long) + */ + public void test_ConstructorJ() { + // Test for method java.util.Date(long) + Date date = new MockDate(1000L); + assertNotNull(date); + } + + /** + * @tests java.util.Date#Date(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + // Test for method java.util.Date(java.lang.String) + Date d1 = new Date("January 1, 1970, 00:00:00 GMT"); // the epoch + Date d2 = new Date(0); // the epoch + assertTrue("Created incorrect date", d1.equals(d2)); + + try { + // Regression for HARMONY-238 + new Date(null); + fail("Constructor Date((String)null) should " + + "throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.util.Date#after(java.util.Date) + */ + public void test_afterLjava_util_Date() { + // Test for method boolean java.util.Date.after(java.util.Date) + Date d1 = new Date(0); + Date d2 = new Date(1900000); + assertTrue("Older was returned as newer", d2.after(d1)); + assertTrue("Newer was returned as older", !d1.after(d2)); + } + + /** + * @tests java.util.Date#before(java.util.Date) + */ + public void test_beforeLjava_util_Date() { + // Test for method boolean java.util.Date.before(java.util.Date) + Date d1 = new Date(0); + Date d2 = new Date(1900000); + assertTrue("Older was returned as newer", !d2.before(d1)); + assertTrue("Newer was returned as older", d1.before(d2)); + } + + /** + * @tests java.util.Date#clone() + */ + public void test_clone() { + // Test for method java.lang.Object java.util.Date.clone() + Date d1 = new Date(100000); + Date d2 = (Date) d1.clone(); + assertTrue( + "Cloning date results in same reference--new date is equivalent", + d1 != d2); + assertTrue("Cloning date results unequal date", d1.equals(d2)); + } + + /** + * @tests java.util.Date#compareTo(java.util.Date) + */ + public void test_compareToLjava_util_Date() { + // Test for method int java.util.Date.compareTo(java.util.Date) + final int someNumber = 10000; + Date d1 = new Date(someNumber); + Date d2 = new Date(someNumber); + Date d3 = new Date(someNumber + 1); + Date d4 = new Date(someNumber - 1); + assertEquals("Comparing a date to itself did not answer zero", 0, d1 + .compareTo(d1)); + assertEquals("Comparing equal dates did not answer zero", 0, d1 + .compareTo(d2)); + assertEquals("date1.compareTo(date2), where date1 > date2, did not result in 1", + 1, d1.compareTo(d4)); + assertEquals("date1.compareTo(date2), where date1 < date2, did not result in -1", + -1, d1.compareTo(d3)); + + } + + /** + * @tests java.util.Date#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + // Test for method boolean java.util.Date.equals(java.lang.Object) + Date d1 = new Date(0); + Date d2 = new Date(1900000); + Date d3 = new Date(1900000); + assertTrue("Equality test failed", d2.equals(d3)); + assertTrue("Equality test failed", !d1.equals(d2)); + } + + /** + * @tests java.util.Date#getDate() + */ + public void test_getDate() { + // Test for method int java.util.Date.getDate() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect date", 13, d.getDate()); + } + + /** + * @tests java.util.Date#getDay() + */ + public void test_getDay() { + // Test for method int java.util.Date.getDay() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect day", 2, d.getDay()); + } + + /** + * @tests java.util.Date#getHours() + */ + public void test_getHours() { + // Test for method int java.util.Date.getHours() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect hours", 19, d.getHours()); + } + + /** + * @tests java.util.Date#getMinutes() + */ + public void test_getMinutes() { + // Test for method int java.util.Date.getMinutes() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect minutes", 9, d.getMinutes()); + } -@TestTargetClass(Date.class) -public class DateTest extends TestCase { - - /** - * @tests java.util.Date#parse(String) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Special regression test. Doesn't verify all cases according to the specification.", - method = "parse", - args = {java.lang.String.class} - ) - @SuppressWarnings("deprecation") - public void test_parseLjava_lang_String() { + /** + * @tests java.util.Date#getMonth() + */ + public void test_getMonth() { + // Test for method int java.util.Date.getMonth() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect month", 9, d.getMonth()); + } + + /** + * @tests java.util.Date#getSeconds() + */ + public void test_getSeconds() { + // Test for method int java.util.Date.getSeconds() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect seconds", 0, d.getSeconds()); + } + + /** + * @tests java.util.Date#getTime() + */ + public void test_getTime() { + // Test for method long java.util.Date.getTime() + Date d1 = new Date(0); + Date d2 = new Date(1900000); + assertEquals("Returned incorrect time", 1900000, d2.getTime()); + assertEquals("Returned incorrect time", 0, d1.getTime()); + } + + /** + * @tests java.util.Date#getTimezoneOffset() + */ + public void test_getTimezoneOffset() { + // Test for method int java.util.Date.getTimezoneOffset() + assertTrue("Used to test", true); + } + + /** + * @tests java.util.Date#getYear() + */ + public void test_getYear() { + // Test for method int java.util.Date.getYear() + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + assertEquals("Returned incorrect year", 98, d.getYear()); + } + + /** + * @tests java.util.Date#hashCode() + */ + public void test_hashCode() { + // Test for method int java.util.Date.hashCode() + Date d1 = new Date(0); + Date d2 = new Date(1900000); + assertEquals("Returned incorrect hash", 1900000, d2.hashCode()); + assertEquals("Returned incorrect hash", 0, d1.hashCode()); + } + + /** + * @tests java.util.Date#parse(java.lang.String) + */ + public void test_parseLjava_lang_String() { + // Test for method long java.util.Date.parse(java.lang.String) + Date d = new Date(Date.parse("13 October 1998")); + GregorianCalendar cal = new GregorianCalendar(); + cal.setTime(d); + assertEquals("Parsed incorrect month", 9, cal.get(Calendar.MONTH)); + assertEquals("Parsed incorrect year", 1998, cal.get(Calendar.YEAR)); + assertEquals("Parsed incorrect date", 13, cal.get(Calendar.DATE)); + + d = new Date(Date.parse("Jan-12 1999")); + assertTrue("Wrong parsed date 1", d.equals(new GregorianCalendar(1999, + 0, 12).getTime())); + d = new Date(Date.parse("Jan12-1999")); + assertTrue("Wrong parsed date 2", d.equals(new GregorianCalendar(1999, + 0, 12).getTime())); + d = new Date(Date.parse("Jan12 69-1")); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.clear(); + cal.set(1969, Calendar.JANUARY, 12, 1, 0); + assertTrue("Wrong parsed date 3", d.equals(cal.getTime())); + d = new Date(Date.parse("6:45:13 3/2/1200 MST")); + cal.setTimeZone(TimeZone.getTimeZone("MST")); + cal.clear(); + cal.set(1200, 2, 2, 6, 45, 13); + assertTrue("Wrong parsed date 4", d.equals(cal.getTime())); + d = new Date(Date.parse("Mon, 22 Nov 1999 12:52:06 GMT")); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.clear(); + cal.set(1999, Calendar.NOVEMBER, 22, 12, 52, 06); + assertTrue("Wrong parsed date 5", d.equals(cal.getTime())); + + try { + // Regression for HARMONY-259 + Date.parse(null); + fail("Date.parse(null) should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + // Regression for HARMONY-102 assertEquals("Assert 0: parse failure", -5400000, Date.parse("Sat, 1 Jan 1970 +0130 00:00:00")); assertEquals("Assert 1: parse failure", 858600000, Date.parse("00:00:00 GMT +0130 Sat, 11 Jan 1970")); - } + } + + /** + * @tests java.util.Date#setDate(int) + */ + public void test_setDateI() { + // Test for method void java.util.Date.setDate(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setDate(23); + assertEquals("Set incorrect date", 23, d.getDate()); + } + + /** + * @tests java.util.Date#setHours(int) + */ + public void test_setHoursI() { + // Test for method void java.util.Date.setHours(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setHours(23); + assertEquals("Set incorrect hours", 23, d.getHours()); + } + + /** + * @tests java.util.Date#setMinutes(int) + */ + public void test_setMinutesI() { + // Test for method void java.util.Date.setMinutes(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setMinutes(45); + assertEquals("Set incorrect mins", 45, d.getMinutes()); + } + + /** + * @tests java.util.Date#setMonth(int) + */ + public void test_setMonthI() { + // Test for method void java.util.Date.setMonth(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setMonth(0); + assertEquals("Set incorrect month", 0, d.getMonth()); + } + + /** + * @tests java.util.Date#setSeconds(int) + */ + public void test_setSecondsI() { + // Test for method void java.util.Date.setSeconds(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setSeconds(13); + assertEquals("Set incorrect seconds", 13, d.getSeconds()); + } + + /** + * @tests java.util.Date#setTime(long) + */ + public void test_setTimeJ() { + // Test for method void java.util.Date.setTime(long) + Date d1 = new Date(0); + Date d2 = new Date(1900000); + d1.setTime(900); + d2.setTime(890000); + assertEquals("Returned incorrect time", 890000, d2.getTime()); + assertEquals("Returned incorrect time", 900, d1.getTime()); + } + + /** + * @tests java.util.Date#setYear(int) + */ + public void test_setYearI() { + // Test for method void java.util.Date.setYear(int) + Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) + .getTime(); + d.setYear(8); + assertEquals("Set incorrect year", 8, d.getYear()); + } + + /** + * @tests java.util.Date#toGMTString() + */ + public void test_toGMTString() { + // Test for method java.lang.String java.util.Date.toGMTString() + assertEquals("Did not convert epoch to GMT string correctly", "1 Jan 1970 00:00:00 GMT", new Date(0) + .toGMTString()); + assertEquals("Did not convert epoch + 1yr to GMT string correctly", + "1 Jan 1971 00:00:00 GMT", new Date((long) 365 * 24 * 60 * 60 * 1000).toGMTString() + ); + } + + /** + * @tests java.util.Date#toString() + */ + public void test_toString() { + // Test for method java.lang.String java.util.Date.toString() + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.DATE, 1); + cal.set(Calendar.MONTH, Calendar.JANUARY); + cal.set(Calendar.YEAR, 1970); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + Date d = cal.getTime(); + String result = d.toString(); + assertTrue("Incorrect result: " + d, result + .startsWith("Thu Jan 01 00:00:00") + && result.endsWith("1970")); + + TimeZone tz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("EST")); + try { + Date d1 = new Date(0); + assertTrue("Returned incorrect string: " + d1, d1.toString() + .startsWith("Wed Dec 31 19:00:00") + && d1.toString().endsWith("1969")); + } finally { + TimeZone.setDefault(tz); + } + + // Test for HARMONY-5468 + TimeZone.setDefault(TimeZone.getTimeZone("MST")); + Date d2 = new Date(108, 7, 27); + assertTrue("Returned incorrect string: " + d2, d2.toString() + .startsWith("Wed Aug 27 00:00:00 MST") + && d2.toString().endsWith("2008")); + } + + /** + * @tests java.util.Date#UTC(int, int, int, int, int, int) + */ + public void test_UTCIIIIII() { + // Test for method long java.util.Date.UTC(int, int, int, int, int, int) + assertTrue("Returned incorrect UTC value for epoch", Date.UTC(70, 0, 1, + 0, 0, 0) == (long) 0); + assertTrue("Returned incorrect UTC value for epoch +1yr", Date.UTC(71, + 0, 1, 0, 0, 0) == (long) 365 * 24 * 60 * 60 * 1000); + } + + static TimeZone defaultTimeZone = TimeZone.getDefault(); + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + } + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + TimeZone.setDefault(defaultTimeZone); + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java index e700fff..ff6c08f 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java @@ -16,31 +16,19 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.DuplicateFormatFlagsException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(DuplicateFormatFlagsException.class) public class DuplicateFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.DuplicateFormatFlagsException#DuplicateFormatFlagsException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DuplicateFormatFlagsException", - args = {java.lang.String.class} - ) public void test_duplicateFormatFlagsException() { try { new DuplicateFormatFlagsException(null); @@ -48,19 +36,11 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase { } catch (NullPointerException e) { // desired } - - assertNotNull(new DuplicateFormatFlagsException("String")); } /** * @tests java.util.DuplicateFormatFlagsException#getFlags() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFlags", - args = {} - ) public void test_getFlags() { String strFlags = "MYTESTFLAGS"; DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException( @@ -71,12 +51,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.DuplicateFormatFlagsException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String strFlags = "MYTESTFLAGS"; DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException( @@ -103,12 +77,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new DuplicateFormatFlagsException( @@ -118,12 +86,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new DuplicateFormatFlagsException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java index a76ff54..2ead734 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java @@ -16,32 +16,20 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.FormatFlagsConversionMismatchException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(FormatFlagsConversionMismatchException.class) public class FormatFlagsConversionMismatchExceptionTest extends TestCase { /** * @tests java.util.FormatFlagsConversionMismatchException#FormatFlagsConversionMismatchException(String, * char) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies NullPointerException.", - method = "FormatFlagsConversionMismatchException", - args = {java.lang.String.class, char.class} - ) public void test_formatFlagsConversionMismatchException() { try { new FormatFlagsConversionMismatchException(null, ' '); @@ -50,18 +38,11 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase { // expected } - assertNotNull(new FormatFlagsConversionMismatchException("String", ' ')); } /** * @tests java.util.FormatFlagsConversionMismatchException#getFlags() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFlags", - args = {} - ) public void test_getFlags() { String flags = "MYTESTFLAGS"; char conversion = 'T'; @@ -73,18 +54,10 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase { /** * @tests java.util.FormatFlagsConversionMismatchException#getConversion() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getConversion", - args = {} - ) public void test_getConversion() { String flags = "MYTESTFLAGS"; char conversion = 'T'; - FormatFlagsConversionMismatchException - formatFlagsConversionMismatchException = - new FormatFlagsConversionMismatchException( + FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException( flags, conversion); assertEquals(conversion, formatFlagsConversionMismatchException .getConversion()); @@ -94,12 +67,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase { /** * @tests java.util.FormatFlagsConversionMismatchException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String flags = "MYTESTFLAGS"; char conversion = 'T'; @@ -129,12 +96,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf( @@ -145,12 +106,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java index 97273f4..1f7e2e9 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java @@ -16,30 +16,17 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.util.FormatterClosedException; import junit.framework.TestCase; -import java.util.FormatterClosedException; - import org.apache.harmony.testframework.serialization.SerializationTest; -import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(FormatterClosedException.class) public class FormatterClosedExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new FormatterClosedException()); @@ -48,24 +35,8 @@ public class FormatterClosedExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new FormatterClosedException()); } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "FormatterClosedException", - args = {} - ) - public void test_constructor() { - assertNotNull(new FormatterClosedException()); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java index 5a2ec99..5468914 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java @@ -13,60 +13,4321 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.io.BufferedOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilePermission; +import java.io.Flushable; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.nio.charset.Charset; +import java.security.Permission; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.DuplicateFormatFlagsException; +import java.util.FormatFlagsConversionMismatchException; +import java.util.Formattable; +import java.util.FormattableFlags; +import java.util.Formatter; +import java.util.FormatterClosedException; +import java.util.IllegalFormatCodePointException; +import java.util.IllegalFormatConversionException; +import java.util.IllegalFormatException; +import java.util.IllegalFormatFlagsException; +import java.util.IllegalFormatPrecisionException; +import java.util.IllegalFormatWidthException; +import java.util.Locale; +import java.util.MissingFormatArgumentException; +import java.util.MissingFormatWidthException; +import java.util.TimeZone; +import java.util.UnknownFormatConversionException; +import java.util.Formatter.BigDecimalLayoutForm; import junit.framework.TestCase; -import java.util.Formatter.BigDecimalLayoutForm; - -@TestTargetClass(java.util. Formatter.BigDecimalLayoutForm.class) public class FormatterTest extends TestCase { + private boolean root; + + class MockAppendable implements Appendable { + public Appendable append(CharSequence arg0) throws IOException { + return null; + } + + public Appendable append(char arg0) throws IOException { + return null; + } + + public Appendable append(CharSequence arg0, int arg1, int arg2) + throws IOException { + return null; + } + } + + class MockSecurityManager extends SecurityManager { + public void checkPermission(Permission p) { + if (p.getActions().equals("write") && p instanceof FilePermission) { + throw new SecurityException("Always throw security exception"); + } + } + + public void checkPermission(Permission p, Object ctx) { + checkPermission(p); + } + } + + class MockFormattable implements Formattable { + public void formatTo(Formatter formatter, int flags, int width, + int precision) throws IllegalFormatException { + if ((flags & FormattableFlags.UPPERCASE) != 0) { + formatter.format("CUSTOMIZED FORMAT FUNCTION" + " WIDTH: " + + width + " PRECISION: " + precision); + } else { + formatter.format("customized format function" + " width: " + + width + " precision: " + precision); + } + } + + public String toString() { + return "formattable object"; + } + + public int hashCode() { + return 0xf; + } + } + + class MockDestination implements Appendable, Flushable { + + private StringBuilder data = new StringBuilder(); + + private boolean enabled = false; + + public Appendable append(char c) throws IOException { + if (enabled) { + data.append(c); + enabled = true; // enable it after the first append + } else { + throw new IOException(); + } + return this; + } + + public Appendable append(CharSequence csq) throws IOException { + if (enabled) { + data.append(csq); + enabled = true; // enable it after the first append + } else { + throw new IOException(); + } + return this; + } + + public Appendable append(CharSequence csq, int start, int end) + throws IOException { + if (enabled) { + data.append(csq, start, end); + enabled = true; // enable it after the first append + } else { + throw new IOException(); + } + return this; + } + + public void flush() throws IOException { + throw new IOException("Always throw IOException"); + } + + public String toString() { + return data.toString(); + } + } + + private File notExist; + + private File fileWithContent; + + private File readOnly; + + private File secret; + + private TimeZone defaultTimeZone; + + /** + * @tests java.util.Formatter#Formatter() + */ + public void test_Constructor() { + Formatter f = new Formatter(); + assertNotNull(f); + assertTrue(f.out() instanceof StringBuilder); + assertEquals(f.locale(), Locale.getDefault()); + assertNotNull(f.toString()); + } + + /** + * @tests java.util.Formatter#Formatter(Appendable) + */ + public void test_ConstructorLjava_lang_Appendable() { + MockAppendable ma = new MockAppendable(); + Formatter f1 = new Formatter(ma); + assertEquals(ma, f1.out()); + assertEquals(f1.locale(), Locale.getDefault()); + assertNotNull(f1.toString()); + + Formatter f2 = new Formatter((Appendable) null); + /* + * If a(the input param) is null then a StringBuilder will be created + * and the output can be attained by invoking the out() method. But RI + * raises an error of FormatterClosedException when invoking out() or + * toString(). + */ + Appendable sb = f2.out(); + assertTrue(sb instanceof StringBuilder); + assertNotNull(f2.toString()); + } + + /** + * @tests java.util.Formatter#Formatter(Locale) + */ + public void test_ConstructorLjava_util_Locale() { + Formatter f1 = new Formatter(Locale.FRANCE); + assertTrue(f1.out() instanceof StringBuilder); + assertEquals(f1.locale(), Locale.FRANCE); + assertNotNull(f1.toString()); + + Formatter f2 = new Formatter((Locale) null); + assertNull(f2.locale()); + assertTrue(f2.out() instanceof StringBuilder); + assertNotNull(f2.toString()); + } + + /** + * @tests java.util.Formatter#Formatter(Appendable, Locale) + */ + public void test_ConstructorLjava_lang_AppendableLjava_util_Locale() { + MockAppendable ma = new MockAppendable(); + Formatter f1 = new Formatter(ma, Locale.CANADA); + assertEquals(ma, f1.out()); + assertEquals(f1.locale(), Locale.CANADA); + + Formatter f2 = new Formatter(ma, null); + assertNull(f2.locale()); + assertEquals(ma, f1.out()); + + Formatter f3 = new Formatter(null, Locale.GERMAN); + assertEquals(f3.locale(), Locale.GERMAN); + assertTrue(f3.out() instanceof StringBuilder); + } + + /** + * @tests java.util.Formatter#Formatter(String) + */ + public void test_ConstructorLjava_lang_String() throws IOException { + Formatter f = null; + try { + f = new Formatter((String) null); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + f = new Formatter(notExist.getPath()); + assertEquals(f.locale(), Locale.getDefault()); + f.close(); + + f = new Formatter(fileWithContent.getPath()); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly.getPath()); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret.getPath()); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + } + + /** + * @tests java.util.Formatter#Formatter(String, String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_String() + throws IOException { + Formatter f = null; + try { + f = new Formatter((String) null, Charset.defaultCharset().name()); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + try { + f = new Formatter(notExist.getPath(), null); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } + + f = new Formatter(notExist.getPath(), Charset.defaultCharset().name()); + assertEquals(f.locale(), Locale.getDefault()); + f.close(); + + try { + f = new Formatter(notExist.getPath(), "ISO 1111-1"); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } + + f = new Formatter(fileWithContent.getPath(), "UTF-16BE"); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly.getPath(), "UTF-16BE"); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret.getPath(), "UTF-16BE"); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + } /** + * @tests java.util.Formatter#Formatter(String, String, Locale) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_util_Locale() + throws IOException { + Formatter f = null; + try { + f = new Formatter((String) null, Charset.defaultCharset().name(), + Locale.KOREA); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + try { + f = new Formatter(notExist.getPath(), null, Locale.KOREA); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } + + f = new Formatter(notExist.getPath(), Charset.defaultCharset().name(), + null); + assertNotNull(f); + f.close(); + + f = new Formatter(notExist.getPath(), Charset.defaultCharset().name(), + Locale.KOREA); + assertEquals(f.locale(), Locale.KOREA); + f.close(); + + try { + f = new Formatter(notExist.getPath(), "ISO 1111-1", Locale.CHINA); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } + + f = new Formatter(fileWithContent.getPath(), "UTF-16BE", + Locale.CANADA_FRENCH); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly.getPath(), Charset.defaultCharset() + .name(), Locale.ITALY); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret.getPath(), + Charset.defaultCharset().name(), Locale.SIMPLIFIED_CHINESE); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + } + + /** + * @tests java.util.Formatter#Formatter(File) + */ + public void test_ConstructorLjava_io_File() throws IOException { + Formatter f = null; + try { + f = new Formatter((File) null); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + f = new Formatter(notExist); + assertEquals(f.locale(), Locale.getDefault()); + f.close(); + + f = new Formatter(fileWithContent); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + } + + /** + * @tests java.util.Formatter#Formatter(File, String) + */ + public void test_ConstructorLjava_io_FileLjava_lang_String() + throws IOException { + Formatter f = null; + try { + f = new Formatter((File) null, Charset.defaultCharset().name()); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + f = new Formatter(notExist, Charset.defaultCharset().name()); + assertEquals(f.locale(), Locale.getDefault()); + f.close(); + + f = new Formatter(fileWithContent, "UTF-16BE"); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly, Charset.defaultCharset().name()); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret, Charset.defaultCharset().name()); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + + try { + f = new Formatter(notExist, null); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } finally { + if (notExist.exists()) { + // Fail on RI on Windows, because output stream is created and + // not closed when exception thrown + assertTrue(notExist.delete()); + } + } + + try { + f = new Formatter(notExist, "ISO 1111-1"); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } finally { + if (notExist.exists()) { + // Fail on RI on Windows, because output stream is created and + // not closed when exception thrown + assertTrue(notExist.delete()); + } + } + } + + /** + * @tests java.util.Formatter#Formatter(File, String, Locale) + */ + public void test_ConstructorLjava_io_FileLjava_lang_StringLjava_util_Locale() + throws IOException { + Formatter f = null; + try { + f = new Formatter((File) null, Charset.defaultCharset().name(), + Locale.KOREA); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + try { + f = new Formatter(notExist, null, Locale.KOREA); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } + + f = new Formatter(notExist, Charset.defaultCharset().name(), null); + assertNotNull(f); + f.close(); + + f = new Formatter(notExist, Charset.defaultCharset().name(), + Locale.KOREA); + assertEquals(f.locale(), Locale.KOREA); + f.close(); + + try { + f = new Formatter(notExist, "ISO 1111-1", Locale.CHINA); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } + f = new Formatter(fileWithContent.getPath(), "UTF-16BE", + Locale.CANADA_FRENCH); + assertEquals(0, fileWithContent.length()); + f.close(); + + if(!root){ + try { + f = new Formatter(readOnly.getPath(), Charset.defaultCharset() + .name(), Locale.ITALY); + fail("should throw FileNotFoundException"); + } catch (FileNotFoundException e) { + // expected + } + } + + SecurityManager oldsm = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + try { + f = new Formatter(secret.getPath(), + Charset.defaultCharset().name(), Locale.SIMPLIFIED_CHINESE); + fail("should throw SecurityException"); + } catch (SecurityException se) { + // expected + } finally { + System.setSecurityManager(oldsm); + } + } + + /** + * @tests java.util.Formatter#Formatter(PrintStream) + */ + public void test_ConstructorLjava_io_PrintStream() throws IOException { + Formatter f = null; + try { + f = new Formatter((PrintStream) null); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + PrintStream ps = new PrintStream(notExist, "UTF-16BE"); + f = new Formatter(ps); + assertEquals(Locale.getDefault(), f.locale()); + f.close(); + } + + /** + * @tests java.util.Formatter#Formatter(OutputStream) + */ + public void test_ConstructorLjava_io_OutputStream() throws IOException { + Formatter f = null; + try { + f = new Formatter((OutputStream) null); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + OutputStream os = new FileOutputStream(notExist); + f = new Formatter(os); + assertEquals(Locale.getDefault(), f.locale()); + f.close(); + } + + /** + * @tests java.util.Formatter#Formatter(OutputStream, String) + */ + public void test_ConstructorLjava_io_OutputStreamLjava_lang_String() + throws IOException { + Formatter f = null; + try { + f = new Formatter((OutputStream) null, Charset.defaultCharset() + .name()); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + OutputStream os = null; + try { + os = new FileOutputStream(notExist); + f = new Formatter(os, null); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } finally { + os.close(); + } + + try { + os = new PipedOutputStream(); + f = new Formatter(os, "TMP-1111"); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } finally { + os.close(); + } + + os = new FileOutputStream(fileWithContent); + f = new Formatter(os, "UTF-16BE"); + assertEquals(Locale.getDefault(), f.locale()); + f.close(); + } + + /** + * Test method for 'java.util.Formatter.Formatter(OutputStream, String, + * Locale) + */ + public void test_ConstructorLjava_io_OutputStreamLjava_lang_StringLjava_util_Locale() + throws IOException { + Formatter f = null; + try { + f = new Formatter((OutputStream) null, Charset.defaultCharset() + .name(), Locale.getDefault()); + fail("should throw NullPointerException"); + } catch (NullPointerException e1) { + // expected + } + + OutputStream os = null; + try { + os = new FileOutputStream(notExist); + f = new Formatter(os, null, Locale.getDefault()); + fail("should throw NullPointerException"); + } catch (NullPointerException e2) { + // expected + } finally { + os.close(); + } + + os = new FileOutputStream(notExist); + f = new Formatter(os, Charset.defaultCharset().name(), null); + f.close(); + + try { + os = new PipedOutputStream(); + f = new Formatter(os, "TMP-1111", Locale.getDefault()); + fail("should throw UnsupportedEncodingException"); + } catch (UnsupportedEncodingException e1) { + // expected + } + + os = new FileOutputStream(fileWithContent); + f = new Formatter(os, "UTF-16BE", Locale.ENGLISH); + assertEquals(Locale.ENGLISH, f.locale()); + f.close(); + } + + /** + * @tests java.util.Formatter#locale() + */ + public void test_locale() { + Formatter f = null; + f = new Formatter((Locale) null); + assertNull(f.locale()); + + f.close(); + try { + f.locale(); + fail("should throw FormatterClosedException"); + } catch (FormatterClosedException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#out() + */ + public void test_out() { + Formatter f = null; + f = new Formatter(); + assertNotNull(f.out()); + assertTrue(f.out() instanceof StringBuilder); + f.close(); + try { + f.out(); + fail("should throw FormatterClosedException"); + } catch (FormatterClosedException e) { + // expected + } + + } + + /** + * @tests java.util.Formatter#flush() + */ + public void test_flush() throws IOException { + Formatter f = null; + f = new Formatter(notExist); + assertTrue(f instanceof Flushable); + f.close(); + try { + f.flush(); + fail("should throw FormatterClosedException"); + } catch (FormatterClosedException e) { + // expected + } + + f = new Formatter(); + // For destination that does not implement Flushable + // No exception should be thrown + f.flush(); + } + + /** + * @tests java.util.Formatter#close() + */ + public void test_close() throws IOException { + Formatter f = new Formatter(notExist); + assertTrue(f instanceof Closeable); + f.close(); + // close next time will not throw exception + f.close(); + assertNull(f.ioException()); + } + + /** + * @tests java.util.Formatter#toString() + */ + public void test_toString() { + Formatter f = new Formatter(); + assertNotNull(f.toString()); + assertEquals(f.out().toString(), f.toString()); + f.close(); + try { + f.toString(); + fail("should throw FormatterClosedException"); + } catch (FormatterClosedException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#ioException() + */ + public void test_ioException() throws IOException { + Formatter f = null; + f = new Formatter(new MockDestination()); + assertNull(f.ioException()); + f.flush(); + assertNotNull(f.ioException()); + f.close(); + + MockDestination md = new MockDestination(); + f = new Formatter(md); + f.format("%s%s", "1", "2"); + // format stop working after IOException + assertNotNull(f.ioException()); + assertEquals("", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for null parameter + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_null() { + Formatter f = new Formatter(); + try { + f.format((String) null, "parameter"); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + f = new Formatter(); + f.format("hello", (Object[]) null); + assertEquals("hello", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for argument index + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_ArgIndex() { + Formatter formatter = new Formatter(Locale.US); + formatter.format("%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%11$s%10$s", "1", + "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"); + assertEquals("1234567891110", formatter.toString()); + + formatter = new Formatter(Locale.JAPAN); + formatter.format("%0$s", "hello"); + assertEquals("hello", formatter.toString()); + + try { + formatter = new Formatter(Locale.US); + formatter.format("%-1$s", "1", "2"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + try { + formatter = new Formatter(Locale.US); + formatter.format("%$s", "hello", "2"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + try { + Formatter f = new Formatter(Locale.US); + f.format("%", "string"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + formatter = new Formatter(Locale.FRANCE); + formatter.format("%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%<s%s%s%<s", "1", + "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"); + assertEquals("123456788122", formatter.toString()); + + formatter = new Formatter(Locale.FRANCE); + formatter.format( + "xx%1$s22%2$s%s%<s%5$s%<s&%7$h%2$s%8$s%<s%s%s%<ssuffix", "1", + "2", "3", "4", "5", "6", 7, "8", "9", "10", "11"); + assertEquals("xx12221155&7288233suffix", formatter.toString()); + + try { + formatter.format("%<s", "hello"); + fail("should throw MissingFormatArgumentException"); + } catch (MissingFormatArgumentException e) { + // expected + } + + formatter = new Formatter(Locale.US); + try { + formatter.format("%123$s", "hello"); + fail("should throw MissingFormatArgumentException"); + } catch (MissingFormatArgumentException e) { + // expected + } + + formatter = new Formatter(Locale.US); + try { + // 2147483648 is the value of Integer.MAX_VALUE + 1 + formatter.format("%2147483648$s", "hello"); + fail("should throw MissingFormatArgumentException"); + } catch (MissingFormatArgumentException e) { + // expected + } + + try { + // 2147483647 is the value of Integer.MAX_VALUE + formatter.format("%2147483647$s", "hello"); + fail("should throw MissingFormatArgumentException"); + } catch (MissingFormatArgumentException e) { + // expected + } + + formatter = new Formatter(Locale.US); + try { + formatter.format("%s%s", "hello"); + fail("should throw MissingFormatArgumentException"); + } catch (MissingFormatArgumentException e) { + // expected + } + + formatter = new Formatter(Locale.US); + formatter.format("$100", 100); + assertEquals("$100", formatter.toString()); + + formatter = new Formatter(Locale.UK); + formatter.format("%01$s", "string"); + assertEquals("string", formatter.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for width + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_Width() { + Formatter f = new Formatter(Locale.US); + f.format("%1$8s", "1"); + assertEquals(" 1", f.toString()); + + f = new Formatter(Locale.US); + f.format("%1$-1%", "string"); + assertEquals("%", f.toString()); + + f = new Formatter(Locale.ITALY); + // 2147483648 is the value of Integer.MAX_VALUE + 1 + f.format("%2147483648s", "string"); + assertEquals("string", f.toString()); + + // the value of Integer.MAX_VALUE will allocate about 4G bytes of + // memory. + // It may cause OutOfMemoryError, so this value is not tested + } + + /** + * @tests java.util.Formatter#format(String, Object...) for precision + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_Precision() { + Formatter f = new Formatter(Locale.US); + f.format("%.5s", "123456"); + assertEquals("12345", f.toString()); + + f = new Formatter(Locale.US); + // 2147483648 is the value of Integer.MAX_VALUE + 1 + f.format("%.2147483648s", "..."); + assertEquals("...", f.toString()); + + // the value of Integer.MAX_VALUE will allocate about 4G bytes of + // memory. + // It may cause OutOfMemoryError, so this value is not tested + + f = new Formatter(Locale.US); + f.format("%10.0b", Boolean.TRUE); + assertEquals(" ", f.toString()); + + f = new Formatter(Locale.US); + f.format("%10.01s", "hello"); + assertEquals(" h", f.toString()); + + try { + f = new Formatter(Locale.US); + f.format("%.s", "hello", "2"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + try { + f = new Formatter(Locale.US); + f.format("%.-5s", "123456"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + try { + f = new Formatter(Locale.US); + f.format("%1.s", "hello", "2"); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + f = new Formatter(Locale.US); + f.format("%5.1s", "hello"); + assertEquals(" h", f.toString()); + + f = new Formatter(Locale.FRANCE); + f.format("%.0s", "hello", "2"); + assertEquals("", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for line sperator + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_LineSeparator() { + Formatter f = null; + + String oldSeparator = System.getProperty("line.separator"); + System.setProperty("line.separator", "!\n"); + + f = new Formatter(Locale.US); + f.format("%1$n", 1); + assertEquals("!\n", f.toString()); + + f = new Formatter(Locale.KOREAN); + f.format("head%1$n%2$n", 1, new Date()); + assertEquals("head!\n!\n", f.toString()); + + f = new Formatter(Locale.US); + f.format("%n%s", "hello"); + assertEquals("!\nhello", f.toString()); + + System.setProperty("line.separator", oldSeparator); + + f = new Formatter(Locale.US); + try { + f.format("%-n"); + fail("should throw IllegalFormatFlagsException: %-n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("%+n"); + fail("should throw IllegalFormatFlagsException: %+n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("%#n"); + fail("should throw IllegalFormatFlagsException: %#n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("% n"); + fail("should throw IllegalFormatFlagsException: % n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("%0n"); + fail("should throw IllegalFormatFlagsException: %0n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("%,n"); + fail("should throw IllegalFormatFlagsException: %,n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + try { + f.format("%(n"); + fail("should throw IllegalFormatFlagsException: %(n"); + } catch (IllegalFormatFlagsException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%4n"); + fail("should throw IllegalFormatWidthException"); + } catch (IllegalFormatWidthException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%-4n"); + fail("should throw IllegalFormatWidthException"); + } catch (IllegalFormatWidthException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%.9n"); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%5.9n"); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + System.setProperty("line.separator", oldSeparator); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for percent + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_Percent() { + Formatter f = null; + + f = new Formatter(Locale.ENGLISH); + f.format("%1$%", 100); + assertEquals("%", f.toString()); + + f = new Formatter(Locale.CHINA); + f.format("%1$%%%", "hello", new Object()); + assertEquals("%%", f.toString()); + + f = new Formatter(Locale.CHINA); + f.format("%%%s", "hello"); + assertEquals("%hello", f.toString()); + + f = new Formatter(Locale.US); + try { + f.format("%.9%"); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%5.9%"); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + f = new Formatter(Locale.US); + assertFormatFlagsConversionMismatchException(f, "%+%"); + assertFormatFlagsConversionMismatchException(f, "%#%"); + assertFormatFlagsConversionMismatchException(f, "% %"); + assertFormatFlagsConversionMismatchException(f, "%0%"); + assertFormatFlagsConversionMismatchException(f, "%,%"); + assertFormatFlagsConversionMismatchException(f, "%(%"); + + + f = new Formatter(Locale.KOREAN); + f.format("%4%", 1); + /* + * fail on RI the output string should be right justified by appending + * spaces till the whole string is 4 chars width. + */ + assertEquals(" %", f.toString()); + + f = new Formatter(Locale.US); + f.format("%-4%", 100); + /* + * fail on RI, throw UnknownFormatConversionException the output string + * should be left justified by appending spaces till the whole string is + * 4 chars width. + */ + assertEquals("% ", f.toString()); + } + + private void assertFormatFlagsConversionMismatchException(Formatter f, String str) { + try { + f.format(str); + fail("should throw FormatFlagsConversionMismatchException: " + + str); + /* + * error on RI, throw IllegalFormatFlagsException specification + * says FormatFlagsConversionMismatchException should be thrown + */ + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for flag + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_Flag() { + Formatter f = new Formatter(Locale.US); + try { + f.format("%1$-#-8s", "something"); + fail("should throw DuplicateFormatFlagsException"); + } catch (DuplicateFormatFlagsException e) { + // expected + } + + final char[] chars = { '-', '#', '+', ' ', '0', ',', '(', '%', '<' }; + Arrays.sort(chars); + f = new Formatter(Locale.US); + for (char i = 0; i <= 256; i++) { + // test 8 bit character + if (Arrays.binarySearch(chars, i) >= 0 || Character.isDigit(i) + || Character.isLetter(i)) { + // Do not test 0-9, a-z, A-Z and characters in the chars array. + // They are characters used as flags, width or conversions + continue; + } + try { + f.format("%" + i + "s", 1); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for general + * conversion b/B + */ + public void test_format_LString$LObject_GeneralConversionB() { + final Object[][] triple = { + { Boolean.FALSE, "%3.2b", " fa", }, + { Boolean.FALSE, "%-4.6b", "false", }, + { Boolean.FALSE, "%.2b", "fa", }, + { Boolean.TRUE, "%3.2b", " tr", }, + { Boolean.TRUE, "%-4.6b", "true", }, + { Boolean.TRUE, "%.2b", "tr", }, + { new Character('c'), "%3.2b", " tr", }, + { new Character('c'), "%-4.6b", "true", }, + { new Character('c'), "%.2b", "tr", }, + { new Byte((byte) 0x01), "%3.2b", " tr", }, + { new Byte((byte) 0x01), "%-4.6b", "true", }, + { new Byte((byte) 0x01), "%.2b", "tr", }, + { new Short((short) 0x0001), "%3.2b", " tr", }, + { new Short((short) 0x0001), "%-4.6b", "true", }, + { new Short((short) 0x0001), "%.2b", "tr", }, + { new Integer(1), "%3.2b", " tr", }, + { new Integer(1), "%-4.6b", "true", }, + { new Integer(1), "%.2b", "tr", }, + { new Float(1.1f), "%3.2b", " tr", }, + { new Float(1.1f), "%-4.6b", "true", }, + { new Float(1.1f), "%.2b", "tr", }, + { new Double(1.1d), "%3.2b", " tr", }, + { new Double(1.1d), "%-4.6b", "true", }, + { new Double(1.1d), "%.2b", "tr", }, + { "", "%3.2b", " tr", }, + { "", "%-4.6b", "true", }, + { "", "%.2b", "tr", }, + { "string content", "%3.2b", " tr", }, + { "string content", "%-4.6b", "true", }, + { "string content", "%.2b", "tr", }, + { new MockFormattable(), "%3.2b", " tr", }, + { new MockFormattable(), "%-4.6b", "true", }, + { new MockFormattable(), "%.2b", "tr", }, + { (Object) null, "%3.2b", " fa", }, + { (Object) null, "%-4.6b", "false", }, + { (Object) null, "%.2b", "fa", }, + }; + + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f = null; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.FRANCE); + f.format((String)triple[i][pattern], triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + + ",pattern[" + i + "]:" + triple[i][pattern], triple[i][output], f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(((String)triple[i][pattern]).toUpperCase(Locale.US), triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + + ",pattern[" + i + "]:" + triple[i][pattern], ((String)triple[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for general + * conversion type 's' and 'S' + */ + public void test_format_LString$LObject_GeneralConversionS() { + + final Object[][] triple = { + { Boolean.FALSE, "%2.3s", "fal", }, + { Boolean.FALSE, "%-6.4s", "fals ", }, + { Boolean.FALSE, "%.5s", "false", }, + { Boolean.TRUE, "%2.3s", "tru", }, + { Boolean.TRUE, "%-6.4s", "true ", }, + { Boolean.TRUE, "%.5s", "true", }, + { new Character('c'), "%2.3s", " c", }, + { new Character('c'), "%-6.4s", "c ", }, + { new Character('c'), "%.5s", "c", }, + { new Byte((byte) 0x01), "%2.3s", " 1", }, + { new Byte((byte) 0x01), "%-6.4s", "1 ", }, + { new Byte((byte) 0x01), "%.5s", "1", }, + { new Short((short) 0x0001), "%2.3s", " 1", }, + { new Short((short) 0x0001), "%-6.4s", "1 ", }, + { new Short((short) 0x0001), "%.5s", "1", }, + { new Integer(1), "%2.3s", " 1", }, + { new Integer(1), "%-6.4s", "1 ", }, + { new Integer(1), "%.5s", "1", }, + { new Float(1.1f), "%2.3s", "1.1", }, + { new Float(1.1f), "%-6.4s", "1.1 ", }, + { new Float(1.1f), "%.5s", "1.1", }, + { new Double(1.1d), "%2.3s", "1.1", }, + { new Double(1.1d), "%-6.4s", "1.1 ", }, + { new Double(1.1d), "%.5s", "1.1", }, + { "", "%2.3s", " ", }, + { "", "%-6.4s", " ", }, + { "", "%.5s", "", }, + { "string content", "%2.3s", "str", }, + { "string content", "%-6.4s", "stri ", }, + { "string content", "%.5s", "strin", }, + { new MockFormattable(), "%2.3s", "customized format function width: 2 precision: 3", }, + { new MockFormattable(), "%-6.4s", "customized format function width: 6 precision: 4", }, + { new MockFormattable(), "%.5s", "customized format function width: -1 precision: 5", }, + { (Object) null, "%2.3s", "nul", }, + { (Object) null, "%-6.4s", "null ", }, + { (Object) null, "%.5s", "null", }, + }; + + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f = null; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.FRANCE); + f.format((String)triple[i][pattern], triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + + ",pattern[" + i + "]:" + triple[i][pattern], triple[i][output], f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(((String)triple[i][pattern]).toUpperCase(Locale.US), triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + + ",pattern[" + i + "]:" + triple[i][pattern], ((String)triple[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for general + * conversion type 'h' and 'H' + */ + public void test_format_LString$LObject_GeneralConversionH() { + + final Object[] input = { + Boolean.FALSE, + Boolean.TRUE, + new Character('c'), + new Byte((byte) 0x01), + new Short((short) 0x0001), + new Integer(1), + new Float(1.1f), + new Double(1.1d), + "", + "string content", + new MockFormattable(), + (Object) null, + }; + + Formatter f = null; + for (int i = 0; i < input.length - 1; i++) { + f = new Formatter(Locale.FRANCE); + f.format("%h", input[i]); + assertEquals("triple[" + i + "]:" + input[i], + Integer.toHexString(input[i].hashCode()), f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%H", input[i]); + assertEquals("triple[" + i + "]:" + input[i], + Integer.toHexString(input[i].hashCode()).toUpperCase(Locale.US), f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for general + * conversion other cases + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_GeneralConversionOther() { + /* + * In Turkish locale, the upper case of '\u0069' is '\u0130'. The + * following test indicate that '\u0069' is coverted to upper case + * without using the turkish locale. + */ + Formatter f = new Formatter(new Locale("tr")); + f.format("%S", "\u0069"); + assertEquals("\u0049", f.toString()); + + final Object[] input = { + Boolean.FALSE, + Boolean.TRUE, + new Character('c'), + new Byte((byte) 0x01), + new Short((short) 0x0001), + new Integer(1), + new Float(1.1f), + new Double(1.1d), + "", + "string content", + new MockFormattable(), + (Object) null, + }; + f = new Formatter(Locale.GERMAN); + for (int i = 0; i < input.length; i++) { + if (!(input[i] instanceof Formattable)) { + try { + f.format("%#s", input[i]); + /* + * fail on RI, spec says if the '#' flag is present and the + * argument is not a Formattable , then a + * FormatFlagsConversionMismatchException will be thrown. + */ + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + } else { + f.format("%#s%<-#8s", input[i]); + assertEquals( + "customized format function width: -1 precision: -1customized format function width: 8 precision: -1", + f.toString()); + } + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for general + * conversion exception + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_GeneralConversionException() { + final String[] flagMismatch = { "%#b", "%+b", "% b", "%0b", "%,b", + "%(b", "%#B", "%+B", "% B", "%0B", "%,B", "%(B", "%#h", "%+h", + "% h", "%0h", "%,h", "%(h", "%#H", "%+H", "% H", "%0H", "%,H", + "%(H", "%+s", "% s", "%0s", "%,s", "%(s", "%+S", "% S", "%0S", + "%,S", "%(S" }; + + Formatter f = new Formatter(Locale.US); + + for (int i = 0; i < flagMismatch.length; i++) { + try { + f.format(flagMismatch[i], "something"); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + } + + final String[] missingWidth = { "%-b", "%-B", "%-h", "%-H", "%-s", + "%-S", }; + for (int i = 0; i < missingWidth.length; i++) { + try { + f.format(missingWidth[i], "something"); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + } + + // Regression test + f = new Formatter(); + try { + f.format("%c", (byte)-0x0001); + fail("Should throw IllegalFormatCodePointException"); + } catch (IllegalFormatCodePointException e) { + // expected + } + + f = new Formatter(); + try { + f.format("%c", (short)-0x0001); + fail("Should throw IllegalFormatCodePointException"); + } catch (IllegalFormatCodePointException e) { + // expected + } + + f = new Formatter(); + try { + f.format("%c", -0x0001); + fail("Should throw IllegalFormatCodePointException"); + } catch (IllegalFormatCodePointException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Character + * conversion + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_CharacterConversion() { + Formatter f = new Formatter(Locale.US); + final Object[] illArgs = { Boolean.TRUE, new Float(1.1f), + new Double(1.1d), "string content", new Float(1.1f), new Date() }; + for (int i = 0; i < illArgs.length; i++) { + try { + f.format("%c", illArgs[i]); + fail("should throw IllegalFormatConversionException"); + } catch (IllegalFormatConversionException e) { + // expected + } + } + + try { + f.format("%c", Integer.MAX_VALUE); + fail("should throw IllegalFormatCodePointException"); + } catch (IllegalFormatCodePointException e) { + // expected + } + + try { + f.format("%#c", 'c'); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + + final Object[][] triple = { + {'c', "%c", "c"}, + {'c', "%-2c", "c "}, + {'\u0123', "%c", "\u0123"}, + {'\u0123', "%-2c", "\u0123 "}, + {(byte) 0x11, "%c", "\u0011"}, + {(byte) 0x11, "%-2c", "\u0011 "}, + {(short) 0x1111, "%c", "\u1111"}, + {(short) 0x1111, "%-2c", "\u1111 "}, + {0x11, "%c", "\u0011"}, + {0x11, "%-2c", "\u0011 "}, + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.US); + f.format((String)triple[i][pattern], triple[i][input]); + assertEquals(triple[i][output], f.toString()); + } + + f = new Formatter(Locale.US); + f.format("%c", 0x10000); + assertEquals(0x10000, f.toString().codePointAt(0)); + + try { + f.format("%2.2c", 'c'); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + f = new Formatter(Locale.US); + f.format("%C", 'w'); + // error on RI, throw UnknownFormatConversionException + // RI do not support converter 'C' + assertEquals("W", f.toString()); + + f = new Formatter(Locale.JAPAN); + f.format("%Ced", 0x1111); + // error on RI, throw UnknownFormatConversionException + // RI do not support converter 'C' + assertEquals("\u1111ed", f.toString()); + } + + + + /** + * @tests java.util.Formatter#format(String, Object...) for legal + * Byte/Short/Integer/Long conversion type 'd' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionD() { + final Object[][] triple = { + { 0, "%d", "0" }, + { 0, "%10d", " 0" }, + { 0, "%-1d", "0" }, + { 0, "%+d", "+0" }, + { 0, "% d", " 0" }, + { 0, "%,d", "0" }, + { 0, "%(d", "0" }, + { 0, "%08d", "00000000" }, + { 0, "%-+,(11d", "+0 " }, + { 0, "%0 ,(11d", " 0000000000" }, + + { (byte) 0xff, "%d", "-1" }, + { (byte) 0xff, "%10d", " -1" }, + { (byte) 0xff, "%-1d", "-1" }, + { (byte) 0xff, "%+d", "-1" }, + { (byte) 0xff, "% d", "-1" }, + { (byte) 0xff, "%,d", "-1" }, + { (byte) 0xff, "%(d", "(1)" }, + { (byte) 0xff, "%08d", "-0000001" }, + { (byte) 0xff, "%-+,(11d", "(1) " }, + { (byte) 0xff, "%0 ,(11d", "(000000001)" }, + + { (short) 0xf123, "%d", "-3805" }, + { (short) 0xf123, "%10d", " -3805" }, + { (short) 0xf123, "%-1d", "-3805" }, + { (short) 0xf123, "%+d", "-3805" }, + { (short) 0xf123, "% d", "-3805" }, + { (short) 0xf123, "%,d", "-3.805" }, + { (short) 0xf123, "%(d", "(3805)" }, + { (short) 0xf123, "%08d", "-0003805" }, + { (short) 0xf123, "%-+,(11d", "(3.805) " }, + { (short) 0xf123, "%0 ,(11d", "(00003.805)" }, + + { 0x123456, "%d", "1193046" }, + { 0x123456, "%10d", " 1193046" }, + { 0x123456, "%-1d", "1193046" }, + { 0x123456, "%+d", "+1193046" }, + { 0x123456, "% d", " 1193046" }, + { 0x123456, "%,d", "1.193.046" }, + { 0x123456, "%(d", "1193046" }, + { 0x123456, "%08d", "01193046" }, + { 0x123456, "%-+,(11d", "+1.193.046 " }, + { 0x123456, "%0 ,(11d", " 01.193.046" }, + + { -3, "%d", "-3" }, + { -3, "%10d", " -3" }, + { -3, "%-1d", "-3" }, + { -3, "%+d", "-3" }, + { -3, "% d", "-3" }, + { -3, "%,d", "-3" }, + { -3, "%(d", "(3)" }, + { -3, "%08d", "-0000003" }, + { -3, "%-+,(11d", "(3) " }, + { -3, "%0 ,(11d", "(000000003)" }, + + { 0x7654321L, "%d", "124076833" }, + { 0x7654321L, "%10d", " 124076833" }, + { 0x7654321L, "%-1d", "124076833" }, + { 0x7654321L, "%+d", "+124076833" }, + { 0x7654321L, "% d", " 124076833" }, + { 0x7654321L, "%,d", "124.076.833" }, + { 0x7654321L, "%(d", "124076833" }, + { 0x7654321L, "%08d", "124076833" }, + { 0x7654321L, "%-+,(11d", "+124.076.833" }, + { 0x7654321L, "%0 ,(11d", " 124.076.833" }, + + { -1L, "%d", "-1" }, + { -1L, "%10d", " -1" }, + { -1L, "%-1d", "-1" }, + { -1L, "%+d", "-1" }, + { -1L, "% d", "-1" }, + { -1L, "%,d", "-1" }, + { -1L, "%(d", "(1)" }, + { -1L, "%08d", "-0000001" }, + { -1L, "%-+,(11d", "(1) " }, + { -1L, "%0 ,(11d", "(000000001)" }, + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.GERMAN); + f.format((String) triple[i][pattern], + triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern[" + + i + "]:" + triple[i][pattern], triple[i][output], f + .toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for legal + * Byte/Short/Integer/Long conversion type 'o' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionO() { + final Object[][] triple = { + { 0, "%o", "0" }, + { 0, "%-6o", "0 " }, + { 0, "%08o", "00000000" }, + { 0, "%#o", "00" }, + { 0, "%0#11o", "00000000000" }, + { 0, "%-#9o", "00 " }, + + { (byte) 0xff, "%o", "377" }, + { (byte) 0xff, "%-6o", "377 " }, + { (byte) 0xff, "%08o", "00000377" }, + { (byte) 0xff, "%#o", "0377" }, + { (byte) 0xff, "%0#11o", "00000000377" }, + { (byte) 0xff, "%-#9o", "0377 " }, + + { (short) 0xf123, "%o", "170443" }, + { (short) 0xf123, "%-6o", "170443" }, + { (short) 0xf123, "%08o", "00170443" }, + { (short) 0xf123, "%#o", "0170443" }, + { (short) 0xf123, "%0#11o", "00000170443" }, + { (short) 0xf123, "%-#9o", "0170443 " }, + + { 0x123456, "%o", "4432126" }, + { 0x123456, "%-6o", "4432126" }, + { 0x123456, "%08o", "04432126" }, + { 0x123456, "%#o", "04432126" }, + { 0x123456, "%0#11o", "00004432126" }, + { 0x123456, "%-#9o", "04432126 " }, + + { -3, "%o", "37777777775" }, + { -3, "%-6o", "37777777775" }, + { -3, "%08o", "37777777775" }, + { -3, "%#o", "037777777775" }, + { -3, "%0#11o", "037777777775" }, + { -3, "%-#9o", "037777777775" }, + + { 0x7654321L, "%o", "731241441" }, + { 0x7654321L, "%-6o", "731241441" }, + { 0x7654321L, "%08o", "731241441" }, + { 0x7654321L, "%#o", "0731241441" }, + { 0x7654321L, "%0#11o", "00731241441" }, + { 0x7654321L, "%-#9o", "0731241441" }, + + { -1L, "%o", "1777777777777777777777" }, + { -1L, "%-6o", "1777777777777777777777" }, + { -1L, "%08o", "1777777777777777777777" }, + { -1L, "%#o", "01777777777777777777777" }, + { -1L, "%0#11o", "01777777777777777777777" }, + { -1L, "%-#9o", "01777777777777777777777" }, + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.ITALY); + f.format((String) triple[i][pattern], + triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern[" + + i + "]:" + triple[i][pattern], triple[i][output], f + .toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for legal + * Byte/Short/Integer/Long conversion type 'x' and 'X' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionX() { + final Object[][] triple = { + { 0, "%x", "0" }, + { 0, "%-8x", "0 " }, + { 0, "%06x", "000000" }, + { 0, "%#x", "0x0" }, + { 0, "%0#12x", "0x0000000000" }, + { 0, "%-#9x", "0x0 " }, + + { (byte) 0xff, "%x", "ff" }, + { (byte) 0xff, "%-8x", "ff " }, + { (byte) 0xff, "%06x", "0000ff" }, + { (byte) 0xff, "%#x", "0xff" }, + { (byte) 0xff, "%0#12x", "0x00000000ff" }, + { (byte) 0xff, "%-#9x", "0xff " }, + + { (short) 0xf123, "%x", "f123" }, + { (short) 0xf123, "%-8x", "f123 " }, + { (short) 0xf123, "%06x", "00f123" }, + { (short) 0xf123, "%#x", "0xf123" }, + { (short) 0xf123, "%0#12x", "0x000000f123" }, + { (short) 0xf123, "%-#9x", "0xf123 " }, + + { 0x123456, "%x", "123456" }, + { 0x123456, "%-8x", "123456 " }, + { 0x123456, "%06x", "123456" }, + { 0x123456, "%#x", "0x123456" }, + { 0x123456, "%0#12x", "0x0000123456" }, + { 0x123456, "%-#9x", "0x123456 " }, + + { -3, "%x", "fffffffd" }, + { -3, "%-8x", "fffffffd" }, + { -3, "%06x", "fffffffd" }, + { -3, "%#x", "0xfffffffd" }, + { -3, "%0#12x", "0x00fffffffd" }, + { -3, "%-#9x", "0xfffffffd" }, + + { 0x7654321L, "%x", "7654321" }, + { 0x7654321L, "%-8x", "7654321 " }, + { 0x7654321L, "%06x", "7654321" }, + { 0x7654321L, "%#x", "0x7654321" }, + { 0x7654321L, "%0#12x", "0x0007654321" }, + { 0x7654321L, "%-#9x", "0x7654321" }, + + { -1L, "%x", "ffffffffffffffff" }, + { -1L, "%-8x", "ffffffffffffffff" }, + { -1L, "%06x", "ffffffffffffffff" }, + { -1L, "%#x", "0xffffffffffffffff" }, + { -1L, "%0#12x", "0xffffffffffffffff" }, + { -1L, "%-#9x", "0xffffffffffffffff" }, + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f; + for (int i = 0; i < triple.length; i++) { + f = new Formatter(Locale.FRANCE); + f.format((String) triple[i][pattern], + triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern[" + + i + "]:" + triple[i][pattern], triple[i][output], f + .toString()); + + f = new Formatter(Locale.FRANCE); + f.format((String) triple[i][pattern], + triple[i][input]); + assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern[" + + i + "]:" + triple[i][pattern], triple[i][output], f + .toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Date/Time + * conversion + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_DateTimeConversion() { + Formatter f = null; + Date now = new Date(1147327147578L); + + Calendar paris = Calendar.getInstance(TimeZone + .getTimeZone("Europe/Paris"), Locale.FRANCE); + paris.set(2006, 4, 8, 12, 0, 0); + paris.set(Calendar.MILLISECOND, 453); + Calendar china = Calendar.getInstance( + TimeZone.getTimeZone("GMT-08:00"), Locale.CHINA); + china.set(2006, 4, 8, 12, 0, 0); + china.set(Calendar.MILLISECOND, 609); + + final Object[][] lowerCaseGermanTriple = { + {0L, 'a', "Do."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'a', "So."}, //$NON-NLS-2$ + {-1000L, 'a', "Do."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'a', "Do."}, //$NON-NLS-2$ + {paris, 'a', "Mo."}, //$NON-NLS-2$ + {china, 'a', "Mo."}, //$NON-NLS-2$ + {0L, 'b', "Jan"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'b', "Aug"}, //$NON-NLS-2$ + {-1000L, 'b', "Jan"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'b', "Mai"}, //$NON-NLS-2$ + {paris, 'b', "Mai"}, //$NON-NLS-2$ + {china, 'b', "Mai"}, //$NON-NLS-2$ + {0L, 'c', "Do. Jan 01 08:00:00 GMT+08:00 1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'c', "So. Aug 17 15:18:47 GMT+08:00 292278994"}, //$NON-NLS-2$ + {-1000L, 'c', "Do. Jan 01 07:59:59 GMT+08:00 1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'c', "Do. Mai 11 13:59:07 GMT+08:00 2006"}, //$NON-NLS-2$ + {paris, 'c', "Mo. Mai 08 12:00:00 MESZ 2006"}, //$NON-NLS-2$ + {china, 'c', "Mo. Mai 08 12:00:00 GMT-08:00 2006"}, //$NON-NLS-2$ + {0L, 'd', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$ + {-1000L, 'd', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$ + {paris, 'd', "08"}, //$NON-NLS-2$ + {china, 'd', "08"}, //$NON-NLS-2$ + {0L, 'e', "1"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$ + {-1000L, 'e', "1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$ + {paris, 'e', "8"}, //$NON-NLS-2$ + {china, 'e', "8"}, //$NON-NLS-2$ + {0L, 'h', "Jan"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'h', "Aug"}, //$NON-NLS-2$ + {-1000L, 'h', "Jan"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'h', "Mai"}, //$NON-NLS-2$ + {paris, 'h', "Mai"}, //$NON-NLS-2$ + {china, 'h', "Mai"}, //$NON-NLS-2$ + {0L, 'j', "001"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$ + {-1000L, 'j', "001"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$ + {paris, 'j', "128"}, //$NON-NLS-2$ + {china, 'j', "128"}, //$NON-NLS-2$ + {0L, 'k', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$ + {-1000L, 'k', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$ + {paris, 'k', "12"}, //$NON-NLS-2$ + {china, 'k', "12"}, //$NON-NLS-2$ + {0L, 'l', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$ + {-1000L, 'l', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$ + {paris, 'l', "12"}, //$NON-NLS-2$ + {china, 'l', "12"}, //$NON-NLS-2$ + {0L, 'm', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$ + {-1000L, 'm', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$ + {paris, 'm', "05"}, //$NON-NLS-2$ + {china, 'm', "05"}, //$NON-NLS-2$ + {0L, 'p', "vorm."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'p', "nachm."}, //$NON-NLS-2$ + {-1000L, 'p', "vorm."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'p', "nachm."}, //$NON-NLS-2$ + {paris, 'p', "nachm."}, //$NON-NLS-2$ + {china, 'p', "nachm."}, //$NON-NLS-2$ + {0L, 'r', "08:00:00 vorm."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'r', "03:18:47 nachm."}, //$NON-NLS-2$ + {-1000L, 'r', "07:59:59 vorm."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'r', "01:59:07 nachm."}, //$NON-NLS-2$ + {paris, 'r', "12:00:00 nachm."}, //$NON-NLS-2$ + {china, 'r', "12:00:00 nachm."}, //$NON-NLS-2$ + {0L, 's', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$ + {-1000L, 's', "-1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$ + {paris, 's', "1147082400"}, //$NON-NLS-2$ + {china, 's', "1147118400"}, //$NON-NLS-2$ + {0L, 'y', "70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$ + {-1000L, 'y', "70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$ + {paris, 'y', "06"}, //$NON-NLS-2$ + {china, 'y', "06"}, //$NON-NLS-2$ + {0L, 'z', "+0800"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$ + {-1000L, 'z', "+0800"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$ + {paris, 'z', "+0100"}, //$NON-NLS-2$ + {china, 'z', "-0800"}, //$NON-NLS-2$ + + }; + + final Object[][] lowerCaseFranceTriple = { + {0L, 'a', "jeu."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'a', "dim."}, //$NON-NLS-2$ + {-1000L, 'a', "jeu."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'a', "jeu."}, //$NON-NLS-2$ + {paris, 'a', "lun."}, //$NON-NLS-2$ + {china, 'a', "lun."}, //$NON-NLS-2$ + {0L, 'b', "janv."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'b', "ao\u00fbt"}, //$NON-NLS-2$ + {-1000L, 'b', "janv."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'b', "mai"}, //$NON-NLS-2$ + {paris, 'b', "mai"}, //$NON-NLS-2$ + {china, 'b', "mai"}, //$NON-NLS-2$ + {0L, 'c', "jeu. janv. 01 08:00:00 UTC+08:00 1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'c', "dim. ao\u00fbt 17 15:18:47 UTC+08:00 292278994"}, //$NON-NLS-2$ + {-1000L, 'c', "jeu. janv. 01 07:59:59 UTC+08:00 1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'c', "jeu. mai 11 13:59:07 UTC+08:00 2006"}, //$NON-NLS-2$ + {paris, 'c', "lun. mai 08 12:00:00 HAEC 2006"}, //$NON-NLS-2$ + {china, 'c', "lun. mai 08 12:00:00 UTC-08:00 2006"}, //$NON-NLS-2$ + {0L, 'd', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$ + {-1000L, 'd', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$ + {paris, 'd', "08"}, //$NON-NLS-2$ + {china, 'd', "08"}, //$NON-NLS-2$ + {0L, 'e', "1"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$ + {-1000L, 'e', "1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$ + {paris, 'e', "8"}, //$NON-NLS-2$ + {china, 'e', "8"}, //$NON-NLS-2$ + {0L, 'h', "janv."}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'h', "ao\u00fbt"}, //$NON-NLS-2$ + {-1000L, 'h', "janv."}, //$NON-NLS-2$ + {new Date(1147327147578L), 'h', "mai"}, //$NON-NLS-2$ + {paris, 'h', "mai"}, //$NON-NLS-2$ + {china, 'h', "mai"}, //$NON-NLS-2$ + {0L, 'j', "001"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$ + {-1000L, 'j', "001"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$ + {paris, 'j', "128"}, //$NON-NLS-2$ + {china, 'j', "128"}, //$NON-NLS-2$ + {0L, 'k', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$ + {-1000L, 'k', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$ + {paris, 'k', "12"}, //$NON-NLS-2$ + {china, 'k', "12"}, //$NON-NLS-2$ + {0L, 'l', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$ + {-1000L, 'l', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$ + {paris, 'l', "12"}, //$NON-NLS-2$ + {china, 'l', "12"}, //$NON-NLS-2$ + {0L, 'm', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$ + {-1000L, 'm', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$ + {paris, 'm', "05"}, //$NON-NLS-2$ + {china, 'm', "05"}, //$NON-NLS-2$ + {0L, 'p', "am"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'p', "pm"}, //$NON-NLS-2$ + {-1000L, 'p', "am"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'p', "pm"}, //$NON-NLS-2$ + {paris, 'p', "pm"}, //$NON-NLS-2$ + {china, 'p', "pm"}, //$NON-NLS-2$ + {0L, 'r', "08:00:00 AM"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'r', "03:18:47 PM"}, //$NON-NLS-2$ + {-1000L, 'r', "07:59:59 AM"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'r', "01:59:07 PM"}, //$NON-NLS-2$ + {paris, 'r', "12:00:00 PM"}, //$NON-NLS-2$ + {china, 'r', "12:00:00 PM"}, //$NON-NLS-2$ + {0L, 's', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$ + {-1000L, 's', "-1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$ + {paris, 's', "1147082400"}, //$NON-NLS-2$ + {china, 's', "1147118400"}, //$NON-NLS-2$ + {0L, 'y', "70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$ + {-1000L, 'y', "70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$ + {paris, 'y', "06"}, //$NON-NLS-2$ + {china, 'y', "06"}, //$NON-NLS-2$ + {0L, 'z', "+0800"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$ + {-1000L, 'z', "+0800"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$ + {paris, 'z', "+0100"}, //$NON-NLS-2$ + {china, 'z', "-0800"}, //$NON-NLS-2$ + + }; + + final Object[][] lowerCaseJapanTriple = { + {0L, 'a', "\u6728"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'a', "\u65e5"}, //$NON-NLS-2$ + {-1000L, 'a', "\u6728"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'a', "\u6728"}, //$NON-NLS-2$ + {paris, 'a', "\u6708"}, //$NON-NLS-2$ + {china, 'a', "\u6708"}, //$NON-NLS-2$ + {0L, 'b', "1\u6708"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'b', "8\u6708"}, //$NON-NLS-2$ + {-1000L, 'b', "1\u6708"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'b', "5\u6708"}, //$NON-NLS-2$ + {paris, 'b', "5\u6708"}, //$NON-NLS-2$ + {china, 'b', "5\u6708"}, //$NON-NLS-2$ + {0L, 'c', "\u6728 1\u6708 01 08:00:00 GMT+08:00 1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'c', "\u65e5 8\u6708 17 15:18:47 GMT+08:00 292278994"}, //$NON-NLS-2$ + {-1000L, 'c', "\u6728 1\u6708 01 07:59:59 GMT+08:00 1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'c', "\u6728 5\u6708 11 13:59:07 GMT+08:00 2006"}, //$NON-NLS-2$ + {paris, 'c', "\u6708 5\u6708 08 12:00:00 GMT+02:00 2006"}, //$NON-NLS-2$ + {china, 'c', "\u6708 5\u6708 08 12:00:00 GMT-08:00 2006"}, //$NON-NLS-2$ + {0L, 'd', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$ + {-1000L, 'd', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$ + {paris, 'd', "08"}, //$NON-NLS-2$ + {china, 'd', "08"}, //$NON-NLS-2$ + {0L, 'e', "1"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$ + {-1000L, 'e', "1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$ + {paris, 'e', "8"}, //$NON-NLS-2$ + {china, 'e', "8"}, //$NON-NLS-2$ + {0L, 'h', "1\u6708"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'h', "8\u6708"}, //$NON-NLS-2$ + {-1000L, 'h', "1\u6708"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'h', "5\u6708"}, //$NON-NLS-2$ + {paris, 'h', "5\u6708"}, //$NON-NLS-2$ + {china, 'h', "5\u6708"}, //$NON-NLS-2$ + {0L, 'j', "001"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$ + {-1000L, 'j', "001"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$ + {paris, 'j', "128"}, //$NON-NLS-2$ + {china, 'j', "128"}, //$NON-NLS-2$ + {0L, 'k', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$ + {-1000L, 'k', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$ + {paris, 'k', "12"}, //$NON-NLS-2$ + {china, 'k', "12"}, //$NON-NLS-2$ + {0L, 'l', "8"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$ + {-1000L, 'l', "7"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$ + {paris, 'l', "12"}, //$NON-NLS-2$ + {china, 'l', "12"}, //$NON-NLS-2$ + {0L, 'm', "01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$ + {-1000L, 'm', "01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$ + {paris, 'm', "05"}, //$NON-NLS-2$ + {china, 'm', "05"}, //$NON-NLS-2$ + {0L, 'p', "\u5348\u524d"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$ + {-1000L, 'p', "\u5348\u524d"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'p', "\u5348\u5f8c"}, //$NON-NLS-2$ + {paris, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$ + {china, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$ + {0L, 'r', "08:00:00 \u5348\u524d"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'r', "03:18:47 \u5348\u5f8c"}, //$NON-NLS-2$ + {-1000L, 'r', "07:59:59 \u5348\u524d"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'r', "01:59:07 \u5348\u5f8c"}, //$NON-NLS-2$ + {paris, 'r', "12:00:00 \u5348\u5f8c"}, //$NON-NLS-2$ + {china, 'r', "12:00:00 \u5348\u5f8c"}, //$NON-NLS-2$ + {0L, 's', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$ + {-1000L, 's', "-1"}, //$NON-NLS-2$ + {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$ + {paris, 's', "1147082400"}, //$NON-NLS-2$ + {china, 's', "1147118400"}, //$NON-NLS-2$ + {0L, 'y', "70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$ + {-1000L, 'y', "70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$ + {paris, 'y', "06"}, //$NON-NLS-2$ + {china, 'y', "06"}, //$NON-NLS-2$ + {0L, 'z', "+0800"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$ + {-1000L, 'z', "+0800"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$ + {paris, 'z', "+0100"}, //$NON-NLS-2$ + {china, 'z', "-0800"}, //$NON-NLS-2$ + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < 90; i++) { + // go through legal conversion + String formatSpecifier = "%t" + lowerCaseGermanTriple[i][pattern]; //$NON-NLS-2$ + String formatSpecifierUpper = "%T" + lowerCaseGermanTriple[i][pattern]; //$NON-NLS-2$ + // test '%t' + f = new Formatter(Locale.GERMAN); + f.format(formatSpecifier, lowerCaseGermanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + lowerCaseGermanTriple[i][input], //$NON-NLS-2$ + lowerCaseGermanTriple[i][output], f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.FRANCE, formatSpecifier, lowerCaseFranceTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + lowerCaseFranceTriple[i][input], //$NON-NLS-2$ + lowerCaseFranceTriple[i][output], f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.JAPAN, formatSpecifier, lowerCaseJapanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + lowerCaseJapanTriple[i][input], //$NON-NLS-2$ + lowerCaseJapanTriple[i][output], f.toString()); + + // test '%T' + f = new Formatter(Locale.GERMAN); + f.format(formatSpecifierUpper, lowerCaseGermanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + lowerCaseGermanTriple[i][input], //$NON-NLS-2$ + ((String)lowerCaseGermanTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.FRANCE, formatSpecifierUpper, lowerCaseFranceTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + lowerCaseFranceTriple[i][input], //$NON-NLS-2$ + ((String)lowerCaseFranceTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.JAPAN, formatSpecifierUpper, lowerCaseJapanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + lowerCaseJapanTriple[i][input], //$NON-NLS-2$ + ((String)lowerCaseJapanTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + + final Object[][] upperCaseGermanTriple = { + {0L, 'A', "Donnerstag"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'A', "Sonntag"}, //$NON-NLS-2$ + {-1000L, 'A', "Donnerstag"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'A', "Donnerstag"}, //$NON-NLS-2$ + {paris, 'A', "Montag"}, //$NON-NLS-2$ + {china, 'A', "Montag"}, //$NON-NLS-2$ + {0L, 'B', "Januar"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'B', "August"}, //$NON-NLS-2$ + {-1000L, 'B', "Januar"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'B', "Mai"}, //$NON-NLS-2$ + {paris, 'B', "Mai"}, //$NON-NLS-2$ + {china, 'B', "Mai"}, //$NON-NLS-2$ + {0L, 'C', "19"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$ + {-1000L, 'C', "19"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$ + {paris, 'C', "20"}, //$NON-NLS-2$ + {china, 'C', "20"}, //$NON-NLS-2$ + {0L, 'D', "01/01/70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$ + {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$ + {paris, 'D', "05/08/06"}, //$NON-NLS-2$ + {china, 'D', "05/08/06"}, //$NON-NLS-2$ + {0L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$ + {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$ + {paris, 'F', "2006-05-08"}, //$NON-NLS-2$ + {china, 'F', "2006-05-08"}, //$NON-NLS-2$ + {0L, 'H', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$ + {-1000L, 'H', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$ + {paris, 'H', "12"}, //$NON-NLS-2$ + {china, 'H', "12"}, //$NON-NLS-2$ + {0L, 'I', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$ + {-1000L, 'I', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$ + {paris, 'I', "12"}, //$NON-NLS-2$ + {china, 'I', "12"}, //$NON-NLS-2$ + {0L, 'L', "000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$ + {-1000L, 'L', "000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$ + {paris, 'L', "453"}, //$NON-NLS-2$ + {china, 'L', "609"}, //$NON-NLS-2$ + {0L, 'M', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'M', "18"}, //$NON-NLS-2$ + {-1000L, 'M', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$ + {paris, 'M', "00"}, //$NON-NLS-2$ + {china, 'M', "00"}, //$NON-NLS-2$ + {0L, 'N', "000000000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$ + {-1000L, 'N', "000000000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$ + {paris, 'N', "609000000"}, //$NON-NLS-2$ + {china, 'N', "609000000"}, //$NON-NLS-2$ + {0L, 'Q', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$ + {-1000L, 'Q', "-1000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$ + {paris, 'Q', "1147082400453"}, //$NON-NLS-2$ + {china, 'Q', "1147118400609"}, //$NON-NLS-2$ + {0L, 'R', "08:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'R', "15:18"}, //$NON-NLS-2$ + {-1000L, 'R', "07:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$ + {paris, 'R', "12:00"}, //$NON-NLS-2$ + {china, 'R', "12:00"}, //$NON-NLS-2$ + {0L, 'S', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'S', "47"}, //$NON-NLS-2$ + {-1000L, 'S', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$ + {paris, 'S', "00"}, //$NON-NLS-2$ + {china, 'S', "00"}, //$NON-NLS-2$ + {0L, 'T', "08:00:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'T', "15:18:47"}, //$NON-NLS-2$ + {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$ + {paris, 'T', "12:00:00"}, //$NON-NLS-2$ + {china, 'T', "12:00:00"}, //$NON-NLS-2$ + {0L, 'Y', "1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$ + {-1000L, 'Y', "1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$ + {paris, 'Y', "2006"}, //$NON-NLS-2$ + {china, 'Y', "2006"}, //$NON-NLS-2$ + {0L, 'Z', "CST"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$ + {-1000L, 'Z', "CST"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$ + {paris, 'Z', "CEST"}, //$NON-NLS-2$ + {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$ + + }; + + final Object[][] upperCaseFranceTriple = { + {0L, 'A', "jeudi"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'A', "dimanche"}, //$NON-NLS-2$ + {-1000L, 'A', "jeudi"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'A', "jeudi"}, //$NON-NLS-2$ + {paris, 'A', "lundi"}, //$NON-NLS-2$ + {china, 'A', "lundi"}, //$NON-NLS-2$ + {0L, 'B', "janvier"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'B', "ao\u00fbt"}, //$NON-NLS-2$ + {-1000L, 'B', "janvier"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'B', "mai"}, //$NON-NLS-2$ + {paris, 'B', "mai"}, //$NON-NLS-2$ + {china, 'B', "mai"}, //$NON-NLS-2$ + {0L, 'C', "19"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$ + {-1000L, 'C', "19"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$ + {paris, 'C', "20"}, //$NON-NLS-2$ + {china, 'C', "20"}, //$NON-NLS-2$ + {0L, 'D', "01/01/70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$ + {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$ + {paris, 'D', "05/08/06"}, //$NON-NLS-2$ + {china, 'D', "05/08/06"}, //$NON-NLS-2$ + {0L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$ + {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$ + {paris, 'F', "2006-05-08"}, //$NON-NLS-2$ + {china, 'F', "2006-05-08"}, //$NON-NLS-2$ + {0L, 'H', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$ + {-1000L, 'H', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$ + {paris, 'H', "12"}, //$NON-NLS-2$ + {china, 'H', "12"}, //$NON-NLS-2$ + {0L, 'I', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$ + {-1000L, 'I', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$ + {paris, 'I', "12"}, //$NON-NLS-2$ + {china, 'I', "12"}, //$NON-NLS-2$ + {0L, 'L', "000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$ + {-1000L, 'L', "000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$ + {paris, 'L', "453"}, //$NON-NLS-2$ + {china, 'L', "609"}, //$NON-NLS-2$ + {0L, 'M', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'M', "18"}, //$NON-NLS-2$ + {-1000L, 'M', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$ + {paris, 'M', "00"}, //$NON-NLS-2$ + {china, 'M', "00"}, //$NON-NLS-2$ + {0L, 'N', "000000000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$ + {-1000L, 'N', "000000000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$ + {paris, 'N', "453000000"}, //$NON-NLS-2$ + {china, 'N', "468000000"}, //$NON-NLS-2$ + {0L, 'Q', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$ + {-1000L, 'Q', "-1000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$ + {paris, 'Q', "1147082400453"}, //$NON-NLS-2$ + {china, 'Q', "1147118400609"}, //$NON-NLS-2$ + {0L, 'R', "08:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'R', "15:18"}, //$NON-NLS-2$ + {-1000L, 'R', "07:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$ + {paris, 'R', "12:00"}, //$NON-NLS-2$ + {china, 'R', "12:00"}, //$NON-NLS-2$ + {0L, 'S', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'S', "47"}, //$NON-NLS-2$ + {-1000L, 'S', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$ + {paris, 'S', "00"}, //$NON-NLS-2$ + {china, 'S', "00"}, //$NON-NLS-2$ + {0L, 'T', "08:00:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'T', "15:18:47"}, //$NON-NLS-2$ + {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$ + {paris, 'T', "12:00:00"}, //$NON-NLS-2$ + {china, 'T', "12:00:00"}, //$NON-NLS-2$ + {0L, 'Y', "1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$ + {-1000L, 'Y', "1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$ + {paris, 'Y', "2006"}, //$NON-NLS-2$ + {china, 'Y', "2006"}, //$NON-NLS-2$ + {0L, 'Z', "CST"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$ + {-1000L, 'Z', "CST"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$ + {paris, 'Z', "CEST"}, //$NON-NLS-2$ + {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$ + + }; + + final Object[][] upperCaseJapanTriple = { + {0L, 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'A', "\u65e5\u66dc\u65e5"}, //$NON-NLS-2$ + {-1000L, 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$ + {paris, 'A', "\u6708\u66dc\u65e5"}, //$NON-NLS-2$ + {china, 'A', "\u6708\u66dc\u65e5"}, //$NON-NLS-2$ + {0L, 'B', "1\u6708"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'B', "8\u6708"}, //$NON-NLS-2$ + {-1000L, 'B', "1\u6708"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'B', "5\u6708"}, //$NON-NLS-2$ + {paris, 'B', "5\u6708"}, //$NON-NLS-2$ + {china, 'B', "5\u6708"}, //$NON-NLS-2$ + {0L, 'C', "19"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$ + {-1000L, 'C', "19"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$ + {paris, 'C', "20"}, //$NON-NLS-2$ + {china, 'C', "20"}, //$NON-NLS-2$ + {0L, 'D', "01/01/70"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$ + {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$ + {paris, 'D', "05/08/06"}, //$NON-NLS-2$ + {china, 'D', "05/08/06"}, //$NON-NLS-2$ + {0L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$ + {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$ + {paris, 'F', "2006-05-08"}, //$NON-NLS-2$ + {china, 'F', "2006-05-08"}, //$NON-NLS-2$ + {0L, 'H', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$ + {-1000L, 'H', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$ + {paris, 'H', "12"}, //$NON-NLS-2$ + {china, 'H', "12"}, //$NON-NLS-2$ + {0L, 'I', "08"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$ + {-1000L, 'I', "07"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$ + {paris, 'I', "12"}, //$NON-NLS-2$ + {china, 'I', "12"}, //$NON-NLS-2$ + {0L, 'L', "000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$ + {-1000L, 'L', "000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$ + {paris, 'L', "453"}, //$NON-NLS-2$ + {china, 'L', "609"}, //$NON-NLS-2$ + {0L, 'M', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'M', "18"}, //$NON-NLS-2$ + {-1000L, 'M', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$ + {paris, 'M', "00"}, //$NON-NLS-2$ + {china, 'M', "00"}, //$NON-NLS-2$ + {0L, 'N', "000000000"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$ + {-1000L, 'N', "000000000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$ + {paris, 'N', "453000000"}, //$NON-NLS-2$ + {china, 'N', "468000000"}, //$NON-NLS-2$ + {0L, 'Q', "0"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$ + {-1000L, 'Q', "-1000"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$ + {paris, 'Q', "1147082400453"}, //$NON-NLS-2$ + {china, 'Q', "1147118400609"}, //$NON-NLS-2$ + {0L, 'R', "08:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'R', "15:18"}, //$NON-NLS-2$ + {-1000L, 'R', "07:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$ + {paris, 'R', "12:00"}, //$NON-NLS-2$ + {china, 'R', "12:00"}, //$NON-NLS-2$ + {0L, 'S', "00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'S', "47"}, //$NON-NLS-2$ + {-1000L, 'S', "59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$ + {paris, 'S', "00"}, //$NON-NLS-2$ + {china, 'S', "00"}, //$NON-NLS-2$ + {0L, 'T', "08:00:00"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'T', "15:18:47"}, //$NON-NLS-2$ + {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$ + {paris, 'T', "12:00:00"}, //$NON-NLS-2$ + {china, 'T', "12:00:00"}, //$NON-NLS-2$ + {0L, 'Y', "1970"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$ + {-1000L, 'Y', "1970"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$ + {paris, 'Y', "2006"}, //$NON-NLS-2$ + {china, 'Y', "2006"}, //$NON-NLS-2$ + {0L, 'Z', "CST"}, //$NON-NLS-2$ + {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$ + {-1000L, 'Z', "CST"}, //$NON-NLS-2$ + {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$ + {paris, 'Z', "CEST"}, //$NON-NLS-2$ + {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$ + }; + + + for (int i = 0; i < 90; i++) { + String formatSpecifier = "%t" + upperCaseGermanTriple[i][pattern]; //$NON-NLS-2$ + String formatSpecifierUpper = "%T" + upperCaseGermanTriple[i][pattern]; //$NON-NLS-2$ + if ((Character)upperCaseGermanTriple[i][pattern] == 'N') { + // result can't be predicted on RI, so skip this test + continue; + } + // test '%t' + f = new Formatter(Locale.JAPAN); + f.format(formatSpecifier, upperCaseJapanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + upperCaseJapanTriple[i][input], //$NON-NLS-2$ + upperCaseJapanTriple[i][output], f.toString()); + + f = new Formatter(Locale.JAPAN); + f.format(Locale.GERMAN, formatSpecifier, upperCaseGermanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + upperCaseGermanTriple[i][input], //$NON-NLS-2$ + upperCaseGermanTriple[i][output], f.toString()); + + f = new Formatter(Locale.JAPAN); + f.format(Locale.FRANCE, formatSpecifier, upperCaseFranceTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$ + + " Argument: " + upperCaseFranceTriple[i][input], //$NON-NLS-2$ + upperCaseFranceTriple[i][output], f.toString()); + + // test '%T' + f = new Formatter(Locale.GERMAN); + f.format(formatSpecifierUpper, upperCaseGermanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + upperCaseGermanTriple[i][input], //$NON-NLS-2$ + ((String)upperCaseGermanTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.JAPAN, formatSpecifierUpper, upperCaseJapanTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + upperCaseJapanTriple[i][input], //$NON-NLS-2$ + ((String)upperCaseJapanTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format(Locale.FRANCE, formatSpecifierUpper, upperCaseFranceTriple[i][input]); + assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$ + + " Argument: " + upperCaseFranceTriple[i][input], //$NON-NLS-2$ + ((String)upperCaseFranceTriple[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + + f = new Formatter(Locale.US); + f.format("%-10ta", now); //$NON-NLS-2$ + assertEquals("Thu ", f.toString()); //$NON-NLS-2$ + + f = new Formatter(Locale.US); + f.format("%10000000000000000000000000000000001ta", now); //$NON-NLS-2$ + assertEquals("Thu", f.toString().trim()); //$NON-NLS-2$ + } + + /** + * @tests java.util.Formatter#format(String, Object...) for null argment for + * Byte/Short/Integer/Long/BigInteger conversion + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongNullConversion() { + + Formatter f = new Formatter(Locale.FRANCE); + f.format("%d%<o%<x%<5X", (Integer) null); + assertEquals("nullnullnull NULL", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%d%<#03o %<0#4x%<6X", (Long) null); + assertEquals("nullnull null NULL", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%(+,07d%<o %<x%<6X", (Byte) null); + assertEquals(" nullnull null NULL", f.toString()); + + f = new Formatter(Locale.ITALY); + f.format("%(+,07d%<o %<x%<0#6X", (Short) null); + assertEquals(" nullnull null NULL", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%(+,-7d%<( o%<+(x %<( 06X", (BigInteger) null); + assertEquals("null nullnull NULL", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for legal + * BigInteger conversion type 'd' + */ + public void test_formatLjava_lang_String$LBigInteger() { + final Object[][] tripleD = { + {new BigInteger("123456789012345678901234567890"), "%d", "123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%10d", "123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-1d", "123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%+d", "+123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "% d", " 123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%,d", "123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%(d", "123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%08d", "123456789012345678901234567890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-+,(11d", "+123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%0 ,(11d", " 123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%10d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-1d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%+d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "% d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%,d", "-9.876.543.210.987.654.321.098.765.432.100.000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%(d", "(9876543210987654321098765432100000)"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%08d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-+,(11d", "(9.876.543.210.987.654.321.098.765.432.100.000)"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%0 ,(11d", "(9.876.543.210.987.654.321.098.765.432.100.000)"}, //$NON-NLS-2$ + }; + + final int input = 0; + final int pattern = 1; + final int output = 2; + Formatter f; + for (int i = 0; i < tripleD.length; i++) { + f = new Formatter(Locale.GERMAN); + f.format((String) tripleD[i][pattern], + tripleD[i][input]); + assertEquals("triple[" + i + "]:" + tripleD[i][input] + ",pattern[" + + i + "]:" + tripleD[i][pattern], tripleD[i][output], f + .toString()); + + } + + final Object[][] tripleO = { + {new BigInteger("123456789012345678901234567890"), "%o", "143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-6o", "143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%08o", "143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%#o", "0143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%0#11o", "0143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-#9o", "0143564417755415637016711617605322"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-6o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%08o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%#o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%0#11o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-#9o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$ + }; + for (int i = 0; i < tripleO.length; i++) { + f = new Formatter(Locale.ITALY); + f.format((String) tripleO[i][pattern], + tripleO[i][input]); + assertEquals("triple[" + i + "]:" + tripleO[i][input] + ",pattern[" + + i + "]:" + tripleO[i][pattern], tripleO[i][output], f + .toString()); + + } + + final Object[][] tripleX = { + {new BigInteger("123456789012345678901234567890"), "%x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-8x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%06x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%#x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%0#12x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("123456789012345678901234567890"), "%-#9x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-8x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%06x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%#x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%0#12x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + {new BigInteger("-9876543210987654321098765432100000"), "%-#9x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$ + }; + + for (int i = 0; i < tripleX.length; i++) { + f = new Formatter(Locale.FRANCE); + f.format((String) tripleX[i][pattern], + tripleX[i][input]); + assertEquals("triple[" + i + "]:" + tripleX[i][input] + ",pattern[" + + i + "]:" + tripleX[i][pattern], tripleX[i][output], f + .toString()); + + } + + f = new Formatter(Locale.GERMAN); + f.format("%(+,-7d%<( o%<+(x %<( 06X", (BigInteger) null); + assertEquals("null nullnull NULL", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for padding of + * BigInteger conversion + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerPaddingConversion() { + Formatter f = null; + + BigInteger bigInt = new BigInteger("123456789012345678901234567890"); + f = new Formatter(Locale.GERMAN); + f.format("%32d", bigInt); + assertEquals(" 123456789012345678901234567890", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%+32x", bigInt); + assertEquals(" +18ee90ff6c373e0ee4e3f0ad2", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("% 32o", bigInt); + assertEquals(" 143564417755415637016711617605322", f.toString()); + + BigInteger negBigInt = new BigInteger( + "-1234567890123456789012345678901234567890"); + f = new Formatter(Locale.GERMAN); + f.format("%( 040X", negBigInt); + assertEquals("(000003A0C92075C0DBF3B8ACBC5F96CE3F0AD2)", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%+(045d", negBigInt); + assertEquals("(0001234567890123456789012345678901234567890)", f + .toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%+,-(60d", negBigInt); + assertEquals( + "(1.234.567.890.123.456.789.012.345.678.901.234.567.890) ", + f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigInteger + * conversion exception + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerConversionException() { + Formatter f = null; + + final String[] flagsConversionMismatches = { "%#d", "%,o", "%,x", "%,X" }; + for (int i = 0; i < flagsConversionMismatches.length; i++) { + try { + f = new Formatter(Locale.CHINA); + f.format(flagsConversionMismatches[i], new BigInteger("1")); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + } + + final String[] missingFormatWidths = { "%-0d", "%0d", "%-d", "%-0o", + "%0o", "%-o", "%-0x", "%0x", "%-x", "%-0X", "%0X", "%-X" }; + for (int i = 0; i < missingFormatWidths.length; i++) { + try { + f = new Formatter(Locale.KOREA); + f.format(missingFormatWidths[i], new BigInteger("1")); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + } + + final String[] illFlags = { "%+ d", "%-08d", "%+ o", "%-08o", "%+ x", + "%-08x", "%+ X", "%-08X" }; + for (int i = 0; i < illFlags.length; i++) { + try { + f = new Formatter(Locale.CANADA); + f.format(illFlags[i], new BigInteger("1")); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + } + + final String[] precisionExceptions = { "%.4d", "%2.5o", "%8.6x", + "%11.17X" }; + for (int i = 0; i < precisionExceptions.length; i++) { + try { + f = new Formatter(Locale.US); + f.format(precisionExceptions[i], new BigInteger("1")); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + } + + f = new Formatter(Locale.US); + try { + f.format("%D", new BigInteger("1")); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + f = new Formatter(Locale.US); + try { + f.format("%O", new BigInteger("1")); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + + try { + f = new Formatter(); + f.format("%010000000000000000000000000000000001d", new BigInteger( + "1")); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigInteger + * exception throwing order + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerExceptionOrder() { + Formatter f = null; + BigInteger big = new BigInteger("100"); + + /* + * Order summary: UnknownFormatConversionException > + * MissingFormatWidthException > IllegalFormatFlagsException > + * IllegalFormatPrecisionException > IllegalFormatConversionException > + * FormatFlagsConversionMismatchException + * + */ + f = new Formatter(Locale.US); + try { + // compare IllegalFormatConversionException and + // FormatFlagsConversionMismatchException + f.format("%(o", false); + fail("should throw IllegalFormatConversionException"); + } catch (IllegalFormatConversionException e) { + // expected + } + + try { + // compare IllegalFormatPrecisionException and + // IllegalFormatConversionException + f.format("%.4o", false); + fail("should throw IllegalFormatPrecisionException"); + } catch (IllegalFormatPrecisionException e) { + // expected + } + + try { + // compare IllegalFormatFlagsException and + // IllegalFormatPrecisionException + f.format("%+ .4o", big); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + + try { + // compare MissingFormatWidthException and + // IllegalFormatFlagsException + f.format("%+ -o", big); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + + try { + // compare UnknownFormatConversionException and + // MissingFormatWidthException + f.format("%-O", big); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Float/Double + * conversion type 'e' and 'E' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionE() { + Formatter f = null; + final Object[][] tripleE = { + {0f, "%e", "0.000000e+00"}, + {0f, "%#.0e", "0.e+00"}, + {0f, "%#- (9.8e", " 0.00000000e+00"}, + {0f, "%#+0(8.4e", "+0.0000e+00"}, + {0f, "%-+(1.6e", "+0.000000e+00"}, + {0f, "% 0(12e", " 0.000000e+00"}, + + {101f, "%e", "1.010000e+02"}, + {101f, "%#.0e", "1.e+02"}, + {101f, "%#- (9.8e", " 1.01000000e+02"}, + {101f, "%#+0(8.4e", "+1.0100e+02"}, + {101f, "%-+(1.6e", "+1.010000e+02"}, + {101f, "% 0(12e", " 1.010000e+02"}, + + {1.f, "%e", "1.000000e+00"}, + {1.f, "%#.0e", "1.e+00"}, + {1.f, "%#- (9.8e", " 1.00000000e+00"}, + {1.f, "%#+0(8.4e", "+1.0000e+00"}, + {1.f, "%-+(1.6e", "+1.000000e+00"}, + {1.f, "% 0(12e", " 1.000000e+00"}, + + {-98f, "%e", "-9.800000e+01"}, + {-98f, "%#.0e", "-1.e+02"}, + {-98f, "%#- (9.8e", "(9.80000000e+01)"}, + {-98f, "%#+0(8.4e", "(9.8000e+01)"}, + {-98f, "%-+(1.6e", "(9.800000e+01)"}, + {-98f, "% 0(12e", "(9.800000e+01)"}, + + {1.23f, "%e", "1.230000e+00"}, + {1.23f, "%#.0e", "1.e+00"}, + {1.23f, "%#- (9.8e", " 1.23000002e+00"}, + {1.23f, "%#+0(8.4e", "+1.2300e+00"}, + {1.23f, "%-+(1.6e", "+1.230000e+00"}, + {1.23f, "% 0(12e", " 1.230000e+00"}, + + {34.1234567f, "%e", "3.412346e+01"}, + {34.1234567f, "%#.0e", "3.e+01"}, + {34.1234567f, "%#- (9.8e", " 3.41234550e+01"}, + {34.1234567f, "%#+0(8.4e", "+3.4123e+01"}, + {34.1234567f, "%-+(1.6e", "+3.412346e+01"}, + {34.1234567f, "% 0(12e", " 3.412346e+01"}, + + {-.12345f, "%e", "-1.234500e-01"}, + {-.12345f, "%#.0e", "-1.e-01"}, + {-.12345f, "%#- (9.8e", "(1.23450004e-01)"}, + {-.12345f, "%#+0(8.4e", "(1.2345e-01)"}, + {-.12345f, "%-+(1.6e", "(1.234500e-01)"}, + {-.12345f, "% 0(12e", "(1.234500e-01)"}, + + {-9876.1234567f, "%e", "-9.876123e+03"}, + {-9876.1234567f, "%#.0e", "-1.e+04"}, + {-9876.1234567f, "%#- (9.8e", "(9.87612305e+03)"}, + {-9876.1234567f, "%#+0(8.4e", "(9.8761e+03)"}, + {-9876.1234567f, "%-+(1.6e", "(9.876123e+03)"}, + {-9876.1234567f, "% 0(12e", "(9.876123e+03)"}, + + {Float.MAX_VALUE, "%e", "3.402823e+38"}, + {Float.MAX_VALUE, "%#.0e", "3.e+38"}, + {Float.MAX_VALUE, "%#- (9.8e", " 3.40282347e+38"}, + {Float.MAX_VALUE, "%#+0(8.4e", "+3.4028e+38"}, + {Float.MAX_VALUE, "%-+(1.6e", "+3.402823e+38"}, + {Float.MAX_VALUE, "% 0(12e", " 3.402823e+38"}, + + {Float.MIN_VALUE, "%e", "1.401298e-45"}, + {Float.MIN_VALUE, "%#.0e", "1.e-45"}, + {Float.MIN_VALUE, "%#- (9.8e", " 1.40129846e-45"}, + {Float.MIN_VALUE, "%#+0(8.4e", "+1.4013e-45"}, + {Float.MIN_VALUE, "%-+(1.6e", "+1.401298e-45"}, + {Float.MIN_VALUE, "% 0(12e", " 1.401298e-45"}, + + {Float.NaN, "%e", "NaN"}, + {Float.NaN, "%#.0e", "NaN"}, + {Float.NaN, "%#- (9.8e", "NaN "}, + {Float.NaN, "%#+0(8.4e", " NaN"}, + {Float.NaN, "%-+(1.6e", "NaN"}, + {Float.NaN, "% 0(12e", " NaN"}, + + + {Float.NEGATIVE_INFINITY, "%e", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#.0e", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"}, + + {Float.NEGATIVE_INFINITY, "%e", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#.0e", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"}, + + {0d, "%e", "0.000000e+00"}, + {0d, "%#.0e", "0.e+00"}, + {0d, "%#- (9.8e", " 0.00000000e+00"}, + {0d, "%#+0(8.4e", "+0.0000e+00"}, + {0d, "%-+(1.6e", "+0.000000e+00"}, + {0d, "% 0(12e", " 0.000000e+00"}, + + {1d, "%e", "1.000000e+00"}, + {1d, "%#.0e", "1.e+00"}, + {1d, "%#- (9.8e", " 1.00000000e+00"}, + {1d, "%#+0(8.4e", "+1.0000e+00"}, + {1d, "%-+(1.6e", "+1.000000e+00"}, + {1d, "% 0(12e", " 1.000000e+00"}, + + {-1d, "%e", "-1.000000e+00"}, + {-1d, "%#.0e", "-1.e+00"}, + {-1d, "%#- (9.8e", "(1.00000000e+00)"}, + {-1d, "%#+0(8.4e", "(1.0000e+00)"}, + {-1d, "%-+(1.6e", "(1.000000e+00)"}, + {-1d, "% 0(12e", "(1.000000e+00)"}, + + + {.00000001d, "%e", "1.000000e-08"}, + {.00000001d, "%#.0e", "1.e-08"}, + {.00000001d, "%#- (9.8e", " 1.00000000e-08"}, + {.00000001d, "%#+0(8.4e", "+1.0000e-08"}, + {.00000001d, "%-+(1.6e", "+1.000000e-08"}, + {.00000001d, "% 0(12e", " 1.000000e-08"}, + + {9122.10d, "%e", "9.122100e+03"}, + {9122.10d, "%#.0e", "9.e+03"}, + {9122.10d, "%#- (9.8e", " 9.12210000e+03"}, + {9122.10d, "%#+0(8.4e", "+9.1221e+03"}, + {9122.10d, "%-+(1.6e", "+9.122100e+03"}, + {9122.10d, "% 0(12e", " 9.122100e+03"}, + + {0.1d, "%e", "1.000000e-01"}, + {0.1d, "%#.0e", "1.e-01"}, + {0.1d, "%#- (9.8e", " 1.00000000e-01"}, + {0.1d, "%#+0(8.4e", "+1.0000e-01"}, + {0.1d, "%-+(1.6e", "+1.000000e-01"}, + {0.1d, "% 0(12e", " 1.000000e-01"}, + + {-2.d, "%e", "-2.000000e+00"}, + {-2.d, "%#.0e", "-2.e+00"}, + {-2.d, "%#- (9.8e", "(2.00000000e+00)"}, + {-2.d, "%#+0(8.4e", "(2.0000e+00)"}, + {-2.d, "%-+(1.6e", "(2.000000e+00)"}, + {-2.d, "% 0(12e", "(2.000000e+00)"}, + + {-.39d, "%e", "-3.900000e-01"}, + {-.39d, "%#.0e", "-4.e-01"}, + {-.39d, "%#- (9.8e", "(3.90000000e-01)"}, + {-.39d, "%#+0(8.4e", "(3.9000e-01)"}, + {-.39d, "%-+(1.6e", "(3.900000e-01)"}, + {-.39d, "% 0(12e", "(3.900000e-01)"}, + + {-1234567890.012345678d, "%e", "-1.234568e+09"}, + {-1234567890.012345678d, "%#.0e", "-1.e+09"}, + {-1234567890.012345678d, "%#- (9.8e", "(1.23456789e+09)"}, + {-1234567890.012345678d, "%#+0(8.4e", "(1.2346e+09)"}, + {-1234567890.012345678d, "%-+(1.6e", "(1.234568e+09)"}, + {-1234567890.012345678d, "% 0(12e", "(1.234568e+09)"}, + + {Double.MAX_VALUE, "%e", "1.797693e+308"}, + {Double.MAX_VALUE, "%#.0e", "2.e+308"}, + {Double.MAX_VALUE, "%#- (9.8e", " 1.79769313e+308"}, + {Double.MAX_VALUE, "%#+0(8.4e", "+1.7977e+308"}, + {Double.MAX_VALUE, "%-+(1.6e", "+1.797693e+308"}, + {Double.MAX_VALUE, "% 0(12e", " 1.797693e+308"}, + + {Double.MIN_VALUE, "%e", "4.900000e-324"}, + {Double.MIN_VALUE, "%#.0e", "5.e-324"}, + {Double.MIN_VALUE, "%#- (9.8e", " 4.90000000e-324"}, + {Double.MIN_VALUE, "%#+0(8.4e", "+4.9000e-324"}, + {Double.MIN_VALUE, "%-+(1.6e", "+4.900000e-324"}, + {Double.MIN_VALUE, "% 0(12e", " 4.900000e-324"}, + + {Double.NaN, "%e", "NaN"}, + {Double.NaN, "%#.0e", "NaN"}, + {Double.NaN, "%#- (9.8e", "NaN "}, + {Double.NaN, "%#+0(8.4e", " NaN"}, + {Double.NaN, "%-+(1.6e", "NaN"}, + {Double.NaN, "% 0(12e", " NaN"}, + + {Double.NEGATIVE_INFINITY, "%e", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%#.0e", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"}, + + {Double.POSITIVE_INFINITY, "%e", "Infinity"}, + {Double.POSITIVE_INFINITY, "%#.0e", "Infinity"}, + {Double.POSITIVE_INFINITY, "%#- (9.8e", " Infinity"}, + {Double.POSITIVE_INFINITY, "%#+0(8.4e", "+Infinity"}, + {Double.POSITIVE_INFINITY, "%-+(1.6e", "+Infinity"}, + {Double.POSITIVE_INFINITY, "% 0(12e", " Infinity"}, + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleE.length; i++) { + f = new Formatter(Locale.US); + f.format((String)tripleE[i][pattern], tripleE[i][input]); + assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern[" + + i + "]:" + tripleE[i][pattern], + tripleE[i][output], f.toString()); + + // test for conversion type 'E' + f = new Formatter(Locale.US); + f.format(((String)tripleE[i][pattern]).toUpperCase(), tripleE[i][input]); + assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern[" + + i + "]:" + tripleE[i][pattern], ((String)tripleE[i][output]) + .toUpperCase(Locale.UK), f.toString()); + } + + f = new Formatter(Locale.GERMAN); + f.format("%e", 1001f); + /* + * fail on RI, spec says 'e' requires the output to be formatted in + * general scientific notation and the localization algorithm is + * applied. But RI format this case to 1.001000e+03, which does not + * conform to the German Locale + */ + assertEquals("1,001000e+03", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Float/Double + * conversion type 'g' and 'G' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionG() { + Formatter f = null; + final Object[][] tripleG = { + {1001f, "%g", "1001.00"}, + {1001f, "%- (,9.8g", " 1,001.0000"}, + {1001f, "%+0(,8.4g", "+001,001"}, + {1001f, "%-+(,1.6g", "+1,001.00"}, + {1001f, "% 0(,12.0g", " 0000001e+03"}, + + {1.f, "%g", "1.00000"}, + {1.f, "%- (,9.8g", " 1.0000000"}, + {1.f, "%+0(,8.4g", "+001.000"}, + {1.f, "%-+(,1.6g", "+1.00000"}, + {1.f, "% 0(,12.0g", " 00000000001"}, + + {-98f, "%g", "-98.0000"}, + {-98f, "%- (,9.8g", "(98.000000)"}, + {-98f, "%+0(,8.4g", "(098.00)"}, + {-98f, "%-+(,1.6g", "(98.0000)"}, + {-98f, "% 0(,12.0g", "(000001e+02)"}, + + {0.000001f, "%g", "1.00000e-06"}, + {0.000001f, "%- (,9.8g", " 1.0000000e-06"}, + {0.000001f, "%+0(,8.4g", "+1.000e-06"}, + {0.000001f, "%-+(,1.6g", "+1.00000e-06"}, + {0.000001f, "% 0(,12.0g", " 0000001e-06"}, + + {345.1234567f, "%g", "345.123"}, + {345.1234567f, "%- (,9.8g", " 345.12344"}, + {345.1234567f, "%+0(,8.4g", "+00345.1"}, + {345.1234567f, "%-+(,1.6g", "+345.123"}, + {345.1234567f, "% 0(,12.0g", " 0000003e+02"}, + + {-.00000012345f, "%g", "-1.23450e-07"}, + {-.00000012345f, "%- (,9.8g", "(1.2344999e-07)"}, + {-.00000012345f, "%+0(,8.4g", "(1.234e-07)"}, + {-.00000012345f, "%-+(,1.6g", "(1.23450e-07)"}, + {-.00000012345f, "% 0(,12.0g", "(000001e-07)"}, + + {-987.1234567f, "%g", "-987.123"}, + {-987.1234567f, "%- (,9.8g", "(987.12347)"}, + {-987.1234567f, "%+0(,8.4g", "(0987.1)"}, + {-987.1234567f, "%-+(,1.6g", "(987.123)"}, + {-987.1234567f, "% 0(,12.0g", "(000001e+03)"}, + + {Float.MAX_VALUE, "%g", "3.40282e+38"}, + {Float.MAX_VALUE, "%- (,9.8g", " 3.4028235e+38"}, + {Float.MAX_VALUE, "%+0(,8.4g", "+3.403e+38"}, + {Float.MAX_VALUE, "%-+(,1.6g", "+3.40282e+38"}, + {Float.MAX_VALUE, "% 0(,12.0g", " 0000003e+38"}, + + {Float.MIN_VALUE, "%g", "1.40130e-45"}, + {Float.MIN_VALUE, "%- (,9.8g", " 1.4012985e-45"}, + {Float.MIN_VALUE, "%+0(,8.4g", "+1.401e-45"}, + {Float.MIN_VALUE, "%-+(,1.6g", "+1.40130e-45"}, + {Float.MIN_VALUE, "% 0(,12.0g", " 0000001e-45"}, + + {Float.NaN, "%g", "NaN"}, + {Float.NaN, "%- (,9.8g", "NaN "}, + {Float.NaN, "%+0(,8.4g", " NaN"}, + {Float.NaN, "%-+(,1.6g", "NaN"}, + {Float.NaN, "% 0(,12.0g", " NaN"}, + + {Float.NEGATIVE_INFINITY, "%g", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%- (,9.8g", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%+0(,8.4g", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%-+(,1.6g", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "% 0(,12.0g", " (Infinity)"}, + + {Float.POSITIVE_INFINITY, "%g", "Infinity"}, + {Float.POSITIVE_INFINITY, "%- (,9.8g", " Infinity"}, + {Float.POSITIVE_INFINITY, "%+0(,8.4g", "+Infinity"}, + {Float.POSITIVE_INFINITY, "%-+(,1.6g", "+Infinity"}, + {Float.POSITIVE_INFINITY, "% 0(,12.0g", " Infinity"}, + + {1d, "%g", "1.00000"}, + {1d, "%- (,9.8g", " 1.0000000"}, + {1d, "%+0(,8.4g", "+001.000"}, + {1d, "%-+(,1.6g", "+1.00000"}, + {1d, "% 0(,12.0g", " 00000000001"}, + + {-1d, "%g", "-1.00000"}, + {-1d, "%- (,9.8g", "(1.0000000)"}, + {-1d, "%+0(,8.4g", "(01.000)"}, + {-1d, "%-+(,1.6g", "(1.00000)"}, + {-1d, "% 0(,12.0g", "(0000000001)"}, + + {.00000001d, "%g", "1.00000e-08"}, + {.00000001d, "%- (,9.8g", " 1.0000000e-08"}, + {.00000001d, "%+0(,8.4g", "+1.000e-08"}, + {.00000001d, "%-+(,1.6g", "+1.00000e-08"}, + {.00000001d, "% 0(,12.0g", " 0000001e-08"}, + + {1912.10d, "%g", "1912.10"}, + {1912.10d, "%- (,9.8g", " 1,912.1000"}, + {1912.10d, "%+0(,8.4g", "+001,912"}, + {1912.10d, "%-+(,1.6g", "+1,912.10"}, + {1912.10d, "% 0(,12.0g", " 0000002e+03"}, + + {0.1d, "%g", "0.100000"}, + {0.1d, "%- (,9.8g", " 0.10000000"}, + {0.1d, "%+0(,8.4g", "+00.1000"}, + {0.1d, "%-+(,1.6g", "+0.100000"}, + {0.1d, "% 0(,12.0g", " 000000000.1"}, + + {-2.d, "%g", "-2.00000"}, + {-2.d, "%- (,9.8g", "(2.0000000)"}, + {-2.d, "%+0(,8.4g", "(02.000)"}, + {-2.d, "%-+(,1.6g", "(2.00000)"}, + {-2.d, "% 0(,12.0g", "(0000000002)"}, + + {-.00039d, "%g", "-0.000390000"}, + {-.00039d, "%- (,9.8g", "(0.00039000000)"}, + {-.00039d, "%+0(,8.4g", "(0.0003900)"}, + {-.00039d, "%-+(,1.6g", "(0.000390000)"}, + {-.00039d, "% 0(,12.0g", "(00000.0004)"}, + + {-1234567890.012345678d, "%g", "-1.23457e+09"}, + {-1234567890.012345678d, "%- (,9.8g", "(1.2345679e+09)"}, + {-1234567890.012345678d, "%+0(,8.4g", "(1.235e+09)"}, + {-1234567890.012345678d, "%-+(,1.6g", "(1.23457e+09)"}, + {-1234567890.012345678d, "% 0(,12.0g", "(000001e+09)"}, + + {Double.MAX_VALUE, "%g", "1.79769e+308"}, + {Double.MAX_VALUE, "%- (,9.8g", " 1.7976931e+308"}, + {Double.MAX_VALUE, "%+0(,8.4g", "+1.798e+308"}, + {Double.MAX_VALUE, "%-+(,1.6g", "+1.79769e+308"}, + {Double.MAX_VALUE, "% 0(,12.0g", " 000002e+308"}, + + {Double.MIN_VALUE, "%g", "4.90000e-324"}, + {Double.MIN_VALUE, "%- (,9.8g", " 4.9000000e-324"}, + {Double.MIN_VALUE, "%+0(,8.4g", "+4.900e-324"}, + {Double.MIN_VALUE, "%-+(,1.6g", "+4.90000e-324"}, + {Double.MIN_VALUE, "% 0(,12.0g", " 000005e-324"}, + + {Double.NaN, "%g", "NaN"}, + {Double.NaN, "%- (,9.8g", "NaN "}, + {Double.NaN, "%+0(,8.4g", " NaN"}, + {Double.NaN, "%-+(,1.6g", "NaN"}, + {Double.NaN, "% 0(,12.0g", " NaN"}, + + {Double.NEGATIVE_INFINITY, "%g", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%- (,9.8g", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "%+0(,8.4g", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "%-+(,1.6g", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "% 0(,12.0g", " (Infinity)"}, + + {Double.POSITIVE_INFINITY, "%g", "Infinity"}, + {Double.POSITIVE_INFINITY, "%- (,9.8g", " Infinity"}, + {Double.POSITIVE_INFINITY, "%+0(,8.4g", "+Infinity"}, + {Double.POSITIVE_INFINITY, "%-+(,1.6g", "+Infinity"}, + {Double.POSITIVE_INFINITY, "% 0(,12.0g", " Infinity"}, + + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleG.length; i++) { + + f = new Formatter(Locale.US); + f.format((String)tripleG[i][pattern], tripleG[i][input]); + assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern[" + + i + "]:" + tripleG[i][pattern], + tripleG[i][output], f.toString()); + + // test for conversion type 'G' + f = new Formatter(Locale.US); + f.format(((String)tripleG[i][pattern]).toUpperCase(), tripleG[i][input]); + assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern[" + + i + "]:" + tripleG[i][pattern], ((String)tripleG[i][output]) + .toUpperCase(Locale.UK), f.toString()); + } + + f = new Formatter(Locale.US); + f.format("%.5g", 0f); + assertEquals("0.0000", f.toString()); + + f = new Formatter(Locale.US); + f.format("%.0g", 0f); + /* + * fail on RI, spec says if the precision is 0, then it is taken to be + * 1. but RI throws ArrayIndexOutOfBoundsException. + */ + assertEquals("0", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%g", 1001f); + /* + * fail on RI, spec says 'g' requires the output to be formatted in + * general scientific notation and the localization algorithm is + * applied. But RI format this case to 1001.00, which does not conform + * to the German Locale + */ + assertEquals("1001,00", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Float/Double + * conversion type 'g' and 'G' overflow + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionG_Overflow() { + Formatter f = new Formatter(); + f.format("%g", 999999.5); + assertEquals("1.00000e+06", f.toString()); + + f = new Formatter(); + f.format("%g", 99999.5); + assertEquals("99999.5", f.toString()); + + f = new Formatter(); + f.format("%.4g", 99.95); + assertEquals("99.95", f.toString()); + + f = new Formatter(); + f.format("%g", 99.95); + assertEquals("99.9500", f.toString()); + + f = new Formatter(); + f.format("%g", 0.9); + assertEquals("0.900000", f.toString()); + + f = new Formatter(); + f.format("%.0g", 0.000095); + assertEquals("0.0001", f.toString()); + + f = new Formatter(); + f.format("%g", 0.0999999); + assertEquals("0.0999999", f.toString()); + + f = new Formatter(); + f.format("%g", 0.00009); + assertEquals("9.00000e-05", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Float/Double + * conversion type 'f' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionF() { + Formatter f = null; + + final Object[][] tripleF = { + {0f, "%f", "0,000000"}, + {0f, "%#.3f", "0,000"}, + {0f, "%,5f", "0,000000"}, + {0f, "%- (12.0f", " 0 "}, + {0f, "%#+0(1.6f", "+0,000000"}, + {0f, "%-+(8.4f", "+0,0000 "}, + {0f, "% 0#(9.8f", " 0,00000000"}, + + {1234f, "%f", "1234,000000"}, + {1234f, "%#.3f", "1234,000"}, + {1234f, "%,5f", "1.234,000000"}, + {1234f, "%- (12.0f", " 1234 "}, + {1234f, "%#+0(1.6f", "+1234,000000"}, + {1234f, "%-+(8.4f", "+1234,0000"}, + {1234f, "% 0#(9.8f", " 1234,00000000"}, + + {1.f, "%f", "1,000000"}, + {1.f, "%#.3f", "1,000"}, + {1.f, "%,5f", "1,000000"}, + {1.f, "%- (12.0f", " 1 "}, + {1.f, "%#+0(1.6f", "+1,000000"}, + {1.f, "%-+(8.4f", "+1,0000 "}, + {1.f, "% 0#(9.8f", " 1,00000000"}, + + {-98f, "%f", "-98,000000"}, + {-98f, "%#.3f", "-98,000"}, + {-98f, "%,5f", "-98,000000"}, + {-98f, "%- (12.0f", "(98) "}, + {-98f, "%#+0(1.6f", "(98,000000)"}, + {-98f, "%-+(8.4f", "(98,0000)"}, + {-98f, "% 0#(9.8f", "(98,00000000)"}, + + {0.000001f, "%f", "0,000001"}, + {0.000001f, "%#.3f", "0,000"}, + {0.000001f, "%,5f", "0,000001"}, + {0.000001f, "%- (12.0f", " 0 "}, + {0.000001f, "%#+0(1.6f", "+0,000001"}, + {0.000001f, "%-+(8.4f", "+0,0000 "}, + {0.000001f, "% 0#(9.8f", " 0,00000100"}, + + {345.1234567f, "%f", "345,123444"}, + {345.1234567f, "%#.3f", "345,123"}, + {345.1234567f, "%,5f", "345,123444"}, + {345.1234567f, "%- (12.0f", " 345 "}, + {345.1234567f, "%#+0(1.6f", "+345,123444"}, + {345.1234567f, "%-+(8.4f", "+345,1234"}, + {345.1234567f, "% 0#(9.8f", " 345,12344360"}, + + {-.00000012345f, "%f", "-0,000000"}, + {-.00000012345f, "%#.3f", "-0,000"}, + {-.00000012345f, "%,5f", "-0,000000"}, + {-.00000012345f, "%- (12.0f", "(0) "}, + {-.00000012345f, "%#+0(1.6f", "(0,000000)"}, + {-.00000012345f, "%-+(8.4f", "(0,0000)"}, + {-.00000012345f, "% 0#(9.8f", "(0,00000012)"}, + + {-987654321.1234567f, "%f", "-987654336,000000"}, + {-987654321.1234567f, "%#.3f", "-987654336,000"}, + {-987654321.1234567f, "%,5f", "-987.654.336,000000"}, + {-987654321.1234567f, "%- (12.0f", "(987654336) "}, + {-987654321.1234567f, "%#+0(1.6f", "(987654336,000000)"}, + {-987654321.1234567f, "%-+(8.4f", "(987654336,0000)"}, + {-987654321.1234567f, "% 0#(9.8f", "(987654336,00000000)"}, + + {Float.MAX_VALUE, "%f", "340282346638528860000000000000000000000,000000"}, + {Float.MAX_VALUE, "%#.3f", "340282346638528860000000000000000000000,000"}, + {Float.MAX_VALUE, "%,5f", "340.282.346.638.528.860.000.000.000.000.000.000.000,000000"}, + {Float.MAX_VALUE, "%- (12.0f", " 340282346638528860000000000000000000000"}, + {Float.MAX_VALUE, "%#+0(1.6f", "+340282346638528860000000000000000000000,000000"}, + {Float.MAX_VALUE, "%-+(8.4f", "+340282346638528860000000000000000000000,0000"}, + {Float.MAX_VALUE, "% 0#(9.8f", " 340282346638528860000000000000000000000,00000000"}, + + {Float.MIN_VALUE, "%f", "0,000000"}, + {Float.MIN_VALUE, "%#.3f", "0,000"}, + {Float.MIN_VALUE, "%,5f", "0,000000"}, + {Float.MIN_VALUE, "%- (12.0f", " 0 "}, + {Float.MIN_VALUE, "%#+0(1.6f", "+0,000000"}, + {Float.MIN_VALUE, "%-+(8.4f", "+0,0000 "}, + {Float.MIN_VALUE, "% 0#(9.8f", " 0,00000000"}, + + {Float.NaN, "%f", "NaN"}, + {Float.NaN, "%#.3f", "NaN"}, + {Float.NaN, "%,5f", " NaN"}, + {Float.NaN, "%- (12.0f", "NaN "}, + {Float.NaN, "%#+0(1.6f", "NaN"}, + {Float.NaN, "%-+(8.4f", "NaN "}, + {Float.NaN, "% 0#(9.8f", " NaN"}, + + {Float.NEGATIVE_INFINITY, "%f", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#.3f", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%,5f", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%- (12.0f", "(Infinity) "}, + {Float.NEGATIVE_INFINITY, "%#+0(1.6f", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "%-+(8.4f", "(Infinity)"}, + {Float.NEGATIVE_INFINITY, "% 0#(9.8f", "(Infinity)"}, + + {Float.POSITIVE_INFINITY, "%f", "Infinity"}, + {Float.POSITIVE_INFINITY, "%#.3f", "Infinity"}, + {Float.POSITIVE_INFINITY, "%,5f", "Infinity"}, + {Float.POSITIVE_INFINITY, "%- (12.0f", " Infinity "}, + {Float.POSITIVE_INFINITY, "%#+0(1.6f", "+Infinity"}, + {Float.POSITIVE_INFINITY, "%-+(8.4f", "+Infinity"}, + {Float.POSITIVE_INFINITY, "% 0#(9.8f", " Infinity"}, + + + {0d, "%f", "0,000000"}, + {0d, "%#.3f", "0,000"}, + {0d, "%,5f", "0,000000"}, + {0d, "%- (12.0f", " 0 "}, + {0d, "%#+0(1.6f", "+0,000000"}, + {0d, "%-+(8.4f", "+0,0000 "}, + {0d, "% 0#(9.8f", " 0,00000000"}, + + {1d, "%f", "1,000000"}, + {1d, "%#.3f", "1,000"}, + {1d, "%,5f", "1,000000"}, + {1d, "%- (12.0f", " 1 "}, + {1d, "%#+0(1.6f", "+1,000000"}, + {1d, "%-+(8.4f", "+1,0000 "}, + {1d, "% 0#(9.8f", " 1,00000000"}, + + {-1d, "%f", "-1,000000"}, + {-1d, "%#.3f", "-1,000"}, + {-1d, "%,5f", "-1,000000"}, + {-1d, "%- (12.0f", "(1) "}, + {-1d, "%#+0(1.6f", "(1,000000)"}, + {-1d, "%-+(8.4f", "(1,0000)"}, + {-1d, "% 0#(9.8f", "(1,00000000)"}, + + {.00000001d, "%f", "0,000000"}, + {.00000001d, "%#.3f", "0,000"}, + {.00000001d, "%,5f", "0,000000"}, + {.00000001d, "%- (12.0f", " 0 "}, + {.00000001d, "%#+0(1.6f", "+0,000000"}, + {.00000001d, "%-+(8.4f", "+0,0000 "}, + {.00000001d, "% 0#(9.8f", " 0,00000001"}, + + {1000.10d, "%f", "1000,100000"}, + {1000.10d, "%#.3f", "1000,100"}, + {1000.10d, "%,5f", "1.000,100000"}, + {1000.10d, "%- (12.0f", " 1000 "}, + {1000.10d, "%#+0(1.6f", "+1000,100000"}, + {1000.10d, "%-+(8.4f", "+1000,1000"}, + {1000.10d, "% 0#(9.8f", " 1000,10000000"}, + + {0.1d, "%f", "0,100000"}, + {0.1d, "%#.3f", "0,100"}, + {0.1d, "%,5f", "0,100000"}, + {0.1d, "%- (12.0f", " 0 "}, + {0.1d, "%#+0(1.6f", "+0,100000"}, + {0.1d, "%-+(8.4f", "+0,1000 "}, + {0.1d, "% 0#(9.8f", " 0,10000000"}, + + {-2.d, "%f", "-2,000000"}, + {-2.d, "%#.3f", "-2,000"}, + {-2.d, "%,5f", "-2,000000"}, + {-2.d, "%- (12.0f", "(2) "}, + {-2.d, "%#+0(1.6f", "(2,000000)"}, + {-2.d, "%-+(8.4f", "(2,0000)"}, + {-2.d, "% 0#(9.8f", "(2,00000000)"}, + + {-.00009d, "%f", "-0,000090"}, + {-.00009d, "%#.3f", "-0,000"}, + {-.00009d, "%,5f", "-0,000090"}, + {-.00009d, "%- (12.0f", "(0) "}, + {-.00009d, "%#+0(1.6f", "(0,000090)"}, + {-.00009d, "%-+(8.4f", "(0,0001)"}, + {-.00009d, "% 0#(9.8f", "(0,00009000)"}, + + {-1234567890.012345678d, "%f", "-1234567890,012346"}, + {-1234567890.012345678d, "%#.3f", "-1234567890,012"}, + {-1234567890.012345678d, "%,5f", "-1.234.567.890,012346"}, + {-1234567890.012345678d, "%- (12.0f", "(1234567890)"}, + {-1234567890.012345678d, "%#+0(1.6f", "(1234567890,012346)"}, + {-1234567890.012345678d, "%-+(8.4f", "(1234567890,0123)"}, + {-1234567890.012345678d, "% 0#(9.8f", "(1234567890,01234580)"}, + + {Double.MAX_VALUE, "%f", "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000000"}, + {Double.MAX_VALUE, "%#.3f", "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000"}, + {Double.MAX_VALUE, "%,5f", "179.769.313.486.231.570.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000,000000"}, + {Double.MAX_VALUE, "%- (12.0f", " 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"}, + {Double.MAX_VALUE, "%#+0(1.6f", "+179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000000"}, + {Double.MAX_VALUE, "%-+(8.4f", "+179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,0000"}, + {Double.MAX_VALUE, "% 0#(9.8f", " 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,00000000"}, + + {Double.MIN_VALUE, "%f", "0,000000"}, + {Double.MIN_VALUE, "%#.3f", "0,000"}, + {Double.MIN_VALUE, "%,5f", "0,000000"}, + {Double.MIN_VALUE, "%- (12.0f", " 0 "}, + {Double.MIN_VALUE, "%#+0(1.6f", "+0,000000"}, + {Double.MIN_VALUE, "%-+(8.4f", "+0,0000 "}, + {Double.MIN_VALUE, "% 0#(9.8f", " 0,00000000"}, + + {Double.NaN, "%f", "NaN"}, + {Double.NaN, "%#.3f", "NaN"}, + {Double.NaN, "%,5f", " NaN"}, + {Double.NaN, "%- (12.0f", "NaN "}, + {Double.NaN, "%#+0(1.6f", "NaN"}, + {Double.NaN, "%-+(8.4f", "NaN "}, + {Double.NaN, "% 0#(9.8f", " NaN"}, + + {Double.POSITIVE_INFINITY, "%f", "Infinity"}, + {Double.POSITIVE_INFINITY, "%#.3f", "Infinity"}, + {Double.POSITIVE_INFINITY, "%,5f", "Infinity"}, + {Double.POSITIVE_INFINITY, "%- (12.0f", " Infinity "}, + {Double.POSITIVE_INFINITY, "%#+0(1.6f", "+Infinity"}, + {Double.POSITIVE_INFINITY, "%-+(8.4f", "+Infinity"}, + {Double.POSITIVE_INFINITY, "% 0#(9.8f", " Infinity"}, + + {Double.NEGATIVE_INFINITY, "%f", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%#.3f", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%,5f", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%- (12.0f", "(Infinity) "}, + {Double.NEGATIVE_INFINITY, "%#+0(1.6f", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "%-+(8.4f", "(Infinity)"}, + {Double.NEGATIVE_INFINITY, "% 0#(9.8f", "(Infinity)"}, + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleF.length; i++) { + f = new Formatter(Locale.GERMAN); + f.format((String)tripleF[i][pattern], tripleF[i][input]); + assertEquals("triple[" + i + "]:" + tripleF[i][input] + ",pattern[" + + i + "]:" + tripleF[i][pattern], + tripleF[i][output], f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for Float/Double + * conversion type 'a' and 'A' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionA() { + Formatter f = null; + final Object[][] tripleA = { + {-0f, "%a", "-0x0.0p0"}, + {-0f, "%#.3a", "-0x0.000p0"}, + {-0f, "%5a", "-0x0.0p0"}, + {-0f, "%- 12.0a", "-0x0.0p0 "}, + {-0f, "%#+01.6a", "-0x0.000000p0"}, + {-0f, "%-+8.4a", "-0x0.0000p0"}, + + {0f, "%a", "0x0.0p0"}, + {0f, "%#.3a", "0x0.000p0"}, + {0f, "%5a", "0x0.0p0"}, + {0f, "%- 12.0a", " 0x0.0p0 "}, + {0f, "%#+01.6a", "+0x0.000000p0"}, + {0f, "%-+8.4a", "+0x0.0000p0"}, + + {1234f, "%a", "0x1.348p10"}, + {1234f, "%#.3a", "0x1.348p10"}, + {1234f, "%5a", "0x1.348p10"}, + {1234f, "%- 12.0a", " 0x1.3p10 "}, + {1234f, "%#+01.6a", "+0x1.348000p10"}, + {1234f, "%-+8.4a", "+0x1.3480p10"}, + + {1.f, "%a", "0x1.0p0"}, + {1.f, "%#.3a", "0x1.000p0"}, + {1.f, "%5a", "0x1.0p0"}, + {1.f, "%- 12.0a", " 0x1.0p0 "}, + {1.f, "%#+01.6a", "+0x1.000000p0"}, + {1.f, "%-+8.4a", "+0x1.0000p0"}, + + {-98f, "%a", "-0x1.88p6"}, + {-98f, "%#.3a", "-0x1.880p6"}, + {-98f, "%5a", "-0x1.88p6"}, + {-98f, "%- 12.0a", "-0x1.8p6 "}, + {-98f, "%#+01.6a", "-0x1.880000p6"}, + {-98f, "%-+8.4a", "-0x1.8800p6"}, + + {345.1234567f, "%a", "0x1.591f9ap8"}, + {345.1234567f, "%5a", "0x1.591f9ap8"}, + {345.1234567f, "%#+01.6a", "+0x1.591f9ap8"}, + + {-987654321.1234567f, "%a", "-0x1.d6f346p29"}, + {-987654321.1234567f, "%#.3a", "-0x1.d6fp29"}, + {-987654321.1234567f, "%5a", "-0x1.d6f346p29"}, + {-987654321.1234567f, "%- 12.0a", "-0x1.dp29 "}, + {-987654321.1234567f, "%#+01.6a", "-0x1.d6f346p29"}, + {-987654321.1234567f, "%-+8.4a", "-0x1.d6f3p29"}, + + {Float.MAX_VALUE, "%a", "0x1.fffffep127"}, + {Float.MAX_VALUE, "%5a", "0x1.fffffep127"}, + {Float.MAX_VALUE, "%#+01.6a", "+0x1.fffffep127"}, + + {Float.NaN, "%a", "NaN"}, + {Float.NaN, "%#.3a", "NaN"}, + {Float.NaN, "%5a", " NaN"}, + {Float.NaN, "%- 12.0a", "NaN "}, + {Float.NaN, "%#+01.6a", "NaN"}, + {Float.NaN, "%-+8.4a", "NaN "}, + + {Float.NEGATIVE_INFINITY, "%a", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%#.3a", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%5a", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%- 12.0a", "-Infinity "}, + {Float.NEGATIVE_INFINITY, "%#+01.6a", "-Infinity"}, + {Float.NEGATIVE_INFINITY, "%-+8.4a", "-Infinity"}, + + {Float.POSITIVE_INFINITY, "%a", "Infinity"}, + {Float.POSITIVE_INFINITY, "%#.3a", "Infinity"}, + {Float.POSITIVE_INFINITY, "%5a", "Infinity"}, + {Float.POSITIVE_INFINITY, "%- 12.0a", " Infinity "}, + {Float.POSITIVE_INFINITY, "%#+01.6a", "+Infinity"}, + {Float.POSITIVE_INFINITY, "%-+8.4a", "+Infinity"}, + + {-0d, "%a", "-0x0.0p0"}, + {-0d, "%#.3a", "-0x0.000p0"}, + {-0d, "%5a", "-0x0.0p0"}, + {-0d, "%- 12.0a", "-0x0.0p0 "}, + {-0d, "%#+01.6a", "-0x0.000000p0"}, + {-0d, "%-+8.4a", "-0x0.0000p0"}, + + {0d, "%a", "0x0.0p0"}, + {0d, "%#.3a", "0x0.000p0"}, + {0d, "%5a", "0x0.0p0"}, + {0d, "%- 12.0a", " 0x0.0p0 "}, + {0d, "%#+01.6a", "+0x0.000000p0"}, + {0d, "%-+8.4a", "+0x0.0000p0"}, + + {1d, "%a", "0x1.0p0"}, + {1d, "%#.3a", "0x1.000p0"}, + {1d, "%5a", "0x1.0p0"}, + {1d, "%- 12.0a", " 0x1.0p0 "}, + {1d, "%#+01.6a", "+0x1.000000p0"}, + {1d, "%-+8.4a", "+0x1.0000p0"}, + + {-1d, "%a", "-0x1.0p0"}, + {-1d, "%#.3a", "-0x1.000p0"}, + {-1d, "%5a", "-0x1.0p0"}, + {-1d, "%- 12.0a", "-0x1.0p0 "}, + {-1d, "%#+01.6a", "-0x1.000000p0"}, + {-1d, "%-+8.4a", "-0x1.0000p0"}, + + {.00000001d, "%a", "0x1.5798ee2308c3ap-27"}, + {.00000001d, "%5a", "0x1.5798ee2308c3ap-27"}, + {.00000001d, "%- 12.0a", " 0x1.5p-27 "}, + {.00000001d, "%#+01.6a", "+0x1.5798eep-27"}, + + {1000.10d, "%a", "0x1.f40cccccccccdp9"}, + {1000.10d, "%5a", "0x1.f40cccccccccdp9"}, + {1000.10d, "%- 12.0a", " 0x1.fp9 "}, + + {0.1d, "%a", "0x1.999999999999ap-4"}, + {0.1d, "%5a", "0x1.999999999999ap-4"}, + + {-2.d, "%a", "-0x1.0p1"}, + {-2.d, "%#.3a", "-0x1.000p1"}, + {-2.d, "%5a", "-0x1.0p1"}, + {-2.d, "%- 12.0a", "-0x1.0p1 "}, + {-2.d, "%#+01.6a", "-0x1.000000p1"}, + {-2.d, "%-+8.4a", "-0x1.0000p1"}, + + {-.00009d, "%a", "-0x1.797cc39ffd60fp-14"}, + {-.00009d, "%5a", "-0x1.797cc39ffd60fp-14"}, + + {-1234567890.012345678d, "%a", "-0x1.26580b480ca46p30"}, + {-1234567890.012345678d, "%5a", "-0x1.26580b480ca46p30"}, + {-1234567890.012345678d, "%- 12.0a", "-0x1.2p30 "}, + {-1234567890.012345678d, "%#+01.6a", "-0x1.26580bp30"}, + {-1234567890.012345678d, "%-+8.4a", "-0x1.2658p30"}, + + {Double.MAX_VALUE, "%a", "0x1.fffffffffffffp1023"}, + {Double.MAX_VALUE, "%5a", "0x1.fffffffffffffp1023"}, + + {Double.MIN_VALUE, "%a", "0x0.0000000000001p-1022"}, + {Double.MIN_VALUE, "%5a", "0x0.0000000000001p-1022"}, + + {Double.NaN, "%a", "NaN"}, + {Double.NaN, "%#.3a", "NaN"}, + {Double.NaN, "%5a", " NaN"}, + {Double.NaN, "%- 12.0a", "NaN "}, + {Double.NaN, "%#+01.6a", "NaN"}, + {Double.NaN, "%-+8.4a", "NaN "}, + + {Double.NEGATIVE_INFINITY, "%a", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%#.3a", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%5a", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%- 12.0a", "-Infinity "}, + {Double.NEGATIVE_INFINITY, "%#+01.6a", "-Infinity"}, + {Double.NEGATIVE_INFINITY, "%-+8.4a", "-Infinity"}, + + {Double.POSITIVE_INFINITY, "%a", "Infinity"}, + {Double.POSITIVE_INFINITY, "%#.3a", "Infinity"}, + {Double.POSITIVE_INFINITY, "%5a", "Infinity"}, + {Double.POSITIVE_INFINITY, "%- 12.0a", " Infinity "}, + {Double.POSITIVE_INFINITY, "%#+01.6a", "+Infinity"}, + {Double.POSITIVE_INFINITY, "%-+8.4a", "+Infinity"}, + + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleA.length; i++) { + f = new Formatter(Locale.UK); + f.format((String)tripleA[i][pattern], tripleA[i][input]); + assertEquals("triple[" + i + "]:" + tripleA[i][input] + ",pattern[" + + i + "]:" + tripleA[i][pattern], + tripleA[i][output], f.toString()); + + // test for conversion type 'A' + f = new Formatter(Locale.UK); + f.format(((String)tripleA[i][pattern]).toUpperCase(), tripleA[i][input]); + assertEquals("triple[" + i + "]:" + tripleA[i][input] + ",pattern[" + + i + "]:" + tripleA[i][pattern], ((String)tripleA[i][output]) + .toUpperCase(Locale.UK), f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigDecimal + * conversion type 'e' and 'E' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionE() { + Formatter f = null; + final Object[][] tripleE = { + {BigDecimal.ZERO, "%e", "0.000000e+00"}, + {BigDecimal.ZERO, "%#.0e", "0.e+00"}, + {BigDecimal.ZERO, "%# 9.8e", " 0.00000000e+00"}, + {BigDecimal.ZERO, "%#+0(8.4e", "+0.0000e+00"}, + {BigDecimal.ZERO, "%-+17.6e", "+0.000000e+00 "}, + {BigDecimal.ZERO, "% 0(20e", " 00000000.000000e+00"}, + + {BigDecimal.ONE, "%e", "1.000000e+00"}, + {BigDecimal.ONE, "%#.0e", "1.e+00"}, + {BigDecimal.ONE, "%# 9.8e", " 1.00000000e+00"}, + {BigDecimal.ONE, "%#+0(8.4e", "+1.0000e+00"}, + {BigDecimal.ONE, "%-+17.6e", "+1.000000e+00 "}, + {BigDecimal.ONE, "% 0(20e", " 00000001.000000e+00"}, + + {BigDecimal.TEN, "%e", "1.000000e+01"}, + {BigDecimal.TEN, "%#.0e", "1.e+01"}, + {BigDecimal.TEN, "%# 9.8e", " 1.00000000e+01"}, + {BigDecimal.TEN, "%#+0(8.4e", "+1.0000e+01"}, + {BigDecimal.TEN, "%-+17.6e", "+1.000000e+01 "}, + {BigDecimal.TEN, "% 0(20e", " 00000001.000000e+01"}, + + {new BigDecimal(-1), "%e", "-1.000000e+00"}, + {new BigDecimal(-1), "%#.0e", "-1.e+00"}, + {new BigDecimal(-1), "%# 9.8e", "-1.00000000e+00"}, + {new BigDecimal(-1), "%#+0(8.4e", "(1.0000e+00)"}, + {new BigDecimal(-1), "%-+17.6e", "-1.000000e+00 "}, + {new BigDecimal(-1), "% 0(20e", "(0000001.000000e+00)"}, + + {new BigDecimal("5.000E999"), "%e", "5.000000e+999"}, + {new BigDecimal("5.000E999"), "%#.0e", "5.e+999"}, + {new BigDecimal("5.000E999"), "%# 9.8e", " 5.00000000e+999"}, + {new BigDecimal("5.000E999"), "%#+0(8.4e", "+5.0000e+999"}, + {new BigDecimal("5.000E999"), "%-+17.6e", "+5.000000e+999 "}, + {new BigDecimal("5.000E999"), "% 0(20e", " 0000005.000000e+999"}, + + {new BigDecimal("-5.000E999"), "%e", "-5.000000e+999"}, + {new BigDecimal("-5.000E999"), "%#.0e", "-5.e+999"}, + {new BigDecimal("-5.000E999"), "%# 9.8e", "-5.00000000e+999"}, + {new BigDecimal("-5.000E999"), "%#+0(8.4e", "(5.0000e+999)"}, + {new BigDecimal("-5.000E999"), "%-+17.6e", "-5.000000e+999 "}, + {new BigDecimal("-5.000E999"), "% 0(20e", "(000005.000000e+999)"}, + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleE.length; i++) { + f = new Formatter(Locale.US); + f.format((String)tripleE[i][pattern], tripleE[i][input]); + assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern[" + + i + "]:" + tripleE[i][pattern], + tripleE[i][output], f.toString()); + + // test for conversion type 'E' + f = new Formatter(Locale.US); + f.format(((String)tripleE[i][pattern]).toUpperCase(), tripleE[i][input]); + assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern[" + + i + "]:" + tripleE[i][pattern], ((String)tripleE[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigDecimal + * conversion type 'g' and 'G' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionG() { + Formatter f = null; + final Object[][] tripleG = { + {BigDecimal.ZERO, "%g", "0.00000"}, + {BigDecimal.ZERO, "%.5g", "0.0000"}, + {BigDecimal.ZERO, "%- (,9.8g", " 0.0000000"}, + {BigDecimal.ZERO, "%+0(,8.4g", "+000.000"}, + {BigDecimal.ZERO, "%-+10.6g", "+0.00000 "}, + {BigDecimal.ZERO, "% 0(,12.0g", " 00000000000"}, + {BigDecimal.ONE, "%g", "1.00000"}, + {BigDecimal.ONE, "%.5g", "1.0000"}, + {BigDecimal.ONE, "%- (,9.8g", " 1.0000000"}, + {BigDecimal.ONE, "%+0(,8.4g", "+001.000"}, + {BigDecimal.ONE, "%-+10.6g", "+1.00000 "}, + {BigDecimal.ONE, "% 0(,12.0g", " 00000000001"}, + + {new BigDecimal(-1), "%g", "-1.00000"}, + {new BigDecimal(-1), "%.5g", "-1.0000"}, + {new BigDecimal(-1), "%- (,9.8g", "(1.0000000)"}, + {new BigDecimal(-1), "%+0(,8.4g", "(01.000)"}, + {new BigDecimal(-1), "%-+10.6g", "-1.00000 "}, + {new BigDecimal(-1), "% 0(,12.0g", "(0000000001)"}, + + {new BigDecimal(-0.000001), "%g", "-1.00000e-06"}, + {new BigDecimal(-0.000001), "%.5g", "-1.0000e-06"}, + {new BigDecimal(-0.000001), "%- (,9.8g", "(1.0000000e-06)"}, + {new BigDecimal(-0.000001), "%+0(,8.4g", "(1.000e-06)"}, + {new BigDecimal(-0.000001), "%-+10.6g", "-1.00000e-06"}, + {new BigDecimal(-0.000001), "% 0(,12.0g", "(000001e-06)"}, + + {new BigDecimal(0.0002), "%g", "0.000200000"}, + {new BigDecimal(0.0002), "%.5g", "0.00020000"}, + {new BigDecimal(0.0002), "%- (,9.8g", " 0.00020000000"}, + {new BigDecimal(0.0002), "%+0(,8.4g", "+0.0002000"}, + {new BigDecimal(0.0002), "%-+10.6g", "+0.000200000"}, + {new BigDecimal(0.0002), "% 0(,12.0g", " 000000.0002"}, + + {new BigDecimal(-0.003), "%g", "-0.00300000"}, + {new BigDecimal(-0.003), "%.5g", "-0.0030000"}, + {new BigDecimal(-0.003), "%- (,9.8g", "(0.0030000000)"}, + {new BigDecimal(-0.003), "%+0(,8.4g", "(0.003000)"}, + {new BigDecimal(-0.003), "%-+10.6g", "-0.00300000"}, + {new BigDecimal(-0.003), "% 0(,12.0g", "(000000.003)"}, + + {new BigDecimal("5.000E999"), "%g", "5.00000e+999"}, + {new BigDecimal("5.000E999"), "%.5g", "5.0000e+999"}, + {new BigDecimal("5.000E999"), "%- (,9.8g", " 5.0000000e+999"}, + {new BigDecimal("5.000E999"), "%+0(,8.4g", "+5.000e+999"}, + {new BigDecimal("5.000E999"), "%-+10.6g", "+5.00000e+999"}, + {new BigDecimal("5.000E999"), "% 0(,12.0g", " 000005e+999"}, + + {new BigDecimal("-5.000E999"), "%g", "-5.00000e+999"}, + {new BigDecimal("-5.000E999"), "%.5g", "-5.0000e+999"}, + {new BigDecimal("-5.000E999"), "%- (,9.8g", "(5.0000000e+999)"}, + {new BigDecimal("-5.000E999"), "%+0(,8.4g", "(5.000e+999)"}, + {new BigDecimal("-5.000E999"), "%-+10.6g", "-5.00000e+999"}, + {new BigDecimal("-5.000E999"), "% 0(,12.0g", "(00005e+999)"}, + }; + final int input = 0; + final int pattern = 1; + final int output = 2; + for (int i = 0; i < tripleG.length; i++) { + f = new Formatter(Locale.US); + f.format((String)tripleG[i][pattern], tripleG[i][input]); + assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern[" + + i + "]:" + tripleG[i][pattern], + tripleG[i][output], f.toString()); + + // test for conversion type 'G' + f = new Formatter(Locale.US); + f.format(((String)tripleG[i][pattern]).toUpperCase(), tripleG[i][input]); + assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern[" + + i + "]:" + tripleG[i][pattern], ((String)tripleG[i][output]) + .toUpperCase(Locale.US), f.toString()); + } + + f = new Formatter(Locale.GERMAN); + f.format("%- (,9.6g", new BigDecimal("4E6")); + /* + * fail on RI, spec says 'g' requires the output to be formatted in + * general scientific notation and the localization algorithm is + * applied. But RI format this case to 4.00000e+06, which does not + * conform to the German Locale + */ + assertEquals(" 4,00000e+06", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigDecimal + * conversion type 'f' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionF() { + + Formatter f = null; + final int input = 0; + final int pattern = 1; + final int output = 2; + final Object[][] tripleF = { + {BigDecimal.ZERO, "%f", "0.000000"}, + {BigDecimal.ZERO, "%#.3f", "0.000"}, + {BigDecimal.ZERO, "%#,5f", "0.000000"}, + {BigDecimal.ZERO, "%- #(12.0f", " 0. "}, + {BigDecimal.ZERO, "%#+0(1.6f", "+0.000000"}, + {BigDecimal.ZERO, "%-+(8.4f", "+0.0000 "}, + {BigDecimal.ZERO, "% 0#(9.8f", " 0.00000000"}, + {BigDecimal.ONE, "%f", "1.000000"}, + {BigDecimal.ONE, "%#.3f", "1.000"}, + {BigDecimal.ONE, "%#,5f", "1.000000"}, + {BigDecimal.ONE, "%- #(12.0f", " 1. "}, + {BigDecimal.ONE, "%#+0(1.6f", "+1.000000"}, + {BigDecimal.ONE, "%-+(8.4f", "+1.0000 "}, + {BigDecimal.ONE, "% 0#(9.8f", " 1.00000000"}, + {BigDecimal.TEN, "%f", "10.000000"}, + {BigDecimal.TEN, "%#.3f", "10.000"}, + {BigDecimal.TEN, "%#,5f", "10.000000"}, + {BigDecimal.TEN, "%- #(12.0f", " 10. "}, + {BigDecimal.TEN, "%#+0(1.6f", "+10.000000"}, + {BigDecimal.TEN, "%-+(8.4f", "+10.0000"}, + {BigDecimal.TEN, "% 0#(9.8f", " 10.00000000"}, + {new BigDecimal(-1), "%f", "-1.000000"}, + {new BigDecimal(-1), "%#.3f", "-1.000"}, + {new BigDecimal(-1), "%#,5f", "-1.000000"}, + {new BigDecimal(-1), "%- #(12.0f", "(1.) "}, + {new BigDecimal(-1), "%#+0(1.6f", "(1.000000)"}, + {new BigDecimal(-1), "%-+(8.4f", "(1.0000)"}, + {new BigDecimal(-1), "% 0#(9.8f", "(1.00000000)"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%f", "9999999999999999999999999999999999999999999.000000"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%#.3f", "9999999999999999999999999999999999999999999.000"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%#,5f", "9,999,999,999,999,999,999,999,999,999,999,999,999,999,999.000000"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%- #(12.0f", " 9999999999999999999999999999999999999999999."}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%#+0(1.6f", "+9999999999999999999999999999999999999999999.000000"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "%-+(8.4f", "+9999999999999999999999999999999999999999999.0000"}, + {new BigDecimal("9999999999999999999999999999999999999999999"), "% 0#(9.8f", " 9999999999999999999999999999999999999999999.00000000"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%f", "-9999999999999999999999999999999999999999999.000000"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#.3f", "-9999999999999999999999999999999999999999999.000"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#,5f", "-9,999,999,999,999,999,999,999,999,999,999,999,999,999,999.000000"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%- #(12.0f", "(9999999999999999999999999999999999999999999.)"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#+0(1.6f", "(9999999999999999999999999999999999999999999.000000)"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "%-+(8.4f", "(9999999999999999999999999999999999999999999.0000)"}, + {new BigDecimal("-9999999999999999999999999999999999999999999"), "% 0#(9.8f", "(9999999999999999999999999999999999999999999.00000000)"}, + }; + for (int i = 0; i < tripleF.length; i++) { + f = new Formatter(Locale.US); + f.format((String)tripleF[i][pattern], tripleF[i][input]); + assertEquals("triple[" + i + "]:" + tripleF[i][input] + ",pattern[" + + i + "]:" + tripleF[i][pattern], tripleF[i][output], f.toString()); + } + + f = new Formatter(Locale.US); + f.format("%f", new BigDecimal("5.0E9")); + // error on RI + // RI throw ArrayIndexOutOfBoundsException + assertEquals("5000000000.000000", f.toString()); + } + + /** + * @tests java.util.Formatter#format(String, Object...) for exceptions in + * Float/Double/BigDecimal conversion type 'e', 'E', 'g', 'G', 'f', 'a', 'A' + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalConversionException() { + Formatter f = null; + + final char[] conversions = { 'e', 'E', 'g', 'G', 'f', 'a', 'A' }; + final Object[] illArgs = { false, (byte) 1, (short) 2, 3, (long) 4, + new BigInteger("5"), new Character('c'), new Object(), + new Date() }; + for (int i = 0; i < illArgs.length; i++) { + for (int j = 0; j < conversions.length; j++) { + try { + f = new Formatter(Locale.UK); + f.format("%" + conversions[j], illArgs[i]); + fail("should throw IllegalFormatConversionException"); + } catch (IllegalFormatConversionException e) { + // expected + } + } + } + + try { + f = new Formatter(Locale.UK); + f.format("%a", new BigDecimal(1)); + fail("should throw IllegalFormatConversionException"); + } catch (IllegalFormatConversionException e) { + // expected + } + + try { + f = new Formatter(Locale.UK); + f.format("%A", new BigDecimal(1)); + fail("should throw IllegalFormatConversionException"); + } catch (IllegalFormatConversionException e) { + // expected + } + + final String[] flagsConversionMismatches = { "%,e", "%,E", "%#g", + "%#G", "%,a", "%,A", "%(a", "%(A" }; + for (int i = 0; i < flagsConversionMismatches.length; i++) { + try { + f = new Formatter(Locale.CHINA); + f.format(flagsConversionMismatches[i], new BigDecimal(1)); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + try { + f = new Formatter(Locale.JAPAN); + f.format(flagsConversionMismatches[i], (BigDecimal) null); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + } + + final String[] missingFormatWidths = { "%-0e", "%0e", "%-e", "%-0E", + "%0E", "%-E", "%-0g", "%0g", "%-g", "%-0G", "%0G", "%-G", + "%-0f", "%0f", "%-f", "%-0a", "%0a", "%-a", "%-0A", "%0A", + "%-A" }; + for (int i = 0; i < missingFormatWidths.length; i++) { + try { + f = new Formatter(Locale.KOREA); + f.format(missingFormatWidths[i], 1f); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + + try { + f = new Formatter(Locale.KOREA); + f.format(missingFormatWidths[i], (Float) null); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + } + + final String[] illFlags = { "%+ e", "%+ E", "%+ g", "%+ G", "%+ f", + "%+ a", "%+ A", "%-03e", "%-03E", "%-03g", "%-03G", "%-03f", + "%-03a", "%-03A" }; + for (int i = 0; i < illFlags.length; i++) { + try { + f = new Formatter(Locale.CANADA); + f.format(illFlags[i], 1.23d); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + + try { + f = new Formatter(Locale.CANADA); + f.format(illFlags[i], (Double) null); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + } + + f = new Formatter(Locale.US); + try { + f.format("%F", 1); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for + * Float/Double/BigDecimal exception throwing order + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalExceptionOrder() { + Formatter f = null; + + /* + * Summary: UnknownFormatConversionException > + * MissingFormatWidthException > IllegalFormatFlagsException > + * FormatFlagsConversionMismatchException > + * IllegalFormatConversionException + * + */ + try { + // compare FormatFlagsConversionMismatchException and + // IllegalFormatConversionException + f = new Formatter(Locale.US); + f.format("%,e", (byte) 1); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + + try { + // compare IllegalFormatFlagsException and + // FormatFlagsConversionMismatchException + f = new Formatter(Locale.US); + f.format("%+ ,e", 1f); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + + try { + // compare MissingFormatWidthException and + // IllegalFormatFlagsException + f = new Formatter(Locale.US); + f.format("%+ -e", 1f); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + + try { + // compare UnknownFormatConversionException and + // MissingFormatWidthException + f = new Formatter(Locale.US); + f.format("%-F", 1f); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for BigDecimal + * exception throwing order + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalExceptionOrder() { + Formatter f = null; + BigDecimal bd = new BigDecimal("1.0"); + + /* + * Summary: UnknownFormatConversionException > + * MissingFormatWidthException > IllegalFormatFlagsException > + * FormatFlagsConversionMismatchException > + * IllegalFormatConversionException + * + */ + try { + // compare FormatFlagsConversionMismatchException and + // IllegalFormatConversionException + f = new Formatter(Locale.US); + f.format("%,e", (byte) 1); + fail("should throw FormatFlagsConversionMismatchException"); + } catch (FormatFlagsConversionMismatchException e) { + // expected + } + + try { + // compare IllegalFormatFlagsException and + // FormatFlagsConversionMismatchException + f = new Formatter(Locale.US); + f.format("%+ ,e", bd); + fail("should throw IllegalFormatFlagsException"); + } catch (IllegalFormatFlagsException e) { + // expected + } + + try { + // compare MissingFormatWidthException and + // IllegalFormatFlagsException + f = new Formatter(Locale.US); + f.format("%+ -e", bd); + fail("should throw MissingFormatWidthException"); + } catch (MissingFormatWidthException e) { + // expected + } + + // compare UnknownFormatConversionException and + // MissingFormatWidthException + try { + f = new Formatter(Locale.US); + f.format("%-F", bd); + fail("should throw UnknownFormatConversionException"); + } catch (UnknownFormatConversionException e) { + // expected + } + } + + /** + * @tests java.util.Formatter#format(String, Object...) for null argment for + * Float/Double/BigDecimal conversion + */ + public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalNullConversion() { + Formatter f = null; + + // test (Float)null + f = new Formatter(Locale.FRANCE); + f.format("%#- (9.0e", (Float) null); + assertEquals(" ", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%-+(1.6E", (Float) null); + assertEquals("NULL", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%+0(,8.4g", (Float) null); + assertEquals(" null", f.toString()); + + f = new Formatter(Locale.FRANCE); + f.format("%- (9.8G", (Float) null); + assertEquals("NULL ", f.toString()); + + f = new Formatter(Locale.FRANCE); + f.format("%- (12.1f", (Float) null); + assertEquals("n ", f.toString()); + + f = new Formatter(Locale.FRANCE); + f.format("% .4a", (Float) null); + assertEquals("null", f.toString()); + + f = new Formatter(Locale.FRANCE); + f.format("%06A", (Float) null); + assertEquals(" NULL", f.toString()); + + // test (Double)null + f = new Formatter(Locale.GERMAN); + f.format("%- (9e", (Double) null); + assertEquals("null ", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%#-+(1.6E", (Double) null); + assertEquals("NULL", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%+0(6.4g", (Double) null); + assertEquals(" null", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%- (,5.8G", (Double) null); + assertEquals("NULL ", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("% (.4f", (Double) null); + assertEquals("null", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("%#.6a", (Double) null); + assertEquals("null", f.toString()); + + f = new Formatter(Locale.GERMAN); + f.format("% 2.5A", (Double) null); + assertEquals("NULL", f.toString()); + + // test (BigDecimal)null + f = new Formatter(Locale.UK); + f.format("%#- (6.2e", (BigDecimal) null); + assertEquals("nu ", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%-+(1.6E", (BigDecimal) null); + assertEquals("NULL", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%+-(,5.3g", (BigDecimal) null); + assertEquals("nul ", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%0 3G", (BigDecimal) null); + assertEquals("NULL", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%0 (9.0G", (BigDecimal) null); + assertEquals(" ", f.toString()); + + f = new Formatter(Locale.UK); + f.format("% (.5f", (BigDecimal) null); + assertEquals("null", f.toString()); + + f = new Formatter(Locale.UK); + f.format("%06a", (BigDecimal) null); + assertEquals(" null", f.toString()); + + f = new Formatter(Locale.UK); + f.format("% .5A", (BigDecimal) null); + assertEquals("NULL", f.toString()); + } + + /** * @tests java.util.Formatter.BigDecimalLayoutForm#values() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "values", - args = {} - ) public void test_values() { BigDecimalLayoutForm[] vals = BigDecimalLayoutForm.values(); assertEquals("Invalid length of enum values", 2, vals.length); - assertEquals("Wrong scientific value in enum", - BigDecimalLayoutForm.SCIENTIFIC, vals[0]); - assertEquals("Wrong dec float value in enum", - BigDecimalLayoutForm.DECIMAL_FLOAT, vals[1]); + assertEquals("Wrong scientific value in enum", BigDecimalLayoutForm.SCIENTIFIC, vals[0]); + assertEquals("Wrong dec float value in enum", BigDecimalLayoutForm.DECIMAL_FLOAT, vals[1]); } /** * @tests java.util.Formatter.BigDecimalLayoutForm#valueOf(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {java.lang.String.class} - ) public void test_valueOfLjava_lang_String() { BigDecimalLayoutForm sci = BigDecimalLayoutForm.valueOf("SCIENTIFIC"); assertEquals("Wrong scientific value in enum", BigDecimalLayoutForm.SCIENTIFIC, sci); BigDecimalLayoutForm decFloat = BigDecimalLayoutForm.valueOf("DECIMAL_FLOAT"); assertEquals("Wrong dec float value from valueOf ", BigDecimalLayoutForm.DECIMAL_FLOAT, decFloat); + } + + /* + * Regression test for Harmony-5845 + * test the short name for timezone whether uses DaylightTime or not + */ + public void test_DaylightTime() { + Calendar c1 = new GregorianCalendar(2007, 0, 1); + Calendar c2 = new GregorianCalendar(2007, 7, 1); - try { - decFloat = BigDecimalLayoutForm.valueOf("Wrong format"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected + for (String tz : TimeZone.getAvailableIDs()) { + if (tz.equals("America/Los_Angeles")) { + c1.setTimeZone(TimeZone.getTimeZone(tz)); + c2.setTimeZone(TimeZone.getTimeZone(tz)); + assertTrue(String.format("%1$tZ%2$tZ", c1, c2).equals("PSTPDT")); + } + if (tz.equals("America/Panama")) { + c1.setTimeZone(TimeZone.getTimeZone(tz)); + c2.setTimeZone(TimeZone.getTimeZone(tz)); + assertTrue(String.format("%1$tZ%2$tZ", c1, c2).equals("ESTEST")); + } + } + } + + /* + * Regression test for Harmony-5845 + * test scientific notation to follow RI's behavior + */ + public void test_ScientificNotation() { + Formatter f = new Formatter(); + MathContext mc = new MathContext(30); + BigDecimal value = new BigDecimal(0.1, mc); + f.format("%.30G", value); + + String result = f.toString(); + String expected = "0.100000000000000005551115123126"; + assertEquals(expected, result); + } + + + /** + * Setup resource files for testing + */ + protected void setUp() throws IOException { + root = System.getProperty("user.name").equalsIgnoreCase("root"); + notExist = File.createTempFile("notexist", null); + notExist.delete(); + + fileWithContent = File.createTempFile("filewithcontent", null); + BufferedOutputStream bw = new BufferedOutputStream( + new FileOutputStream(fileWithContent)); + bw.write(1);// write something into the file + bw.close(); + + readOnly = File.createTempFile("readonly", null); + readOnly.setReadOnly(); + + secret = File.createTempFile("secret", null); + + defaultTimeZone = TimeZone.getDefault(); + TimeZone cst = TimeZone.getTimeZone("Asia/Shanghai"); + TimeZone.setDefault(cst); + } + + /** + * Delete the resource files if they exist + */ + protected void tearDown() { + if (notExist.exists()) { + notExist.delete(); + } + + if (fileWithContent.exists()) { + fileWithContent.delete(); + } + if (readOnly.exists()) { + readOnly.delete(); + } + if (secret.exists()) { + secret.delete(); } + + TimeZone.setDefault(defaultTimeZone); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java index 56ba684..39f7216 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java @@ -1,71 +1,754 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(HashMap.class) -public class HashMapTest extends TestCase { - class SubMap<K, V> extends HashMap<K, V> { - public SubMap(Map<? extends K, ? extends V> m) { - super(m); +import tests.support.Support_MapTest2; +import tests.support.Support_UnmodifiableCollectionTest; + +public class HashMapTest extends junit.framework.TestCase { + class MockMap extends AbstractMap { + public Set entrySet() { + return null; + } + public int size(){ + return 0; + } + } + + private static class MockMapNull extends AbstractMap { + public Set entrySet() { + return null; } - public V put(K key, V value) { - throw new UnsupportedOperationException(); + public int size() { + return 10; } } + + interface MockInterface { + public String mockMethod(); + } - /** - * @tests java.util.HashMap#HashMap(java.util.Map) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "NullPointerException is not verified.", - method = "HashMap", - args = {java.util.Map.class} - ) - public void test_ConstructorLjava_util_Map() { + class MockClass implements MockInterface { + public String mockMethod() { + return "This is a MockClass"; + } + } + + class MockHandler implements InvocationHandler { + + Object obj; + + public MockHandler(Object o) { + obj = o; + } + + public Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { + + Object result = null; + + try { + + result = m.invoke(obj, args); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + + } + return result; + } + + } + + + HashMap hm; + + final static int hmSize = 1000; + + static Object[] objArray; + + static Object[] objArray2; + { + objArray = new Object[hmSize]; + objArray2 = new Object[hmSize]; + for (int i = 0; i < objArray.length; i++) { + objArray[i] = new Integer(i); + objArray2[i] = objArray[i].toString(); + } + } + + /** + * @tests java.util.HashMap#HashMap() + */ + public void test_Constructor() { + // Test for method java.util.HashMap() + new Support_MapTest2(new HashMap()).runTest(); + + HashMap hm2 = new HashMap(); + assertEquals("Created incorrect HashMap", 0, hm2.size()); + } + + /** + * @tests java.util.HashMap#HashMap(int) + */ + public void test_ConstructorI() { + // Test for method java.util.HashMap(int) + HashMap hm2 = new HashMap(5); + assertEquals("Created incorrect HashMap", 0, hm2.size()); + try { + new HashMap(-1); + } catch (IllegalArgumentException e) { + return; + } + fail( + "Failed to throw IllegalArgumentException for initial capacity < 0"); + + HashMap empty = new HashMap(0); + assertNull("Empty hashmap access", empty.get("nothing")); + empty.put("something", "here"); + assertTrue("cannot get element", empty.get("something") == "here"); + } + + /** + * @tests java.util.HashMap#HashMap(int, float) + */ + public void test_ConstructorIF() { + // Test for method java.util.HashMap(int, float) + HashMap hm2 = new HashMap(5, (float) 0.5); + assertEquals("Created incorrect HashMap", 0, hm2.size()); + try { + new HashMap(0, 0); + } catch (IllegalArgumentException e) { + return; + } + fail( + "Failed to throw IllegalArgumentException for initial load factor <= 0"); + + HashMap empty = new HashMap(0, 0.75f); + assertNull("Empty hashtable access", empty.get("nothing")); + empty.put("something", "here"); + assertTrue("cannot get element", empty.get("something") == "here"); + } + + /** + * @tests java.util.HashMap#HashMap(java.util.Map) + */ + public void test_ConstructorLjava_util_Map() { + // Test for method java.util.HashMap(java.util.Map) + Map myMap = new TreeMap(); + for (int counter = 0; counter < hmSize; counter++) + myMap.put(objArray2[counter], objArray[counter]); + HashMap hm2 = new HashMap(myMap); + for (int counter = 0; counter < hmSize; counter++) + assertTrue("Failed to construct correct HashMap", hm + .get(objArray2[counter]) == hm2.get(objArray2[counter])); + + try { + Map mockMap = new MockMap(); + hm = new HashMap(mockMap); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + //empty + } + HashMap map = new HashMap(); map.put("a", "a"); SubMap map2 = new SubMap(map); assertTrue(map2.containsKey("a")); assertTrue(map2.containsValue("a")); + } + + /** + * @tests java.util.HashMap#clear() + */ + public void test_clear() { + hm.clear(); + assertEquals("Clear failed to reset size", 0, hm.size()); + for (int i = 0; i < hmSize; i++) + assertNull("Failed to clear all elements", + hm.get(objArray2[i])); + + // Check clear on a large loaded map of Integer keys + HashMap<Integer, String> map = new HashMap<Integer, String>(); + for (int i = -32767; i < 32768; i++) { + map.put(i, "foobar"); + } + map.clear(); + assertEquals("Failed to reset size on large integer map", 0, hm.size()); + for (int i = -32767; i < 32768; i++) { + assertNull("Failed to clear integer map values", map.get(i)); + } + } + + /** + * @tests java.util.HashMap#clone() + */ + public void test_clone() { + // Test for method java.lang.Object java.util.HashMap.clone() + HashMap hm2 = (HashMap) hm.clone(); + assertTrue("Clone answered equivalent HashMap", hm2 != hm); + for (int counter = 0; counter < hmSize; counter++) + assertTrue("Clone answered unequal HashMap", hm + .get(objArray2[counter]) == hm2.get(objArray2[counter])); + + HashMap map = new HashMap(); + map.put("key", "value"); + // get the keySet() and values() on the original Map + Set keys = map.keySet(); + Collection values = map.values(); + assertEquals("values() does not work", + "value", values.iterator().next()); + assertEquals("keySet() does not work", + "key", keys.iterator().next()); + AbstractMap map2 = (AbstractMap) map.clone(); + map2.put("key", "value2"); + Collection values2 = map2.values(); + assertTrue("values() is identical", values2 != values); + // values() and keySet() on the cloned() map should be different + assertEquals("values() was not cloned", + "value2", values2.iterator().next()); + map2.clear(); + map2.put("key2", "value3"); + Set key2 = map2.keySet(); + assertTrue("keySet() is identical", key2 != keys); + assertEquals("keySet() was not cloned", + "key2", key2.iterator().next()); + + // regresion test for HARMONY-4603 + HashMap hashmap = new HashMap(); + MockClonable mock = new MockClonable(1); + hashmap.put(1, mock); + assertEquals(1, ((MockClonable) hashmap.get(1)).i); + HashMap hm3 = (HashMap)hashmap.clone(); + assertEquals(1, ((MockClonable) hm3.get(1)).i); + mock.i = 0; + assertEquals(0, ((MockClonable) hashmap.get(1)).i); + assertEquals(0, ((MockClonable) hm3.get(1)).i); + } + + /** + * @tests java.util.HashMap#containsKey(java.lang.Object) + */ + public void test_containsKeyLjava_lang_Object() { + // Test for method boolean + // java.util.HashMap.containsKey(java.lang.Object) + assertTrue("Returned false for valid key", hm.containsKey(new Integer( + 876).toString())); + assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD")); + + HashMap m = new HashMap(); + m.put(null, "test"); + assertTrue("Failed with null key", m.containsKey(null)); + assertTrue("Failed with missing key matching null hash", !m + .containsKey(new Integer(0))); + } + + /** + * @tests java.util.HashMap#containsValue(java.lang.Object) + */ + public void test_containsValueLjava_lang_Object() { + // Test for method boolean + // java.util.HashMap.containsValue(java.lang.Object) + assertTrue("Returned false for valid value", hm + .containsValue(new Integer(875))); + assertTrue("Returned true for invalid valie", !hm + .containsValue(new Integer(-9))); + } + + /** + * @tests java.util.HashMap#entrySet() + */ + public void test_entrySet() { + // Test for method java.util.Set java.util.HashMap.entrySet() + Set s = hm.entrySet(); + Iterator i = s.iterator(); + assertTrue("Returned set of incorrect size", hm.size() == s.size()); + while (i.hasNext()) { + Map.Entry m = (Map.Entry) i.next(); + assertTrue("Returned incorrect entry set", hm.containsKey(m + .getKey()) + && hm.containsValue(m.getValue())); + } + + Iterator iter = s.iterator(); + s.remove(iter.next()); + assertEquals(1001, s.size()); + } + + /** + * @tests java.util.HashMap#get(java.lang.Object) + */ + public void test_getLjava_lang_Object() { + // Test for method java.lang.Object + // java.util.HashMap.get(java.lang.Object) + assertNull("Get returned non-null for non existent key", + hm.get("T")); + hm.put("T", "HELLO"); + assertEquals("Get returned incorrect value for existing key", "HELLO", hm.get("T") + ); + + HashMap m = new HashMap(); + m.put(null, "test"); + assertEquals("Failed with null key", "test", m.get(null)); + assertNull("Failed with missing key matching null hash", m + .get(new Integer(0))); + + // Regression for HARMONY-206 + ReusableKey k = new ReusableKey(); + HashMap map = new HashMap(); + k.setKey(1); + map.put(k, "value1"); + + k.setKey(18); + assertNull(map.get(k)); + + k.setKey(17); + assertNull(map.get(k)); + } + + /** + * Tests for proxy object keys and values + */ + public void test_proxies() { + // Regression for HARMONY-6237 + MockInterface proxyKey = (MockInterface) Proxy.newProxyInstance( + MockInterface.class.getClassLoader(), + new Class[] { MockInterface.class }, new MockHandler( + new MockClass())); + MockInterface proxyValue = (MockInterface) Proxy.newProxyInstance( + MockInterface.class.getClassLoader(), + new Class[] { MockInterface.class }, new MockHandler( + new MockClass())); + + // Proxy key + Object val = new Object(); + hm.put(proxyKey, val); + + assertEquals("Failed with proxy object key", val, hm + .get(proxyKey)); + assertTrue("Failed to find proxy key", hm.containsKey(proxyKey)); + assertEquals("Failed to remove proxy object key", val, + hm.remove(proxyKey)); + assertFalse("Should not have found proxy key", hm.containsKey(proxyKey)); + + // Proxy value + Object k = new Object(); + hm.put(k, proxyValue); + + assertTrue("Failed to find proxy object as value", hm.containsValue(proxyValue)); + + // Proxy key and value + HashMap map = new HashMap(); + map.put(proxyKey, proxyValue); + assertTrue("Failed to find proxy key", map.containsKey(proxyKey)); + assertEquals(1, map.size()); + Object[] entries = map.entrySet().toArray(); + Map.Entry entry = (Map.Entry)entries[0]; + assertTrue("Failed to find proxy association", map.entrySet().contains(entry)); + } + + /** + * @tests java.util.HashMap#isEmpty() + */ + public void test_isEmpty() { + // Test for method boolean java.util.HashMap.isEmpty() + assertTrue("Returned false for new map", new HashMap().isEmpty()); + assertTrue("Returned true for non-empty", !hm.isEmpty()); + } + + /** + * @tests java.util.HashMap#keySet() + */ + public void test_keySet() { + // Test for method java.util.Set java.util.HashMap.keySet() + Set s = hm.keySet(); + assertTrue("Returned set of incorrect size()", s.size() == hm.size()); + for (int i = 0; i < objArray.length; i++) + assertTrue("Returned set does not contain all keys", s + .contains(objArray[i].toString())); + + HashMap m = new HashMap(); + m.put(null, "test"); + assertTrue("Failed with null key", m.keySet().contains(null)); + assertNull("Failed with null key", m.keySet().iterator().next()); + + Map map = new HashMap(101); + map.put(new Integer(1), "1"); + map.put(new Integer(102), "102"); + map.put(new Integer(203), "203"); + Iterator it = map.keySet().iterator(); + Integer remove1 = (Integer) it.next(); + it.hasNext(); + it.remove(); + Integer remove2 = (Integer) it.next(); + it.remove(); + ArrayList list = new ArrayList(Arrays.asList(new Integer[] { + new Integer(1), new Integer(102), new Integer(203) })); + list.remove(remove1); + list.remove(remove2); + assertTrue("Wrong result", it.next().equals(list.get(0))); + assertEquals("Wrong size", 1, map.size()); + assertTrue("Wrong contents", map.keySet().iterator().next().equals( + list.get(0))); + + Map map2 = new HashMap(101); + map2.put(new Integer(1), "1"); + map2.put(new Integer(4), "4"); + Iterator it2 = map2.keySet().iterator(); + Integer remove3 = (Integer) it2.next(); + Integer next; + if (remove3.intValue() == 1) + next = new Integer(4); + else + next = new Integer(1); + it2.hasNext(); + it2.remove(); + assertTrue("Wrong result 2", it2.next().equals(next)); + assertEquals("Wrong size 2", 1, map2.size()); + assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals( + next)); + } + + /** + * @tests java.util.HashMap#put(java.lang.Object, java.lang.Object) + */ + public void test_putLjava_lang_ObjectLjava_lang_Object() { + hm.put("KEY", "VALUE"); + assertEquals("Failed to install key/value pair", "VALUE", hm.get("KEY")); + + HashMap<Object,Object> m = new HashMap<Object,Object>(); + m.put(new Short((short) 0), "short"); + m.put(null, "test"); + m.put(new Integer(0), "int"); + assertEquals("Failed adding to bucket containing null", "short", m + .get(new Short((short) 0))); + assertEquals("Failed adding to bucket containing null2", "int", m + .get(new Integer(0))); + + // Check my actual key instance is returned + HashMap<Integer, String> map = new HashMap<Integer, String>(); + for (int i = -32767; i < 32768; i++) { + map.put(i, "foobar"); + } + Integer myKey = new Integer(0); + // Put a new value at the old key position + map.put(myKey, "myValue"); + assertTrue(map.containsKey(myKey)); + assertEquals("myValue", map.get(myKey)); + boolean found = false; + for (Iterator<Integer> itr = map.keySet().iterator(); itr.hasNext();) { + Integer key = itr.next(); + if (found = key == myKey) { + break; + } + } + assertFalse("Should not find new key instance in hashmap", found); + + // Add a new key instance and check it is returned + assertNotNull(map.remove(myKey)); + map.put(myKey, "myValue"); + assertTrue(map.containsKey(myKey)); + assertEquals("myValue", map.get(myKey)); + for (Iterator<Integer> itr = map.keySet().iterator(); itr.hasNext();) { + Integer key = itr.next(); + if (found = key == myKey) { + break; + } + } + assertTrue("Did not find new key instance in hashmap", found); + + // Ensure keys with identical hashcode are stored separately + HashMap<Object,Object> objmap = new HashMap<Object, Object>(); + for (int i = 0; i < 32768; i++) { + objmap.put(i, "foobar"); + } + // Put non-equal object with same hashcode + MyKey aKey = new MyKey(); + assertNull(objmap.put(aKey, "value")); + assertNull(objmap.remove(new MyKey())); + assertEquals("foobar", objmap.get(0)); + assertEquals("value", objmap.get(aKey)); + } + + static class MyKey { + public MyKey() { + super(); + } + + public int hashCode() { + return 0; + } + } + /** + * @tests java.util.HashMap#putAll(java.util.Map) + */ + public void test_putAllLjava_util_Map() { + // Test for method void java.util.HashMap.putAll(java.util.Map) + HashMap hm2 = new HashMap(); + hm2.putAll(hm); + for (int i = 0; i < 1000; i++) + assertTrue("Failed to clear all elements", hm2.get( + new Integer(i).toString()).equals((new Integer(i)))); + + Map mockMap = new MockMap(); + hm2 = new HashMap(); + hm2.putAll(mockMap); + assertEquals("Size should be 0", 0, hm2.size()); + } + + /** + * @tests java.util.HashMap#putAll(java.util.Map) + */ + public void test_putAllLjava_util_Map_Null() { + HashMap hashMap = new HashMap(); + try { + hashMap.putAll(new MockMapNull()); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected. + } + + try { + hashMap = new HashMap(new MockMapNull()); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected. + } + } + + /** + * @tests java.util.HashMap#remove(java.lang.Object) + */ + public void test_removeLjava_lang_Object() { + int size = hm.size(); + Integer y = new Integer(9); + Integer x = ((Integer) hm.remove(y.toString())); + assertTrue("Remove returned incorrect value", x.equals(new Integer(9))); + assertNull("Failed to remove given key", hm.get(new Integer(9))); + assertTrue("Failed to decrement size", hm.size() == (size - 1)); + assertNull("Remove of non-existent key returned non-null", hm + .remove("LCLCLC")); + + HashMap m = new HashMap(); + m.put(null, "test"); + assertNull("Failed with same hash as null", + m.remove(new Integer(0))); + assertEquals("Failed with null key", "test", m.remove(null)); + + HashMap<Integer, Object> map = new HashMap<Integer, Object>(); + for (int i = 0; i < 32768; i++) { + map.put(i, "const"); + } + Object[] values = new Object[32768]; + for (int i = 0; i < 32768; i++) { + values[i] = new Object(); + map.put(i, values[i]); + } + for (int i = 32767; i >= 0; i--) { + assertEquals("Failed to remove same value", values[i], map.remove(i)); + } + + // Ensure keys with identical hashcode are removed properly + map = new HashMap<Integer, Object>(); + for (int i = -32767; i < 32768; i++) { + map.put(i, "foobar"); + } + // Remove non equal object with same hashcode + assertNull(map.remove(new MyKey())); + assertEquals("foobar", map.get(0)); + map.remove(0); + assertNull(map.get(0)); + } + + /** + * @tests java.util.HashMap#size() + */ + public void test_size() { + // Test for method int java.util.HashMap.size() + assertTrue("Returned incorrect size", + hm.size() == (objArray.length + 2)); + } + + /** + * @tests java.util.HashMap#values() + */ + public void test_values() { + // Test for method java.util.Collection java.util.HashMap.values() + Collection c = hm.values(); + assertTrue("Returned collection of incorrect size()", c.size() == hm + .size()); + for (int i = 0; i < objArray.length; i++) + assertTrue("Returned collection does not contain all keys", c + .contains(objArray[i])); + + HashMap myHashMap = new HashMap(); + for (int i = 0; i < 100; i++) + myHashMap.put(objArray2[i], objArray[i]); + Collection values = myHashMap.values(); + new Support_UnmodifiableCollectionTest( + "Test Returned Collection From HashMap.values()", values) + .runTest(); + values.remove(new Integer(0)); + assertTrue( + "Removing from the values collection should remove from the original map", + !myHashMap.containsValue(new Integer(0))); + + } + + /** + * @tests java.util.AbstractMap#toString() + */ + public void test_toString() { + + HashMap m = new HashMap(); + m.put(m, m); + String result = m.toString(); + assertTrue("should contain self ref", result.indexOf("(this") > -1); + } + + static class ReusableKey { + private int key = 0; + + public void setKey(int key) { + this.key = key; + } + + public int hashCode() { + return key; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ReusableKey)) { + return false; + } + return key == ((ReusableKey) o).key; + } + } + + public void test_Map_Entry_hashCode() { + //Related to HARMONY-403 + HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(10); + Integer key = new Integer(1); + Integer val = new Integer(2); + map.put(key, val); + int expected = key.hashCode() ^ val.hashCode(); + assertEquals(expected, map.hashCode()); + key = new Integer(4); + val = new Integer(8); + map.put(key, val); + expected += key.hashCode() ^ val.hashCode(); + assertEquals(expected, map.hashCode()); + } + + class MockClonable implements Cloneable{ + public int i; + + public MockClonable(int i) { + this.i = i; + } + + @Override + protected Object clone() throws CloneNotSupportedException { + return new MockClonable(i); + } + } + + /* + * Regression test for HY-4750 + */ + public void test_EntrySet() { + HashMap map = new HashMap(); + map.put(new Integer(1), "ONE"); + + Set entrySet = map.entrySet(); + Iterator e = entrySet.iterator(); + Object real = e.next(); + Map.Entry copyEntry = new MockEntry(); + assertEquals(real, copyEntry); + assertTrue(entrySet.contains(copyEntry)); + + entrySet.remove(copyEntry); + assertFalse(entrySet.contains(copyEntry)); + + + } + + private static class MockEntry implements Map.Entry { + + public Object getKey() { + return new Integer(1); + } + + public Object getValue() { + return "ONE"; + } + + public Object setValue(Object object) { + return null; + } + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + hm = new HashMap(); + for (int i = 0; i < objArray.length; i++) + hm.put(objArray2[i], objArray[i]); + hm.put("test", null); + hm.put(null, "test"); + } + + + class SubMap<K, V> extends HashMap<K, V> { + public SubMap(Map<? extends K, ? extends V> m) { + super(m); + } + + public V put(K key, V value) { + throw new UnsupportedOperationException(); + } } /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("key", "value"); @@ -80,16 +763,11 @@ public class HashMapTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("key", "value"); SerializationTest.verifyGolden(this, hm); } + } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java index 43bb856..83ef5e0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java @@ -17,11 +17,6 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.Serializable; import java.util.Collection; import java.util.HashSet; @@ -34,102 +29,69 @@ import java.util.TreeSet; import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IdentityHashMap.class) public class IdentityHashMapTest extends junit.framework.TestCase { - /** - * @tests java.util.IdentityHashMap#containsKey(java.lang.Object) - * @tests java.util.IdentityHashMap#containsValue(java.lang.Object) - * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object) - * @tests java.util.IdentityHashMap#get(java.lang.Object) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "containsKey", - args = {java.lang.Object.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "containsValue", - args = {java.lang.Object.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "put", - args = {java.lang.Object.class, java.lang.Object.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "get", - args = {java.lang.Object.class} - ) - }) - public void test_null_Keys_and_Values() { - // tests with null keys and values - IdentityHashMap map = new IdentityHashMap(); - Object result; - - // null key and null value - result = map.put(null, null); - assertTrue("testA can not find null key", map.containsKey(null)); - assertTrue("testA can not find null value", map.containsValue(null)); - assertNull("testA can not get null value for null key", - map.get(null)); - assertNull("testA put returned wrong value", result); - - // null value - String value = "a value"; - result = map.put(null, value); - assertTrue("testB can not find null key", map.containsKey(null)); - assertTrue("testB can not find a value with null key", map - .containsValue(value)); - assertTrue("testB can not get value for null key", - map.get(null) == value); - assertNull("testB put returned wrong value", result); - - // a null key - String key = "a key"; - result = map.put(key, null); - assertTrue("testC can not find a key with null value", map - .containsKey(key)); - assertTrue("testC can not find null value", map.containsValue(null)); - assertNull("testC can not get null value for key", map.get(key)); - assertNull("testC put returned wrong value", result); - - // another null key - String anothervalue = "another value"; - result = map.put(null, anothervalue); - assertTrue("testD can not find null key", map.containsKey(null)); - assertTrue("testD can not find a value with null key", map - .containsValue(anothervalue)); - assertTrue("testD can not get value for null key", - map.get(null) == anothervalue); - assertTrue("testD put returned wrong value", result == value); - - // remove a null key - result = map.remove(null); - assertTrue("testE remove returned wrong value", result == anothervalue); - assertTrue("testE should not find null key", !map.containsKey(null)); - assertTrue("testE should not find a value with null key", !map - .containsValue(anothervalue)); - assertNull("testE should not get value for null key", - map.get(null)); - } + /** + * @tests java.util.IdentityHashMap#containsKey(java.lang.Object) + * @tests java.util.IdentityHashMap#containsValue(java.lang.Object) + * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object) + * @tests java.util.IdentityHashMap#get(java.lang.Object) + */ + public void test_null_Keys_and_Values() { + // tests with null keys and values + IdentityHashMap map = new IdentityHashMap(); + Object result; + + // null key and null value + result = map.put(null, null); + assertTrue("testA can not find null key", map.containsKey(null)); + assertTrue("testA can not find null value", map.containsValue(null)); + assertNull("testA can not get null value for null key", + map.get(null)); + assertNull("testA put returned wrong value", result); + + // null value + String value = "a value"; + result = map.put(null, value); + assertTrue("testB can not find null key", map.containsKey(null)); + assertTrue("testB can not find a value with null key", map + .containsValue(value)); + assertTrue("testB can not get value for null key", + map.get(null) == value); + assertNull("testB put returned wrong value", result); + + // a null key + String key = "a key"; + result = map.put(key, null); + assertTrue("testC can not find a key with null value", map + .containsKey(key)); + assertTrue("testC can not find null value", map.containsValue(null)); + assertNull("testC can not get null value for key", map.get(key)); + assertNull("testC put returned wrong value", result); + + // another null key + String anothervalue = "another value"; + result = map.put(null, anothervalue); + assertTrue("testD can not find null key", map.containsKey(null)); + assertTrue("testD can not find a value with null key", map + .containsValue(anothervalue)); + assertTrue("testD can not get value for null key", + map.get(null) == anothervalue); + assertTrue("testD put returned wrong value", result == value); + + // remove a null key + result = map.remove(null); + assertTrue("testE remove returned wrong value", result == anothervalue); + assertTrue("testE should not find null key", !map.containsKey(null)); + assertTrue("testE should not find a value with null key", !map + .containsValue(anothervalue)); + assertNull("testE should not get value for null key", + map.get(null)); + } /** * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks null as a parameter.", - method = "put", - args = {java.lang.Object.class, java.lang.Object.class} - ) public void test_putLjava_lang_ObjectLjava_lang_Object() { IdentityHashMap<Object, Object> map = new IdentityHashMap<Object, Object>(); @@ -144,41 +106,29 @@ public class IdentityHashMapTest extends junit.framework.TestCase { assertNull("Assert 1: Failure getting null value", map.get(key)); } - /** - * @tests java.util.IdentityHashMap#remove(java.lang.Object) - * @tests java.util.IdentityHashMap#keySet() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify removed value.", - method = "remove", - args = {java.lang.Object.class} - ) - public void test_remove() { - IdentityHashMap map = new IdentityHashMap(); - map.put(null, null); - map.put("key1", "value1"); - map.put("key2", "value2"); - map.remove("key1"); - - assertTrue("Did not remove key1", !map.containsKey("key1")); - assertTrue("Did not remove the value for key1", !map - .containsValue("value1")); - - assertTrue("Modified key2", map.get("key2") != null - && map.get("key2") == "value2"); - assertNull("Modified null entry", map.get(null)); - } + /** + * @tests java.util.IdentityHashMap#remove(java.lang.Object) + * @tests java.util.IdentityHashMap#keySet() + */ + public void test_remove() { + IdentityHashMap map = new IdentityHashMap(); + map.put(null, null); + map.put("key1", "value1"); + map.put("key2", "value2"); + map.remove("key1"); + + assertTrue("Did not remove key1", !map.containsKey("key1")); + assertTrue("Did not remove the value for key1", !map + .containsValue("value1")); + + assertTrue("Modified key2", map.get("key2") != null + && map.get("key2") == "value2"); + assertNull("Modified null entry", map.get(null)); + } /** * @tests java.util.IdentityHashMapTest#remove(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test.", - method = "remove", - args = {java.lang.Object.class} - ) public void test_removeLjava_lang_Object() { // Regression for HARMONY-37 IdentityHashMap<String, String> hashMap = new IdentityHashMap<String, String>(); @@ -195,288 +145,269 @@ public class IdentityHashMapTest extends junit.framework.TestCase { assertEquals("Assert 3: After removing null element size is incorrect", 0, hashMap.size()); } - /** - * @tests java.util.IdentityHashMap#entrySet() - * @tests java.util.IdentityHashMap#keySet() - * @tests java.util.IdentityHashMap#values() - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "keySet", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "entrySet", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "values", - args = {} - ) - }) - public void test_sets() { - // tests with null keys and values - IdentityHashMap map = new IdentityHashMap(); - - // null key and null value - map.put("key", "value"); - map.put(null, null); - map.put("a key", null); - map.put("another key", null); - - Set keyset = map.keySet(); - Collection valueset = map.values(); - Set entries = map.entrySet(); - Iterator it = entries.iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - assertTrue("EntrySetIterator can not find entry ", entries - .contains(entry)); - - assertTrue("entry key not found in map", map.containsKey(entry - .getKey())); - assertTrue("entry value not found in map", map.containsValue(entry - .getValue())); - - assertTrue("entry key not found in the keyset", keyset - .contains(entry.getKey())); - assertTrue("entry value not found in the valueset", valueset - .contains(entry.getValue())); - } - } - - /** - * @tests java.util.IdentityHashMap#entrySet() - * @tests java.util.IdentityHashMap#remove(java.lang.Object) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies positive functionality. Doesn't verify that remove method returns null if there was no entry for key.", - method = "entrySet", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies positive functionality. Doesn't verify that remove method returns null if there was no entry for key.", - method = "remove", - args = {java.lang.Object.class} - ) - }) - public void test_entrySet_removeAll() { - IdentityHashMap map = new IdentityHashMap(); - for (int i = 0; i < 1000; i++) { - map.put(new Integer(i), new Integer(i)); - } - Set set = map.entrySet(); - - set.removeAll(set); - assertEquals("did not remove all elements in the map", 0, map.size()); - assertTrue("did not remove all elements in the entryset", set.isEmpty()); - - Iterator it = set.iterator(); - assertTrue("entrySet iterator still has elements", !it.hasNext()); - } - - /** - * @tests java.util.IdentityHashMap#keySet() - * @tests java.util.IdentityHashMap#clear() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "clear", - args = {} - ) - public void test_keySet_clear() { - IdentityHashMap map = new IdentityHashMap(); - for (int i = 0; i < 1000; i++) { - map.put(new Integer(i), new Integer(i)); - } - Set set = map.keySet(); - set.clear(); - - assertEquals("did not remove all elements in the map", 0, map.size()); - assertTrue("did not remove all elements in the keyset", set.isEmpty()); - - Iterator it = set.iterator(); - assertTrue("keySet iterator still has elements", !it.hasNext()); + /** + * @tests java.util.IdentityHashMap#entrySet() + * @tests java.util.IdentityHashMap#keySet() + * @tests java.util.IdentityHashMap#values() + */ + public void test_sets() { + // tests with null keys and values + IdentityHashMap map = new IdentityHashMap(); + + // null key and null value + map.put("key", "value"); + map.put(null, null); + map.put("a key", null); + map.put("another key", null); + + Set keyset = map.keySet(); + Collection valueset = map.values(); + Set entries = map.entrySet(); + Iterator it = entries.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + assertTrue("EntrySetIterator can not find entry ", entries + .contains(entry)); + + assertTrue("entry key not found in map", map.containsKey(entry + .getKey())); + assertTrue("entry value not found in map", map.containsValue(entry + .getValue())); + + assertTrue("entry key not found in the keyset", keyset + .contains(entry.getKey())); + assertTrue("entry value not found in the valueset", valueset + .contains(entry.getValue())); + } + } + + /** + * @tests java.util.IdentityHashMap#entrySet() + * @tests java.util.IdentityHashMap#remove(java.lang.Object) + */ + public void test_entrySet_removeAll() { + IdentityHashMap map = new IdentityHashMap(); + for (int i = 0; i < 1000; i++) { + map.put(new Integer(i), new Integer(i)); + } + Set set = map.entrySet(); + + set.removeAll(set); + assertEquals("did not remove all elements in the map", 0, map.size()); + assertTrue("did not remove all elements in the entryset", set.isEmpty()); + + Iterator it = set.iterator(); + assertTrue("entrySet iterator still has elements", !it.hasNext()); + } + + /** + * @tests java.util.IdentityHashMap#keySet() + * @tests java.util.IdentityHashMap#clear() + */ + public void test_keySet_clear() { + IdentityHashMap map = new IdentityHashMap(); + for (int i = 0; i < 1000; i++) { + map.put(new Integer(i), new Integer(i)); + } + Set set = map.keySet(); + set.clear(); + + assertEquals("did not remove all elements in the map", 0, map.size()); + assertTrue("did not remove all elements in the keyset", set.isEmpty()); + + Iterator it = set.iterator(); + assertTrue("keySet iterator still has elements", !it.hasNext()); + } + + /** + * @tests java.util.IdentityHashMap#values() + */ + public void test_values() { + + IdentityHashMap map = new IdentityHashMap(); + for (int i = 0; i < 10; i++) { + map.put(new Integer(i), new Integer(i)); + } + + Integer key = new Integer(20); + Integer value = new Integer(40); + map.put(key, value); + + Collection vals = map.values(); + boolean result = vals.remove(key); + assertTrue("removed entries incorrectly", map.size() == 11 && !result); + assertTrue("removed key incorrectly", map.containsKey(key)); + assertTrue("removed value incorrectly", map.containsValue(value)); + + result = vals.remove(value); + assertTrue("Did not remove entry as expected", map.size() == 10 + && result); + assertTrue("Did not remove key as expected", !map.containsKey(key)); + assertTrue("Did not remove value as expected", !map + .containsValue(value)); + + // put an equivalent key to a value + key = new Integer(1); + value = new Integer(100); + map.put(key, value); + + result = vals.remove(key); + assertTrue("TestB. removed entries incorrectly", map.size() == 11 + && !result); + assertTrue("TestB. removed key incorrectly", map.containsKey(key)); + assertTrue("TestB. removed value incorrectly", map.containsValue(value)); + + result = vals.remove(value); + assertTrue("TestB. Did not remove entry as expected", map.size() == 10 + && result); + assertTrue("TestB. Did not remove key as expected", !map + .containsKey(key)); + assertTrue("TestB. Did not remove value as expected", !map + .containsValue(value)); + + vals.clear(); + assertEquals("Did not remove all entries as expected", 0, map.size()); + } + + /** + * @tests java.util.IdentityHashMap#keySet() + * @tests java.util.IdentityHashMap#remove(java.lang.Object) + */ + public void test_keySet_removeAll() { + IdentityHashMap map = new IdentityHashMap(); + for (int i = 0; i < 1000; i++) { + map.put(new Integer(i), new Integer(i)); + } + Set set = map.keySet(); + set.removeAll(set); + + assertEquals("did not remove all elements in the map", 0, map.size()); + assertTrue("did not remove all elements in the keyset", set.isEmpty()); + + Iterator it = set.iterator(); + assertTrue("keySet iterator still has elements", !it.hasNext()); + } + + /** + * @tests java.util.IdentityHashMap#keySet() + */ + public void test_keySet_retainAll() { + IdentityHashMap map = new IdentityHashMap(); + for (int i = 0; i < 1000; i++) { + map.put(new Integer(i), new Integer(i)); + } + Set set = map.keySet(); + + // retain all the elements + boolean result = set.retainAll(set); + assertTrue("retain all should return false", !result); + assertEquals("did not retain all", 1000, set.size()); + + // send empty set to retainAll + result = set.retainAll(new TreeSet()); + assertTrue("retain all should return true", result); + assertEquals("did not remove all elements in the map", 0, map.size()); + assertTrue("did not remove all elements in the keyset", set.isEmpty()); + + Iterator it = set.iterator(); + assertTrue("keySet iterator still has elements", !it.hasNext()); + } + + /** + * @tests java.util.IdentityHashMap#keySet() + * @tests java.util.IdentityHashMap#remove(java.lang.Object) + */ + public void test_keyset_remove() { + IdentityHashMap map = new IdentityHashMap(); + + Integer key = new Integer(21); + + map.put(new Integer(1), null); + map.put(new Integer(11), null); + map.put(key, null); + map.put(new Integer(31), null); + map.put(new Integer(41), null); + map.put(new Integer(51), null); + map.put(new Integer(61), null); + map.put(new Integer(71), null); + map.put(new Integer(81), null); + map.put(new Integer(91), null); + + Set set = map.keySet(); + + Set newset = new HashSet(); + Iterator it = set.iterator(); + while (it.hasNext()) { + Object element = it.next(); + if (element == key) { + it.remove(); + } else + newset.add(element); + } + int size = newset.size(); + assertTrue("keyset and newset don't have same size", + newset.size() == size); + assertTrue("element is in newset ", !newset.contains(key)); + assertTrue("element not removed from keyset", !set.contains(key)); + assertTrue("element not removed from map", !map.containsKey(key)); + + assertTrue("newset and keyset do not have same elements 1", newset + .equals(set)); + assertTrue("newset and keyset do not have same elements 2", set + .equals(newset)); + } + + public void test_clone_scenario1() { + IdentityHashMap hashMap = new IdentityHashMap(); + assertEquals(0, hashMap.hashCode()); + Object cloneHashMap = hashMap.clone(); + ((IdentityHashMap) cloneHashMap).put("key", "value"); + assertEquals(0, hashMap.hashCode()); + assertTrue(0 != cloneHashMap.hashCode()); } - /** - * @tests java.util.IdentityHashMap#values() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "values", - args = {} - ) - public void test_values() { - - IdentityHashMap map = new IdentityHashMap(); - for (int i = 0; i < 10; i++) { - map.put(new Integer(i), new Integer(i)); - } - - Integer key = new Integer(20); - Integer value = new Integer(40); - map.put(key, value); - - Collection vals = map.values(); - boolean result = vals.remove(key); - assertTrue("removed entries incorrectly", map.size() == 11 && !result); - assertTrue("removed key incorrectly", map.containsKey(key)); - assertTrue("removed value incorrectly", map.containsValue(value)); - - result = vals.remove(value); - assertTrue("Did not remove entry as expected", map.size() == 10 - && result); - assertTrue("Did not remove key as expected", !map.containsKey(key)); - assertTrue("Did not remove value as expected", !map - .containsValue(value)); - - // put an equivalent key to a value - key = new Integer(1); - value = new Integer(100); - map.put(key, value); - - result = vals.remove(key); - assertTrue("TestB. removed entries incorrectly", map.size() == 11 - && !result); - assertTrue("TestB. removed key incorrectly", map.containsKey(key)); - assertTrue("TestB. removed value incorrectly", map.containsValue(value)); - - result = vals.remove(value); - assertTrue("TestB. Did not remove entry as expected", map.size() == 10 - && result); - assertTrue("TestB. Did not remove key as expected", !map - .containsKey(key)); - assertTrue("TestB. Did not remove value as expected", !map - .containsValue(value)); - - vals.clear(); - assertEquals("Did not remove all entries as expected", 0, map.size()); + public void test_clone_scenario2() { + IdentityHashMap hashMap = new IdentityHashMap(); + assertEquals(0, hashMap.hashCode()); + Object cloneHashMap = hashMap.clone(); + hashMap.put("key", "value"); + assertEquals(1, hashMap.size()); + assertEquals(0, ((IdentityHashMap) cloneHashMap).size()); + assertEquals("value", hashMap.get("key")); + assertNull(((IdentityHashMap) cloneHashMap).get("key")); + assertTrue(0 != hashMap.hashCode()); + assertEquals(0, cloneHashMap.hashCode()); } - /** - * @tests java.util.IdentityHashMap#keySet() - * @tests java.util.IdentityHashMap#remove(java.lang.Object) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "keySet", - args = {} - ) - public void test_keySet_removeAll() { - IdentityHashMap map = new IdentityHashMap(); - for (int i = 0; i < 1000; i++) { - map.put(new Integer(i), new Integer(i)); - } - Set set = map.keySet(); - set.removeAll(set); - - assertEquals("did not remove all elements in the map", 0, map.size()); - assertTrue("did not remove all elements in the keyset", set.isEmpty()); - - Iterator it = set.iterator(); - assertTrue("keySet iterator still has elements", !it.hasNext()); + public void test_clone_scenario3() { + IdentityHashMap hashMap = new IdentityHashMap(); + assertEquals(0, hashMap.hashCode()); + hashMap.put("key", "value"); + Object cloneHashMap = hashMap.clone(); + assertEquals(1, hashMap.size()); + assertEquals(1, ((IdentityHashMap) cloneHashMap).size()); + assertEquals("value", hashMap.get("key")); + assertEquals("value", ((IdentityHashMap) cloneHashMap).get("key")); + assertEquals(hashMap.hashCode(), cloneHashMap.hashCode()); } - /** - * @tests java.util.IdentityHashMap#keySet() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "keySet", - args = {} - ) - public void test_keySet_retainAll() { - IdentityHashMap map = new IdentityHashMap(); - for (int i = 0; i < 1000; i++) { - map.put(new Integer(i), new Integer(i)); - } - Set set = map.keySet(); - - // retain all the elements - boolean result = set.retainAll(set); - assertTrue("retain all should return false", !result); - assertEquals("did not retain all", 1000, set.size()); - - // send empty set to retainAll - result = set.retainAll(new TreeSet()); - assertTrue("retain all should return true", result); - assertEquals("did not remove all elements in the map", 0, map.size()); - assertTrue("did not remove all elements in the keyset", set.isEmpty()); - - Iterator it = set.iterator(); - assertTrue("keySet iterator still has elements", !it.hasNext()); + public void test_clone_scenario4() { + IdentityHashMap hashMap = new IdentityHashMap(); + Object cloneHashMap = hashMap.clone(); + assertNull(((IdentityHashMap) cloneHashMap).get((Object) null)); + hashMap.put((Object) null, cloneHashMap); + assertNull(((IdentityHashMap) cloneHashMap).get((Object) null)); + assertEquals(cloneHashMap, hashMap.get((Object) null)); } - /** - * @tests java.util.IdentityHashMap#keySet() - * @tests java.util.IdentityHashMap#remove(java.lang.Object) - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "keySet", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "remove", - args = {java.lang.Object.class} - ) - }) - public void test_keyset_remove() { - IdentityHashMap map = new IdentityHashMap(); - - Integer key = new Integer(21); - - map.put(new Integer(1), null); - map.put(new Integer(11), null); - map.put(key, null); - map.put(new Integer(31), null); - map.put(new Integer(41), null); - map.put(new Integer(51), null); - map.put(new Integer(61), null); - map.put(new Integer(71), null); - map.put(new Integer(81), null); - map.put(new Integer(91), null); - - Set set = map.keySet(); - - Set newset = new HashSet(); - Iterator it = set.iterator(); - while (it.hasNext()) { - Object element = it.next(); - if (element == key) { - it.remove(); - } else - newset.add(element); - } - int size = newset.size(); - assertTrue("keyset and newset don't have same size", - newset.size() == size); - assertTrue("element is in newset ", !newset.contains(key)); - assertTrue("element not removed from keyset", !set.contains(key)); - assertTrue("element not removed from map", !map.containsKey(key)); - - assertTrue("newset and keyset do not have same elements 1", newset - .equals(set)); - assertTrue("newset and keyset do not have same elements 2", set - .equals(newset)); + public void test_clone_scenario5() throws Exception { + IdentityHashMap hashMap = new IdentityHashMap(); + Object cloneHashMap = hashMap.clone(); + assertNull(hashMap.remove((Object) null)); + ((IdentityHashMap) cloneHashMap).put((Object) null, cloneHashMap); + assertNull(hashMap.remove((Object) null)); + assertEquals(cloneHashMap, ((IdentityHashMap) cloneHashMap) + .get((Object) null)); } // comparator for IdentityHashMap objects @@ -494,12 +425,6 @@ public class IdentityHashMapTest extends junit.framework.TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>(); identityHashMap.put("key1", "value1"); diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java index 602d1db..7ef9715 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java @@ -16,31 +16,19 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.IllegalFormatCodePointException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IllegalFormatCodePointException.class) public class IllegalFormatCodePointExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatCodePointException.IllegalFormatCodePointException(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalFormatCodePointException", - args = {int.class} - ) public void test_illegalFormatCodePointException() { IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException( -1); @@ -50,12 +38,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatCodePointException.getCodePoint() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCodePoint", - args = {} - ) public void test_getCodePoint() { int codePoint = 12345; IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException( @@ -66,12 +48,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatCodePointException.getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { int codePoint = 12345; IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException( @@ -98,12 +74,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf( @@ -113,12 +83,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java index 22a845d..4d5c37d 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java @@ -16,32 +16,20 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.IllegalFormatConversionException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IllegalFormatConversionException.class) public class IllegalFormatConversionExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatConversionException#IllegalFormatConversionException(char, * Class) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalFormatConversionException", - args = {char.class, java.lang.Class.class} - ) public void test_illegalFormatConversionException() { try { new IllegalFormatConversionException(' ', null); @@ -49,19 +37,11 @@ public class IllegalFormatConversionExceptionTest extends TestCase { } catch (NullPointerException e) { // desired } - - assertNotNull(new IllegalFormatConversionException(' ', String.class)); } /** * @tests java.util.IllegalFormatConversionException#getArgumentClass() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getArgumentClass", - args = {} - ) public void test_getArgumentClass() { char c = '*'; Class<String> argClass = String.class; @@ -75,12 +55,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatConversionException#getConversion() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getConversion", - args = {} - ) public void test_getConversion() { char c = '*'; Class<String> argClass = String.class; @@ -93,12 +67,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatConversionException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { char c = '*'; Class<String> argClass = String.class; @@ -129,12 +97,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new IllegalFormatConversionException('*', @@ -144,12 +106,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java index 8ae825c..530f281 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java @@ -16,31 +16,19 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.IllegalFormatFlagsException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IllegalFormatFlagsException.class) public class IllegalFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatFlagsException#IllegalFormatFlagsException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalFormatFlagsException", - args = {java.lang.String.class} - ) public void test_illegalFormatFlagsException() { try { new IllegalFormatFlagsException(null); @@ -48,19 +36,11 @@ public class IllegalFormatFlagsExceptionTest extends TestCase { } catch (NullPointerException e) { // expected } - - assertNotNull(new IllegalFormatFlagsException("String")); } /** * @tests java.util.IllegalFormatFlagsException.getFlags() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFlags", - args = {} - ) public void test_getFlags() { String flags = "TESTFLAGS"; IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException( @@ -71,12 +51,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatFlagsException.getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String flags = "TESTFLAGS"; IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException( @@ -103,12 +77,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new IllegalFormatFlagsException( @@ -118,12 +86,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new IllegalFormatFlagsException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java index 823473e..f7c60ea 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java @@ -15,31 +15,19 @@ */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.IllegalFormatPrecisionException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IllegalFormatPrecisionException.class) public class IllegalFormatPrecisionExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatPrecisionException#IllegalFormatPrecisionException(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalFormatPrecisionException", - args = {int.class} - ) public void test_illegalFormatPrecisionException() { IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException( Integer.MIN_VALUE); @@ -50,12 +38,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatPrecisionException#getPrecision() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPrecision", - args = {} - ) public void test_getPrecision() { int precision = 12345; IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException( @@ -66,12 +48,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase { /** * @tests method for 'java.util.IllegalFormatPrecisionException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { int precision = 12345; IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException( @@ -99,12 +75,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf( @@ -114,12 +84,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java index 6885a4e..4262aa0 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java @@ -15,31 +15,19 @@ */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.IllegalFormatWidthException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(IllegalFormatWidthException.class) public class IllegalFormatWidthExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatWidthException#IllegalFormatWidthException(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "IllegalFormatWidthException", - args = {int.class} - ) public void test_illegalFormatWidthException() { int width = Integer.MAX_VALUE; IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException( @@ -51,12 +39,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatWidthException#getWidth() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getWidth", - args = {} - ) public void test_getWidth() { int width = 12345; IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException( @@ -68,12 +50,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase { /** * @tests java.util.IllegalFormatWidthException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { int width = 12345; IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException( @@ -100,12 +76,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new IllegalFormatWidthException(12345), @@ -115,12 +85,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new IllegalFormatWidthException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java index e14987e..60c5dc7 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java @@ -15,20 +15,14 @@ */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.InputMismatchException; import java.util.NoSuchElementException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(InputMismatchException.class) public class InputMismatchExceptionTest extends TestCase { private static final String ERROR_MESSAGE = "for serialization test"; //$NON-NLS-1$ @@ -36,12 +30,6 @@ public class InputMismatchExceptionTest extends TestCase { /** * @tests java.util.InputMismatchException#InputMismatchException() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InputMismatchException", - args = {} - ) @SuppressWarnings("cast") public void test_Constructor() { InputMismatchException exception = new InputMismatchException(); @@ -53,12 +41,6 @@ public class InputMismatchExceptionTest extends TestCase { /** * @tests java.util.InputMismatchException#InputMismatchException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InputMismatchException", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { InputMismatchException exception = new InputMismatchException( ERROR_MESSAGE); @@ -69,12 +51,6 @@ public class InputMismatchExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new InputMismatchException(ERROR_MESSAGE)); @@ -83,12 +59,6 @@ public class InputMismatchExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new InputMismatchException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java index 0996a24..63ab11e 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java @@ -1,53 +1,50 @@ -/* - * 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 - * +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - +import java.io.NotSerializableException; import java.util.InvalidPropertiesFormatException; -@TestTargetClass(InvalidPropertiesFormatException.class) -public class InvalidPropertiesFormatExceptionTest extends TestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InvalidPropertiesFormatException", - args = {java.lang.Throwable.class} - ) - public void testInvalidPropertiesFormatExceptionThrowable() { - assertNotNull(new InvalidPropertiesFormatException(new Exception())); - assertNotNull(new InvalidPropertiesFormatException((Throwable)null)); +import org.apache.harmony.testframework.serialization.SerializationTest; + +public class InvalidPropertiesFormatExceptionTest extends + junit.framework.TestCase { + + /** + * @tests java.util.InvalidPropertiesFormatException#SerializationTest() + */ + public void test_Serialization() throws Exception { + InvalidPropertiesFormatException ipfe = new InvalidPropertiesFormatException( + "Hey, this is InvalidPropertiesFormatException"); + try { + SerializationTest.verifySelf(ipfe); + } catch (NotSerializableException e) { + // expected + } } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "InvalidPropertiesFormatException", - args = {java.lang.String.class} - ) - public void testInvalidPropertiesFormatExceptionString() { - assertNotNull(new InvalidPropertiesFormatException("String")); - assertNotNull(new InvalidPropertiesFormatException((String)null)); + /** + * @tests {@link java.util.InvalidPropertiesFormatException#InvalidPropertiesFormatException(Throwable)} + */ + public void test_Constructor_Ljava_lang_Throwable() { + Throwable throwable = new Throwable(); + InvalidPropertiesFormatException exception = new InvalidPropertiesFormatException( + throwable); + assertEquals("the casue did not equals argument passed in constructor", + throwable, exception.getCause()); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java index 5acb81c..1abfc49 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java @@ -1,49 +1,408 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; -import junit.framework.TestCase; +public class LocaleTest extends junit.framework.TestCase { -import java.util.Locale; + Locale testLocale; + + Locale l; + + Locale defaultLocale; + + /** + * @tests java.util.Locale#Locale(java.lang.String, java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_String() { + // Test for method java.util.Locale(java.lang.String, java.lang.String) + Locale x = new Locale("xx", "CV"); + assertTrue("Failed to create Locale", x.getCountry().equals("CV") + && x.getVariant().equals("")); + } + + /** + * @tests java.util.Locale#Locale(java.lang.String, java.lang.String, + * java.lang.String) + */ + public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() { + // Test for method java.util.Locale(java.lang.String, java.lang.String, + // java.lang.String) + Locale x = new Locale("xx", "CV", "ZZ"); + assertTrue("Failed to create Locale", x.getLanguage().equals("xx") + && (x.getCountry().equals("CV") && x.getVariant().equals("ZZ"))); + try { + new Locale(null, "CV", "ZZ"); + fail("expected NullPointerException with 1st parameter == null"); + } catch(NullPointerException e) { + } -@TestTargetClass(Locale.class) -public class LocaleTest extends TestCase { + try { + new Locale("xx", null, "ZZ"); + fail("expected NullPointerException with 2nd parameter == null"); + } catch(NullPointerException e) { + } - /** + try { + new Locale("xx", "CV", null); + fail("expected NullPointerException with 3rd parameter == null"); + } catch(NullPointerException e) { + } + } + + /** + * @tests java.util.Locale#clone() + */ + public void test_clone() { + // Test for method java.lang.Object java.util.Locale.clone() + assertTrue("Clone failed", l.clone().equals(l)); + } + + /** + * @tests java.util.Locale#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + // Test for method boolean java.util.Locale.equals(java.lang.Object) + Locale l2 = new Locale("en", "CA", "WIN32"); + assertTrue("Same object returned false", testLocale.equals(testLocale)); + assertTrue("Same values returned false", testLocale.equals(l2)); + assertTrue("Different locales returned true", !testLocale.equals(l)); + + } + + /** * @tests java.util.Locale#getAvailableLocales() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAvailableLocales", - args = {} - ) public void test_getAvailableLocales() { + // Test for method java.util.Locale [] + // java.util.Locale.getAvailableLocales() + // Assumes there will generally be about 100+ available locales... Locale[] locales = Locale.getAvailableLocales(); - // Assumes that there will be a decent number of locales - // BEGIN android-changed - // this assumption is wrong. Android has a reduced locale repository. - // was >100, now it's >10 - assertTrue("Assert 0: Cannot find locales", locales.length > 10); - // END android-changed + assertTrue("Wrong number of locales: ", locales.length > 100); + // regression test for HARMONY-1514 + // HashSet can filter duplicate locales + Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales)); + // Non-bug difference for HARMONY-5442 + assertTrue(localesSet.size() <= locales.length); } + + /** + * @tests java.util.Locale#getCountry() + */ + public void test_getCountry() { + // Test for method java.lang.String java.util.Locale.getCountry() + assertTrue("Returned incorrect country: " + testLocale.getCountry(), + testLocale.getCountry().equals("CA")); + } + + /** + * @tests java.util.Locale#getDefault() + */ + public void test_getDefault() { + // Test for method java.util.Locale java.util.Locale.getDefault() + assertTrue("returns copy", Locale.getDefault() == Locale.getDefault()); + Locale org = Locale.getDefault(); + Locale.setDefault(l); + Locale x = Locale.getDefault(); + Locale.setDefault(org); + assertEquals("Failed to get locale", "fr_CA_WIN32", x.toString()); + } + + /** + * @tests java.util.Locale#getDisplayCountry() + */ + public void test_getDisplayCountry() { + // Test for method java.lang.String java.util.Locale.getDisplayCountry() + assertTrue("Returned incorrect country: " + + testLocale.getDisplayCountry(), testLocale + .getDisplayCountry().equals("Canada")); + + // Regression for Harmony-1146 + // Non-bug difference for HARMONY-5442 + Locale l_countryCD = new Locale("", "CD"); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("Congo - Kinshasa", //$NON-NLS-1$ + l_countryCD.getDisplayCountry()); + } + + /** + * @tests java.util.Locale#getDisplayCountry(java.util.Locale) + */ + public void test_getDisplayCountryLjava_util_Locale() { + // Test for method java.lang.String + // java.util.Locale.getDisplayCountry(java.util.Locale) + assertEquals("Returned incorrect country", "Italie", Locale.ITALY + .getDisplayCountry(l)); + } + + /** + * @tests java.util.Locale#getDisplayLanguage() + */ + public void test_getDisplayLanguage() { + // Test for method java.lang.String + // java.util.Locale.getDisplayLanguage() + assertTrue("Returned incorrect language: " + + testLocale.getDisplayLanguage(), testLocale + .getDisplayLanguage().equals("English")); + + // Regression for Harmony-1146 + Locale l_languageAE = new Locale("ae", ""); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("Avestan", l_languageAE.getDisplayLanguage()); //$NON-NLS-1$ + + // Regression for HARMONY-4402 + Locale defaultLocale = Locale.getDefault(); + try { + Locale locale = new Locale("no", "NO"); + Locale.setDefault(locale); + assertEquals("norsk", locale.getDisplayLanguage()); //$NON-NLS-1$ + } finally { + Locale.setDefault(defaultLocale); + } + } + + /** + * @tests java.util.Locale#getDisplayLanguage(java.util.Locale) + */ + public void test_getDisplayLanguageLjava_util_Locale() { + // Test for method java.lang.String + // java.util.Locale.getDisplayLanguage(java.util.Locale) + assertTrue("Returned incorrect language: " + + testLocale.getDisplayLanguage(l), testLocale + .getDisplayLanguage(l).equals("anglais")); + } + + /** + * @tests java.util.Locale#getDisplayName() + */ + public void test_getDisplayName() { + // Test for method java.lang.String java.util.Locale.getDisplayName() + assertTrue("Returned incorrect name: " + testLocale.getDisplayName(), + testLocale.getDisplayName().equals("English (Canada,WIN32)")); + } + + /** + * @tests java.util.Locale#getDisplayName(java.util.Locale) + */ + public void test_getDisplayNameLjava_util_Locale() { + // Test for method java.lang.String + // java.util.Locale.getDisplayName(java.util.Locale) + assertTrue("Returned incorrect name: " + testLocale.getDisplayName(l), + testLocale.getDisplayName(l).equals("anglais (Canada,WIN32)")); + } + + /** + * @tests java.util.Locale#getDisplayVariant() + */ + public void test_getDisplayVariant() { + // Test for method java.lang.String java.util.Locale.getDisplayVariant() + assertTrue("Returned incorrect variant: " + + testLocale.getDisplayVariant(), testLocale + .getDisplayVariant().equals("WIN32")); + } + + /** + * @tests java.util.Locale#getDisplayVariant(java.util.Locale) + */ + public void test_getDisplayVariantLjava_util_Locale() { + // Test for method java.lang.String + // java.util.Locale.getDisplayVariant(java.util.Locale) + assertTrue("Returned incorrect variant: " + + testLocale.getDisplayVariant(l), testLocale + .getDisplayVariant(l).equals("WIN32")); + } + + /** + * @tests java.util.Locale#getISO3Country() + */ + public void test_getISO3Country() { + // Test for method java.lang.String java.util.Locale.getISO3Country() + assertTrue("Returned incorrect ISO3 country: " + + testLocale.getISO3Country(), testLocale.getISO3Country() + .equals("CAN")); + + Locale l = new Locale("", "CD"); + assertEquals("COD", l.getISO3Country()); + } + + /** + * @tests java.util.Locale#getISO3Language() + */ + public void test_getISO3Language() { + // Test for method java.lang.String java.util.Locale.getISO3Language() + assertTrue("Returned incorrect ISO3 language: " + + testLocale.getISO3Language(), testLocale.getISO3Language() + .equals("eng")); + + Locale l = new Locale("ae"); + assertEquals("ave", l.getISO3Language()); + + // Regression for Harmony-1146 + + // Non-bug difference for HARMONY-5442 + Locale l_CountryCS = new Locale("", "CS"); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("SCG", l_CountryCS.getISO3Country()); //$NON-NLS-1$ + + // Regression for Harmony-1129 + l = new Locale("ak", ""); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("aka", l.getISO3Language()); //$NON-NLS-1$ + } + + /** + * @tests java.util.Locale#getISOCountries() + */ + public void test_getISOCountries() { + // Test for method java.lang.String [] + // java.util.Locale.getISOCountries() + // Assumes all countries are 2 digits, and that there will always be + // 230 countries on the list... + String[] isoCountries = Locale.getISOCountries(); + int length = isoCountries.length; + int familiarCount = 0; + for (int i = 0; i < length; i++) { + if (isoCountries[i].length() != 2) { + fail("Wrong format for ISOCountries."); + } + if (isoCountries[i].equals("CA") || isoCountries[i].equals("BB") + || isoCountries[i].equals("US") + || isoCountries[i].equals("KR")) + familiarCount++; + } + assertTrue("ISOCountries missing.", familiarCount == 4 && length > 230); + } + + /** + * @tests java.util.Locale#getISOLanguages() + */ + public void test_getISOLanguages() { + // Test for method java.lang.String [] + // java.util.Locale.getISOLanguages() + // Assumes always at least 131 ISOlanguages... + String[] isoLang = Locale.getISOLanguages(); + int length = isoLang.length; + + // Non-bug difference for HARMONY-5442 + assertTrue(isoLang[length / 2].length() == 3); + assertTrue(isoLang[length / 2].toLowerCase().equals(isoLang[length / 2])); + assertTrue("Wrong number of ISOLanguages.", length > 130); + } + + /** + * @tests java.util.Locale#getLanguage() + */ + public void test_getLanguage() { + // Test for method java.lang.String java.util.Locale.getLanguage() + assertTrue("Returned incorrect language: " + testLocale.getLanguage(), + testLocale.getLanguage().equals("en")); + } + + /** + * @tests java.util.Locale#getVariant() + */ + public void test_getVariant() { + // Test for method java.lang.String java.util.Locale.getVariant() + assertTrue("Returned incorrect variant: " + testLocale.getVariant(), + testLocale.getVariant().equals("WIN32")); + } + + /** + * @tests java.util.Locale#setDefault(java.util.Locale) + */ + public void test_setDefaultLjava_util_Locale() { + // Test for method void java.util.Locale.setDefault(java.util.Locale) + + Locale org = Locale.getDefault(); + Locale.setDefault(l); + Locale x = Locale.getDefault(); + Locale.setDefault(org); + assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString()); + + Locale.setDefault(new Locale("tr", "")); + String res1 = "\u0069".toUpperCase(); + String res2 = "\u0049".toLowerCase(); + Locale.setDefault(org); + assertEquals("Wrong toUppercase conversion", "\u0130", res1); + assertEquals("Wrong toLowercase conversion", "\u0131", res2); + } + + /** + * @tests java.util.Locale#toString() + */ + public void test_toString() { + // Test for method java.lang.String java.util.Locale.toString() + assertEquals("Returned incorrect string representation", "en_CA_WIN32", testLocale + .toString()); + + Locale l = new Locale("en", ""); + assertEquals("Wrong representation 1", "en", l.toString()); + l = new Locale("", "CA"); + assertEquals("Wrong representation 2", "_CA", l.toString()); + + // Non-bug difference for HARMONY-5442 + l = new Locale("", "CA", "var"); + assertEquals("Wrong representation 2.5", "_CA_var", l.toString()); + l = new Locale("en", "", "WIN"); + assertEquals("Wrong representation 4", "en__WIN", l.toString()); + l = new Locale("en", "CA"); + assertEquals("Wrong representation 6", "en_CA", l.toString()); + l = new Locale("en", "CA", "VAR"); + assertEquals("Wrong representation 7", "en_CA_VAR", l.toString()); + + l = new Locale("", "", "var"); + assertEquals("Wrong representation 8", "", l.toString()); + + } + + // Regression Test for HARMONY-2953 + public void test_getISO() { + Locale locale = new Locale("an"); + assertEquals("arg", locale.getISO3Language()); + + locale = new Locale("PS"); + assertEquals("pus", locale.getISO3Language()); + + List<String> languages = Arrays.asList(Locale.getISOLanguages()); + assertTrue(languages.contains("ak")); + + // Non-bug difference for HARMONY-5442 + List<String> countries = Arrays.asList(Locale.getISOCountries()); + assertFalse(countries.contains("CS")); + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + defaultLocale = Locale.getDefault(); + Locale.setDefault(Locale.US); + testLocale = new Locale("en", "CA", "WIN32"); + l = new Locale("fr", "CA", "WIN32"); + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + Locale.setDefault(defaultLocale); + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java index d93b069..705b597 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java @@ -16,33 +16,20 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.MissingFormatArgumentException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(MissingFormatArgumentException.class) public class MissingFormatArgumentExceptionTest extends TestCase { /** * @tests java.util.MissingFormatArgumentException#MissingFormatArgumentException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MissingFormatArgumentException", - args = {java.lang.String.class} - ) public void test_missingFormatArgumentException() { - assertNotNull(new MissingFormatArgumentException("String")); try { new MissingFormatArgumentException(null); @@ -55,12 +42,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase { /** * @tests java.util.MissingFormatArgumentException#getFormatSpecifier() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFormatSpecifier", - args = {} - ) public void test_getFormatSpecifier() { String s = "MYTESTSTRING"; MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException( @@ -71,12 +52,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase { /** * @tests java.util.MissingFormatArgumentException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String s = "MYTESTSTRING"; MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException( @@ -104,12 +79,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new MissingFormatArgumentException( @@ -119,12 +88,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java index be94d1c..81fa2d7 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java @@ -15,33 +15,20 @@ */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.MissingFormatWidthException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(MissingFormatWidthException.class) public class MissingFormatWidthExceptionTest extends TestCase { /** * @tests java.util.MissingFormatWidthException#MissingFormatWidthException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MissingFormatWidthException", - args = {java.lang.String.class} - ) public void test_missingFormatWidthException() { - assertNotNull(new MissingFormatWidthException("String")); try { new MissingFormatWidthException(null); fail("should throw NullPointerExcepiton"); @@ -53,12 +40,6 @@ public class MissingFormatWidthExceptionTest extends TestCase { /** * @tests java.util.MissingFormatWidthException#getFormatSpecifier() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFormatSpecifier", - args = {} - ) public void test_getFormatSpecifier() { String s = "MYTESTSTRING"; MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException( @@ -70,12 +51,6 @@ public class MissingFormatWidthExceptionTest extends TestCase { /** * @tests java.util.MissingFormatWidthException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String s = "MYTESTSTRING"; MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException( @@ -103,12 +78,6 @@ public class MissingFormatWidthExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new MissingFormatWidthException( @@ -118,12 +87,6 @@ public class MissingFormatWidthExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new MissingFormatWidthException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java index 562da42..d8f4cc4 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java @@ -17,30 +17,18 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.util.UUID; import org.apache.harmony.testframework.serialization.SerializationTest; -@TestTargetClass(UUID.class) +import junit.framework.TestCase; + public class UUIDTest extends TestCase { /** * @see UUID#UUID(long, long) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UUID", - args = {long.class, long.class} - ) - public void test_ConstructurJJ() { + public void test_ConstructorJJ() { UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); assertEquals(2, uuid.variant()); assertEquals(1, uuid.version()); @@ -53,12 +41,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#getLeastSignificantBits() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getLeastSignificantBits", - args = {} - ) public void test_getLeastSignificantBits() { UUID uuid = new UUID(0, 0); assertEquals(0, uuid.getLeastSignificantBits()); @@ -71,12 +53,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#getMostSignificantBits() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMostSignificantBits", - args = {} - ) public void test_getMostSignificantBits() { UUID uuid = new UUID(0, 0); assertEquals(0, uuid.getMostSignificantBits()); @@ -89,12 +65,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#version() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "version", - args = {} - ) public void test_version() { UUID uuid = new UUID(0, 0); assertEquals(0, uuid.version()); @@ -113,12 +83,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#variant() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "variant", - args = {} - ) public void test_variant() { UUID uuid = new UUID(0, 0x0000000000000000L); assertEquals(0, uuid.variant()); @@ -152,12 +116,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#timestamp() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "timestamp", - args = {} - ) public void test_timestamp() { UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); assertEquals(0x0, uuid.timestamp()); @@ -181,12 +139,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#clockSequence() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clockSequence", - args = {} - ) public void test_clockSequence() { UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); assertEquals(0x0, uuid.clockSequence()); @@ -213,12 +165,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#node() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "node", - args = {} - ) public void test_node() { UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); assertEquals(0x0, uuid.node()); @@ -242,12 +188,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#compareTo(UUID) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.util.UUID.class} - ) public void test_compareTo() { UUID uuid1 = new UUID(0, 0); assertEquals(0, uuid1.compareTo(uuid1)); @@ -263,12 +203,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { UUID uuid = new UUID(0, 0); assertEquals(0, uuid.hashCode()); @@ -280,12 +214,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#equals(Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsObject() { UUID uuid1 = new UUID(0, 0); assertEquals(uuid1, uuid1); @@ -308,12 +236,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); String actual = uuid.toString(); @@ -327,12 +249,6 @@ public class UUIDTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L)); @@ -341,12 +257,6 @@ public class UUIDTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L)); @@ -355,12 +265,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#randomUUID() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "randomUUID", - args = {} - ) public void test_randomUUID() { UUID uuid = UUID.randomUUID(); assertEquals(2, uuid.variant()); @@ -370,12 +274,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#nameUUIDFromBytes(byte[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "nameUUIDFromBytes", - args = {byte[].class} - ) public void test_nameUUIDFromBytes() throws Exception { byte[] name = { (byte) 0x6b, (byte) 0xa7, (byte) 0xb8, (byte) 0x11, (byte) 0x9d, (byte) 0xad, (byte) 0x11, (byte) 0xd1, @@ -406,12 +304,6 @@ public class UUIDTest extends TestCase { /** * @see UUID#fromString(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "fromString", - args = {java.lang.String.class} - ) public void test_fromString() { UUID actual = UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); UUID expected = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); @@ -464,108 +356,102 @@ public class UUIDTest extends TestCase { } catch (IllegalArgumentException e) {} } - /** - * @tests java.util.UUID#fromString(String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "fromString", - args = {java.lang.String.class} - ) - public void test_fromString_LString_Exception() { - - UUID uuid = UUID.fromString("0-0-0-0-0"); - - try { - uuid = UUID.fromString("0-0-0-0-"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("-0-0-0-0-0"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("-0-0-0-0"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("-0-0-0-"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("0--0-0-0"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("0-0-0-0-"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - uuid = UUID.fromString("-1-0-0-0-0"); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - uuid = UUID.fromString("123456789-0-0-0-0"); - assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); - assertEquals(0x0L, uuid.getLeastSignificantBits()); - - uuid = UUID.fromString("111123456789-0-0-0-0"); - assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); - assertEquals(0x0L, uuid.getLeastSignificantBits()); - - uuid = UUID.fromString("7fffffffffffffff-0-0-0-0"); - assertEquals(0xffffffff00000000L, uuid.getMostSignificantBits()); - assertEquals(0x0L, uuid.getLeastSignificantBits()); - - try { - uuid = UUID.fromString("8000000000000000-0-0-0-0"); - fail("should throw NumberFormatException"); - } catch (NumberFormatException e) { - // expected - } - - uuid = UUID - .fromString("7fffffffffffffff-7fffffffffffffff-7fffffffffffffff-0-0"); - assertEquals(0xffffffffffffffffL, uuid.getMostSignificantBits()); - assertEquals(0x0L, uuid.getLeastSignificantBits()); - - uuid = UUID.fromString("0-0-0-7fffffffffffffff-7fffffffffffffff"); - assertEquals(0x0L, uuid.getMostSignificantBits()); - assertEquals(0xffffffffffffffffL, uuid.getLeastSignificantBits()); - - try { - uuid = UUID.fromString("0-0-0-8000000000000000-0"); - fail("should throw NumberFormatException"); - } catch (NumberFormatException e) { - // expected - } - - try { - uuid = UUID.fromString("0-0-0-0-8000000000000000"); - fail("should throw NumberFormatException"); - } catch (NumberFormatException e) { - // expected - } - } + /** + * @tests java.util.UUID#fromString(String) + */ + public void test_fromString_LString_Exception() { + + UUID uuid = UUID.fromString("0-0-0-0-0"); + + try { + uuid = UUID.fromString("0-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("0--0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("0-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-1-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + uuid = UUID.fromString("123456789-0-0-0-0"); + assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("111123456789-0-0-0-0"); + assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("7fffffffffffffff-0-0-0-0"); + assertEquals(0xffffffff00000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + try { + uuid = UUID.fromString("8000000000000000-0-0-0-0"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + + uuid = UUID + .fromString("7fffffffffffffff-7fffffffffffffff-7fffffffffffffff-0-0"); + assertEquals(0xffffffffffffffffL, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("0-0-0-7fffffffffffffff-7fffffffffffffff"); + assertEquals(0x0L, uuid.getMostSignificantBits()); + assertEquals(0xffffffffffffffffL, uuid.getLeastSignificantBits()); + + try { + uuid = UUID.fromString("0-0-0-8000000000000000-0"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + + try { + uuid = UUID.fromString("0-0-0-0-8000000000000000"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java index 14ed171..262db4d 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java @@ -15,31 +15,19 @@ */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.UnknownFormatConversionException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(UnknownFormatConversionException.class) public class UnknownFormatConversionExceptionTest extends TestCase { /** * @tests java.util.UnknownFormatConversionException#UnknownFormatConversionException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnknownFormatConversionException", - args = {java.lang.String.class} - ) public void test_unknownFormatConversionException() { // RI 5.0 will not throw NullPointerException, it is the bug according @@ -54,12 +42,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase { /** * @tests java.util.UnknownFormatConversionException#getConversion() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getConversion", - args = {} - ) public void test_getConversion() { String s = "MYTESTSTRING"; UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException( @@ -70,12 +52,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase { /** * @tests java.util.UnknownFormatConversionException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String s = "MYTESTSTRING"; UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException( @@ -102,12 +78,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new UnknownFormatConversionException( @@ -117,12 +87,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java index c14cdee..3221cc5 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java @@ -16,31 +16,19 @@ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - import java.io.Serializable; import java.util.UnknownFormatFlagsException; +import junit.framework.TestCase; + import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -@TestTargetClass(UnknownFormatFlagsException.class) public class UnknownFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.UnknownFormatFlagsException#UnknownFormatFlagsException(String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "UnknownFormatFlagsException", - args = {java.lang.String.class} - ) public void test_unknownFormatFlagsException() { try { @@ -49,18 +37,11 @@ public class UnknownFormatFlagsExceptionTest extends TestCase { } catch (NullPointerException e) { // expected } - assertNotNull(new UnknownFormatFlagsException("String")); } /** * @tests java.util.UnknownFormatFlagsException#getFlags() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getFlags", - args = {} - ) public void test_getFlags() { String s = "MYTESTSTRING"; UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException( @@ -71,12 +52,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase { /** * @tests java.util.UnknownFormatFlagsException#getMessage() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMessage", - args = {} - ) public void test_getMessage() { String s = "MYTESTSTRING"; UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException( @@ -102,12 +77,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationSelf", - args = {} - ) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new UnknownFormatFlagsException( @@ -117,12 +86,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase { /** * @tests serialization/deserialization compatibility with RI. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "!SerializationGolden", - args = {} - ) public void testSerializationCompatibility() throws Exception { SerializationTest.verifyGolden(this, new UnknownFormatFlagsException( diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java index 18cb550..82592b1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java @@ -1,42 +1,1230 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +import java.util.Arrays; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Vector; -import junit.framework.TestCase; +import tests.support.Support_ListTest; -import java.util.Vector; +public class VectorTest extends junit.framework.TestCase { + + private Vector tVector = new Vector(); + + Object[] objArray; + + private String vString = "[Test 0, Test 1, Test 2, Test 3, Test 4, Test 5, Test 6, Test 7, Test 8, Test 9, Test 10, Test 11, Test 12, Test 13, Test 14, Test 15, Test 16, Test 17, Test 18, Test 19, Test 20, Test 21, Test 22, Test 23, Test 24, Test 25, Test 26, Test 27, Test 28, Test 29, Test 30, Test 31, Test 32, Test 33, Test 34, Test 35, Test 36, Test 37, Test 38, Test 39, Test 40, Test 41, Test 42, Test 43, Test 44, Test 45, Test 46, Test 47, Test 48, Test 49, Test 50, Test 51, Test 52, Test 53, Test 54, Test 55, Test 56, Test 57, Test 58, Test 59, Test 60, Test 61, Test 62, Test 63, Test 64, Test 65, Test 66, Test 67, Test 68, Test 69, Test 70, Test 71, Test 72, Test 73, Test 74, Test 75, Test 76, Test 77, Test 78, Test 79, Test 80, Test 81, Test 82, Test 83, Test 84, Test 85, Test 86, Test 87, Test 88, Test 89, Test 90, Test 91, Test 92, Test 93, Test 94, Test 95, Test 96, Test 97, Test 98, Test 99]"; + + /** + * @tests java.util.Vector#Vector() + */ + public void test_Constructor() { + // Test for method java.util.Vector() + + Vector tv = new Vector(100); + for (int i = 0; i < 100; i++) + tv.addElement(new Integer(i)); + new Support_ListTest("", tv).runTest(); + + tv = new Vector(200); + for (int i = -50; i < 150; i++) + tv.addElement(new Integer(i)); + new Support_ListTest("", tv.subList(50, 150)).runTest(); + + Vector v = new Vector(); + assertEquals("Vector creation failed", 0, v.size()); + assertEquals("Wrong capacity", 10, v.capacity()); + } + + /** + * @tests java.util.Vector#Vector(int) + */ + public void test_ConstructorI() { + // Test for method java.util.Vector(int) + + Vector v = new Vector(100); + assertEquals("Vector creation failed", 0, v.size()); + assertEquals("Wrong capacity", 100, v.capacity()); + } + + /** + * @tests java.util.Vector#Vector(int, int) + */ + public void test_ConstructorII() { + // Test for method java.util.Vector(int, int) + + Vector v = new Vector(2, 10); + v.addElement(new Object()); + v.addElement(new Object()); + v.addElement(new Object()); + + assertEquals("Failed to inc capacity by proper amount", + 12, v.capacity()); + + Vector grow = new Vector(3, -1); + grow.addElement("one"); + grow.addElement("two"); + grow.addElement("three"); + grow.addElement("four"); + assertEquals("Wrong size", 4, grow.size()); + assertEquals("Wrong capacity", 6, grow.capacity()); + + Vector emptyVector = new Vector(0, 0); + emptyVector.addElement("one"); + assertEquals("Wrong size", 1, emptyVector.size()); + emptyVector.addElement("two"); + emptyVector.addElement("three"); + assertEquals("Wrong size", 3, emptyVector.size()); + + try { + Vector negativeVector = new Vector(-1, 0); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#Vector(java.util.Collection) + */ + public void test_ConstructorLjava_util_Collection() { + // Test for method java.util.Vector(java.util.Collection) + Collection l = new LinkedList(); + for (int i = 0; i < 100; i++) + l.add("Test " + i); + Vector myVector = new Vector(l); + assertTrue("Vector is not correct size", + myVector.size() == objArray.length); + for (int counter = 0; counter < objArray.length; counter++) + assertTrue("Vector does not contain correct elements", myVector + .contains(((List) l).get(counter))); + } + + /** + * @tests java.util.Vector#add(int, java.lang.Object) + */ + public void test_addILjava_lang_Object() { + // Test for method void java.util.Vector.add(int, java.lang.Object) + Object o = new Object(); + Object prev = tVector.get(45); + tVector.add(45, o); + assertTrue("Failed to add Object", tVector.get(45) == o); + assertTrue("Failed to fix-up existing indices", tVector.get(46) == prev); + assertEquals("Wrong size after add", 101, tVector.size()); + + prev = tVector.get(50); + tVector.add(50, null); + assertNull("Failed to add null", tVector.get(50)); + assertTrue("Failed to fix-up existing indices after adding null", + tVector.get(51) == prev); + assertEquals("Wrong size after add", 102, tVector.size()); + } + + /** + * @tests java.util.Vector#add(java.lang.Object) + */ + public void test_addLjava_lang_Object() { + // Test for method boolean java.util.Vector.add(java.lang.Object) + Object o = new Object(); + tVector.add(o); + assertTrue("Failed to add Object", tVector.lastElement() == o); + assertEquals("Wrong size after add", 101, tVector.size()); + + tVector.add(null); + assertNull("Failed to add null", tVector.lastElement()); + assertEquals("Wrong size after add", 102, tVector.size()); + } + + /** + * @tests java.util.Vector#addAll(int, java.util.Collection) + */ + public void test_addAllILjava_util_Collection() { + // Test for method boolean java.util.Vector.addAll(int, + // java.util.Collection) + Collection l = new LinkedList(); + for (int i = 0; i < 100; i++) + l.add("Test " + i); + Vector v = new Vector(); + tVector.addAll(50, l); + for (int i = 50; i < 100; i++) + assertTrue("Failed to add all elements", + tVector.get(i) == ((List) l).get(i - 50)); + v = new Vector(); + v.add("one"); + int r = 0; + try { + v.addAll(3, Arrays.asList(new String[] { "two", "three" })); + } catch (ArrayIndexOutOfBoundsException e) { + r = 1; + } catch (IndexOutOfBoundsException e) { + r = 2; + } + assertTrue("Invalid add: " + r, r == 1); + l = new LinkedList(); + l.add(null); + l.add("gah"); + l.add(null); + tVector.addAll(50, l); + assertNull("Wrong element at position 50--wanted null", + tVector.get(50)); + assertEquals("Wrong element at position 51--wanted 'gah'", "gah", tVector + .get(51)); + assertNull("Wrong element at position 52--wanted null", + tVector.get(52)); + + try { + v.addAll(0, null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // Excepted + } + + try { + v.addAll(-1, null); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#addAll(java.util.Collection) + */ + public void test_addAllLjava_util_Collection() { + // Test for method boolean java.util.Vector.addAll(java.util.Collection) + Vector v = new Vector(); + Collection l = new LinkedList(); + for (int i = 0; i < 100; i++) + l.add("Test " + i); + v.addAll(l); + assertTrue("Failed to add all elements", tVector.equals(v)); + + v.addAll(l); + int vSize = tVector.size(); + for (int counter = vSize - 1; counter >= 0; counter--) + assertTrue("Failed to add elements correctly", v.get(counter) == v + .get(counter + vSize)); + + l = new LinkedList(); + l.add(null); + l.add("gah"); + l.add(null); + tVector.addAll(l); + assertNull("Wrong element at 3rd last position--wanted null", tVector + .get(vSize)); + assertEquals("Wrong element at 2nd last position--wanted 'gah'", "gah", tVector + .get(vSize + 1)); + assertNull("Wrong element at last position--wanted null", tVector + .get(vSize + 2)); + + try { + v.addAll(null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#addElement(java.lang.Object) + */ + public void test_addElementLjava_lang_Object() { + // Test for method void java.util.Vector.addElement(java.lang.Object) + Vector v = vectorClone(tVector); + v.addElement("Added Element"); + assertTrue("Failed to add element", v.contains("Added Element")); + assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100)) + ); + v.addElement(null); + assertTrue("Failed to add null", v.contains(null)); + assertNull("Added null to wrong slot", v.elementAt(101)); + } + + /** + * @tests java.util.Vector#addElement(java.lang.Object) + */ + public void test_addElementLjava_lang_Object_subtest0() { + // Test for method void java.util.Vector.addElement(java.lang.Object) + Vector v = vectorClone(tVector); + v.addElement("Added Element"); + assertTrue("Failed to add element", v.contains("Added Element")); + assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100)) + ); + v.addElement(null); + assertTrue("Failed to add null", v.contains(null)); + assertNull("Added null to wrong slot", v.elementAt(101)); + } + + /** + * @tests java.util.Vector#capacity() + */ + public void test_capacity() { + // Test for method int java.util.Vector.capacity() + + Vector v = new Vector(9); + assertEquals("Incorrect capacity returned", 9, v.capacity()); + } + + /** + * @tests java.util.Vector#clear() + */ + public void test_clear() { + // Test for method void java.util.Vector.clear() + Vector orgVector = vectorClone(tVector); + tVector.clear(); + assertEquals("a) Cleared Vector has non-zero size", 0, tVector.size()); + Enumeration e = orgVector.elements(); + while (e.hasMoreElements()) + assertTrue("a) Cleared vector contained elements", !tVector + .contains(e.nextElement())); + + tVector.add(null); + tVector.clear(); + assertEquals("b) Cleared Vector has non-zero size", 0, tVector.size()); + e = orgVector.elements(); + while (e.hasMoreElements()) + assertTrue("b) Cleared vector contained elements", !tVector + .contains(e.nextElement())); + } + + /** + * @tests java.util.Vector#clone() + */ + public void test_clone() { + // Test for method java.lang.Object java.util.Vector.clone() + tVector.add(25, null); + tVector.add(75, null); + Vector v = (Vector) tVector.clone(); + Enumeration orgNum = tVector.elements(); + Enumeration cnum = v.elements(); + + while (orgNum.hasMoreElements()) { + assertTrue("Not enough elements copied", cnum.hasMoreElements()); + assertTrue("Vector cloned improperly, elements do not match", + orgNum.nextElement() == cnum.nextElement()); + } + assertTrue("Not enough elements copied", !cnum.hasMoreElements()); + + } + + /** + * @tests java.util.Vector#contains(java.lang.Object) + */ + public void test_containsLjava_lang_Object() { + // Test for method boolean java.util.Vector.contains(java.lang.Object) + assertTrue("Did not find element", tVector.contains("Test 42")); + assertTrue("Found bogus element", !tVector.contains("Hello")); + assertTrue( + "Returned true looking for null in vector without null element", + !tVector.contains(null)); + tVector.insertElementAt(null, 20); + assertTrue( + "Returned false looking for null in vector with null element", + tVector.contains(null)); + } + + /** + * @tests java.util.Vector#containsAll(java.util.Collection) + */ + public void test_containsAllLjava_util_Collection() { + // Test for method boolean + // java.util.Vector.containsAll(java.util.Collection) + Collection s = new HashSet(); + for (int i = 0; i < 100; i++) + s.add("Test " + i); + + assertTrue("Returned false for valid collection", tVector + .containsAll(s)); + s.add(null); + assertTrue("Returned true for invlaid collection containing null", + !tVector.containsAll(s)); + tVector.add(25, null); + assertTrue("Returned false for valid collection containing null", + tVector.containsAll(s)); + s = new HashSet(); + s.add(new Object()); + assertTrue("Returned true for invalid collection", !tVector + .containsAll(s)); + } + + /** + * @tests java.util.Vector#copyInto(java.lang.Object[]) + */ + public void test_copyInto$Ljava_lang_Object() { + // Test for method void java.util.Vector.copyInto(java.lang.Object []) + + Object[] a = new Object[100]; + tVector.setElementAt(null, 20); + tVector.copyInto(a); + + for (int i = 0; i < 100; i++) + assertTrue("copyInto failed", a[i] == tVector.elementAt(i)); + } + + /** + * @tests java.util.Vector#elementAt(int) + */ + public void test_elementAtI() { + // Test for method java.lang.Object java.util.Vector.elementAt(int) + assertEquals("Incorrect element returned", "Test 18", ((String) tVector + .elementAt(18))); + tVector.setElementAt(null, 20); + assertNull("Incorrect element returned--wanted null", tVector + .elementAt(20)); + + } + + /** + * @tests java.util.Vector#elements() + */ + public void test_elements() { + // Test for method java.util.Enumeration java.util.Vector.elements() + tVector.insertElementAt(null, 20); + Enumeration e = tVector.elements(); + int i = 0; + while (e.hasMoreElements()) { + assertTrue("Enumeration returned incorrect element at pos: " + i, e + .nextElement() == tVector.elementAt(i)); + i++; + } + assertTrue("Invalid enumeration", i == tVector.size()); + } + + /** + * @tests java.util.Vector#elements() + */ + public void test_elements_subtest0() { + final int iterations = 10000; + final Vector v = new Vector(); + Thread t1 = new Thread() { + public void run() { + for (int i = 0; i < iterations; i++) { + synchronized (v) { + v.addElement(String.valueOf(i)); + v.removeElementAt(0); + } + } + } + }; + t1.start(); + for (int i = 0; i < iterations; i++) { + Enumeration en = v.elements(); + try { + while (true) { + Object result = en.nextElement(); + if (result == null) { + fail("Null result: " + i); + } + } + } catch (NoSuchElementException e) { + } + } + } + + /** + * @tests java.util.Vector#ensureCapacity(int) + */ + public void test_ensureCapacityI() { + // Test for method void java.util.Vector.ensureCapacity(int) + + Vector v = new Vector(9); + v.ensureCapacity(20); + assertEquals("ensureCapacity failed to set correct capacity", 20, v + .capacity()); + v = new Vector(100); + assertEquals("ensureCapacity reduced capacity", 100, v.capacity()); + + v.ensureCapacity(150); + assertEquals( + "ensuieCapacity failed to set to be twice the old capacity", + 200, v.capacity()); + + v = new Vector(9, -1); + v.ensureCapacity(20); + assertEquals("ensureCapacity failed to set to be minCapacity", 20, v + .capacity()); + v.ensureCapacity(15); + assertEquals("ensureCapacity reduced capacity", 20, v.capacity()); + v.ensureCapacity(35); + assertEquals( + "ensuieCapacity failed to set to be twice the old capacity", + 40, v.capacity()); + + v = new Vector(9, 4); + v.ensureCapacity(11); + assertEquals("ensureCapacity failed to set correct capacity", 13, v + .capacity()); + v.ensureCapacity(5); + assertEquals("ensureCapacity reduced capacity", 13, v.capacity()); + v.ensureCapacity(20); + assertEquals( + "ensuieCapacity failed to set to be twice the old capacity", + 20, v.capacity()); + } + + /** + * @tests java.util.Vector#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + // Test for method boolean java.util.Vector.equals(java.lang.Object) + Vector v = new Vector(); + for (int i = 0; i < 100; i++) + v.addElement("Test " + i); + assertTrue("a) Equal vectors returned false", tVector.equals(v)); + v.addElement(null); + assertTrue("b) UnEqual vectors returned true", !tVector.equals(v)); + tVector.addElement(null); + assertTrue("c) Equal vectors returned false", tVector.equals(v)); + tVector.removeElementAt(22); + assertTrue("d) UnEqual vectors returned true", !tVector.equals(v)); + assertTrue("e) Equal vectors returned false", tVector.equals(tVector)); + assertFalse("f) UnEqual vectors returned true", tVector + .equals(new Object())); + assertFalse("g) Unequal vectors returned true", tVector.equals(null)); + } + + /** + * @tests java.util.Vector#firstElement() + */ + public void test_firstElement() { + // Test for method java.lang.Object java.util.Vector.firstElement() + assertEquals("Returned incorrect firstElement", "Test 0", tVector.firstElement() + ); + tVector.insertElementAt(null, 0); + assertNull("Returned incorrect firstElement--wanted null", tVector + .firstElement()); + + Vector v = new Vector(); + try { + v.firstElement(); + fail("Should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#get(int) + */ + public void test_getI() { + // Test for method java.lang.Object java.util.Vector.get(int) + assertEquals("Get returned incorrect object", + "Test 80", tVector.get(80)); + tVector.add(25, null); + assertNull("Returned incorrect element--wanted null", + tVector.get(25)); + } + + /** + * @tests java.util.Vector#hashCode() + */ + public void test_hashCode() { + // Test for method int java.util.Vector.hashCode() + int hashCode = 1; // one + tVector.insertElementAt(null, 20); + for (int i = 0; i < tVector.size(); i++) { + Object obj = tVector.elementAt(i); + hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); + } + assertTrue("Incorrect hashCode returned. Wanted: " + hashCode + + " got: " + tVector.hashCode(), tVector.hashCode() == hashCode); + } + + /** + * @tests java.util.Vector#indexOf(java.lang.Object) + */ + public void test_indexOfLjava_lang_Object() { + // Test for method int java.util.Vector.indexOf(java.lang.Object) + assertEquals("Incorrect index returned", 10, tVector.indexOf("Test 10")); + assertEquals("Index returned for invalid Object", -1, tVector + .indexOf("XXXXXXXXXXX")); + tVector.setElementAt(null, 20); + tVector.setElementAt(null, 40); + assertTrue("Incorrect indexOf returned for null: " + + tVector.indexOf(null), tVector.indexOf(null) == 20); + } + + /** + * @tests java.util.Vector#indexOf(java.lang.Object, int) + */ + public void test_indexOfLjava_lang_ObjectI() { + // Test for method int java.util.Vector.indexOf(java.lang.Object, int) + assertEquals("Failed to find correct index", tVector.indexOf("Test 98", + 50), 98); + assertTrue("Found index of bogus element", (tVector.indexOf( + "Test 1001", 50) == -1)); + tVector.setElementAt(null, 20); + tVector.setElementAt(null, 40); + tVector.setElementAt(null, 60); + assertTrue("a) Incorrect indexOf returned for null: " + + tVector.indexOf(null, 25), tVector.indexOf(null, 25) == 40); + assertTrue("b) Incorrect indexOf returned for null: " + + tVector.indexOf(null, 20), tVector.indexOf(null, 20) == 20); + try { + tVector.indexOf("Test 98", -1); + fail("should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + + } + assertEquals(-1, tVector.indexOf("Test 98", 1000)); + assertEquals(-1, tVector.indexOf("Test 98", Integer.MAX_VALUE)); + assertEquals(-1, tVector.indexOf("Test 98", tVector.size())); + assertEquals(98, tVector.indexOf("Test 98", 0)); + try { + tVector.indexOf("Test 98", Integer.MIN_VALUE); + fail("should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + + } + } + + /** + * @tests java.util.Vector#insertElementAt(java.lang.Object, int) + */ + public void test_insertElementAtLjava_lang_ObjectI() { + // Test for method void + // java.util.Vector.insertElementAt(java.lang.Object, int) + Vector v = vectorClone(tVector); + String prevElement = (String) v.elementAt(99); + v.insertElementAt("Inserted Element", 99); + assertEquals("Element not inserted", "Inserted Element", ((String) v.elementAt(99)) + ); + assertTrue("Elements shifted incorrectly", ((String) v.elementAt(100)) + .equals(prevElement)); + v.insertElementAt(null, 20); + assertNull("null not inserted", v.elementAt(20)); + + try { + tVector.insertElementAt("Inserted Element", -1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.insertElementAt(null, -1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.insertElementAt("Inserted Element", tVector.size() + 1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.insertElementAt(null, tVector.size() + 1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#isEmpty() + */ + public void test_isEmpty() { + // Test for method boolean java.util.Vector.isEmpty()Vector + Vector v = new java.util.Vector(); + assertTrue("Empty vector returned false", v.isEmpty()); + v.addElement(new Object()); + assertTrue("non-Empty vector returned true", !v.isEmpty()); + } + + /** + * @tests java.util.Vector#isEmpty() + */ + public void test_isEmpty_subtest0() { + final Vector v = new Vector(); + v.addElement("initial"); + Thread t1 = new Thread() { + public void run() { + while (!v.isEmpty()) + ; + v.addElement("final"); + } + }; + t1.start(); + for (int i = 0; i < 10000; i++) { + synchronized (v) { + v.removeElementAt(0); + v.addElement(String.valueOf(i)); + } + int size; + if ((size = v.size()) != 1) { + String result = "Size is not 1: " + size + " " + v; + // terminate the thread + v.removeAllElements(); + fail(result); + } + } + // terminate the thread + v.removeElementAt(0); + } -@TestTargetClass(Vector.class) -public class VectorTest extends TestCase { + /** + * @tests java.util.Vector#lastElement() + */ + public void test_lastElement() { + // Test for method java.lang.Object java.util.Vector.lastElement() + assertEquals("Incorrect last element returned", "Test 99", tVector.lastElement() + ); + tVector.addElement(null); + assertNull("Incorrect last element returned--wanted null", tVector + .lastElement()); + + Vector vector = new Vector(); + try { + vector.lastElement(); + fail("Should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#lastIndexOf(java.lang.Object) + */ + public void test_lastIndexOfLjava_lang_Object() { + // Test for method int java.util.Vector.lastIndexOf(java.lang.Object) + Vector v = new Vector(9); + for (int i = 0; i < 9; i++) + v.addElement("Test"); + v.addElement("z"); + assertEquals("Failed to return correct index", 8, v.lastIndexOf("Test")); + tVector.setElementAt(null, 20); + tVector.setElementAt(null, 40); + assertTrue("Incorrect lastIndexOf returned for null: " + + tVector.lastIndexOf(null), tVector.lastIndexOf(null) == 40); + } + + /** + * @tests java.util.Vector#lastIndexOf(java.lang.Object, int) + */ + public void test_lastIndexOfLjava_lang_ObjectI() { + // Test for method int java.util.Vector.lastIndexOf(java.lang.Object, + // int) + assertEquals("Failed to find object", + 0, tVector.lastIndexOf("Test 0", 0)); + assertTrue("Found Object outside of index", (tVector.lastIndexOf( + "Test 0", 10) > -1)); + tVector.setElementAt(null, 20); + tVector.setElementAt(null, 40); + tVector.setElementAt(null, 60); + assertTrue("Incorrect lastIndexOf returned for null: " + + tVector.lastIndexOf(null, 15), + tVector.lastIndexOf(null, 15) == -1); + assertTrue("Incorrect lastIndexOf returned for null: " + + tVector.lastIndexOf(null, 45), + tVector.lastIndexOf(null, 45) == 40); + + assertEquals(-1, tVector.lastIndexOf("Test 98", -1)); + assertEquals(-1, tVector.lastIndexOf("Test 98", 0)); + try { + assertEquals(-1, tVector.lastIndexOf("Test 98", 1000)); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + try { + assertEquals(-1, tVector.lastIndexOf("Test 98", Integer.MAX_VALUE)); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + try { + tVector.lastIndexOf("Test 98", tVector.size()); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + try { + tVector.indexOf("Test 98", Integer.MIN_VALUE); + fail("should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + } + } + + /** + * @tests java.util.Vector#remove(int) + */ + public void test_removeI() { + // Test for method java.lang.Object java.util.Vector.remove(int) + Object removeElement = tVector.get(36); + Object result = tVector.remove(36); + assertFalse("Contained element after remove", tVector + .contains("Test 36")); + assertEquals("Should return the element that was removed", + removeElement, result); + assertEquals("Failed to decrement size after remove", + 99, tVector.size()); + tVector.add(20, null); + removeElement = tVector.get(19); + result = tVector.remove(19); + assertNull("Didn't move null element over", tVector.get(19)); + assertEquals("Should return the element that was removed", + removeElement, result); + removeElement = tVector.get(19); + result = tVector.remove(19); + assertNotNull("Didn't remove null element", tVector.get(19)); + assertEquals("Should return the element that was removed", + removeElement, result); + assertEquals("Failed to decrement size after removing null", 98, tVector + .size()); + + try { + tVector.remove(-1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.remove(tVector.size()); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#remove(java.lang.Object) + */ + public void test_removeLjava_lang_Object() { + // Test for method boolean java.util.Vector.remove(java.lang.Object) + tVector.remove("Test 0"); + assertTrue("Contained element after remove", !tVector + .contains("Test 0")); + assertEquals("Failed to decrement size after remove", + 99, tVector.size()); + tVector.add(null); + tVector.remove(null); + assertTrue("Contained null after remove", !tVector.contains(null)); + assertEquals("Failed to decrement size after removing null", 99, tVector + .size()); + } + + /** + * @tests java.util.Vector#removeAll(java.util.Collection) + */ + public void test_removeAllLjava_util_Collection() { + // Test for method boolean + // java.util.Vector.removeAll(java.util.Collection) + Vector v = new Vector(); + Collection l = new LinkedList(); + for (int i = 0; i < 5; i++) + l.add("Test " + i); + v.addElement(l); + + Collection s = new HashSet(); + Object o; + s.add(o = v.firstElement()); + v.removeAll(s); + assertTrue("Failed to remove items in collection", !v.contains(o)); + v.removeAll(l); + assertTrue("Failed to remove all elements", v.isEmpty()); + + v.add(null); + v.add(null); + v.add("Boom"); + v.removeAll(s); + assertEquals("Should not have removed any elements", 3, v.size()); + l = new LinkedList(); + l.add(null); + v.removeAll(l); + assertEquals("Should only have one element", 1, v.size()); + assertEquals("Element should be 'Boom'", "Boom", v.firstElement()); + } + + /** + * @tests java.util.Vector#removeAllElements() + */ + public void test_removeAllElements() { + // Test for method void java.util.Vector.removeAllElements() + Vector v = vectorClone(tVector); + v.removeAllElements(); + assertEquals("Failed to remove all elements", 0, v.size()); + } + + /** + * @tests java.util.Vector#removeElement(java.lang.Object) + */ + public void test_removeElementLjava_lang_Object() { + // Test for method boolean + // java.util.Vector.removeElement(java.lang.Object) + Vector v = vectorClone(tVector); + v.removeElement("Test 98"); + assertEquals("Element not removed", "Test 99", ((String) v.elementAt(98)) + ); + assertTrue("Vector is wrong size after removal: " + v.size(), + v.size() == 99); + tVector.addElement(null); + v.removeElement(null); + assertTrue("Vector is wrong size after removing null: " + v.size(), v + .size() == 99); + } + + /** + * @tests java.util.Vector#removeElementAt(int) + */ + public void test_removeElementAtI() { + // Test for method void java.util.Vector.removeElementAt(int) + Vector v = vectorClone(tVector); + int size = v.size(); + v.removeElementAt(50); + assertEquals("Failed to remove element", -1, v.indexOf("Test 50", 0)); + assertEquals("Test 51", v.get(50)); + assertEquals(size - 1, v.size()); + + tVector.insertElementAt(null, 60); + assertNull(tVector.get(60)); + size = tVector.size(); + tVector.removeElementAt(60); + assertNotNull("Element at 60 should not be null after removal", tVector + .elementAt(60)); + assertEquals(size - 1, tVector.size()); + + try { + tVector.removeElementAt(-1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.removeElementAt(tVector.size()); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests {@link java.util.Vector#removeRange(int, int)} + */ + public void test_removeRange() { + MockVector myVector = new MockVector(); + myVector.removeRange(0, 0); + + try { + myVector.removeRange(0, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Excepted + } + + int[] data = { 1, 2, 3, 4 }; + for (int i = 0; i < data.length; i++) { + myVector.add(i, data[i]); + } + + myVector.removeRange(0, 2); + assertEquals(data[2], myVector.get(0)); + assertEquals(data[3], myVector.get(1)); + + try { + myVector.removeRange(-1, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Excepted + } + + try { + myVector.removeRange(0, -1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Excepted + } + + try { + myVector.removeRange(1, 0); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Excepted + } + + try { + myVector.removeRange(2, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#retainAll(java.util.Collection) + */ + public void test_retainAllLjava_util_Collection() { + // Test for method boolean + // java.util.Vector.retainAll(java.util.Collection) + Object o = tVector.firstElement(); + tVector.add(null); + Collection s = new HashSet(); + s.add(o); + s.add(null); + tVector.retainAll(s); + assertTrue("Retained items other than specified", tVector.size() == 2 + && tVector.contains(o) && tVector.contains(null)); + } + + /** + * @tests java.util.Vector#set(int, java.lang.Object) + */ + public void test_setILjava_lang_Object() { + // Test for method java.lang.Object java.util.Vector.set(int, + // java.lang.Object) + Object o = new Object(); + Object previous = tVector.get(23); + Object result = tVector.set(23, o); + assertEquals( + "Should return the element previously at the specified position", + previous, result); + assertTrue("Failed to set Object", tVector.get(23) == o); + + previous = tVector.get(0); + result = tVector.set(0, null); + assertEquals( + "Should return the element previously at the specified position", + previous, result); + assertNull("Failed to set Object", tVector.get(0)); + + try { + tVector.set(-1, o); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.set(-1, null); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.set(tVector.size(), o); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + tVector.set(tVector.size(), null); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#setElementAt(java.lang.Object, int) + */ + public void test_setElementAtLjava_lang_ObjectI() { + // Test for method void java.util.Vector.setElementAt(java.lang.Object, + // int) + Vector v = vectorClone(tVector); + v.setElementAt("Inserted Element", 99); + assertEquals("Element not set", "Inserted Element", ((String) v.elementAt(99)) + ); + + v.setElementAt(null, 0); + assertNull("Null element not set", v.elementAt(0)); + + try { + v.setElementAt("Inserted Element", -1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + v.setElementAt(null, -1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + v.setElementAt("Inserted Element", v.size()); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + + try { + v.setElementAt(null, v.size()); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#setSize(int) + */ + public void test_setSizeI() { + // Test for method void java.util.Vector.setSize(int) + Vector v = vectorClone(tVector); + int oldSize = v.size(); + Object preElement = v.get(10); + v.setSize(10); + assertEquals("Failed to set size", 10, v.size()); + assertEquals( + "All components at index newSize and greater should be discarded", + -1, v.indexOf(preElement)); + try { + v.get(oldSize - 1); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted; + } + + oldSize = v.size(); + v.setSize(20); + assertEquals("Failed to set size", 20, v.size()); + for (int i = oldSize; i < v.size(); i++) { + assertNull(v.get(i)); + } + + try { + v.setSize(-1); + fail("Should throw ArrayIndexOutOfBoundsException"); + } catch (ArrayIndexOutOfBoundsException e) { + // Excepted + } + } + + /** + * @tests java.util.Vector#size() + */ + public void test_size() { + // Test for method int java.util.Vector.size() + assertEquals("Returned incorrect size", 100, tVector.size()); + + final Vector v = new Vector(); + v.addElement("initial"); + Thread t1 = new Thread() { + public void run() { + while (v.size() > 0) + ; + v.addElement("final"); + } + }; + t1.start(); + for (int i = 0; i < 10000; i++) { + synchronized (v) { + v.removeElementAt(0); + v.addElement(String.valueOf(i)); + } + int size; + if ((size = v.size()) != 1) { + String result = "Size is not 1: " + size + " " + v; + // terminate the thread + v.removeAllElements(); + fail(result); + } + } + // terminate the thread + v.removeElementAt(0); + } + + /** + * @tests java.util.Vector#subList(int, int) + */ + public void test_subListII() { + // Test for method java.util.List java.util.Vector.subList(int, int) + List sl = tVector.subList(10, 25); + assertEquals("Returned sublist of incorrect size", 15, sl.size()); + for (int i = 10; i < 25; i++) + assertTrue("Returned incorrect sublist", sl + .contains(tVector.get(i))); + + assertEquals("Not synchronized random access", "java.util.Collections$SynchronizedRandomAccessList", sl.getClass().getName() + ); + + } + + /** + * @tests java.util.Vector#toArray() + */ + public void test_toArray() { + // Test for method java.lang.Object [] java.util.Vector.toArray() + assertTrue("Returned incorrect array", Arrays.equals(objArray, tVector + .toArray())); + } + + /** + * @tests java.util.Vector#toArray(java.lang.Object[]) + */ + public void test_toArray$Ljava_lang_Object() { + // Test for method java.lang.Object [] + // java.util.Vector.toArray(java.lang.Object []) + Object[] o = new Object[1000]; + Object f = new Object(); + for (int i = 0; i < o.length; i++) + o[i] = f; + tVector.toArray(o); + assertNull("Failed to set slot to null", o[100]); + for (int i = 0; i < tVector.size(); i++) + assertTrue("Returned incorrect array", tVector.elementAt(i) == o[i]); + } + + + + class SubVector<E> extends Vector<E> { + + private static final long serialVersionUID = 1L; + + public SubVector() { + super(); + } + + public synchronized boolean add(E obj) { + super.addElement(obj); + return true; + } + + public synchronized void addElement(E obj) { + super.add(obj); + } + + /** + * @tests java.util.Vector#add(Object) + */ + @SuppressWarnings("nls") + public void test_add() { + SubVector<String> subvector = new SubVector<String>(); + subvector.add("foo"); + subvector.addElement("bar"); + assertEquals("Expected two elements in vector", 2, subvector.size()); + } + + } /** * @tests java.util.Vector#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { // Ensure toString works with self-referencing elements. Vector<Object> vec = new Vector<Object>(3); @@ -44,5 +1232,81 @@ public class VectorTest extends TestCase { vec.add(new Object()); vec.add(vec); assertNotNull(vec.toString()); + + // Test for method java.lang.String java.util.Vector.toString() + assertTrue("Incorrect String returned", tVector.toString().equals( + vString)); + + Vector v = new Vector(); + v.addElement("one"); + v.addElement(v); + v.addElement("3"); + // test last element + v.addElement(v); + String result = v.toString(); + assertTrue("should contain self ref", result.indexOf("(this") > -1); + } + + public void test_override_size() throws Exception { + Vector v = new Vector(); + Vector testv = new MockVector(); + // though size is overriden, it should passed without exception + testv.add(1); + testv.add(2); + testv.clear(); + + testv.add(1); + testv.add(2); + v.add(1); + v.add(2); + // RI's bug here + assertTrue(testv.equals(v)); } + + /** + * @tests java.util.Vector#trimToSize() + */ + public void test_trimToSize() { + // Test for method void java.util.Vector.trimToSize() + Vector v = new Vector(10); + v.addElement(new Object()); + v.trimToSize(); + assertEquals("Failed to trim capacity", 1, v.capacity()); + } + + protected Vector vectorClone(Vector s) { + return (Vector) s.clone(); + } + + public class MockVector extends Vector{ + @Override + public synchronized int size() { + return 0; + } + + public void removeRange(int start, int end) { + super.removeRange(start, end); + } + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + for (int i = 0; i < 100; i++) { + tVector.addElement("Test " + i); + } + objArray = new Object[100]; + for (int i = 0; i < 100; i++) { + objArray[i] = "Test " + i; + } + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java index 9521641..02f0409 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java @@ -1,51 +1,163 @@ -/* 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 - * +/* + * 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. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.apache.harmony.luni.tests.java.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - +import java.util.AbstractMap; import java.util.Arrays; +import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; -@TestTargetClass(WeakHashMap.class) -public class WeakHashMapTest extends TestCase { +import tests.support.Support_MapTest2; + +public class WeakHashMapTest extends junit.framework.TestCase { + class MockMap extends AbstractMap { + public Set entrySet() { + return null; + } + public int size(){ + return 0; + } + } + + Object[] keyArray = new Object[100]; + Object[] valueArray = new Object[100]; + + WeakHashMap whm; + Object[] KEY_ARRAY; Object[] VALUE_ARRAY; + /** + * @tests java.util.WeakHashMap#WeakHashMap() + */ + public void test_Constructor() { + // Test for method java.util.WeakHashMap() + new Support_MapTest2(new WeakHashMap()).runTest(); + + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + for (int i = 0; i < 100; i++) + assertTrue("Incorrect value retrieved", + whm.get(keyArray[i]) == valueArray[i]); + + } + + /** + * @tests java.util.WeakHashMap#WeakHashMap(int) + */ + public void test_ConstructorI() { + // Test for method java.util.WeakHashMap(int) + whm = new WeakHashMap(50); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + for (int i = 0; i < 100; i++) + assertTrue("Incorrect value retrieved", + whm.get(keyArray[i]) == valueArray[i]); + + WeakHashMap empty = new WeakHashMap(0); + assertNull("Empty weakhashmap access", empty.get("nothing")); + empty.put("something", "here"); + assertTrue("cannot get element", empty.get("something") == "here"); + } + + /** + * @tests java.util.WeakHashMap#WeakHashMap(int, float) + */ + public void test_ConstructorIF() { + // Test for method java.util.WeakHashMap(int, float) + whm = new WeakHashMap(50, 0.5f); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + for (int i = 0; i < 100; i++) + assertTrue("Incorrect value retrieved", + whm.get(keyArray[i]) == valueArray[i]); + + WeakHashMap empty = new WeakHashMap(0, 0.75f); + assertNull("Empty hashtable access", empty.get("nothing")); + empty.put("something", "here"); + assertTrue("cannot get element", empty.get("something") == "here"); + } + + /** + * @tests java.util.WeakHashMap#WeakHashMap(java.util.Map) + */ + public void test_ConstructorLjava_util_Map() { + Map mockMap = new MockMap(); + WeakHashMap map = new WeakHashMap(mockMap); + assertEquals("Size should be 0", 0, map.size()); + } + + /** + * @tests java.util.WeakHashMap#clear() + */ + public void test_clear() { + // Test for method boolean java.util.WeakHashMap.clear() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + whm.clear(); + assertTrue("Cleared map should be empty", whm.isEmpty()); + for (int i = 0; i < 100; i++) + assertNull("Cleared map should only return null", whm + .get(keyArray[i])); + + } + + /** + * @tests java.util.WeakHashMap#containsKey(java.lang.Object) + */ + public void test_containsKeyLjava_lang_Object() { + // Test for method boolean java.util.WeakHashMap.containsKey() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + for (int i = 0; i < 100; i++) + assertTrue("Should contain referenced key", whm + .containsKey(keyArray[i])); + keyArray[25] = null; + keyArray[50] = null; + } + + /** + * @tests java.util.WeakHashMap#containsValue(java.lang.Object) + */ + public void test_containsValueLjava_lang_Object() { + // Test for method boolean java.util.WeakHashMap.containsValue() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + for (int i = 0; i < 100; i++) + assertTrue("Should contain referenced value", whm + .containsValue(valueArray[i])); + keyArray[25] = null; + keyArray[50] = null; + } + /** * @tests java.util.WeakHashMap#entrySet() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "entrySet", - args = {} - ) public void test_entrySet() { WeakHashMap<Object, Object> weakMap = new WeakHashMap<Object, Object>(); KEY_ARRAY = new Object[100]; @@ -131,4 +243,240 @@ public class WeakHashMapTest extends TestCase { assertTrue("Assert 8: iterator not empty", !entrySet.iterator() .hasNext()); } + + /** + * @tests java.util.WeakHashMap#entrySet() + */ + public void test_entrySet_2() { + // Test for method java.util.Set java.util.WeakHashMap.entrySet() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + List keys = Arrays.asList(keyArray); + List values = Arrays.asList(valueArray); + Set entrySet = whm.entrySet(); + assertTrue("Incorrect number of entries returned--wanted 100, got: " + + entrySet.size(), entrySet.size() == 100); + Iterator it = entrySet.iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + assertTrue("Invalid map entry returned--bad key", keys + .contains(entry.getKey())); + assertTrue("Invalid map entry returned--bad key", values + .contains(entry.getValue())); + } + keys = null; + values = null; + keyArray[50] = null; + + int count = 0; + do { + System.gc(); + System.gc(); + Runtime.getRuntime().runFinalization(); + count++; + } while (count <= 5 && entrySet.size() == 100); + + assertTrue( + "Incorrect number of entries returned after gc--wanted 99, got: " + + entrySet.size(), entrySet.size() == 99); + } + + /** + * @tests java.util.WeakHashMap#get(java.lang.Object) + */ + public void test_getLjava_lang_Object() { + // Test for method java.lang.Object + // java.util.WeakHashMap.get(java.lang.Object) + assertTrue("Used to test", true); + } + + /** + * @tests java.util.WeakHashMap#isEmpty() + */ + public void test_isEmpty() { + // Test for method boolean java.util.WeakHashMap.isEmpty() + whm = new WeakHashMap(); + assertTrue("New map should be empty", whm.isEmpty()); + Object myObject = new Object(); + whm.put(myObject, myObject); + assertTrue("Map should not be empty", !whm.isEmpty()); + whm.remove(myObject); + assertTrue("Map with elements removed should be empty", whm.isEmpty()); + } + + /** + * @tests java.util.WeakHashMap#put(java.lang.Object, java.lang.Object) + */ + public void test_putLjava_lang_ObjectLjava_lang_Object() { + // Test for method java.lang.Object + // java.util.WeakHashMap.put(java.lang.Object, java.lang.Object) + WeakHashMap map = new WeakHashMap(); + map.put(null, "value"); // add null key + System.gc(); + System.runFinalization(); + map.remove("nothing"); // Cause objects in queue to be removed + assertEquals("null key was removed", 1, map.size()); + } + + /** + * @tests java.util.WeakHashMap#putAll(java.util.Map) + */ + public void test_putAllLjava_util_Map() { + Map mockMap=new MockMap(); + WeakHashMap map = new WeakHashMap(); + map.putAll(mockMap); + assertEquals("Size should be 0", 0, map.size()); + } + + /** + * @tests java.util.WeakHashMap#remove(java.lang.Object) + */ + public void test_removeLjava_lang_Object() { + // Test for method java.lang.Object + // java.util.WeakHashMap.remove(java.lang.Object) + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + + assertTrue("Remove returned incorrect value", + whm.remove(keyArray[25]) == valueArray[25]); + assertNull("Remove returned incorrect value", + whm.remove(keyArray[25])); + assertEquals("Size should be 99 after remove", 99, whm.size()); + } + + /** + * @tests java.util.WeakHashMap#size() + */ + public void test_size() { + // Test for method int java.util.WeakHashMap.size() + assertTrue("Used to test", true); + } + + /** + * @tests java.util.WeakHashMap#keySet() + */ + public void test_keySet() { + // Test for method java.util.Set java.util.WeakHashMap.keySet() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + + List keys = Arrays.asList(keyArray); + List values = Arrays.asList(valueArray); + + Set keySet = whm.keySet(); + assertEquals("Incorrect number of keys returned,", 100, keySet.size()); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + Object key = it.next(); + assertTrue("Invalid map entry returned--bad key", keys + .contains(key)); + } + keys = null; + values = null; + keyArray[50] = null; + + int count = 0; + do { + System.gc(); + System.gc(); + Runtime.getRuntime().runFinalization(); + count++; + } while (count <= 5 && keySet.size() == 100); + + assertEquals("Incorrect number of keys returned after gc,", 99, keySet + .size()); + } + + /** + * Regression test for HARMONY-3883 + * @tests java.util.WeakHashMap#keySet() + */ + public void test_keySet_hasNext() { + WeakHashMap map = new WeakHashMap(); + ConstantHashClass cl = new ConstantHashClass(2); + map.put(new ConstantHashClass(1), null); + map.put(cl, null); + map.put(new ConstantHashClass(3), null); + Iterator iter = map.keySet().iterator(); + iter.next(); + iter.next(); + System.gc(); + assertFalse("Wrong hasNext() value", iter.hasNext()); + } + + static class ConstantHashClass { + private int id = 0; + + public ConstantHashClass(int id) { + this.id = id; + } + + public int hashCode() { + return 0; + } + + public String toString() { + return "ConstantHashClass[id=" + id + "]"; + } + } + + + /** + * @tests java.util.WeakHashMap#values() + */ + public void test_values() { + // Test for method java.util.Set java.util.WeakHashMap.values() + whm = new WeakHashMap(); + for (int i = 0; i < 100; i++) + whm.put(keyArray[i], valueArray[i]); + + List keys = Arrays.asList(keyArray); + List values = Arrays.asList(valueArray); + + Collection valuesCollection = whm.values(); + assertEquals("Incorrect number of keys returned,", 100, + valuesCollection.size()); + Iterator it = valuesCollection.iterator(); + while (it.hasNext()) { + Object value = it.next(); + assertTrue("Invalid map entry returned--bad value", values + .contains(value)); + } + keys = null; + values = null; + keyArray[50] = null; + + int count = 0; + do { + System.gc(); + System.gc(); + Runtime.getRuntime().runFinalization(); + count++; + } while (count <= 5 && valuesCollection.size() == 100); + + assertEquals("Incorrect number of keys returned after gc,", 99, + valuesCollection.size()); + } + + /** + * Sets up the fixture, for example, open a network connection. This method + * is called before a test is executed. + */ + protected void setUp() { + for (int i = 0; i < 100; i++) { + keyArray[i] = new Object(); + valueArray[i] = new Object(); + } + + } + + /** + * Tears down the fixture, for example, close a network connection. This + * method is called after a test is executed. + */ + protected void tearDown() { + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java index 1795745..70318ed 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java @@ -15,12 +15,7 @@ * limitations under the License. */ -package org.apache.harmony.luni.tests.util; - -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; +package org.apache.harmony.luni.tests.util; import org.apache.harmony.luni.util.Base64; @@ -30,19 +25,12 @@ import junit.framework.TestSuite; /** * Base64 encoder/decoder test. - */ -@TestTargetClass(Base64.class) + */ public class Base64Test extends TestCase { /** * Checks the result on empty parameter. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "decode", - args = {byte[].class} - ) public static void testDecodeEmpty() throws Exception { // Regression for HARMONY-1513 byte[] result = Base64.decode(new byte[0]); @@ -53,9 +41,5 @@ public class Base64Test extends TestCase { public static Test suite() { return new TestSuite(Base64Test.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java index b30501e..2c8d450 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java @@ -17,11 +17,6 @@ package org.apache.harmony.luni.tests.util; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; @@ -33,16 +28,8 @@ import org.apache.harmony.luni.util.NotImplementedException; /** * Testing the NYI framework code. */ -// well this should be the past now. -@TestTargetClass(NotImplementedException.class) public class NYITest extends TestCase { - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NotImplementedException", - args = {java.io.PrintStream.class} - ) public void testNYI() throws UnsupportedEncodingException { ByteArrayOutputStream bos = new ByteArrayOutputStream(400); PrintStream stream = new PrintStream(bos, true, "UTF-8"); diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java index 864a3ed..3110026 100644 --- a/luni/src/test/java/tests/AllTests.java +++ b/luni/src/test/java/tests/AllTests.java @@ -30,7 +30,7 @@ public class AllTests } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); // Harmony-written test suites (often with Android tests added in). suite.addTest(tests.annotation.AllTests.suite()); diff --git a/luni/src/test/java/tests/TestSuiteFactory.java b/luni/src/test/java/tests/TestSuiteFactory.java deleted file mode 100644 index 98f998c..0000000 --- a/luni/src/test/java/tests/TestSuiteFactory.java +++ /dev/null @@ -1,34 +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; - -import junit.framework.TestSuite; - -/** - * This is about to go away... - */ -public class TestSuiteFactory { - - public static TestSuite createTestSuite(String name) { - return new TestSuite(name); - } - - public static TestSuite createTestSuite() { - return new TestSuite(); - } - -} diff --git a/luni/src/test/java/tests/api/java/io/AllTests.java b/luni/src/test/java/tests/api/java/io/AllTests.java index 2747ab2..0bc062d 100644 --- a/luni/src/test/java/tests/api/java/io/AllTests.java +++ b/luni/src/test/java/tests/api/java/io/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.io;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.io;"); // $JUnit-BEGIN$ suite.addTestSuite(BufferedInputStreamTest.class); diff --git a/luni/src/test/java/tests/api/java/io/FileTest.java b/luni/src/test/java/tests/api/java/io/FileTest.java index adcaccd..09adac6 100644 --- a/luni/src/test/java/tests/api/java/io/FileTest.java +++ b/luni/src/test/java/tests/api/java/io/FileTest.java @@ -2154,9 +2154,6 @@ public class FileTest extends junit.framework.TestCase { args = {} ) }) - @KnownFailure("canWrite() returns true even when a file is marked " + - "read-only (Test 2). It is also possible to open this file " + - "for writing (Test 3).") public void test_setReadOnly() { // Test for method java.io.File.setReadOnly() diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java index a8621a1..ebfe013 100644 --- a/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java +++ b/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java @@ -1354,7 +1354,6 @@ public class SerializationStressTest1 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("nested writeReplace is not handled") public void test_18_28_writeObject() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.lang.Object) diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java index d3bbc29..71da321 100644 --- a/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java +++ b/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java @@ -1419,7 +1419,6 @@ public class SerializationStressTest2 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("Executed replacement when it should not: class java.lang.String") public void test_18_57_writeObject() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.lang.Object) @@ -1457,7 +1456,6 @@ public class SerializationStressTest2 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("Executed replacement when it should not: class java.lang.String") public void test_18_58_writeObject() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.lang.Object) diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java index ba83ab6..f704819 100644 --- a/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java +++ b/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java @@ -1483,7 +1483,6 @@ public class SerializationStressTest3 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("Serialization of SimpleDateFormat object fails") public void test_18_113_writeObject() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.lang.Object) @@ -1552,7 +1551,6 @@ public class SerializationStressTest3 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("Serialization of NumberFormat object fails") public void test_18_115_writeObject() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.lang.Object) diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java index 3b1a063..fbda23d 100644 --- a/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java +++ b/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java @@ -2849,7 +2849,6 @@ public class SerializationStressTest4 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("deserialization of a date fomat field seems to fail") public void test_writeObject_DateFormat_Field() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.text.DateFormat.Field) @@ -2894,7 +2893,6 @@ public class SerializationStressTest4 extends SerializationStressTest { method = "!Serialization", args = {} ) - @KnownFailure("deserialization of a number fomat field seems to fail") public void test_writeObject_NumberFormat_Field() { // Test for method void // java.io.ObjectOutputStream.writeObject(java.text.NumberFormat.Field) diff --git a/luni/src/test/java/tests/api/java/lang/AllTests.java b/luni/src/test/java/tests/api/java/lang/AllTests.java index 5a70224..26e313c 100644 --- a/luni/src/test/java/tests/api/java/lang/AllTests.java +++ b/luni/src/test/java/tests/api/java/lang/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * TODO Type description */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang"); + TestSuite suite = new TestSuite("Test for java.lang"); // $JUnit-BEGIN$ diff --git a/luni/src/test/java/tests/api/java/lang/ref/AllTests.java b/luni/src/test/java/tests/api/java/lang/ref/AllTests.java index 75b7b9f..a21d3d8 100644 --- a/luni/src/test/java/tests/api/java/lang/ref/AllTests.java +++ b/luni/src/test/java/tests/api/java/lang/ref/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * TODO Type description */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.ref"); + TestSuite suite = new TestSuite("Test for java.lang.ref"); // $JUnit-BEGIN$ diff --git a/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java b/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java index bba0915..dd427e1 100644 --- a/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java +++ b/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * TODO Type description */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.reflect"); + TestSuite suite = new TestSuite("Test for java.lang.reflect"); // $JUnit-BEGIN$ suite.addTestSuite(AccessibleObjectTest.class); diff --git a/luni/src/test/java/tests/api/java/net/AllTests.java b/luni/src/test/java/tests/api/java/net/AllTests.java index 10dd9d8..2d9921d 100644 --- a/luni/src/test/java/tests/api/java/net/AllTests.java +++ b/luni/src/test/java/tests/api/java/net/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.net;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.net;"); // $JUnit-BEGIN$ suite.addTestSuite(AuthenticatorRequestorTypeTest.class); diff --git a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java b/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java index 256c5ba..89f9f3c 100644 --- a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java +++ b/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java @@ -157,7 +157,6 @@ public class CookieHandlerTest extends TestCase { args = {java.net.URI.class, java.util.Map.class} ) }) - @KnownFailure("Cache is not used") public void test_get_put() { MockCookieHandler mch = new MockCookieHandler(); CookieHandler defaultHandler = CookieHandler.getDefault(); diff --git a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java b/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java index 0272af1..26960c4 100644 --- a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java +++ b/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java @@ -17,597 +17,545 @@ package tests.api.java.net; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.net.InetAddress; +import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; -import java.security.Permission; import java.util.ArrayList; import java.util.Enumeration; +import java.util.List; -@TestTargetClass(NetworkInterface.class) public class NetworkInterfaceTest extends junit.framework.TestCase { - // private member variables used for tests - boolean atLeastOneInterface = false; - - boolean atLeastTwoInterfaces = false; - - private NetworkInterface networkInterface1 = null; - - private NetworkInterface sameAsNetworkInterface1 = null; - - private NetworkInterface networkInterface2 = null; - - /** - * @tests java.net.NetworkInterface#getName() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getName", - args = {} - ) - public void test_getName() { - if (atLeastOneInterface) { - assertNotNull("validate that non null name is returned", - networkInterface1.getName()); - assertFalse("validate that non-zero length name is generated", - networkInterface1.getName().equals("")); - } - if (atLeastTwoInterfaces) { - assertFalse( - "Validate strings are different for different interfaces", - networkInterface1.getName().equals( - networkInterface2.getName())); - } - } - - /** - * @tests java.net.NetworkInterface#getInetAddresses() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getInetAddresses", - args = {} - ) - public void test_getInetAddresses() { - - // security manager that allows us to check that we only return the - // addresses that we should - class mySecurityManager extends SecurityManager { - - ArrayList disallowedNames = null; - - public mySecurityManager(ArrayList addresses) { - disallowedNames = new ArrayList(); - for (int i = 0; i < addresses.size(); i++) { - disallowedNames.add(((InetAddress) addresses.get(i)) - .getHostName()); - disallowedNames.add(((InetAddress) addresses.get(i)) - .getHostAddress()); - } - } - - public void checkConnect(String host, int port) { - - if (host == null) { - throw new NullPointerException("host was null)"); - } - - for (int i = 0; i < disallowedNames.size(); i++) { - if (((String) disallowedNames.get(i)).equals(host)) { - throw new SecurityException("not allowed"); - } - } - } - - public void checkPermission(Permission perm) { - // allow everything + // private member variables used for tests + Enumeration<NetworkInterface> theInterfaces = null; + + boolean atLeastOneInterface = false; + + boolean atLeastTwoInterfaces = false; + + private NetworkInterface networkInterface1 = null; + + private NetworkInterface sameAsNetworkInterface1 = null; + + private NetworkInterface networkInterface2 = null; + + /** + * @tests java.net.NetworkInterface#getName() + */ + public void test_getName() { + if (atLeastOneInterface) { + assertNotNull("validate that non null name is returned", + networkInterface1.getName()); + assertFalse("validate that non-zero length name is generated", + networkInterface1.getName().equals("")); + } + if (atLeastTwoInterfaces) { + assertFalse( + "Validate strings are different for different interfaces", + networkInterface1.getName().equals( + networkInterface2.getName())); + } + } + + /** + * @tests java.net.NetworkInterface#getInetAddresses() + */ + public void test_getInetAddresses() throws Exception { + + // security manager that allows us to check that we only return the + // addresses that we should + class mySecurityManager extends SecurityManager { + + ArrayList disallowedNames = null; + + public mySecurityManager(ArrayList addresses) { + disallowedNames = new ArrayList(); + for (int i = 0; i < addresses.size(); i++) { + disallowedNames.add(((InetAddress) addresses.get(i)) + .getHostName()); + disallowedNames.add(((InetAddress) addresses.get(i)) + .getHostAddress()); + } + } + + public void checkConnect(String host, int port) { + + if (host == null) { + throw new NullPointerException("host was null)"); + } + + for (int i = 0; i < disallowedNames.size(); i++) { + if (((String) disallowedNames.get(i)).equals(host)) { + throw new SecurityException("not allowed"); + } + } + } + + } + + if (atLeastOneInterface) { + Enumeration theAddresses = networkInterface1.getInetAddresses(); + while (theAddresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) theAddresses + .nextElement(); + assertNotNull("validate that address is not null", theAddress); } } - if (atLeastOneInterface) { - Enumeration theAddresses = networkInterface1.getInetAddresses(); - if (theAddresses != null) { - while (theAddresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) theAddresses - .nextElement(); - assertTrue("validate that address is not null", - null != theAddress); + if (atLeastTwoInterfaces) { + Enumeration theAddresses = networkInterface2.getInetAddresses(); + while (theAddresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) theAddresses + .nextElement(); + assertNotNull("validate that address is not null", theAddress); + } + } + + // create the list of ok and not ok addresses to return + if (atLeastOneInterface) { + ArrayList okAddresses = new ArrayList(); + Enumeration addresses = networkInterface1.getInetAddresses(); + int index = 0; + ArrayList notOkAddresses = new ArrayList(); + while (addresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) addresses.nextElement(); + if (index != 0) { + okAddresses.add(theAddress); + } else { + notOkAddresses.add(theAddress); } + index++; } - } - if (atLeastTwoInterfaces) { - Enumeration theAddresses = networkInterface2.getInetAddresses(); - if (theAddresses != null) { - while (theAddresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) theAddresses + // do the same for network interface 2 if it exists + if (atLeastTwoInterfaces) { + addresses = networkInterface2.getInetAddresses(); + index = 0; + while (addresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) addresses + .nextElement(); + if (index != 0) { + okAddresses.add(theAddress); + } else { + notOkAddresses.add(theAddress); + } + index++; + } + } + + // set the security manager that will make the first address not + // visible + System.setSecurityManager(new mySecurityManager(notOkAddresses)); + + // validate not ok addresses are not returned + for (int i = 0; i < notOkAddresses.size(); i++) { + Enumeration reducedAddresses = networkInterface1 + .getInetAddresses(); + while (reducedAddresses.hasMoreElements()) { + InetAddress nextAddress = (InetAddress) reducedAddresses .nextElement(); - assertTrue("validate that address is not null", - null != theAddress); + assertTrue( + "validate that address without permission is not returned", + !nextAddress.equals(notOkAddresses.get(i))); } - } - } - - // create the list of ok and not ok addresses to return - if (atLeastOneInterface) { - ArrayList okAddresses = new ArrayList(); - Enumeration addresses = networkInterface1.getInetAddresses(); - int index = 0; - ArrayList notOkAddresses = new ArrayList(); - if (addresses != null) { - while (addresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) addresses + if (atLeastTwoInterfaces) { + reducedAddresses = networkInterface2.getInetAddresses(); + while (reducedAddresses.hasMoreElements()) { + InetAddress nextAddress = (InetAddress) reducedAddresses + .nextElement(); + assertTrue( + "validate that address without permission is not returned", + !nextAddress.equals(notOkAddresses.get(i))); + } + } + } + + // validate that ok addresses are returned + for (int i = 0; i < okAddresses.size(); i++) { + boolean addressReturned = false; + Enumeration reducedAddresses = networkInterface1 + .getInetAddresses(); + while (reducedAddresses.hasMoreElements()) { + InetAddress nextAddress = (InetAddress) reducedAddresses .nextElement(); - if (index != 0) { - okAddresses.add(theAddress); - } else { - notOkAddresses.add(theAddress); + if (nextAddress.equals(okAddresses.get(i))) { + addressReturned = true; } - index++; } + if (atLeastTwoInterfaces) { + reducedAddresses = networkInterface2.getInetAddresses(); + while (reducedAddresses.hasMoreElements()) { + InetAddress nextAddress = (InetAddress) reducedAddresses + .nextElement(); + if (nextAddress.equals(okAddresses.get(i))) { + addressReturned = true; + } + } + } + assertTrue("validate that address with permission is returned", + addressReturned); + } + + // validate that we can get the interface by specifying the address. + // This is to be compatible + for (int i = 0; i < notOkAddresses.size(); i++) { + assertNotNull( + "validate we cannot get the NetworkInterface with an address for which we have no privs", + NetworkInterface + .getByInetAddress((InetAddress) notOkAddresses + .get(i))); } - // do the same for network interface 2 it it exists - if (atLeastTwoInterfaces) { - addresses = networkInterface2.getInetAddresses(); - index = 0; - if (addresses != null) { - while (addresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) addresses - .nextElement(); - if (index != 0) { - okAddresses.add(theAddress); - } else { - notOkAddresses.add(theAddress); - } - index++; - } - } + // validate that we can get the network interface for the good + // addresses + for (int i = 0; i < okAddresses.size(); i++) { + assertNotNull( + "validate we cannot get the NetworkInterface with an address fro which we have no privs", + NetworkInterface + .getByInetAddress((InetAddress) okAddresses + .get(i))); } - // set the security manager that will make the first address not - // visible - System.setSecurityManager(new mySecurityManager(notOkAddresses)); - - // validate not ok addresses are not returned - for (int i = 0; i < notOkAddresses.size(); i++) { - Enumeration reducedAddresses = networkInterface1 - .getInetAddresses(); - if (reducedAddresses != null) { - while (reducedAddresses.hasMoreElements()) { - InetAddress nextAddress = (InetAddress) reducedAddresses - .nextElement(); - assertTrue( - "validate that address without permission is not returned", - !nextAddress.equals(notOkAddresses.get(i))); - } - } - if (atLeastTwoInterfaces) { - reducedAddresses = networkInterface2.getInetAddresses(); - if (reducedAddresses != null) { - while (reducedAddresses.hasMoreElements()) { - InetAddress nextAddress = (InetAddress) reducedAddresses - .nextElement(); - assertTrue( - "validate that address without permission is not returned", - !nextAddress.equals(notOkAddresses.get(i))); - } - } - } + System.setSecurityManager(null); + } + } + + /** + * @tests java.net.NetworkInterface#getDisplayName() + */ + public void test_getDisplayName() { + if (atLeastOneInterface) { + assertNotNull("validate that non null display name is returned", + networkInterface1.getDisplayName()); + assertFalse( + "validate that non-zero length display name is generated", + networkInterface1.getDisplayName().equals("")); + } + if (atLeastTwoInterfaces) { + assertFalse( + "Validate strings are different for different interfaces", + networkInterface1.getDisplayName().equals( + networkInterface2.getDisplayName())); + } + } + + /** + * @tests java.net.NetworkInterface#getByName(java.lang.String) + */ + public void test_getByNameLjava_lang_String() throws Exception { + try { + assertNull("validate null handled ok", + NetworkInterface.getByName(null)); + fail("getByName did not throw NullPointerException for null argument"); + } catch (NullPointerException e) { + } + + assertNull("validate handled ok if we ask for name not associated with any interface", + NetworkInterface.getByName("8not a name4")); + + // for each address in an interface validate that we get the right + // interface for that name + if (atLeastOneInterface) { + String theName = networkInterface1.getName(); + if (theName != null) { + assertEquals( + "validate that Interface can be obtained with its name", + networkInterface1, NetworkInterface.getByName(theName)); } - - // validate that ok addresses are returned - for (int i = 0; i < okAddresses.size(); i++) { - boolean addressReturned = false; - Enumeration reducedAddresses = networkInterface1 - .getInetAddresses(); - if (reducedAddresses != null) { - while (reducedAddresses.hasMoreElements()) { - InetAddress nextAddress = (InetAddress) reducedAddresses - .nextElement(); - if (nextAddress.equals(okAddresses.get(i))) { - addressReturned = true; - } - } - } - if (atLeastTwoInterfaces) { - reducedAddresses = networkInterface2.getInetAddresses(); - if (reducedAddresses != null) { - while (reducedAddresses.hasMoreElements()) { - InetAddress nextAddress = (InetAddress) reducedAddresses - .nextElement(); - if (nextAddress.equals(okAddresses.get(i))) { - addressReturned = true; - } - } - } - } - assertTrue("validate that address with permission is returned", - addressReturned); + } + + // validate that we get the right interface with the second interface as + // well (ie we just don't always get the first interface + if (atLeastTwoInterfaces) { + String theName = networkInterface2.getName(); + if (theName != null) { + assertEquals( + "validate that Interface can be obtained with its name", + networkInterface2, NetworkInterface.getByName(theName)); } - - // validate that we can get the interface by specifying the address. - // This is to be compatible - for (int i = 0; i < notOkAddresses.size(); i++) { - try { - assertNotNull( - "validate we cannot get the NetworkInterface with an address for which we have no privs", - NetworkInterface - .getByInetAddress((InetAddress) notOkAddresses - .get(i))); - } catch (Exception e) { - fail("get NetworkInterface for address with no perm - exception"); - } + } + } + + /** + * @tests java.net.NetworkInterface#getByInetAddress(java.net.InetAddress) + */ + public void test_getByInetAddressLjava_net_InetAddress() throws Exception { + + byte addressBytes[] = new byte[4]; + addressBytes[0] = 0; + addressBytes[1] = 0; + addressBytes[2] = 0; + addressBytes[3] = 0; + + try { + assertNull("validate null handled ok", + NetworkInterface.getByInetAddress(null)); + fail("should not get here if getByInetAddress throws " + + "NullPointerException if null passed in"); + } catch (NullPointerException e) { + } + + assertNull("validate handled ok if we ask for address not associated with any interface", + NetworkInterface.getByInetAddress(InetAddress + .getByAddress(addressBytes))); + + // for each address in an interface validate that we get the right + // interface for that address + if (atLeastOneInterface) { + Enumeration addresses = networkInterface1.getInetAddresses(); + while (addresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) addresses.nextElement(); + assertEquals( + "validate that Interface can be obtained with any one of its addresses", + networkInterface1, NetworkInterface + .getByInetAddress(theAddress)); } - - // validate that we can get the network interface for the good - // addresses - try { - for (int i = 0; i < okAddresses.size(); i++) { - assertNotNull( - "validate we cannot get the NetworkInterface with an address fro which we have no privs", - NetworkInterface - .getByInetAddress((InetAddress) okAddresses - .get(i))); - } - } catch (Exception e) { - fail("get NetworkInterface for address with perm - exception"); + } + + // validate that we get the right interface with the second interface as + // well (ie we just don't always get the first interface + if (atLeastTwoInterfaces) { + Enumeration addresses = networkInterface2.getInetAddresses(); + while (addresses.hasMoreElements()) { + InetAddress theAddress = (InetAddress) addresses.nextElement(); + assertEquals( + "validate that Interface can be obtained with any one of its addresses", + networkInterface2, NetworkInterface + .getByInetAddress(theAddress)); } - - System.setSecurityManager(null); + } + } + + /** + * @tests java.net.NetworkInterface#getNetworkInterfaces() + */ + public void test_getNetworkInterfaces() throws Exception { + + // really this is tested by all of the other calls but just make sure we + // can call it and get a list of interfaces if they exist + Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces(); + } + + /** + * @tests java.net.NetworkInterface#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + // Test for method boolean + // java.net.SocketPermission.equals(java.lang.Object) + if (atLeastOneInterface) { + assertEquals("If objects are the same true is returned", + sameAsNetworkInterface1, networkInterface1); + assertNotNull("Validate Null handled ok", networkInterface1); } - } - - /** - * @tests java.net.NetworkInterface#getDisplayName() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getDisplayName", - args = {} - ) - public void test_getDisplayName() { - if (atLeastOneInterface) { - assertNotNull("validate that non null display name is returned", - networkInterface1.getDisplayName()); - assertFalse( - "validate that non-zero lengtj display name is generated", - networkInterface1.getDisplayName().equals("")); - } - if (atLeastTwoInterfaces) { - assertFalse( - "Validate strings are different for different interfaces", - networkInterface1.getDisplayName().equals( - networkInterface2.getDisplayName())); + if (atLeastTwoInterfaces) { + assertFalse("If objects are different false is returned", + networkInterface1.equals(networkInterface2)); + } + } + + /** + * @tests java.net.NetworkInterface#hashCode() + */ + public void test_hashCode() { + + if (atLeastOneInterface) { + assertTrue( + "validate that hash codes are the same for two calls on the same object", + networkInterface1.hashCode() == networkInterface1 + .hashCode()); + assertTrue( + "validate that hash codes are the same for two objects for which equals is true", + networkInterface1.hashCode() == sameAsNetworkInterface1 + .hashCode()); + } + } + + /** + * @tests java.net.NetworkInterface#toString() + */ + public void test_toString() { + if (atLeastOneInterface) { + assertNotNull("validate that non null string is generated", + networkInterface1.toString()); + assertFalse("validate that non-zero length string is generated", + networkInterface1.toString().equals("")); + } + if (atLeastTwoInterfaces) { + assertFalse( + "Validate strings are different for different interfaces", + networkInterface1.toString().equals( + networkInterface2.toString())); + } + } + + private class MockSecurityManager extends SecurityManager { + @Override + public void checkConnect(String host, int port) { + throw new SecurityException(); } } /** - * @tests java.net.NetworkInterface#getByName(java.lang.String) + * + * @tests java.net.NetworkInterface#getInterfaceAddresses() + * + * @since 1.6 */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "SocketException checking missed.", - method = "getByName", - args = {java.lang.String.class} - ) - public void test_getByNameLjava_lang_String() { - try { - assertNull("validate null handled ok", - NetworkInterface.getByName(null)); - fail("getByName did not throw NullPointerException for null argument"); - } catch (NullPointerException e) { - } catch (Exception e) { - fail("getByName, null inetAddress - raised exception : " - + e.getMessage()); - } - - try { - assertNull("validate handled ok if we ask for name not associated with any interface", - NetworkInterface.getByName("8not a name4")); - } catch (Exception e) { - fail("getByName, unknown inetAddress - raised exception : " - + e.getMessage()); - } - - // for each address in an interface validate that we get the right - // interface for that name - if (atLeastOneInterface) { - String theName = networkInterface1.getName(); - if (theName != null) { - try { - assertTrue( - "validate that Interface can be obtained with its name", - NetworkInterface.getByName(theName).equals( - networkInterface1)); - } catch (Exception e) { - fail("validate to get network interface using name - socket exception"); - } - } - try { - NetworkInterface.getByName(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } catch (SocketException e) { - fail("SocketException was thrown."); + public void test_getInterfaceAddresses() throws SocketException { + if (theInterfaces != null) { + SecurityManager oldSM = System.getSecurityManager(); + System.setSecurityManager(new MockSecurityManager()); + + while (theInterfaces.hasMoreElements()) { + NetworkInterface netif = theInterfaces.nextElement(); + assertEquals(netif.getName() + + " getInterfaceAddresses should contain no element", 0, + netif.getInterfaceAddresses().size()); } - } - - // validate that we get the right interface with the second interface as - // well (ie we just don't always get the first interface - if (atLeastTwoInterfaces) { - String theName = networkInterface2.getName(); - if (theName != null) { - try { - assertTrue( - "validate that Interface can be obtained with its name", - NetworkInterface.getByName(theName).equals( - networkInterface2)); - } catch (Exception e) { - fail("validate to get network interface using name - socket exception"); + System.setSecurityManager(oldSM); + + theInterfaces = NetworkInterface.getNetworkInterfaces(); + while (theInterfaces.hasMoreElements()) { + NetworkInterface netif = theInterfaces.nextElement(); + List<InterfaceAddress> interfaceAddrs = netif.getInterfaceAddresses(); + assertTrue(interfaceAddrs instanceof ArrayList); + for (InterfaceAddress addr : interfaceAddrs) { + assertNotNull(addr); } + + List<InterfaceAddress> interfaceAddrs2 = netif.getInterfaceAddresses(); + // RI fails on this since it cannot tolerate null broadcast address. + assertEquals(interfaceAddrs, interfaceAddrs2); } } - } - + } + /** - * @tests java.net.NetworkInterface#getByInetAddress(java.net.InetAddress) + * @tests java.net.NetworkInterface#isLoopback() + * + * @since 1.6 */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "SocketException checking missed.", - method = "getByInetAddress", - args = {java.net.InetAddress.class} - ) - public void test_getByInetAddressLjava_net_InetAddress() { - - byte addressBytes[] = new byte[4]; - addressBytes[0] = 0; - addressBytes[1] = 0; - addressBytes[2] = 0; - addressBytes[3] = 0; - - try { - assertNull("validate null handled ok", - NetworkInterface.getByInetAddress(null)); - fail("should not get here if getByInetAddress throws " - + "NullPointerException if null passed in"); - } catch (NullPointerException e) { - } catch (Exception e) { - fail("getByInetAddress, null inetAddress should have raised NPE" - + " but instead threw a : " + e.getMessage()); - } - - try { - assertNull("validate handled ok if we ask for address not associated with any interface", - NetworkInterface.getByInetAddress(InetAddress - .getByAddress(addressBytes))); - } catch (Exception e) { - fail("getByInetAddress, unknown inetAddress threw exception : " + e); - } - - // for each address in an interface validate that we get the right - // interface for that address - if (atLeastOneInterface) { - Enumeration addresses = networkInterface1.getInetAddresses(); - if (addresses != null) { - while (addresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) addresses - .nextElement(); - try { - assertTrue( - "validate that Interface can be obtained with any one of its addresses", - NetworkInterface.getByInetAddress(theAddress) - .equals(networkInterface1)); - } catch (Exception e) { - fail("validate to get address using inetAddress " + - "threw exception : " + e); + public void test_isLoopback() throws SocketException { + if (theInterfaces != null) { + while (theInterfaces.hasMoreElements()) { + NetworkInterface netif = theInterfaces.nextElement(); + boolean loopback = false; + Enumeration<InetAddress> addrs = netif.getInetAddresses(); + while(addrs != null && addrs.hasMoreElements()){ + if(addrs.nextElement().isLoopbackAddress()){ + loopback = true; + break; } } + assertEquals(loopback, netif.isLoopback()); } - - try { - NetworkInterface.getByInetAddress(null); - fail("NullPointerException should be thrown."); - } catch(NullPointerException npe) { - //expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } - } - - // validate that we get the right interface with the second interface as - // well (ie we just don't always get the first interface - if (atLeastTwoInterfaces) { - Enumeration addresses = networkInterface2.getInetAddresses(); - if (addresses != null) { - while (addresses.hasMoreElements()) { - InetAddress theAddress = (InetAddress) addresses - .nextElement(); - try { - assertTrue( - "validate that Interface can be obtained with any one of its addresses", - NetworkInterface.getByInetAddress(theAddress) - .equals(networkInterface2)); - } catch (Exception e) { - fail("validate to get address using inetAddress " - + "threw exception : " + e); - } - } - } - } - } - - /** - * @tests java.net.NetworkInterface#getNetworkInterfaces() - */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "SocketException checking missed.", - method = "getNetworkInterfaces", - args = {} - ) - public void test_getNetworkInterfaces() { - - // really this is tested by all of the other calls but just make sure we - // can call it and get a list of interfaces if they exist - try { - Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces(); - } catch (Exception e) { - fail("get Network Interfaces - raised exception : " - + e.getMessage()); - } - } - - /** - * @tests java.net.NetworkInterface#equals(java.lang.Object) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) - public void test_equalsLjava_lang_Object() { - // Test for method boolean - // java.net.SocketPermission.equals(java.lang.Object) - if (atLeastOneInterface) { - assertTrue("If objects are the same true is returned", - networkInterface1.equals(sameAsNetworkInterface1)); - assertFalse("Validate Null handled ok", networkInterface1 - .equals(null)); - } - if (atLeastTwoInterfaces) { - assertFalse("If objects are different false is returned", - networkInterface1.equals(networkInterface2)); } } - + /** - * @tests java.net.NetworkInterface#hashCode() + * @tests java.net.NetworkInterface#getHardwareAddress() + * + * @since 1.6 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) - public void test_hashCode() { - - if (atLeastOneInterface) { - assertTrue( - "validate that hash codes are the same for two calls on the same object", - networkInterface1.hashCode() == networkInterface1 - .hashCode()); - assertTrue( - "validate that hash codes are the same for two objects for which equals is true", - networkInterface1.hashCode() == sameAsNetworkInterface1 - .hashCode()); + public void test_getHardwareAddress() throws SocketException { + if (theInterfaces != null) { + while (theInterfaces.hasMoreElements()) { + NetworkInterface netif = theInterfaces.nextElement(); + byte[] hwAddr = netif.getHardwareAddress(); + if (netif.isLoopback()) { + assertTrue(hwAddr == null || hwAddr.length == 0); + } else { + assertTrue(hwAddr.length >= 0); + } + } } } - + /** - * @tests java.net.NetworkInterface#toString() + * + * @tests java.net.NetworkInterface#getHardwareAddress() + * + * @since 1.6 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - public void test_toString() { - if (atLeastOneInterface) { - assertNotNull("validate that non null string is generated", - networkInterface1.toString()); - assertFalse("validate that non-zero length string is generated", - networkInterface1.toString().equals("")); + public void test_getMTU() throws SocketException { + if (theInterfaces != null) { + while (theInterfaces.hasMoreElements()) { + NetworkInterface netif = theInterfaces.nextElement(); + assertTrue(netif.getName() + "has non-positive MTU", netif.getMTU() >= 0); + } } - if (atLeastTwoInterfaces) { - assertFalse( - "Validate strings are different for different interfaces", - networkInterface1.toString().equals( - networkInterface2.toString())); - } - } - - protected void setUp() { - - Enumeration theInterfaces = null; - try { - theInterfaces = NetworkInterface.getNetworkInterfaces(); - } catch (Exception e) { - fail("Exception occurred getting network interfaces : " + e); - } - - // Set up NetworkInterface instance members. Note that because the call - // to NetworkInterface.getNetworkInterfaces() returns *all* of the - // interfaces on the test machine it is possible that one or more of - // them will not currently be bound to an InetAddress. e.g. a laptop - // running connected by a wire to the local network may also have a - // wireless interface that is not active and so has no InetAddress - // bound to it. For these tests only work with NetworkInterface objects - // that are bound to an InetAddress. - if ((theInterfaces != null) && (theInterfaces.hasMoreElements())) { - while ((theInterfaces.hasMoreElements()) - && (atLeastOneInterface == false)) { - NetworkInterface theInterface = (NetworkInterface) theInterfaces - .nextElement(); - if (theInterface.getInetAddresses() != null) { - // Ensure that the current NetworkInterface has at least - // one InetAddress bound to it. - Enumeration addrs = theInterface.getInetAddresses(); - if ((addrs != null) && (addrs.hasMoreElements())) { - atLeastOneInterface = true; - networkInterface1 = theInterface; - }// end if - } - } - - while ((theInterfaces.hasMoreElements()) - && (atLeastTwoInterfaces == false)) { - NetworkInterface theInterface = (NetworkInterface) theInterfaces - .nextElement(); - if (theInterface.getInetAddresses() != null) { - // Ensure that the current NetworkInterface has at least - // one InetAddress bound to it. - Enumeration addrs = theInterface.getInetAddresses(); - if ((addrs != null) && (addrs.hasMoreElements())) { - atLeastTwoInterfaces = true; - networkInterface2 = theInterface; - }// end if - } - } - - // Only set sameAsNetworkInterface1 if we succeeded in finding - // at least one good NetworkInterface - if (atLeastOneInterface) { - Enumeration addresses = networkInterface1.getInetAddresses(); - if (addresses != null) { - try { - if (addresses.hasMoreElements()) { - sameAsNetworkInterface1 = NetworkInterface - .getByInetAddress((InetAddress) addresses - .nextElement()); - } - } catch (SocketException e) { - fail("SocketException occurred : " + e); - } - } - }// end if atLeastOneInterface - } - } - - protected void tearDown() { - System.setSecurityManager(null); } + + protected void setUp() throws SocketException { + + Enumeration theInterfaces = null; + try { + theInterfaces = NetworkInterface.getNetworkInterfaces(); + } catch (Exception e) { + fail("Exception occurred getting network interfaces : " + e); + } + + // Set up NetworkInterface instance members. Note that because the call + // to NetworkInterface.getNetworkInterfaces() returns *all* of the + // interfaces on the test machine it is possible that one or more of + // them will not currently be bound to an InetAddress. e.g. a laptop + // running connected by a wire to the local network may also have a + // wireless interface that is not active and so has no InetAddress + // bound to it. For these tests only work with NetworkInterface objects + // that are bound to an InetAddress. + if ((theInterfaces != null) && (theInterfaces.hasMoreElements())) { + while ((theInterfaces.hasMoreElements()) + && (atLeastOneInterface == false)) { + NetworkInterface theInterface = (NetworkInterface) theInterfaces + .nextElement(); + if (theInterface.getInetAddresses().hasMoreElements()) { + // Ensure that the current NetworkInterface has at least + // one InetAddress bound to it. + Enumeration addrs = theInterface.getInetAddresses(); + if ((addrs != null) && (addrs.hasMoreElements())) { + atLeastOneInterface = true; + networkInterface1 = theInterface; + }// end if + } + } + + while ((theInterfaces.hasMoreElements()) + && (atLeastTwoInterfaces == false)) { + NetworkInterface theInterface = (NetworkInterface) theInterfaces + .nextElement(); + if (theInterface.getInetAddresses().hasMoreElements()) { + // Ensure that the current NetworkInterface has at least + // one InetAddress bound to it. + Enumeration addrs = theInterface.getInetAddresses(); + if ((addrs != null) && (addrs.hasMoreElements())) { + atLeastTwoInterfaces = true; + networkInterface2 = theInterface; + }// end if + } + } + + // Only set sameAsNetworkInterface1 if we succeeded in finding + // at least one good NetworkInterface + if (atLeastOneInterface) { + Enumeration addresses = networkInterface1.getInetAddresses(); + if (addresses.hasMoreElements()) { + try { + if (addresses.hasMoreElements()) { + sameAsNetworkInterface1 = NetworkInterface + .getByInetAddress((InetAddress) addresses + .nextElement()); + } + } catch (SocketException e) { + fail("SocketException occurred : " + e); + } + } + }// end if atLeastOneInterface + } + theInterfaces = NetworkInterface.getNetworkInterfaces(); + } + + protected void tearDown() { + System.setSecurityManager(null); + } } diff --git a/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java b/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java index 8aeb820..15a0a82 100644 --- a/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java +++ b/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java @@ -185,9 +185,6 @@ public class ResponseCacheTest extends TestCase { method = "put", args = {URI.class, URLConnection.class} ) - @KnownFailure("the call to put is made with a wrong uri." - + " The RI calls with http://localhost:<port>/test1," - + " but android only calls with http://localhost:<port>") public void test_put() throws Exception { // Create test ResponseCache TestResponseCache cache = new TestResponseCache( @@ -338,4 +335,4 @@ public class ResponseCacheTest extends TestCase { return null; } } -}
\ No newline at end of file +} diff --git a/luni/src/test/java/tests/api/java/util/AllTests.java b/luni/src/test/java/tests/api/java/util/AllTests.java index c2651d9..2d9c422 100644 --- a/luni/src/test/java/tests/api/java/util/AllTests.java +++ b/luni/src/test/java/tests/api/java/util/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * TODO Type description */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.util"); + TestSuite suite = new TestSuite("Test for java.util"); // $JUnit-BEGIN$ suite.addTestSuite(AbstractListTest.class); diff --git a/luni/src/test/java/tests/api/java/util/FormatterTest.java b/luni/src/test/java/tests/api/java/util/FormatterTest.java index 7709b88..89be2ef 100644 --- a/luni/src/test/java/tests/api/java/util/FormatterTest.java +++ b/luni/src/test/java/tests/api/java/util/FormatterTest.java @@ -3165,8 +3165,6 @@ public class FormatterTest extends TestCase { method = "format", args = {java.lang.String.class, java.lang.Object[].class} ) - @KnownFailure("Formatting of Double.MIN_VALUE works improperly") - @AndroidOnly("last case fails on RI. See comment below") public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionE() { Formatter f = null; final Object[][] tripleE = { @@ -3400,8 +3398,6 @@ public class FormatterTest extends TestCase { method = "format", args = {java.lang.String.class, java.lang.Object[].class} ) - @KnownFailure("Formatting of Double.MIN_VALUE works improperly") - @AndroidOnly("last case fails on RI. See comment below") public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionG() { Formatter f = null; final Object[][] tripleG = { @@ -3652,7 +3648,6 @@ public class FormatterTest extends TestCase { method = "format", args = {java.lang.String.class, java.lang.Object[].class} ) - @KnownFailure("Formatting of Float.MAX_VALUE works improperly") public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionF() { Formatter f = null; @@ -4157,8 +4152,6 @@ public class FormatterTest extends TestCase { method = "format", args = {java.lang.String.class, java.lang.Object[].class} ) - @KnownFailure("Formatting of BigDecimal lost precission sometimes") - @AndroidOnly("last case fails on RI. See comment below") public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionG() { Formatter f = null; final Object[][] tripleG = { diff --git a/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java b/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java index aba02a5..b64fcd1 100644 --- a/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java +++ b/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java @@ -770,8 +770,6 @@ public class GregorianCalendarTest extends junit.framework.TestCase { method = "getMinimalDaysInFirstWeek", args = {} ) - @KnownFailure("Some difference in timezones and/or locales data" - + "Who is right, the CLDR or the RI?") public void test_getMinimalDaysInFirstWeek() { // Regression for Harmony-1037 GregorianCalendar g = new GregorianCalendar(TimeZone diff --git a/luni/src/test/java/tests/api/java/util/PropertiesTest.java b/luni/src/test/java/tests/api/java/util/PropertiesTest.java index ddf9994..84a81d2 100644 --- a/luni/src/test/java/tests/api/java/util/PropertiesTest.java +++ b/luni/src/test/java/tests/api/java/util/PropertiesTest.java @@ -387,7 +387,6 @@ public class PropertiesTest extends junit.framework.TestCase { method = "loadFromXML", args = {java.io.InputStream.class} ) - @KnownFailure("Expected Exception is not thrown.") public void test_loadFromXMLLjava_io_InputStream() throws IOException { Properties myProps = new Properties(); myProps.put("Property A", " aye\\\f\t\n\r\b"); diff --git a/luni/src/test/java/tests/api/java/util/ScannerTest.java b/luni/src/test/java/tests/api/java/util/ScannerTest.java index bd13383..cd6ac09 100644 --- a/luni/src/test/java/tests/api/java/util/ScannerTest.java +++ b/luni/src/test/java/tests/api/java/util/ScannerTest.java @@ -1872,7 +1872,6 @@ public class ScannerTest extends TestCase { method = "nextBigInteger", args = {int.class} ) - @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits") public void test_nextBigIntegerI() throws IOException { s = new Scanner("123 456"); assertEquals(new BigInteger("123"), s.nextBigInteger(10)); @@ -2021,7 +2020,6 @@ public class ScannerTest extends TestCase { method = "nextBigInteger", args = {} ) - @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits") public void test_nextBigInteger() throws IOException { s = new Scanner("123 456"); assertEquals(new BigInteger("123"), s.nextBigInteger()); @@ -3380,7 +3378,6 @@ public class ScannerTest extends TestCase { method = "hasNextBigInteger", args = {int.class} ) - @KnownFailure("hasNextBigInteger method doesn't work properly if input string has Arabic-Indic digits") public void test_hasNextBigIntegerI() throws IOException { s = new Scanner("123 456"); assertTrue(s.hasNextBigInteger(10)); @@ -3586,7 +3583,6 @@ public class ScannerTest extends TestCase { method = "hasNextBigInteger", args = {} ) - @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits") public void test_hasNextBigInteger() throws IOException { s = new Scanner("123 456"); assertTrue(s.hasNextBigInteger()); @@ -5452,7 +5448,6 @@ public class ScannerTest extends TestCase { method = "findWithinHorizon", args = {java.util.regex.Pattern.class, int.class} ) - @KnownFailure("findWithinHorizon method doesn't work properly") public void test_findWithinHorizon_LPatternI(){ // This method searches through the input up to the specified search diff --git a/luni/src/test/java/tests/api/java/util/TimeZoneTest.java b/luni/src/test/java/tests/api/java/util/TimeZoneTest.java index aacf6ce..2919a75 100644 --- a/luni/src/test/java/tests/api/java/util/TimeZoneTest.java +++ b/luni/src/test/java/tests/api/java/util/TimeZoneTest.java @@ -63,7 +63,6 @@ public class TimeZoneTest extends junit.framework.TestCase { method = "getDSTSavings", args = {} ) - @KnownFailure("Might be a difference in data.") public void test_getDSTSavings() { // Test for method int java.util.TimeZone.getDSTSavings() @@ -138,7 +137,6 @@ public class TimeZoneTest extends junit.framework.TestCase { method = "getTimeZone", args = {java.lang.String.class} ) - @KnownFailure("Android fails the last test.") public void test_getTimeZoneLjava_lang_String() { assertEquals("Must return GMT when given an invalid TimeZone id SMT-8.", "GMT", TimeZone.getTimeZone("SMT-8").getID()); @@ -375,7 +373,6 @@ public class TimeZoneTest extends junit.framework.TestCase { method = "hasSameRules", args = {java.util.TimeZone.class} ) - @KnownFailure("Arizona doesn't observe DST") public void test_hasSameRulesLjava_util_TimeZone() { TimeZone tz1 = TimeZone.getTimeZone("America/Denver"); TimeZone tz2 = TimeZone.getTimeZone("America/Phoenix"); diff --git a/luni/src/test/java/tests/luni/AllTestsIo.java b/luni/src/test/java/tests/luni/AllTestsIo.java index d135244..010916c 100644 --- a/luni/src/test/java/tests/luni/AllTestsIo.java +++ b/luni/src/test/java/tests/luni/AllTestsIo.java @@ -31,7 +31,7 @@ public class AllTestsIo } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io"); + TestSuite suite = new TestSuite("Tests for java.io"); suite.addTest(tests.api.java.io.AllTests.suite()); diff --git a/luni/src/test/java/tests/luni/AllTestsLang.java b/luni/src/test/java/tests/luni/AllTestsLang.java index 418571e..1a3b240 100644 --- a/luni/src/test/java/tests/luni/AllTestsLang.java +++ b/luni/src/test/java/tests/luni/AllTestsLang.java @@ -31,7 +31,7 @@ public class AllTestsLang } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang"); + TestSuite suite = new TestSuite("Tests for java.lang"); suite.addTest(org.apache.harmony.luni.tests.java.lang.AllTests.suite()); diff --git a/luni/src/test/java/tests/luni/AllTestsNet.java b/luni/src/test/java/tests/luni/AllTestsNet.java index c61cb5f..835cfc7 100644 --- a/luni/src/test/java/tests/luni/AllTestsNet.java +++ b/luni/src/test/java/tests/luni/AllTestsNet.java @@ -31,7 +31,7 @@ public class AllTestsNet } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net"); + TestSuite suite = new TestSuite("Tests for java.net"); suite.addTest(org.apache.harmony.luni.tests.java.net.AllTests.suite()); diff --git a/luni/src/test/java/tests/luni/AllTestsUtil.java b/luni/src/test/java/tests/luni/AllTestsUtil.java index a157a95..102093e 100644 --- a/luni/src/test/java/tests/luni/AllTestsUtil.java +++ b/luni/src/test/java/tests/luni/AllTestsUtil.java @@ -31,7 +31,7 @@ public class AllTestsUtil } public static final Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util"); + TestSuite suite = new TestSuite("Tests for java.util"); suite.addTest(tests.api.java.util.AllTests.suite()); suite.addTest(org.apache.harmony.luni.tests.java.util.AllTests.suite()); diff --git a/math/src/main/java/java/math/BigInt.java b/math/src/main/java/java/math/BigInt.java index 1eae2e0..6a1cb97 100644 --- a/math/src/main/java/java/math/BigInt.java +++ b/math/src/main/java/java/math/BigInt.java @@ -254,12 +254,12 @@ class BigInt // n > 0: shift left (multiply) public static BigInt shift(BigInt a, int n) { BigInt r = newBigInt(); - Check(NativeBN.BN_lshift(r.bignum, a.bignum, n)); + Check(NativeBN.BN_shift(r.bignum, a.bignum, n)); return r; } public void shift(int n) { - Check(NativeBN.BN_lshift(this.bignum, this.bignum, n)); + Check(NativeBN.BN_shift(this.bignum, this.bignum, n)); } public void addPositiveInt(int w) { diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java index 318e4b6..21f2ec5 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.tests.java.math;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.tests.java.math;"); // $JUnit-BEGIN$ suite.addTestSuite(BigDecimalArithmeticTest.class); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalArithmeticTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalArithmeticTest.java index 3119131..bdb4cf9 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalArithmeticTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalArithmeticTest.java @@ -17,18 +17,13 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; -@TestTargetClass(BigDecimal.class) + /** * Class: java.math.BigDecimal * Methods: add, subtract, multiply, divide @@ -38,12 +33,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of equal positive scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void testAddEqualScalePosPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -61,12 +50,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of equal positive scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Together with all other methods including a MathContext these tests form m a complete test set.", - method = "add", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testAddMathContextEqualScalePosPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -85,12 +68,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of equal negative scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void testAddEqualScaleNegNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -10; @@ -108,12 +85,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of equal negative scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Together with all other methods including a MathContext these tests form a complete test set.", - method = "add", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testAddMathContextEqualScaleNegNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -10; @@ -132,12 +103,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of different scales; the first is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void testAddDiffScalePosNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -155,12 +120,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of different scales using MathContext; the first is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Together with all other methods including a MathContext these tests form a complete test set.", - method = "add", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testAddMathContextDiffScalePosNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -179,12 +138,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two numbers of different scales; the first is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void testAddDiffScaleNegPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -202,12 +155,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Add two zeroes of different scales; the first is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void testAddDiffScaleZeroZero() { String a = "0"; int aScale = -15; @@ -225,12 +172,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "add", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testAddMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -259,12 +200,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Subtract two numbers of equal positive scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "subtract", - args = {java.math.BigDecimal.class} - ) public void testSubtractEqualScalePosPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -282,12 +217,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Subtract two numbers of equal positive scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "subtract", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testSubtractMathContextEqualScalePosPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -306,12 +235,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Subtract two numbers of equal negative scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "subtract", - args = {java.math.BigDecimal.class} - ) public void testSubtractEqualScaleNegNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -10; @@ -329,12 +252,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Subtract two numbers of different scales; the first is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "subtract", - args = {java.math.BigDecimal.class} - ) public void testSubtractDiffScalePosNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -353,12 +270,6 @@ public class BigDecimalArithmeticTest extends TestCase { * Subtract two numbers of different scales using MathContext; * the first is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "subtract", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testSubtractMathContextDiffScalePosNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -377,12 +288,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Subtract two numbers of different scales; the first is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "subtract", - args = {java.math.BigDecimal.class} - ) public void testSubtractDiffScaleNegPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -401,12 +306,6 @@ public class BigDecimalArithmeticTest extends TestCase { * Subtract two numbers of different scales using MathContext; * the first is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "subtract", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testSubtractMathContextDiffScaleNegPos() { String a = "986798656676789766678767876078779810457634781384756794987"; int aScale = -15; @@ -425,12 +324,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "subtract", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testSubtractMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -457,12 +350,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of positive scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "multiply", - args = {java.math.BigDecimal.class} - ) public void testMultiplyScalePosPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -480,12 +367,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of positive scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "multiply", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testMultiplyMathContextScalePosPos() { String a = "97665696756578755423325476545428779810457634781384756794987"; int aScale = -25; @@ -504,12 +385,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of negative scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "multiply", - args = {java.math.BigDecimal.class} - ) public void testMultiplyEqualScaleNegNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -527,12 +402,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of different scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "multiply", - args = {java.math.BigDecimal.class} - ) public void testMultiplyDiffScalePosNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -550,12 +419,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of different scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "multiply", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testMultiplyMathContextDiffScalePosNeg() { String a = "987667796597975765768768767866756808779810457634781384756794987"; int aScale = 100; @@ -574,12 +437,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of different scales */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method.", - method = "multiply", - args = {java.math.BigDecimal.class} - ) public void testMultiplyDiffScaleNegPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -597,12 +454,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Multiply two numbers of different scales using MathContext */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "multiply", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testMultiplyMathContextDiffScaleNegPos() { String a = "488757458676796558668876576576579097029810457634781384756794987"; int aScale = -63; @@ -621,12 +472,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "multiply", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testMultiplyMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -647,12 +492,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * pow(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "pow", - args = {int.class} - ) public void testPow() { String a = "123121247898748298842980"; int aScale = 10; @@ -671,12 +510,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * pow(0) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "pow", - args = {int.class} - ) public void testPow0() { String a = "123121247898748298842980"; int aScale = 10; @@ -692,12 +525,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * ZERO.pow(0) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "pow", - args = {int.class} - ) public void testZeroPow0() { String c = "1"; int cScale = 0; @@ -709,12 +536,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "pow", - args = {int.class} - ) public void testPowNonTrivial() { BigDecimal a, b, res; @@ -736,12 +557,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * pow(int, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "pow", - args = {int.class, java.math.MathContext.class} - ) public void testPowMathContext() { String a = "123121247898748298842980"; int aScale = 10; @@ -758,12 +573,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "pow", - args = {int.class, java.math.MathContext.class} - ) public void testPowMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -832,12 +641,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide by zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "ArithmeticException checked.", - method = "divide", - args = {java.math.BigDecimal.class} - ) public void testDivideByZero() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -854,12 +657,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide with ROUND_UNNECESSARY */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException only checked.", - method = "divide", - args = {java.math.BigDecimal.class, int.class} - ) public void testDivideExceptionRM() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -878,12 +675,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide with invalid rounding mode */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "IllegalArgumentException only checked.", - method = "divide", - args = {java.math.BigDecimal.class, int.class} - ) public void testDivideExceptionInvalidRM() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -902,12 +693,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divide", - args = {java.math.BigDecimal.class, int.class} - ) public void testDivideINonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -938,12 +723,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: local variable exponent is less than zero */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideExpLessZero() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 15; @@ -961,12 +740,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: local variable exponent is equal to zero */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed. Should be added checking for ArithmeticException to complete functional testing.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideExpEqualsZero() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -984,12 +757,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: local variable exponent is greater than zero */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideExpGreaterZero() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -15; @@ -1007,12 +774,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: remainder is zero */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRemainderIsZero() { String a = "8311389578904553209874735431110"; int aScale = -15; @@ -1030,12 +791,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_UP, result is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundUpNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1053,12 +808,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_UP, result is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundUpPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1076,12 +825,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_DOWN, result is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundDownNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1099,12 +842,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_DOWN, result is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundDownPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1122,12 +859,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_FLOOR, result is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundFloorPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1145,12 +876,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_FLOOR, result is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundFloorNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1168,12 +893,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_CEILING, result is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundCeilingPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1191,12 +910,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_CEILING, result is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundCeilingNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1214,12 +927,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is positive; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfUpPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1237,12 +944,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is negative; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfUpNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1260,12 +961,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is positive; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfUpPos1() { String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1283,12 +978,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is negative; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfUpNeg1() { String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1306,12 +995,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is negative; equidistant */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfUpNeg2() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1329,12 +1012,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_DOWN, result is positive; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfDownPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1352,12 +1029,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_DOWN, result is negative; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfDownNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1375,12 +1046,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_DOWN, result is positive; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfDownPos1() { String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1398,12 +1063,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_DOWN, result is negative; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfDownNeg1() { String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1421,12 +1080,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_UP, result is negative; equidistant */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfDownNeg2() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1444,12 +1097,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_EVEN, result is positive; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfEvenPos() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1467,12 +1114,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; distance = -1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfEvenNeg() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -1490,12 +1131,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_EVEN, result is positive; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfEvenPos1() { String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1513,12 +1148,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; distance = 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfEvenNeg1() { String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; int aScale = -24; @@ -1536,12 +1165,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; equidistant */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ROUND_UNNECESSARY and exceptions checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideRoundHalfEvenNeg2() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1559,12 +1182,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void testDivideIINonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -1593,12 +1210,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide to BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Common functionality checked", - method = "divide", - args = {java.math.BigDecimal.class} - ) public void testDivideBigDecimal1() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1616,12 +1227,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Divide to BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Common functionality checked", - method = "divide", - args = {java.math.BigDecimal.class} - ) public void testDivideBigDecimal2() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1639,12 +1244,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeUP() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1663,12 +1262,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeDOWN() { String a = "-37361671119238118911893939591735"; int aScale = 10; @@ -1687,12 +1280,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeCEILING() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 100; @@ -1711,12 +1298,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeFLOOR() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 100; @@ -1735,12 +1316,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -51; @@ -1761,12 +1336,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeHALF_DOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 5; @@ -1785,12 +1354,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, scale, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException and UNNECESSARY round mode checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) public void testDivideBigDecimalScaleRoundingModeHALF_EVEN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 5; @@ -1809,15 +1372,9 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divide", - args = {java.math.BigDecimal.class, int.class, java.math.RoundingMode.class} - ) - @KnownFailure("Has a rounding problem. seems like the precision is" - + " 1 too small and cuts off the last digit. also this test might" - + "not be correct. The name implies that scale should be used.") + // Has a rounding problem. seems like the precision is + // 1 too small and cuts off the last digit. also this test might + // not be correct. The name implies that scale should be used. public void testDivideScaleRoundingModeNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -1850,12 +1407,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextUP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 15; @@ -1876,12 +1427,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextDOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 15; @@ -1902,12 +1447,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextCEILING() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 15; @@ -1928,12 +1467,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextFLOOR() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 15; @@ -1954,12 +1487,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -1980,12 +1507,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextHALF_DOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2006,12 +1527,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divide(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideBigDecimalScaleMathContextHALF_EVEN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2032,14 +1547,7 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divide", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) - @KnownFailure("The same test and the same problem like " - + "testDivideScaleRoundingModeNonTrivial") + // The same test and the same problem like testDivideScaleRoundingModeNonTrivial. public void testDivideMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -2090,11 +1598,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideToIntegralValue(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "divideToIntegralValue", - args = {java.math.BigDecimal.class} - ) public void testDivideToIntegralValue() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2109,11 +1612,6 @@ public class BigDecimalArithmeticTest extends TestCase { assertEquals("incorrect scale", resScale, result.scale()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "divideToIntegralValue", - args = {java.math.BigDecimal.class} - ) public void testDivideToIntegralValueByZero() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2136,12 +1634,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideToIntegralValue(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divideToIntegralValue", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideToIntegralValueMathContextUP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2162,12 +1654,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideToIntegralValue(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divideToIntegralValue", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideToIntegralValueMathContextDOWN() { String a = "3736186567876876578956958769675785435673453453653543654354365435675671119238118911893939591735"; int aScale = 45; @@ -2188,12 +1674,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divideToIntegralValue", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideToIntegralValueMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -2229,12 +1709,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideAndRemainder(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class} - ) public void testDivideAndRemainder1() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2256,12 +1730,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideAndRemainder(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class} - ) public void testDivideAndRemainder2() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -45; @@ -2285,12 +1753,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideAndRemainder(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class} - ) public void testDivideAndRemainderByZero() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2313,12 +1775,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideAndRemainder(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideAndRemainderMathContextUP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2343,12 +1799,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * divideAndRemainder(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideAndRemainderMathContextDOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2373,12 +1823,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divideAndRemainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testDivideAndRemainderMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res[]; @@ -2413,11 +1857,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * remainder(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "remainder", - args = {java.math.BigDecimal.class} - ) public void testRemainder1() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2435,11 +1874,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * remainder(BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "remainder", - args = {java.math.BigDecimal.class} - ) public void testRemainder2() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -45; @@ -2454,11 +1888,6 @@ public class BigDecimalArithmeticTest extends TestCase { assertEquals("incorrect quotient scale", resScale, result.scale()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "remainder", - args = {java.math.BigDecimal.class} - ) public void testRemainderByZero() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2480,12 +1909,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * remainder(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "remainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testRemainderMathContextHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2506,12 +1929,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * remainder(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "remainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testRemainderMathContextHALF_DOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -45; @@ -2532,12 +1949,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * Non-trivial tests using MathContext: */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "remainder", - args = {java.math.BigDecimal.class, java.math.MathContext.class} - ) public void testRemainderMathContextNonTrivial() { MathContext mc; BigDecimal a, b, res; @@ -2572,12 +1983,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * round(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "round", - args = {java.math.MathContext.class} - ) public void testRoundMathContextHALF_DOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -45; @@ -2595,12 +2000,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * round(BigDecimal, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "round", - args = {java.math.MathContext.class} - ) public void testRoundMathContextHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2618,12 +2017,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * round(BigDecimal, MathContext) when precision = 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "round", - args = {java.math.MathContext.class} - ) public void testRoundMathContextPrecision0() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2637,12 +2030,6 @@ public class BigDecimalArithmeticTest extends TestCase { assertEquals("incorrect quotient scale", aScale, result.scale()); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "round", - args = {java.math.MathContext.class} - ) public void testRoundNonTrivial() { MathContext mc; String biStr = new String( "12345678901234567890123456789012345.0E+10"); @@ -2693,12 +2080,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * ulp() of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for ulp method.", - method = "ulp", - args = {} - ) public void testUlpPos() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = -45; @@ -2713,12 +2094,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * ulp() of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for ulp method.", - method = "ulp", - args = {} - ) public void testUlpNeg() { String a = "-3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; @@ -2733,12 +2108,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * ulp() of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for ulp method.", - method = "ulp", - args = {} - ) public void testUlpZero() { String a = "0"; int aScale = 2; @@ -2755,12 +2124,6 @@ public class BigDecimalArithmeticTest extends TestCase { /** * @tests java.math.BigDecimal#add(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigDecimal.class} - ) public void test_addBigDecimal() { BigDecimal add1 = new BigDecimal("23.456"); BigDecimal add2 = new BigDecimal("3849.235"); @@ -2779,12 +2142,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.MathContext) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeUP() { String a = "-37361671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2800,12 +2157,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeDOWN() { String a = "-37361671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2821,12 +2172,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeCEILING() { String a = "3736186567876876578956958765675671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2842,12 +2187,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeFLOOR() { String a = "3736186567876876578956958765675671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2863,12 +2202,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2884,12 +2217,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeHALF_DOWN() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 5; @@ -2909,12 +2236,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingModeHALF_EVEN() { String a = "3736186567876876578956958765675671119238118911893939591735"; String b = "74723342238476237823787879183470"; @@ -2930,12 +2251,6 @@ public class BigDecimalArithmeticTest extends TestCase { * @tests java.math.BigDecimal#divide(java.math.BigDecimal, * java.math.RoundingMode) divide(BigDecimal, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigDecimal.class, java.math.RoundingMode.class} - ) public void test_DivideBigDecimalRoundingExc() { String a = "3736186567876876578956958765675671119238118911893939591735"; String b = "74723342238476237823787879183470"; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalCompareTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalCompareTest.java index 97e8a5d..b20491b 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalCompareTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalCompareTest.java @@ -21,17 +21,13 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; -@TestTargetClass(BigDecimal.class) + /** * Class: java.math.BigDecimal * Methods: abs, compareTo, equals, hashCode, @@ -41,12 +37,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Abs() of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for abs method.", - method = "abs", - args = {} - ) public void testAbsNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -57,12 +47,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Abs() of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for abs method.", - method = "abs", - args = {} - ) public void testAbsPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -73,12 +57,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Abs(MathContext) of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "abs", - args = {java.math.MathContext.class} - ) public void testAbsMathContextNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -115,12 +93,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Abs(MathContext) of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "abs", - args = {java.math.MathContext.class} - ) public void testAbsMathContextPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -137,12 +109,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an equal scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareEqualScale1() { String a = "12380964839238475457356735674573563567890295784902768787678287"; int aScale = 18; @@ -157,12 +123,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an equal scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareEqualScale2() { String a = "12380964839238475457356735674573563567890295784902768787678287"; int aScale = 18; @@ -177,12 +137,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an greater scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareGreaterScale1() { String a = "12380964839238475457356735674573563567890295784902768787678287"; int aScale = 28; @@ -197,12 +151,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an greater scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareGreaterScale2() { String a = "12380964839238475457356735674573563567890295784902768787678287"; int aScale = 48; @@ -217,12 +165,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an less scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareLessScale1() { String a = "12380964839238475457356735674573563567890295784902768787678287"; int aScale = 18; @@ -237,12 +179,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Compare to a number of an less scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void testCompareLessScale2() { String a = "12380964839238475457356735674573"; int aScale = 36; @@ -257,12 +193,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Equals() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsUnequal1() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -276,12 +206,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Equals() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsUnequal2() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -295,12 +219,6 @@ public class BigDecimalCompareTest extends TestCase { /** * Equals() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsUnequal3() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -312,12 +230,6 @@ public class BigDecimalCompareTest extends TestCase { /** * equals() for equal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsEqual() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -331,12 +243,6 @@ public class BigDecimalCompareTest extends TestCase { /** * equals() for equal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsNull() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -347,12 +253,6 @@ public class BigDecimalCompareTest extends TestCase { /** * hashCode() for equal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for hashCode method.", - method = "hashCode", - args = {} - ) public void testHashCodeEqual() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = -24; @@ -366,12 +266,6 @@ public class BigDecimalCompareTest extends TestCase { /** * hashCode() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for hashCode method.", - method = "hashCode", - args = {} - ) public void testHashCodeUnequal() { String a = "8478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -385,12 +279,6 @@ public class BigDecimalCompareTest extends TestCase { /** * max() for equal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigDecimal.class} - ) public void testMaxEqual() { String a = "8478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -407,12 +295,6 @@ public class BigDecimalCompareTest extends TestCase { /** * max() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigDecimal.class} - ) public void testMaxUnequal1() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 24; @@ -429,12 +311,6 @@ public class BigDecimalCompareTest extends TestCase { /** * max() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigDecimal.class} - ) public void testMaxUnequal2() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -451,12 +327,6 @@ public class BigDecimalCompareTest extends TestCase { /** * min() for equal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for min method.", - method = "min", - args = {java.math.BigDecimal.class} - ) public void testMinEqual() { String a = "8478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -473,12 +343,6 @@ public class BigDecimalCompareTest extends TestCase { /** * min() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for min method.", - method = "min", - args = {java.math.BigDecimal.class} - ) public void testMinUnequal1() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 24; @@ -495,12 +359,6 @@ public class BigDecimalCompareTest extends TestCase { /** * min() for unequal BigDecimals */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for min method.", - method = "min", - args = {java.math.BigDecimal.class} - ) public void testMinUnequal2() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -517,12 +375,6 @@ public class BigDecimalCompareTest extends TestCase { /** * plus() for a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for plus method.", - method = "plus", - args = {} - ) public void testPlusPositive() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -536,12 +388,6 @@ public class BigDecimalCompareTest extends TestCase { /** * plus(MathContext) for a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "plus", - args = {java.math.MathContext.class} - ) public void testPlusMathContextPositive() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -559,12 +405,6 @@ public class BigDecimalCompareTest extends TestCase { /** * plus() for a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for plus method.", - method = "plus", - args = {} - ) public void testPlusNegative() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -578,12 +418,6 @@ public class BigDecimalCompareTest extends TestCase { /** * plus(MathContext) for a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "plus", - args = {java.math.MathContext.class} - ) public void testPlusMathContextNegative() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 49; @@ -601,12 +435,6 @@ public class BigDecimalCompareTest extends TestCase { /** * negate() for a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for negate method.", - method = "negate", - args = {} - ) public void testNegatePositive() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -620,12 +448,6 @@ public class BigDecimalCompareTest extends TestCase { /** * negate(MathContext) for a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "negate", - args = {java.math.MathContext.class} - ) public void testNegateMathContextPositive() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; MathContext mc = new MathContext(37, RoundingMode.FLOOR); @@ -650,12 +472,6 @@ public class BigDecimalCompareTest extends TestCase { /** * negate() for a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for negate method.", - method = "negate", - args = {} - ) public void testNegateNegative() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -669,12 +485,6 @@ public class BigDecimalCompareTest extends TestCase { /** * negate(MathContext) for a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Together with all other methods including a MathContext these tests for a complete test set.", - method = "negate", - args = {java.math.MathContext.class} - ) public void testNegateMathContextNegative() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 49; @@ -692,12 +502,6 @@ public class BigDecimalCompareTest extends TestCase { /** * signum() for a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumPositive() { String a = "92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -708,12 +512,6 @@ public class BigDecimalCompareTest extends TestCase { /** * signum() for a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumNegative() { String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale = 41; @@ -724,12 +522,6 @@ public class BigDecimalCompareTest extends TestCase { /** * signum() for zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumZero() { String a = "0"; int aScale = 41; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConstructorsTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConstructorsTest.java index 74d0cb0..3657096 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConstructorsTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConstructorsTest.java @@ -21,17 +21,13 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; -@TestTargetClass(BigDecimal.class) + /** * Class: java.math.BigDecimal * Methods: constructors and fields @@ -40,11 +36,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * check ONE */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "tests BigDecimal.ONE to be 1.0d", - method = "!field:BigDecimal.ONE" - ) public void testFieldONE() { String oneS = "1"; double oneD = 1.0; @@ -55,11 +46,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * check TEN */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "tests BigDecimal.TEN to be 10.0d", - method = "!field:BigDecimal.TEN" - ) public void testFieldTEN() { String oneS = "10"; double oneD = 10.0; @@ -70,11 +56,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * check ZERO */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "tests BigDecimal.ZERO to be 0.0d", - method = "!field:BigDecimal.ZERO" - ) public void testFieldZERO() { String oneS = "0"; double oneD = 0.0; @@ -85,12 +66,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(BigInteger value) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class} - ) public void testConstrBI() { String a = "1231212478987482988429808779810457634781384756794987"; BigInteger bA = new BigInteger(a); @@ -109,12 +84,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(BigInteger value, int scale) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class, int.class} - ) public void testConstrBIScale() { String a = "1231212478987482988429808779810457634781384756794987"; BigInteger bA = new BigInteger(a); @@ -127,12 +96,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(BigInteger value, MathContext) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class, java.math.MathContext.class} - ) public void testConstrBigIntegerMathContext() { String a = "1231212478987482988429808779810457634781384756794987"; BigInteger bA = new BigInteger(a); @@ -213,11 +176,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(BigInteger value, int scale, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "BigDecimal", - args = {java.math.BigInteger.class, int.class, java.math.MathContext.class} - ) public void testConstrBigIntegerScaleMathContext() { String a = "1231212478987482988429808779810457634781384756794987"; BigInteger bA = new BigInteger(a); @@ -368,11 +326,6 @@ public class BigDecimalConstructorsTest extends TestCase { assertEquals("incorrect value", "-1234567890123456789012345.679", bd.toString()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "BigDecimal", - args = {java.math.BigInteger.class, int.class, java.math.MathContext.class} - ) public void testConstrBigIntegerScaleMathContext_AndroidFailure() { MathContext mc; BigDecimal bd; @@ -385,12 +338,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(char[] value); */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {char[].class} - ) public void testConstrChar() { char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; BigDecimal result = new BigDecimal(value); @@ -410,12 +357,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(char[] value, int offset, int len); */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {char[].class, int.class, int.class} - ) public void testConstrCharIntInt() { char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; int offset = 3; @@ -437,12 +378,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(char[] value, int offset, int len, MathContext mc); */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "BigDecimal", - args = {char[].class, int.class, int.class, java.math.MathContext.class} - ) public void testConstrCharIntIntMathContext() { char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; int offset = 3; @@ -536,12 +471,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(char[] value, int offset, int len, MathContext mc); */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "BigDecimal", - args = {char[].class, int.class, int.class, java.math.MathContext.class} - ) public void testConstrCharIntIntMathContextException1() { char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; int offset = 3; @@ -559,12 +488,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(char[] value, MathContext mc); */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {char[].class, java.math.MathContext.class} - ) public void testConstrCharMathContext() { try { // Regression for HARMONY-783 @@ -617,12 +540,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double value) when value is NaN */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDoubleNaN() { double a = Double.NaN; try { @@ -637,12 +554,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double value) when value is positive infinity */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDoublePosInfinity() { double a = Double.POSITIVE_INFINITY; try { @@ -657,12 +568,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double value) when value is positive infinity */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDoubleNegInfinity() { double a = Double.NEGATIVE_INFINITY; try { @@ -677,12 +582,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double value) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDouble() { double a = 732546982374982347892379283571094797.287346782359284756; int aScale = 0; @@ -695,11 +594,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double, MathContext) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "BigDecimal", - args = {double.class, java.math.MathContext.class} - ) public void testConstrDoubleMathContext() { double a = 732546982374982347892379283571094797.287346782359284756; int precision = 21; @@ -795,11 +689,6 @@ public class BigDecimalConstructorsTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "BigDecimal", - args = {double.class, java.math.MathContext.class} - ) public void testConstrDoubleMathContext_AndroidFailure() { BigDecimal bd; MathContext mc; @@ -843,12 +732,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(0.1) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDouble01() { double a = 1.E-1; int aScale = 55; @@ -861,12 +744,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(0.555) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDouble02() { double a = 0.555; int aScale = 53; @@ -879,12 +756,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(-0.1) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDoubleMinus01() { double a = -1.E-1; int aScale = 55; @@ -897,12 +768,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(int value) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {int.class} - ) public void testConstrInt() { int a = 732546982; String res = "732546982"; @@ -915,12 +780,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(int, MathContext) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {int.class, java.math.MathContext.class} - ) public void testConstrIntMathContext() { int a = 732546982; int precision = 21; @@ -936,12 +795,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(long value) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {long.class} - ) public void testConstrLong() { long a = 4576578677732546982L; String res = "4576578677732546982"; @@ -954,12 +807,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(long, MathContext) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {long.class, java.math.MathContext.class} - ) public void testConstrLongMathContext() { long a = 4576578677732546982L; int precision = 5; @@ -1037,12 +884,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(double value) when value is denormalized */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(double) constructor.", - method = "BigDecimal", - args = {double.class} - ) public void testConstrDoubleDenormalized() { double a = 2.274341322658976E-309; int aScale = 1073; @@ -1056,12 +897,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value) * when value is not a valid representation of BigDecimal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringException() { String a = "-238768.787678287a+10"; try { @@ -1075,12 +910,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value) when exponent is empty. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExceptionEmptyExponent1() { String a = "-238768.787678287e"; try { @@ -1093,12 +922,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value) when exponent is empty. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExceptionEmptyExponent2() { String a = "-238768.787678287e-"; try { @@ -1112,12 +935,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value) when exponent is greater than * Integer.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExceptionExponentGreaterIntegerMax() { String a = "-238768.787678287e214748364767876"; try { @@ -1131,12 +948,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value) when exponent is less than * Integer.MIN_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExceptionExponentLessIntegerMin() { String a = "-238768.787678287e-214748364767876"; try { @@ -1150,12 +961,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value) * when exponent is Integer.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExponentIntegerMax() { String a = "-238768.787678287e2147483647"; int aScale = -2147483638; @@ -1169,12 +974,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value) * when exponent is Integer.MIN_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringExponentIntegerMin() { String a = ".238768e-2147483648"; try { @@ -1189,12 +988,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value); value does not contain exponent */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithoutExpPos1() { String a = "732546982374982347892379283571094797.287346782359284756"; int aScale = 18; @@ -1207,12 +1000,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value); value does not contain exponent */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithoutExpPos2() { String a = "+732546982374982347892379283571094797.287346782359284756"; int aScale = 18; @@ -1225,12 +1012,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value); value does not contain exponent */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithoutExpNeg() { String a = "-732546982374982347892379283571094797.287346782359284756"; int aScale = 18; @@ -1244,12 +1025,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value does not contain exponent * and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithoutExpWithoutPoint() { String a = "-732546982374982347892379283571094797287346782359284756"; int aScale = 0; @@ -1263,12 +1038,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value contains exponent * and does not contain decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithoutPoint1() { String a = "-238768787678287e214"; int aScale = -214; @@ -1282,12 +1051,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value contains exponent * and does not contain decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithoutPoint2() { String a = "-238768787678287e-214"; int aScale = 214; @@ -1301,12 +1064,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value contains exponent * and does not contain decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithoutPoint3() { String a = "238768787678287e-214"; int aScale = 214; @@ -1320,12 +1077,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value contains exponent * and does not contain decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithoutPoint4() { String a = "238768787678287e+214"; int aScale = -214; @@ -1339,12 +1090,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); value contains exponent * and does not contain decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithoutPoint5() { String a = "238768787678287E214"; int aScale = -214; @@ -1358,12 +1103,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); * value contains both exponent and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithPoint1() { String a = "23985439837984782435652424523876878.7678287e+214"; int aScale = -207; @@ -1377,12 +1116,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); * value contains both exponent and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithPoint2() { String a = "238096483923847545735673567457356356789029578490276878.7678287e-214"; int aScale = 221; @@ -1396,12 +1129,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); * value contains both exponent and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithPoint3() { String a = "2380964839238475457356735674573563567890.295784902768787678287E+21"; int aScale = 0; @@ -1415,12 +1142,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); * value contains both exponent and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithPoint4() { String a = "23809648392384754573567356745735635678.90295784902768787678287E+21"; int aScale = 2; @@ -1434,12 +1155,6 @@ public class BigDecimalConstructorsTest extends TestCase { * new BigDecimal(String value); * value contains both exponent and decimal point */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigDecimal(String) constructor.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void testConstrStringWithExponentWithPoint5() { String a = "238096483923847545735673567457356356789029.5784902768787678287E+21"; int aScale = -2; @@ -1452,12 +1167,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * new BigDecimal(String value, MathContext) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.lang.String.class, java.math.MathContext.class} - ) public void testConstrStringMathContext() { String a = "-238768787678287e214"; int precision = 5; @@ -1517,12 +1226,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.math.BigInteger, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class, int.class} - ) public void test_Constructor_java_math_BigInteger_int() { BigInteger value = new BigInteger("12345908"); BigDecimal big = new BigDecimal(value); @@ -1542,12 +1245,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * @tests java.math.BigDecimal#BigDecimal(double) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "BigDecimal", - args = {double.class} - ) public void test_Constructor_Double() { BigDecimal big = new BigDecimal(123E04); assertTrue("the BigDecimal value taking a double argument is not initialized properly", big @@ -1576,12 +1273,6 @@ public class BigDecimalConstructorsTest extends TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void test_Constructor_java_lang_String() throws NumberFormatException { BigDecimal big = new BigDecimal("345.23499600293850"); assertTrue("the BigDecimal value is not initialized properly", big.toString().equals( diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConvertTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConvertTest.java index 5015ae0..e9a150e 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConvertTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalConvertTest.java @@ -21,18 +21,13 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.math.MathContext; import junit.framework.TestCase; -@TestTargetClass(BigDecimal.class) + /** * Class: java.math.BigDecimal * Methods: doubleValue, floatValue, intValue, longValue, @@ -42,12 +37,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -58,12 +47,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -74,12 +57,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a large positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosInfinity() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+400"; BigDecimal aNumber = new BigDecimal(a); @@ -90,12 +67,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a large negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegInfinity() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+400"; BigDecimal aNumber = new BigDecimal(a); @@ -106,12 +77,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a small negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueMinusZero() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-400"; BigDecimal aNumber = new BigDecimal(a); @@ -123,12 +88,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Double value of a small positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePlusZero() { String a = "123809648392384754573567356745735.63567890295784902768787678287E-400"; BigDecimal aNumber = new BigDecimal(a); @@ -140,12 +99,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNeg() { String a = "-1238096483923847.6356789029578E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -156,12 +109,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePos() { String a = "1238096483923847.6356789029578E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -172,12 +119,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a large positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosInfinity() { String a = "123809648373567356745735.6356789787678287E+200"; BigDecimal aNumber = new BigDecimal(a); @@ -188,12 +129,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a large negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegInfinity() { String a = "-123809648392384755735.63567887678287E+200"; BigDecimal aNumber = new BigDecimal(a); @@ -204,12 +139,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a small negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueMinusZero() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-400"; BigDecimal aNumber = new BigDecimal(a); @@ -221,12 +150,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Float value of a small positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePlusZero() { String a = "123809648392384754573567356745735.63567890295784902768787678287E-400"; BigDecimal aNumber = new BigDecimal(a); @@ -238,12 +161,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Integer value of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValueNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -254,12 +171,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Integer value of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValuePos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -270,12 +181,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Long value of a negative BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method", - method = "longValue", - args = {} - ) public void testLongValueNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -286,12 +191,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Long value of a positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method", - method = "longValue", - args = {} - ) public void testLongValuePos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -302,12 +201,6 @@ public class BigDecimalConvertTest extends TestCase { /** * scaleByPowerOfTen(int n) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed", - method = "scaleByPowerOfTen", - args = {int.class} - ) public void testScaleByPowerOfTen1() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 13; @@ -322,12 +215,6 @@ public class BigDecimalConvertTest extends TestCase { /** * scaleByPowerOfTen(int n) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed", - method = "scaleByPowerOfTen", - args = {int.class} - ) public void testScaleByPowerOfTen2() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -13; @@ -342,12 +229,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a positive BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerPos1() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687"); @@ -359,12 +240,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a positive BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerPos2() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+15"; BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849"); @@ -376,12 +251,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a positive BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerPos3() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+45"; BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687876782870000000000000000"); @@ -393,12 +262,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerNeg1() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849027687"); @@ -410,12 +273,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerNeg2() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+15"; BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849"); @@ -427,12 +284,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerNeg3() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+45"; BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849027687876782870000000000000000"); @@ -444,12 +295,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a small BigDecimal to BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigInteger method", - method = "toBigInteger", - args = {} - ) public void testToBigIntegerZero() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-500"; BigInteger bNumber = new BigInteger("0"); @@ -461,12 +306,6 @@ public class BigDecimalConvertTest extends TestCase { /** * toBigIntegerExact() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigIntegerExact method", - method = "toBigIntegerExact", - args = {} - ) public void testToBigIntegerExact1() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+45"; BigDecimal aNumber = new BigDecimal(a); @@ -478,12 +317,6 @@ public class BigDecimalConvertTest extends TestCase { /** * toBigIntegerExact() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toBigIntegerExact method", - method = "toBigIntegerExact", - args = {} - ) public void testToBigIntegerExactException() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-10"; BigDecimal aNumber = new BigDecimal(a); @@ -498,12 +331,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a positive BigDecimal to an engineering string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toEngineeringString method", - method = "toEngineeringString", - args = {} - ) public void testToEngineeringStringPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E-501"; BigDecimal aNumber = new BigDecimal(a); @@ -514,12 +341,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to an engineering string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toEngineeringString method", - method = "toEngineeringString", - args = {} - ) public void testToEngineeringStringNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-501"; BigDecimal aNumber = new BigDecimal(a); @@ -530,12 +351,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to an engineering string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toEngineeringString method", - method = "toEngineeringString", - args = {} - ) public void testToEngineeringStringZeroPosExponent() { String a = "0.0E+16"; BigDecimal aNumber = new BigDecimal(a); @@ -546,12 +361,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to an engineering string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toEngineeringString method", - method = "toEngineeringString", - args = {} - ) public void testToEngineeringStringZeroNegExponent() { String a = "0.0E-16"; BigDecimal aNumber = new BigDecimal(a); @@ -563,12 +372,6 @@ public class BigDecimalConvertTest extends TestCase { * Convert a negative BigDecimal with a negative exponent to a plain string * representation; scale == 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toPlainString method", - method = "toPlainString", - args = {} - ) public void testToPlainStringNegNegExp() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E-100"; BigDecimal aNumber = new BigDecimal(a); @@ -581,12 +384,6 @@ public class BigDecimalConvertTest extends TestCase { * to a plain string representation; * scale == 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toPlainString method", - method = "toPlainString", - args = {} - ) public void testToPlainStringNegPosExp() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E100"; BigDecimal aNumber = new BigDecimal(a); @@ -599,12 +396,6 @@ public class BigDecimalConvertTest extends TestCase { * to a plain string representation; * scale == 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toPlainString method", - method = "toPlainString", - args = {} - ) public void testToPlainStringPosNegExp() { String a = "123809648392384754573567356745735.63567890295784902768787678287E-100"; BigDecimal aNumber = new BigDecimal(a); @@ -617,12 +408,6 @@ public class BigDecimalConvertTest extends TestCase { * to a plain string representation; * scale == 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toPlainString method", - method = "toPlainString", - args = {} - ) public void testToPlainStringPosPosExp() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+100"; BigDecimal aNumber = new BigDecimal(a); @@ -634,12 +419,6 @@ public class BigDecimalConvertTest extends TestCase { * Convert a BigDecimal to a string representation; * scale == 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void testToStringZeroScale() { String a = "-123809648392384754573567356745735635678902957849027687876782870"; BigDecimal aNumber = new BigDecimal(new BigInteger(a)); @@ -650,12 +429,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a positive BigDecimal to a string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void testToStringPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E-500"; BigDecimal aNumber = new BigDecimal(a); @@ -666,12 +439,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Convert a negative BigDecimal to a string representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void testToStringNeg() { String a = "-123.4564563673567380964839238475457356735674573563567890295784902768787678287E-5"; BigDecimal aNumber = new BigDecimal(a); @@ -682,12 +449,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a positive long value; scale == 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfPosZeroScale() { long a = 98374823947823578L; BigDecimal aNumber = BigDecimal.valueOf(a); @@ -698,12 +459,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative long value; scale is 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfNegZeroScale() { long a = -98374823947823578L; BigDecimal aNumber = BigDecimal.valueOf(a); @@ -714,12 +469,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative long value; scale is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfNegScalePos() { long a = -98374823947823578L; int scale = 12; @@ -731,12 +480,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative long value; scale is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfNegScaleNeg() { long a = -98374823947823578L; int scale = -12; @@ -748,12 +491,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative long value; scale is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfPosScalePos() { long a = 98374823947823578L; int scale = 12; @@ -765,12 +502,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative long value; scale is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(long) method", - method = "valueOf", - args = {long.class} - ) public void testValueOfPosScaleNeg() { long a = 98374823947823578L; int scale = -12; @@ -782,12 +513,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a negative double value */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(double) method", - method = "valueOf", - args = {double.class} - ) public void testValueOfDoubleNeg() { double a = -65678765876567576.98788767; BigDecimal result = BigDecimal.valueOf(a); @@ -800,12 +525,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a positive double value */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(double) method", - method = "valueOf", - args = {double.class} - ) public void testValueOfDoublePos1() { double a = 65678765876567576.98788767; BigDecimal result = BigDecimal.valueOf(a); @@ -818,12 +537,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a positive double value */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(double) method", - method = "valueOf", - args = {double.class} - ) public void testValueOfDoublePos2() { double a = 12321237576.98788767; BigDecimal result = BigDecimal.valueOf(a); @@ -836,12 +549,6 @@ public class BigDecimalConvertTest extends TestCase { /** * Create a BigDecimal from a positive double value */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(double) method", - method = "valueOf", - args = {double.class} - ) public void testValueOfDoublePos3() { double a = 12321237576.9878838; BigDecimal result = BigDecimal.valueOf(a); @@ -854,12 +561,6 @@ public class BigDecimalConvertTest extends TestCase { /** * valueOf(Double.NaN) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf(double) method", - method = "valueOf", - args = {double.class} - ) public void testValueOfDoubleNaN() { double a = Double.NaN; try { @@ -876,12 +577,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -897,12 +592,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -918,12 +607,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactFloatNeg() { BigDecimal aNumber = new BigDecimal("-2147483647.999"); try { @@ -938,12 +621,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactFloatPos() { float a = 2147483646.99999F; BigDecimal aNumber = new BigDecimal(a); @@ -959,12 +636,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactLongPos() { long a = 2147483647L; BigDecimal aNumber = new BigDecimal(a); @@ -976,12 +647,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#intValueExact() Integer value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValueExact method", - method = "intValueExact", - args = {} - ) public void test_IntValueExactLongNeg() { long a = -2147483648L; BigDecimal aNumber = new BigDecimal(a); @@ -993,12 +658,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#longValueExact() Long value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checked", - method = "longValueExact", - args = {} - ) public void test_LongValueExactNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1014,12 +673,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#longValueExact() Long value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "ArithmeticException checked", - method = "longValueExact", - args = {} - ) public void test_LongValueExactPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1035,12 +688,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#longValueExact() Long value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "ArithmeticException checked", - method = "longValueExact", - args = {} - ) public void test_LongValueExactFloatNeg() { BigDecimal aNumber = new BigDecimal("-9223372036854775807.99999"); try { @@ -1055,12 +702,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#longValueExact() Long value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "ArithmeticException checked", - method = "longValueExact", - args = {} - ) public void test_LongValueExactFloatPos() { float a = 9223372036854775806.99999F; BigDecimal aNumber = new BigDecimal(a); @@ -1076,12 +717,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValueExact() Convert pisitive BigDesimal * to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactPos() { int i = 127; BigDecimal bdNumber = new BigDecimal(i); @@ -1093,12 +728,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValueExact() Convert negative BigDesimal * to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactNeg() { String sNumber = "-127.56789"; int iNumber = -128; @@ -1114,12 +743,6 @@ public class BigDecimalConvertTest extends TestCase { * from char array to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactCharZero() { char[] cNumber = { '-', '0', '.', '0' @@ -1137,12 +760,6 @@ public class BigDecimalConvertTest extends TestCase { * from String to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactStringZero() { String sNumber = "00000000000000"; int iNumber = 0; @@ -1158,12 +775,6 @@ public class BigDecimalConvertTest extends TestCase { * from double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactDoubleMax() { double dNumber = Double.MAX_VALUE; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1180,12 +791,6 @@ public class BigDecimalConvertTest extends TestCase { * from double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactDoubleMin() { double dNumber = Double.MIN_VALUE; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1202,12 +807,6 @@ public class BigDecimalConvertTest extends TestCase { * from float to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactFloatPos() { float fNumber = 123.5445F; BigDecimal bdNumber = new BigDecimal(fNumber); @@ -1224,12 +823,6 @@ public class BigDecimalConvertTest extends TestCase { * from float to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactFloatNeg() { float fNumber = -12.987654321F; BigDecimal bdNumber = new BigDecimal(fNumber); @@ -1246,12 +839,6 @@ public class BigDecimalConvertTest extends TestCase { * from double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactDouble() { double dNumber = 123.0000D; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1264,12 +851,6 @@ public class BigDecimalConvertTest extends TestCase { * from long to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactLongMin() { long lNumber = Long.MIN_VALUE; BigDecimal bdNumber = new BigDecimal(lNumber); @@ -1286,12 +867,6 @@ public class BigDecimalConvertTest extends TestCase { * from int to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for byteValueExact method", - method = "byteValueExact", - args = {} - ) public void test_ByteValueExactIntMax() { int iNumber = Integer.MAX_VALUE; BigDecimal bdNumber = new BigDecimal(iNumber); @@ -1307,11 +882,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert pisitive BigDesimal to * byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValuePos() { int i = 127; BigDecimal bdNumber = new BigDecimal(i); @@ -1323,11 +893,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert negative BigDesimal to * byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueNeg() { String sNumber = "-127.56789"; int iNumber = -128; @@ -1342,11 +907,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * char array to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueCharZero() { char[] cNumber = { '-', '0', '.', '0' @@ -1363,11 +923,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * String to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueStringZero() { String sNumber = "00000"; int iNumber = 0; @@ -1382,11 +937,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueDoubleMax() { double dNumber = Double.MAX_VALUE; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1399,11 +949,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueDoubleMin() { double dNumber = Double.MIN_VALUE; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1416,11 +961,6 @@ public class BigDecimalConvertTest extends TestCase { * @test_ java.math.BigDecimal#byteValue() Convert BigDesimal created from * float to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueFloatNeg() { float fNumber = -12.987654321F; byte bValue = -12; @@ -1433,11 +973,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * double to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueDouble() { double dNumber = 123.0000D; BigDecimal bdNumber = new BigDecimal(dNumber); @@ -1449,11 +984,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * long to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueLongMin() { long lNumber = Long.MIN_VALUE; int result = 0; @@ -1466,11 +996,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * int to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueIntMin() { int iNumber = Integer.MIN_VALUE; int result = 0; @@ -1483,11 +1008,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#byteValue() Convert BigDesimal created from * int to byte type */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "byteValue", - args = {} - ) public void test_ByteValueIntMax() { int iNumber = Integer.MAX_VALUE; int result = -1; @@ -1500,11 +1020,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValue() Short value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "shortValue", - args = {} - ) public void test_ShortValueNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1516,11 +1031,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValue() Short value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "shortValue", - args = {} - ) public void test_ShortValuePos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1532,12 +1042,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactNeg() { String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1553,12 +1057,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactPos() { String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; BigDecimal aNumber = new BigDecimal(a); @@ -1574,12 +1072,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a negative * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactFloatNeg() { BigDecimal aNumber = new BigDecimal("-32766.99999"); try { @@ -1594,12 +1086,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactFloatPos() { float a = 32767.99999F; BigDecimal aNumber = new BigDecimal(a); @@ -1615,12 +1101,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactLongPos() { long a = 12345L; BigDecimal aNumber = new BigDecimal(a); @@ -1632,12 +1112,6 @@ public class BigDecimalConvertTest extends TestCase { * @test java.math.BigDecimal#shortValueExact() Short value of a positive * BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shortValueExact method", - method = "shortValueExact", - args = {} - ) public void test_ShortValueExactLongNeg() { long a = -12345L; BigDecimal aNumber = new BigDecimal(a); @@ -1649,12 +1123,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#stripTrailingZeros() stripTrailingZeros() for * BigDecimal with zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for stripTrailingZeros method", - method = "stripTrailingZeros", - args = {} - ) public void test_stripTrailingZerosZeros() { BigDecimal bdNumber = new BigDecimal("0000000"); @@ -1677,12 +1145,6 @@ public class BigDecimalConvertTest extends TestCase { * @tests java.math.BigDecimal#stripTrailingZeros() stripTrailingZeros() for * positive BigDecimal */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for stripTrailingZeros method", - method = "stripTrailingZeros", - args = {} - ) public void test_stripTrailingZeros() { String s = "00000000100000000100000000.000000000100000000"; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalScaleOperationsTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalScaleOperationsTest.java index 17c9a26..aa91f08 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalScaleOperationsTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigDecimalScaleOperationsTest.java @@ -21,17 +21,11 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; -@TestTargetClass(BigDecimal.class) /** * Class: java.math.BigDecimal * Methods: movePointLeft, movePointRight, scale, setScale, unscaledValue * @@ -40,12 +34,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Check the default scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for scale method.", - method = "scale", - args = {} - ) public void testScaleDefault() { String a = "1231212478987482988429808779810457634781384756794987"; int cScale = 0; @@ -56,12 +44,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Check a negative scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for scale method.", - method = "scale", - args = {} - ) public void testScaleNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = -10; @@ -73,12 +55,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Check a positive scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for scale method.", - method = "scale", - args = {} - ) public void testScalePos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 10; @@ -90,12 +66,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Check the zero scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for scale method.", - method = "scale", - args = {} - ) public void testScaleZero() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 0; @@ -107,12 +77,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Check the unscaled value */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "unscaledValue", - args = {} - ) public void testUnscaledValue() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 100; @@ -124,12 +88,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a greater new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setScale method.", - method = "setScale", - args = {int.class} - ) public void testSetScaleGreater() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 18; @@ -143,12 +101,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a less new scale; this.scale == 8; newScale == 5. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setScale method.", - method = "setScale", - args = {int.class} - ) public void testSetScaleLess() { String a = "2.345726458768760000E+10"; int newScale = 5; @@ -161,12 +113,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Verify an exception when setting a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setScale method.", - method = "setScale", - args = {int.class} - ) public void testSetScaleException() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -183,12 +129,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set the same new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setScale method.", - method = "setScale", - args = {int.class} - ) public void testSetScaleSame() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 18; @@ -202,12 +142,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundUp() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478139"; @@ -222,12 +156,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundDown() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138"; @@ -242,12 +170,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundCeiling() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478139"; @@ -262,12 +184,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundFloor() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138"; @@ -282,12 +198,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundHalfUp() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138"; @@ -302,12 +212,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundHalfDown() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138"; @@ -322,12 +226,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Set a new scale */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleRoundHalfEven() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138"; @@ -342,12 +240,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * SetScale(int, RoundingMode) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checking missed.", - method = "setScale", - args = {int.class, int.class} - ) public void testSetScaleIntRoundingMode() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -363,11 +255,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the left; the shift value is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "movePointLeft", - args = {int.class} - ) public void testMovePointLeftPos() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -382,11 +269,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the left; the shift value is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "movePointLeft", - args = {int.class} - ) public void testMovePointLeftNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -398,11 +280,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(a)); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "movePointLeft", - args = {int.class} - ) public void testMovePointLeftEx() { BigDecimal a = new BigDecimal("12345.6789012345678901234567890123456789"); BigDecimal res = a.movePointLeft(10); @@ -423,12 +300,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the right; the shift value is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for movePointRight method.", - method = "movePointRight", - args = {int.class} - ) public void testMovePointRightPosGreater() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -443,12 +314,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the right; the shift value is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for movePointRight method.", - method = "movePointRight", - args = {int.class} - ) public void testMovePointRightPosLess() { String a = "1231212478987482988429808779810457634781384756794987"; String b = "123121247898748298842980877981045763478138475679498700"; @@ -464,12 +329,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the right; the shift value is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for movePointRight method.", - method = "movePointRight", - args = {int.class} - ) public void testMovePointRightNeg() { String a = "1231212478987482988429808779810457634781384756794987"; int aScale = 28; @@ -484,12 +343,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * Move the decimal point to the right when the scale overflows */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for movePointRight method.", - method = "movePointRight", - args = {int.class} - ) public void testMovePointRightException() { String a = "12312124789874829887348723648726347429808779810457634781384756794987"; int aScale = Integer.MAX_VALUE; //2147483647 @@ -503,11 +356,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "movePointRight", - args = {int.class} - ) public void testMovePointRightEx() { BigDecimal a = new BigDecimal("12345.6789012345678901234567890123456789"); BigDecimal res = a.movePointRight(10); @@ -524,12 +372,7 @@ public class BigDecimalScaleOperationsTest extends TestCase { } } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "movePointRight", - args = {int.class} - ) - @KnownFailure("Throws OutOfMemoryError instead of ArithmeticException!") + // Throws OutOfMemoryError instead of ArithmeticException! public void testMovePointRightEx2() { BigDecimal a = new BigDecimal("123456789012345678901234567890123456789E25"); try { @@ -543,11 +386,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * scaleByPowerOfTen(int n) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "scaleByPowerOfTen", - args = {int.class} - ) public void testScaleByPowerOfTenEx() { BigDecimal a = new BigDecimal("12345.6789012345678901234567890123456789"); BigDecimal res = a.movePointRight(10); @@ -577,12 +415,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { /** * precision() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "precision", - args = {} - ) public void testPrecision() { String a = "12312124789874829887348723648726347429808779810457634781384756794987"; int aScale = 14; @@ -597,12 +429,6 @@ public class BigDecimalScaleOperationsTest extends TestCase { * check that setScale with a scale greater to the existing scale does not * change the value. */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "precision", - args = {} - ) public void testSetScale() { BigDecimal x1 = new BigDecimal(1.23400); BigDecimal x2 = x1.setScale(75); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAddTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAddTest.java index e7041fc..e3129cc 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAddTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAddTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: add @@ -38,12 +33,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add two positive numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase1() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -64,12 +53,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add two negative numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase2() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -92,12 +75,6 @@ public class BigIntegerAddTest extends TestCase { * The first one is positive and the second is negative. * The first one is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase3() { byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -120,12 +97,6 @@ public class BigIntegerAddTest extends TestCase { * The first one is negative and the second is positive. * The first one is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase4() { byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -148,12 +119,6 @@ public class BigIntegerAddTest extends TestCase { * The first is positive and the second is negative. * The first is less in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase5() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; @@ -176,12 +141,6 @@ public class BigIntegerAddTest extends TestCase { * The first one is negative and the second is positive. * The first one is less in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase6() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; @@ -203,12 +162,6 @@ public class BigIntegerAddTest extends TestCase { * Add two positive numbers of different length. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase7() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -230,12 +183,6 @@ public class BigIntegerAddTest extends TestCase { * Add two positive numbers of different length. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase8() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -255,12 +202,6 @@ public class BigIntegerAddTest extends TestCase { * Add two negative numbers of different length. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase9() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -282,12 +223,6 @@ public class BigIntegerAddTest extends TestCase { * Add two negative numbers of different length. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase10() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -310,12 +245,6 @@ public class BigIntegerAddTest extends TestCase { * The first is positive. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase11() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -338,12 +267,6 @@ public class BigIntegerAddTest extends TestCase { * The first is positive. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase12() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -366,12 +289,6 @@ public class BigIntegerAddTest extends TestCase { * The first is negative. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase13() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -394,12 +311,6 @@ public class BigIntegerAddTest extends TestCase { * The first is negative. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase14() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -420,12 +331,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add two equal numbers of different signs */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase15() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -445,12 +350,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add zero to a number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase16() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {0}; @@ -471,12 +370,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add a number to zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase17() { byte aBytes[] = {0}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -497,12 +390,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add zero to zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase18() { byte aBytes[] = {0}; byte bBytes[] = {0}; @@ -523,12 +410,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add ZERO to a number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase19() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -547,12 +428,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add a number to zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase20() { byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; @@ -571,12 +446,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add ZERO to ZERO */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase21() { byte rBytes[] = {0}; BigInteger aNumber = BigInteger.ZERO; @@ -593,12 +462,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add ONE to ONE */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase22() { byte rBytes[] = {2}; BigInteger aNumber = BigInteger.ONE; @@ -615,12 +478,6 @@ public class BigIntegerAddTest extends TestCase { /** * Add two numbers so that carry is 1 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for add method.", - method = "add", - args = {java.math.BigInteger.class} - ) public void testCase23() { byte aBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; byte bBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAndTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAndTest.java index 6dc96e9..fb1f9db 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAndTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerAndTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: and @@ -38,12 +33,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for zero and a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testZeroPos() { byte aBytes[] = {0}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -64,12 +53,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for zero and a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testZeroNeg() { byte aBytes[] = {0}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -90,12 +73,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a positive number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosZero() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {0}; @@ -116,12 +93,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a negative number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegPos() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {0}; @@ -142,12 +113,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for zero and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testZeroZero() { byte aBytes[] = {0}; byte bBytes[] = {0}; @@ -168,12 +133,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for zero and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testZeroOne() { BigInteger aNumber = BigInteger.ZERO; BigInteger bNumber = BigInteger.ONE; @@ -185,12 +144,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for one and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testOneOne() { BigInteger aNumber = BigInteger.ONE; BigInteger bNumber = BigInteger.ONE; @@ -202,12 +155,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two positive numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosPosSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -228,12 +175,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -254,12 +195,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two positive numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -280,12 +215,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two negative numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegNegSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -306,12 +235,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -332,12 +255,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -358,12 +275,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosNegSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -384,12 +295,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegPosSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -410,12 +315,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a negative and a positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -436,12 +335,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a negative and a positive numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -462,12 +355,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a positive and a negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -488,12 +375,6 @@ public class BigIntegerAndTest extends TestCase { /** * And for a positive and a negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -514,12 +395,6 @@ public class BigIntegerAndTest extends TestCase { /** * Test for a special case */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testSpecialCase1() { byte aBytes[] = {-1, -1, -1, -1}; byte bBytes[] = {5, -4, -3, -2}; @@ -540,12 +415,6 @@ public class BigIntegerAndTest extends TestCase { /** * Test for a special case */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for and method.", - method = "and", - args = {java.math.BigInteger.class} - ) public void testSpecialCase2() { byte aBytes[] = {-51}; byte bBytes[] = {-52, -51, -50, -49, -48}; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerCompareTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerCompareTest.java index ef982cb..bfd1070 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerCompareTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerCompareTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: abs, compareTo, equals, max, min, negate, signum @@ -38,12 +33,6 @@ public class BigIntegerCompareTest extends TestCase { /** * abs() for a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for abs method.", - method = "abs", - args = {} - ) public void testAbsPositive() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; @@ -61,12 +50,6 @@ public class BigIntegerCompareTest extends TestCase { /** * abs() for a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for abs method.", - method = "abs", - args = {} - ) public void testAbsNegative() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = -1; @@ -86,12 +69,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two positive numbers. * The first is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToPosPos1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -107,12 +84,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two positive numbers. * The first is less. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToPosPos2() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -127,12 +98,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare two equal positive numbers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToEqualPos() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -148,12 +113,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two negative numbers. * The first is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToNegNeg1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -169,12 +128,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two negative numbers. * The first is less in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareNegNeg2() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -189,12 +142,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare two equal negative numbers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToEqualNeg() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -210,12 +157,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two numbers of different signs. * The first is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToDiffSigns1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -231,12 +172,6 @@ public class BigIntegerCompareTest extends TestCase { * Compare two numbers of different signs. * The first is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToDiffSigns2() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -251,12 +186,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare a positive number to ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToPosZero() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -269,12 +198,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare ZERO to a positive number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToZeroPos() { byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int bSign = 1; @@ -287,12 +210,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare a negative number to ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToNegZero() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = -1; @@ -305,12 +222,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare ZERO to a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToZeroNeg() { byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int bSign = -1; @@ -323,12 +234,6 @@ public class BigIntegerCompareTest extends TestCase { * compareTo(BigInteger a). * Compare ZERO to ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for compareTo method.", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void testCompareToZeroZero() { BigInteger aNumber = BigInteger.ZERO; BigInteger bNumber = BigInteger.ZERO; @@ -339,12 +244,6 @@ public class BigIntegerCompareTest extends TestCase { * equals(Object obj). * obj is not a BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsObject() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -356,12 +255,6 @@ public class BigIntegerCompareTest extends TestCase { /** * equals(null). */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsNull() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -374,12 +267,6 @@ public class BigIntegerCompareTest extends TestCase { * obj is a BigInteger. * numbers are equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsBigIntegerTrue() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -395,12 +282,6 @@ public class BigIntegerCompareTest extends TestCase { * obj is a BigInteger. * numbers are not equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for equals method.", - method = "equals", - args = {java.lang.Object.class} - ) public void testEqualsBigIntegerFalse() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; @@ -415,12 +296,6 @@ public class BigIntegerCompareTest extends TestCase { * max(BigInteger val). * the first is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigInteger.class} - ) public void testMaxGreater() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; @@ -442,12 +317,6 @@ public class BigIntegerCompareTest extends TestCase { * max(BigInteger val). * the first is less. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigInteger.class} - ) public void testMaxLess() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -469,12 +338,6 @@ public class BigIntegerCompareTest extends TestCase { * max(BigInteger val). * numbers are equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigInteger.class} - ) public void testMaxEqual() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; @@ -496,12 +359,6 @@ public class BigIntegerCompareTest extends TestCase { * max(BigInteger val). * max of negative and ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for max method.", - method = "max", - args = {java.math.BigInteger.class} - ) public void testMaxNegZero() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; int aSign = -1; @@ -521,12 +378,6 @@ public class BigIntegerCompareTest extends TestCase { * min(BigInteger val). * the first is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mix method.", - method = "min", - args = {java.math.BigInteger.class} - ) public void testMinGreater() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; @@ -548,12 +399,6 @@ public class BigIntegerCompareTest extends TestCase { * min(BigInteger val). * the first is less. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mix method.", - method = "min", - args = {java.math.BigInteger.class} - ) public void testMinLess() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -575,12 +420,6 @@ public class BigIntegerCompareTest extends TestCase { * min(BigInteger val). * numbers are equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mix method.", - method = "min", - args = {java.math.BigInteger.class} - ) public void testMinEqual() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; @@ -602,12 +441,6 @@ public class BigIntegerCompareTest extends TestCase { * max(BigInteger val). * min of positive and ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mix method.", - method = "min", - args = {java.math.BigInteger.class} - ) public void testMinPosZero() { byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -626,12 +459,6 @@ public class BigIntegerCompareTest extends TestCase { /** * negate() a positive number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for negate method.", - method = "negate", - args = {} - ) public void testNegatePositive() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -649,12 +476,6 @@ public class BigIntegerCompareTest extends TestCase { /** * negate() a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for negate method.", - method = "negate", - args = {} - ) public void testNegateNegative() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = -1; @@ -672,12 +493,6 @@ public class BigIntegerCompareTest extends TestCase { /** * negate() ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for negate method.", - method = "negate", - args = {} - ) public void testNegateZero() { byte rBytes[] = {0}; BigInteger aNumber = BigInteger.ZERO; @@ -693,12 +508,6 @@ public class BigIntegerCompareTest extends TestCase { /** * signum() of a positive number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumPositive() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -709,12 +518,6 @@ public class BigIntegerCompareTest extends TestCase { /** * signum() of a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumNegative() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = -1; @@ -725,12 +528,6 @@ public class BigIntegerCompareTest extends TestCase { /** * signum() of ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for signum method.", - method = "signum", - args = {} - ) public void testSignumZero() { BigInteger aNumber = BigInteger.ZERO; assertEquals("incorrect sign", 0, aNumber.signum()); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConstructorsTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConstructorsTest.java index 043d278..1835d68 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConstructorsTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConstructorsTest.java @@ -21,16 +21,11 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import java.util.Random; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Constructors: BigInteger(byte[] a), BigInteger(int sign, byte[] a), @@ -41,12 +36,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from an array of bytes. * Verify an exception thrown if an array is zero bytes long */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesException() { byte aBytes[] = {}; try { @@ -61,12 +50,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a positive number from an array of bytes. * The number fits in an array of integers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesPositive1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -83,12 +66,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a positive number from an array of bytes. * The number fits in an integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesPositive2() { byte aBytes[] = {12, 56, 100}; byte rBytes[] = {12, 56, 100}; @@ -105,12 +82,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a positive number from an array of bytes. * The number of bytes is 4. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesPositive3() { byte aBytes[] = {127, 56, 100, -1}; byte rBytes[] = {127, 56, 100, -1}; @@ -127,12 +98,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a positive number from an array of bytes. * The number of bytes is multiple of 4. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesPositive() { byte aBytes[] = {127, 56, 100, -1, 14, 75, -24, -100}; byte rBytes[] = {127, 56, 100, -1, 14, 75, -24, -100}; @@ -149,12 +114,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a negative number from an array of bytes. * The number fits in an array of integers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesNegative1() { byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; byte rBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; @@ -171,12 +130,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a negative number from an array of bytes. * The number fits in an integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesNegative2() { byte aBytes[] = {-12, 56, 100}; byte rBytes[] = {-12, 56, 100}; @@ -193,12 +146,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a negative number from an array of bytes. * The number of bytes is 4. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesNegative3() { byte aBytes[] = {-128, -12, 56, 100}; byte rBytes[] = {-128, -12, 56, 100}; @@ -215,12 +162,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a negative number from an array of bytes. * The number of bytes is multiple of 4. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesNegative4() { byte aBytes[] = {-128, -12, 56, 100, -13, 56, 93, -78}; byte rBytes[] = {-128, -12, 56, 100, -13, 56, 93, -78}; @@ -236,12 +177,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a zero number from an array of zero bytes. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(byte[]) constructor.", - method = "BigInteger", - args = {byte[].class} - ) public void testConstructorBytesZero() { byte aBytes[] = {0, 0, 0, -0, +0, 0, -0}; byte rBytes[] = {0}; @@ -258,12 +193,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a sign and an array of bytes. * Verify an exception thrown if a sign has improper value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesException1() { byte aBytes[] = {123, 45, -3, -76}; int aSign = 3; @@ -279,12 +208,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a sign and an array of bytes. * Verify an exception thrown if the array contains non-zero bytes while the sign is 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesException2() { byte aBytes[] = {123, 45, -3, -76}; int aSign = 0; @@ -301,12 +224,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number fits in an array of integers. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; int aSign = 1; @@ -325,12 +242,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number fits in an array of integers. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive2() { byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; int aSign = 1; @@ -348,12 +259,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a positive number from a sign and an array of bytes. * The number fits in an integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive3() { byte aBytes[] = {-12, 56, 100}; int aSign = 1; @@ -372,12 +277,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is 4. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive4() { byte aBytes[] = {127, 56, 100, -2}; int aSign = 1; @@ -396,12 +295,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is 4. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive5() { byte aBytes[] = {-127, 56, 100, -2}; int aSign = 1; @@ -420,12 +313,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is multiple of 4. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive6() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; int aSign = 1; @@ -444,12 +331,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is multiple of 4. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesPositive7() { byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; int aSign = 1; @@ -468,12 +349,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number fits in an array of integers. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; int aSign = -1; @@ -492,12 +367,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number fits in an array of integers. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative2() { byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; int aSign = -1; @@ -515,12 +384,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a negative number from a sign and an array of bytes. * The number fits in an integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative3() { byte aBytes[] = {-12, 56, 100}; int aSign = -1; @@ -539,12 +402,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is 4. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative4() { byte aBytes[] = {127, 56, 100, -2}; int aSign = -1; @@ -563,12 +420,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is 4. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative5() { byte aBytes[] = {-127, 56, 100, -2}; int aSign = -1; @@ -587,12 +438,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is multiple of 4. * The most significant byte is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative6() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; int aSign = -1; @@ -611,12 +456,6 @@ public class BigIntegerConstructorsTest extends TestCase { * The number of bytes is multiple of 4. * The most significant byte is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesNegative7() { byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; int aSign = -1; @@ -634,12 +473,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero bytes. * The sign is -1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZero1() { byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; int aSign = -1; @@ -657,12 +490,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero bytes. * The sign is 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZero2() { byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; int aSign = 0; @@ -680,12 +507,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero bytes. * The sign is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZero3() { byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; int aSign = 1; @@ -703,12 +524,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero length. * The sign is -1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZeroNull1() { byte aBytes[] = {}; int aSign = -1; @@ -726,12 +541,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero length. * The sign is 0. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZeroNull2() { byte aBytes[] = {}; int aSign = 0; @@ -749,12 +558,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a zero number from a sign and an array of zero length. * The sign is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(int, byte[]) constructor.", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void testConstructorSignBytesZeroNull3() { byte aBytes[] = {}; int aSign = 1; @@ -772,12 +575,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a string value and radix. * Verify an exception thrown if a radix is out of range */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringException1() { String value = "9234853876401"; int radix = 45; @@ -793,12 +590,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a string value and radix. * Verify an exception thrown if the string starts with a space. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringException2() { String value = " 9234853876401"; int radix = 10; @@ -813,12 +604,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a string value and radix. * Verify an exception thrown if the string contains improper characters. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringException3() { String value = "92348$*#78987"; int radix = 34; @@ -833,12 +618,6 @@ public class BigIntegerConstructorsTest extends TestCase { * Create a number from a string value and radix. * Verify an exception thrown if some digits are greater than radix. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringException4() { String value = "98zv765hdsaiy"; int radix = 20; @@ -852,12 +631,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a positive number from a string value and radix 2. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix2() { String value = "10101010101010101"; int radix = 2; @@ -874,12 +647,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a positive number from a string value and radix 8. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix8() { String value = "76356237071623450"; int radix = 8; @@ -896,12 +663,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a positive number from a string value and radix 10. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix10() { String value = "987328901348934898"; int radix = 10; @@ -918,12 +679,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a positive number from a string value and radix 16. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix16() { String value = "fe2340a8b5ce790"; int radix = 16; @@ -940,12 +695,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a positive number from a string value and radix 36. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix36() { String value = "skdjgocvhdjfkl20jndjkf347ejg457"; int radix = 36; @@ -962,12 +711,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a negative number from a string value and radix 10. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix10Negative() { String value = "-234871376037"; int radix = 36; @@ -984,12 +727,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a zero number from a string value and radix 36. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String, int) constructor.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void testConstructorStringRadix10Zero() { String value = "-00000000000000"; int radix = 10; @@ -1006,12 +743,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a random number of 75 bits length. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "IllegalArgumentException checking missed for negative number of bits.", - method = "BigInteger", - args = {int.class, java.util.Random.class} - ) public void testConstructorRandom() { int bitLen = 75; Random rnd = new Random(); @@ -1022,12 +753,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * Create a prime number of 25 bits length. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed for incorrect bitLength parameter.", - method = "BigInteger", - args = {int.class, int.class, java.util.Random.class} - ) public void testConstructorPrime() { int bitLen = 25; Random rnd = new Random(); @@ -1058,12 +783,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrString1() { String s = "0"; BigInteger bi_s = new BigInteger(s); @@ -1074,12 +793,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrString2() { String s = "-2147483648"; BigInteger bi_s = new BigInteger(s); @@ -1091,12 +804,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrString3() { String s = "2147483647"; BigInteger bi_s = new BigInteger(s); @@ -1108,12 +815,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrStringExc1() { try { new BigInteger("01234 56"); @@ -1125,12 +826,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrStringExc2() { try { new BigInteger("1234#56"); @@ -1142,12 +837,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrStringExc3() { try { new BigInteger("1234.56"); @@ -1159,12 +848,6 @@ public class BigIntegerConstructorsTest extends TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for BigInteger(String) constructor.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstrStringExc4() { try { new BigInteger("1E+1"); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConvertTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConvertTest.java index aaef132..c0f17b1 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConvertTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerConvertTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: intValue, longValue, toByteArray(), valueOf(long val), @@ -39,12 +34,6 @@ public class BigIntegerConvertTest extends TestCase { /** * Return the double value of ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueZero() { String a = "0"; double result = 0.0; @@ -56,12 +45,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * The number's length is less than 64 bits. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePositive1() { String a = "27467238945"; double result = 2.7467238945E10; @@ -73,12 +56,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * The number's bit length is inside [63, 1024]. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePositive2() { String a = "2746723894572364578265426346273456972"; double result = 2.7467238945723645E36; @@ -90,12 +67,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a double value. * The number's bit length is less than 64 bits. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegative1() { String a = "-27467238945"; double result = -2.7467238945E10; @@ -107,12 +78,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a double value. * The number's bit length is inside [63, 1024]. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegative2() { String a = "-2746723894572364578265426346273456972"; double result = -2.7467238945723645E36; @@ -125,12 +90,6 @@ public class BigIntegerConvertTest extends TestCase { * Rounding is needed. * The rounding bit is 1 and the next bit to the left is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosRounded1() { byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; int aSign = 1; @@ -145,12 +104,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1 and the next bit to the left is 0 * but some of dropped bits are 1s. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosRounded2() { byte[] a = {-128, 1, 2, 3, 4, 5, 36, 23, 1, -3, -5}; int aSign = 1; @@ -162,12 +115,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * Rounding is NOT needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosNotRounded() { byte[] a = {-128, 1, 2, 3, 4, 5, -128, 23, 1, -3, -5}; int aSign = 1; @@ -180,12 +127,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * Rounding is needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegRounded1() { byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; int aSign = -1; @@ -200,12 +141,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1 and the next bit to the left is 0 * but some of dropped bits are 1s. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegRounded2() { byte[] a = {-128, 1, 2, 3, 4, 5, 36, 23, 1, -3, -5}; int aSign = -1; @@ -218,12 +153,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * Rounding is NOT needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegNotRounded() { byte[] a = {-128, 1, 2, 3, 4, 5, -128, 23, 1, -3, -5}; int aSign = -1; @@ -238,12 +167,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 0. * The result is Double.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosMaxValue() { byte[] a = {0, -1, -1, -1, -1, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, @@ -264,12 +187,6 @@ public class BigIntegerConvertTest extends TestCase { * The exponent is 1023 and the mantissa is all 1s. * The result is -Double.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegMaxValue() { byte[] a = {0, -1, -1, -1, -1, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, @@ -291,12 +208,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1. * The result is Double.POSITIVE_INFINITY. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePositiveInfinity1() { byte[] a = {-1, -1, -1, -1, -1, -1, -1, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -316,12 +227,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a double value. * The number's bit length is greater than 1024. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePositiveInfinity2() { String a = "2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; double aNumber = new BigInteger(a).doubleValue(); @@ -332,12 +237,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a double value. * The number's bit length is greater than 1024. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegativeInfinity1() { String a = "-2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; double aNumber = new BigInteger(a).doubleValue(); @@ -350,12 +249,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 0. * The result is Double.NEGATIVE_INFINITY. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegativeInfinity2() { byte[] a = {-1, -1, -1, -1, -1, -1, -1, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -376,12 +269,6 @@ public class BigIntegerConvertTest extends TestCase { * The exponent is 1023 and the mantissa is all 0s * but the 54th bit (implicit) is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValuePosMantissaIsZero() { byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -403,12 +290,6 @@ public class BigIntegerConvertTest extends TestCase { * The exponent is 1023 and the mantissa is all 0s * but the 54th bit (implicit) is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for doubleValue method.", - method = "doubleValue", - args = {} - ) public void testDoubleValueNegMantissaIsZero() { byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -427,12 +308,6 @@ public class BigIntegerConvertTest extends TestCase { /** * Return the float value of ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueZero() { String a = "0"; float result = 0.0f; @@ -444,12 +319,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * The number's length is less than 32 bits. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePositive1() { String a = "27467238"; float result = 2.7467238E7f; @@ -461,12 +330,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * The number's bit length is inside [32, 127]. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePositive2() { String a = "27467238945723645782"; float result = 2.7467239E19f; @@ -478,12 +341,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a float value. * The number's bit length is less than 32 bits. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegative1() { String a = "-27467238"; float result = -2.7467238E7f; @@ -495,12 +352,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a doufloatble value. * The number's bit length is inside [63, 1024]. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegative2() { String a = "-27467238945723645782"; float result = -2.7467239E19f; @@ -513,12 +364,6 @@ public class BigIntegerConvertTest extends TestCase { * Rounding is needed. * The rounding bit is 1 and the next bit to the left is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosRounded1() { byte[] a = {-128, 1, -1, -4, 4, 5, 60, 23, 1, -3, -5}; int aSign = 1; @@ -533,12 +378,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1 and the next bit to the left is 0 * but some of dropped bits are 1s. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosRounded2() { byte[] a = {-128, 1, 2, -128, 4, 5, 60, 23, 1, -3, -5}; int aSign = 1; @@ -550,12 +389,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * Rounding is NOT needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosNotRounded() { byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; int aSign = 1; @@ -568,12 +401,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * Rounding is needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegRounded1() { byte[] a = {-128, 1, -1, -4, 4, 5, 60, 23, 1, -3, -5}; int aSign = -1; @@ -588,12 +415,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1 and the next bit to the left is 0 * but some of dropped bits are 1s. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegRounded2() { byte[] a = {-128, 1, 2, -128, 4, 5, 60, 23, 1, -3, -5}; int aSign = -1; @@ -606,12 +427,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * Rounding is NOT needed. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegNotRounded() { byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; int aSign = -1; @@ -626,12 +441,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 0. * The result is Float.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosMaxValue() { byte[] a = {0, -1, -1, -1, 0, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1}; int aSign = 1; @@ -645,12 +454,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 0. * The result is -Float.MAX_VALUE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegMaxValue() { byte[] a = {0, -1, -1, -1, 0, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1}; int aSign = -1; @@ -664,12 +467,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 1. * The result is Float.POSITIVE_INFINITY. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePositiveInfinity1() { byte[] a = {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; int aSign = 1; @@ -681,12 +478,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive number to a float value. * The number's bit length is greater than 127. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePositiveInfinity2() { String a = "2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; float aNumber = new BigInteger(a).floatValue(); @@ -697,12 +488,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a float value. * The number's bit length is greater than 127. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegativeInfinity1() { String a = "-2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; float aNumber = new BigInteger(a).floatValue(); @@ -715,12 +500,6 @@ public class BigIntegerConvertTest extends TestCase { * The rounding bit is 0. * The result is Float.NEGATIVE_INFINITY. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegativeInfinity2() { byte[] a = {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; int aSign = -1; @@ -733,12 +512,6 @@ public class BigIntegerConvertTest extends TestCase { * The exponent is 1023 and the mantissa is all 0s * but the 54th bit (implicit) is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValuePosMantissaIsZero() { byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = 1; @@ -752,12 +525,6 @@ public class BigIntegerConvertTest extends TestCase { * The exponent is 1023 and the mantissa is all 0s * but the 54th bit (implicit) is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueNegMantissaIsZero() { byte[] a = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -769,12 +536,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative number to a float value. * The number's bit length is less than 32 bits. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for floatValue method.", - method = "floatValue", - args = {} - ) public void testFloatValueBug2482() { String a = "2147483649"; float result = 2.14748365E9f; @@ -786,12 +547,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive BigInteger to an integer value. * The low digit is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValuePositive1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3}; int resInt = 1496144643; @@ -803,12 +558,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive BigInteger to an integer value. * The low digit is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValuePositive2() { byte aBytes[] = {12, 56, 100}; int resInt = 800868; @@ -820,12 +569,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a positive BigInteger to an integer value. * The low digit is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValuePositive3() { byte aBytes[] = {56, 13, 78, -12, -5, 56, 100}; int sign = 1; @@ -838,12 +581,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative BigInteger to an integer value. * The low digit is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValueNegative1() { byte aBytes[] = {12, 56, 100, -2, -76, -128, 45, 91, 3}; int sign = -1; @@ -856,12 +593,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative BigInteger to an integer value. * The low digit is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValueNegative2() { byte aBytes[] = {-12, 56, 100}; int result = -771996; @@ -873,12 +604,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a negative BigInteger to an integer value. * The low digit is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for intValue method.", - method = "intValue", - args = {} - ) public void testIntValueNegative3() { byte aBytes[] = {12, 56, 100, -2, -76, 127, 45, 91, 3}; int sign = -1; @@ -891,12 +616,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a BigInteger to a positive long value * The BigInteger is longer than int. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method.", - method = "longValue", - args = {} - ) public void testLongValuePositive1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, 120, -34, -12, 45, 98}; long result = 3268209772258930018L; @@ -908,12 +627,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a number to a positive long value * The number fits in a long. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method.", - method = "longValue", - args = {} - ) public void testLongValuePositive2() { byte aBytes[] = {12, 56, 100, 18, -105, 34, -18, 45}; long result = 880563758158769709L; @@ -925,12 +638,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a number to a negative long value * The BigInteger is longer than int. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method.", - method = "longValue", - args = {} - ) public void testLongValueNegative1() { byte aBytes[] = {12, -1, 100, -2, -76, -128, 45, 91, 3}; long result = -43630045168837885L; @@ -942,12 +649,6 @@ public class BigIntegerConvertTest extends TestCase { * Convert a number to a negative long value * The number fits in a long. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for longValue method.", - method = "longValue", - args = {} - ) public void testLongValueNegative2() { byte aBytes[] = {-12, 56, 100, 45, -101, 45, 98}; long result = -3315696807498398L; @@ -958,12 +659,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert Integer.MAX_VALUE to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfIntegerMax() { long longVal = Integer.MAX_VALUE; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -979,12 +674,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert Integer.MIN_VALUE to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfIntegerMin() { long longVal = Integer.MIN_VALUE; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1000,12 +689,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert Long.MAX_VALUE to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongMax() { long longVal = Long.MAX_VALUE; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1021,12 +704,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert Long.MIN_VALUE to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongMin() { long longVal = Long.MIN_VALUE; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1042,12 +719,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert a positive long value to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongPositive1() { long longVal = 268209772258930018L; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1064,12 +735,6 @@ public class BigIntegerConvertTest extends TestCase { * valueOf (long val): convert a positive long value to a BigInteger. * The long value fits in integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongPositive2() { long longVal = 58930018L; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1085,12 +750,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert a negative long value to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongNegative1() { long longVal = -268209772258930018L; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1107,12 +766,6 @@ public class BigIntegerConvertTest extends TestCase { * valueOf (long val): convert a negative long value to a BigInteger. * The long value fits in integer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongNegative2() { long longVal = -58930018L; BigInteger aNumber = BigInteger.valueOf(longVal); @@ -1127,12 +780,6 @@ public class BigIntegerConvertTest extends TestCase { /** * valueOf (long val): convert a zero long value to a BigInteger. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for valueOf method.", - method = "valueOf", - args = {long.class} - ) public void testValueOfLongZero() { long longVal = 0L; BigInteger aNumber = BigInteger.valueOf(longVal); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerDivideTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerDivideTest.java index f46a6ec..b3fec51 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerDivideTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerDivideTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: divide, remainder, mod, and divideAndRemainder @@ -38,12 +33,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide by zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase1() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {0}; @@ -62,12 +51,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide by ZERO */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase2() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; @@ -84,12 +67,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide two equal positive numbers */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase3() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; @@ -110,12 +87,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide two equal in absolute value numbers of different signs. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase4() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; @@ -137,12 +108,6 @@ public class BigIntegerDivideTest extends TestCase { * Divide two numbers of different length and different signs. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase5() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 1, 2, 3, 4, 5}; @@ -164,12 +129,6 @@ public class BigIntegerDivideTest extends TestCase { * Divide two positive numbers of the same length. * The second is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase6() { byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127}; byte bBytes[] = {15, 100, 56, 7, 98, -1, 39, -128, 127}; @@ -190,12 +149,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide two positive numbers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase7() { byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; @@ -216,12 +169,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide a positive number by a negative one. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase8() { byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; @@ -242,12 +189,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide a negative number by a positive one. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase9() { byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; @@ -268,12 +209,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide two negative numbers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase10() { byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; @@ -294,12 +229,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide zero by a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase11() { byte aBytes[] = {0}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; @@ -320,12 +249,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide ZERO by a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase12() { byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; int bSign = -1; @@ -344,12 +267,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide a positive number by ONE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase13() { byte aBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; int aSign = 1; @@ -368,12 +285,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide ONE by ONE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testCase14() { byte rBytes[] = {1}; BigInteger aNumber = BigInteger.ONE; @@ -390,12 +301,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Verifies the case when borrow != 0 in the private divide method. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testDivisionKnuth1() { byte aBytes[] = {-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {-3, -3, -3, -3}; @@ -416,12 +321,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Verifies the case when the divisor is already normalized. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testDivisionKnuthIsNormalized() { byte aBytes[] = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; byte bBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; @@ -443,12 +342,6 @@ public class BigIntegerDivideTest extends TestCase { * Verifies the case when the first digits of the dividend * and divisor equal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testDivisionKnuthFirstDigitsEqual() { byte aBytes[] = {2, -3, -4, -5, -1, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; byte bBytes[] = {2, -3, -4, -5, -1, -1, -1, -1}; @@ -469,12 +362,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide the number of one digit by the number of one digit */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testDivisionKnuthOneDigitByOneDigit() { byte aBytes[] = {113, -83, 123, -5}; byte bBytes[] = {2, -3, -4, -5}; @@ -495,12 +382,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide the number of multi digits by the number of one digit */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for divide method.", - method = "divide", - args = {java.math.BigInteger.class} - ) public void testDivisionKnuthMultiDigitsByOneDigit() { byte aBytes[] = {113, -83, 123, -5, 18, -34, 67, 39, -29}; byte bBytes[] = {2, -3, -4, -5}; @@ -521,12 +402,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Remainder of division by zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase15() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {0}; @@ -545,12 +420,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Remainder of division of equal numbers */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase16() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; @@ -571,12 +440,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Remainder of division of two positive numbers */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase17() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -597,12 +460,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Remainder of division of two negative numbers */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase18() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -624,12 +481,6 @@ public class BigIntegerDivideTest extends TestCase { * Remainder of division of two numbers of different signs. * The first is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase19() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -651,12 +502,6 @@ public class BigIntegerDivideTest extends TestCase { * Remainder of division of two numbers of different signs. * The first is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testCase20() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -677,12 +522,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Tests the step D6 from the Knuth algorithm */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testRemainderKnuth1() { byte aBytes[] = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1}; byte bBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; @@ -703,12 +542,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide the number of one digit by the number of one digit */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testRemainderKnuthOneDigitByOneDigit() { byte aBytes[] = {113, -83, 123, -5}; byte bBytes[] = {2, -3, -4, -50}; @@ -729,12 +562,6 @@ public class BigIntegerDivideTest extends TestCase { /** * Divide the number of multi digits by the number of one digit */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for remainder method.", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void testRemainderKnuthMultiDigitsByOneDigit() { byte aBytes[] = {113, -83, 123, -5, 18, -34, 67, 39, -29}; byte bBytes[] = {2, -3, -4, -50}; @@ -756,11 +583,6 @@ public class BigIntegerDivideTest extends TestCase { * divideAndRemainder of two numbers of different signs. * The first is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "divideAndRemainder", - args = {java.math.BigInteger.class} - ) public void testCase21() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -793,11 +615,6 @@ public class BigIntegerDivideTest extends TestCase { /** * divideAndRemainder of division by zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "divideAndRemainder", - args = {java.math.BigInteger.class} - ) public void testCase21byZero() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {0}; @@ -816,12 +633,6 @@ public class BigIntegerDivideTest extends TestCase { /** * mod when modulus is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mod method.", - method = "mod", - args = {java.math.BigInteger.class} - ) public void testCase22() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {1, 30, 40, 56, -1, 45}; @@ -840,12 +651,6 @@ public class BigIntegerDivideTest extends TestCase { /** * mod when a divisor is positive */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mod method.", - method = "mod", - args = {java.math.BigInteger.class} - ) public void testCase23() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; @@ -866,12 +671,6 @@ public class BigIntegerDivideTest extends TestCase { /** * mod when a divisor is negative */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for mod method.", - method = "mod", - args = {java.math.BigInteger.class} - ) public void testCase24() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; byte bBytes[] = {27, -15, 65, 39, 100}; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerHashCodeTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerHashCodeTest.java index d351fa8..a63a514 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerHashCodeTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerHashCodeTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: hashCode() @@ -38,12 +33,6 @@ public class BigIntegerHashCodeTest extends TestCase { /** * Test hash codes for the same object */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for hashCode method.", - method = "hashCode", - args = {} - ) public void testSameObject() { String value1 = "12378246728727834290276457386374882976782849"; String value2 = "-5634562095872038262928728727834290276457386374882976782849"; @@ -62,12 +51,6 @@ public class BigIntegerHashCodeTest extends TestCase { /** * Test hash codes for equal objects. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for hashCode method.", - method = "hashCode", - args = {} - ) public void testEqualObjects() { String value1 = "12378246728727834290276457386374882976782849"; String value2 = "12378246728727834290276457386374882976782849"; @@ -84,12 +67,6 @@ public class BigIntegerHashCodeTest extends TestCase { * Test hash codes for unequal objects. * The codes are unequal. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for hashCode method.", - method = "hashCode", - args = {} - ) public void testUnequalObjectsUnequal() { String value1 = "12378246728727834290276457386374882976782849"; String value2 = "-5634562095872038262928728727834290276457386374882976782849"; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerModPowTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerModPowTest.java index 7142f16..1c5cba3 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerModPowTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerModPowTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: modPow, modInverse, and gcd @@ -38,12 +33,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modPow: non-positive modulus */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modPow method.", - method = "modPow", - args = {java.math.BigInteger.class, java.math.BigInteger.class} - ) public void testModPowException() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte eBytes[] = {1, 2, 3, 4, 5}; @@ -65,12 +54,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modPow: positive exponent */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modPow method.", - method = "modPow", - args = {java.math.BigInteger.class, java.math.BigInteger.class} - ) public void testModPowPosExp() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7}; byte eBytes[] = {27, -15, 65, 39}; @@ -94,12 +77,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modPow: negative exponent */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modPow method.", - method = "modPow", - args = {java.math.BigInteger.class, java.math.BigInteger.class} - ) public void testModPowNegExp() { byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7}; byte eBytes[] = {27, -15, 65, 39}; @@ -123,12 +100,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: non-positive modulus */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInverseException() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte mBytes[] = {1, 2, 3}; @@ -147,12 +118,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: non-invertible number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInverseNonInvertible() { byte aBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; byte mBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; @@ -171,12 +136,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInversePos1() { byte aBytes[] = {24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; byte mBytes[] = {122, 45, 36, 100, 122, 45}; @@ -197,12 +156,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: positive number (another case: a < 0) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInversePos2() { byte aBytes[] = {15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; byte mBytes[] = {2, 122, 45, 36, 100}; @@ -223,12 +176,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInverseNeg1() { byte aBytes[] = {15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; byte mBytes[] = {2, 122, 45, 36, 100}; @@ -249,12 +196,6 @@ public class BigIntegerModPowTest extends TestCase { /** * modInverse: negative number (another case: x < 0) */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for modInverse method.", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void testmodInverseNeg2() { byte aBytes[] = {-15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; byte mBytes[] = {122, 2, 4, 122, 2, 4}; @@ -273,12 +214,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: the second number is zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdSecondZero() { byte aBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; byte bBytes[] = {0}; @@ -299,12 +234,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: the first number is zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdFirstZero() { byte aBytes[] = {0}; byte bBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; @@ -325,12 +254,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: the first number is ZERO */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdFirstZERO() { byte bBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; int bSign = 1; @@ -349,12 +272,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: both numbers are zeros */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdBothZeros() { byte rBytes[] = {0}; BigInteger aNumber = new BigInteger("0"); @@ -370,12 +287,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: the first number is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdFirstLonger() { byte aBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; byte bBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; @@ -396,12 +307,6 @@ public class BigIntegerModPowTest extends TestCase { /** * gcd: the second number is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for gcd method.", - method = "gcd", - args = {java.math.BigInteger.class} - ) public void testGcdSecondLonger() { byte aBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; byte bBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerMultiplyTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerMultiplyTest.java index 59ff3c6..e016294 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerMultiplyTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerMultiplyTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: multiply @@ -38,12 +33,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply two negative numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase1() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -65,12 +54,6 @@ public class BigIntegerMultiplyTest extends TestCase { * Multiply two numbers of the same length and different signs. * The first is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase2() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -92,12 +75,6 @@ public class BigIntegerMultiplyTest extends TestCase { * Multiply two positive numbers of different length. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase3() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -120,12 +97,6 @@ public class BigIntegerMultiplyTest extends TestCase { * Multiply two positive numbers of different length. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase4() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; @@ -149,12 +120,6 @@ public class BigIntegerMultiplyTest extends TestCase { * The first is positive. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase5() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -178,12 +143,6 @@ public class BigIntegerMultiplyTest extends TestCase { * The first is positive. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase6() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; @@ -205,12 +164,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply a number by zero. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase7() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; byte bBytes[] = {0}; @@ -231,12 +184,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply a number by ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase8() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; int aSign = 1; @@ -255,12 +202,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply a positive number by ONE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase9() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; int aSign = 1; @@ -279,12 +220,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply a negative number by ONE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testCase10() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; int aSign = -1; @@ -303,12 +238,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply two numbers of 4 bytes length. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testIntbyInt1() { byte aBytes[] = {10, 20, 30, 40}; byte bBytes[] = {1, 2, 3, 4}; @@ -329,12 +258,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Multiply two numbers of 4 bytes length. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for multiply method.", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void testIntbyInt2() { byte aBytes[] = {-1, -1, -1, -1}; byte bBytes[] = {-1, -1, -1, -1}; @@ -355,12 +278,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Negative exponent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowException() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; @@ -377,12 +294,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Exponentiation of a negative number to an odd exponent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowNegativeNumToOddExp() { byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; int aSign = -1; @@ -404,12 +315,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Exponentiation of a negative number to an even exponent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowNegativeNumToEvenExp() { byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; int aSign = -1; @@ -430,12 +335,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Exponentiation of a negative number to zero exponent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowNegativeNumToZeroExp() { byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; int aSign = -1; @@ -454,12 +353,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Exponentiation of a positive number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowPositiveNum() { byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; int aSign = 1; @@ -481,12 +374,6 @@ public class BigIntegerMultiplyTest extends TestCase { /** * Exponentiation of a negative number to zero exponent. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for pow method.", - method = "pow", - args = {int.class} - ) public void testPowPositiveNumToZeroExp() { byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; int aSign = 1; diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerNotTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerNotTest.java index 6ca350b..c88c412 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerNotTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerNotTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: and, andNot @@ -38,12 +33,6 @@ public class BigIntegerNotTest extends TestCase { /** * andNot for two positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for andNot method.", - method = "andNot", - args = {java.math.BigInteger.class} - ) public void testAndNotPosPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -64,12 +53,6 @@ public class BigIntegerNotTest extends TestCase { /** * andNot for two positive numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for andNot method.", - method = "andNot", - args = {java.math.BigInteger.class} - ) public void testAndNotPosPosFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -90,12 +73,6 @@ public class BigIntegerNotTest extends TestCase { /** * andNot for two negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for andNot method.", - method = "andNot", - args = {java.math.BigInteger.class} - ) public void testAndNotNegNegFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -116,12 +93,6 @@ public class BigIntegerNotTest extends TestCase { /** * andNot for a negative and a positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for andNot method.", - method = "andNot", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -142,12 +113,6 @@ public class BigIntegerNotTest extends TestCase { /** * Not for ZERO */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for not method.", - method = "not", - args = {} - ) public void testNotZero() { byte rBytes[] = {-1}; BigInteger aNumber = BigInteger.ZERO; @@ -163,12 +128,6 @@ public class BigIntegerNotTest extends TestCase { /** * Not for ONE */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for not method.", - method = "not", - args = {} - ) public void testNotOne() { byte rBytes[] = {-2}; BigInteger aNumber = BigInteger.ONE; @@ -184,12 +143,6 @@ public class BigIntegerNotTest extends TestCase { /** * Not for a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for not method.", - method = "not", - args = {} - ) public void testNotPos() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; int aSign = 1; @@ -207,12 +160,6 @@ public class BigIntegerNotTest extends TestCase { /** * Not for a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for not method.", - method = "not", - args = {} - ) public void testNotNeg() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; int aSign = -1; @@ -231,12 +178,6 @@ public class BigIntegerNotTest extends TestCase { * Not for a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for not method.", - method = "not", - args = {} - ) public void testNotSpecialCase() { byte aBytes[] = {-1, -1, -1, -1}; int aSign = 1; @@ -250,4 +191,4 @@ public class BigIntegerNotTest extends TestCase { } assertEquals("incorrect sign", -1, result.signum()); } -}
\ No newline at end of file +} diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOperateBitsTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOperateBitsTest.java index f28ec43..d55a992 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOperateBitsTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOperateBitsTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Methods: bitLength, shiftLeft, shiftRight, @@ -39,12 +34,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitCount() of zero. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitCount method.", - method = "bitCount", - args = {} - ) public void testBitCountZero() { BigInteger aNumber = new BigInteger("0"); assertEquals(0, aNumber.bitCount()); @@ -53,12 +42,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitCount() of a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitCount method.", - method = "bitCount", - args = {} - ) public void testBitCountNeg() { BigInteger aNumber = new BigInteger("-12378634756382937873487638746283767238657872368748726875"); assertEquals(87, aNumber.bitCount()); @@ -67,12 +50,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitCount() of a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitCount method.", - method = "bitCount", - args = {} - ) public void testBitCountPos() { BigInteger aNumber = new BigInteger("12378634756343564757582937873487638746283767238657872368748726875"); assertEquals(107, aNumber.bitCount()); @@ -81,12 +58,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of zero. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthZero() { BigInteger aNumber = new BigInteger("0"); assertEquals(0, aNumber.bitLength()); @@ -95,12 +66,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a positive number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthPositive1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = 1; @@ -111,12 +76,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a positive number with the leftmost bit set */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthPositive2() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -127,12 +86,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a positive number which is a power of 2 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthPositive3() { byte aBytes[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = 1; @@ -143,12 +96,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a negative number. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthNegative1() { byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; int aSign = -1; @@ -159,12 +106,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a negative number with the leftmost bit set */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthNegative2() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -175,12 +116,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * bitLength() of a negative number which is a power of 2 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for bitLength method.", - method = "bitLength", - args = {} - ) public void testBitLengthNegative3() { byte aBytes[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -191,12 +126,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) of a negative n */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitException() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -213,12 +142,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitZero() { byte aBytes[] = {0}; int aSign = 0; @@ -237,12 +160,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitZeroOutside1() { byte aBytes[] = {0}; int aSign = 0; @@ -261,12 +178,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -285,12 +196,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -309,12 +214,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(2) in the negative number with all ones in bit representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeInside3() { String as = "-18446744073709551615"; int number = 2; @@ -328,12 +227,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 2. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeInside4() { String as = "-4294967295"; String res = "-4294967296"; @@ -348,12 +241,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 3. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeInside5() { String as = "-18446744073709551615"; String res = "-18446744073709551616"; @@ -366,12 +253,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -390,12 +271,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitNegativeOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -414,12 +289,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -438,12 +307,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -462,12 +325,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveInside3() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -486,12 +343,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveInside4 () { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -510,12 +361,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveInside5 () { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -534,12 +379,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -558,12 +397,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitPositiveOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -582,12 +415,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * clearBit(int n) the leftmost bit in a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for clearBit method.", - method = "clearBit", - args = {int.class} - ) public void testClearBitTopNegative() { byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; int aSign = -1; @@ -606,12 +433,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) of a negative n */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitException() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -628,12 +449,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitZero() { byte aBytes[] = {0}; int aSign = 0; @@ -652,12 +467,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitZeroOutside1() { byte aBytes[] = {0}; int aSign = 0; @@ -676,12 +485,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitZeroOutside2() { byte aBytes[] = {0}; int aSign = 0; @@ -700,12 +503,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) the leftmost bit in a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitLeftmostNegative() { byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; int aSign = -1; @@ -724,12 +521,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) the leftmost bit in a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitLeftmostPositive() { byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; int aSign = 1; @@ -748,12 +539,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -772,12 +557,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -796,12 +575,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) inside a negative number with all ones in bit representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeInside3() { String as = "-18446744073709551615"; String res = "-18446744073709551611"; @@ -816,12 +589,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 2. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeInside4() { String as = "-4294967295"; String res = "-4294967296"; @@ -836,12 +603,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 3. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeInside5() { String as = "-18446744073709551615"; String res = "-18446744073709551616"; @@ -854,12 +615,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -878,12 +633,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitNegativeOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -902,12 +651,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitPositiveInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -926,12 +669,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitPositiveInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -950,12 +687,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitPositiveOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -974,12 +705,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * flipBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for flipBit method.", - method = "flipBit", - args = {int.class} - ) public void testFlipBitPositiveOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -998,12 +723,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) of a negative n */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitException() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1020,12 +739,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitZero() { byte aBytes[] = {0}; int aSign = 0; @@ -1044,12 +757,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitZeroOutside1() { byte aBytes[] = {0}; int aSign = 0; @@ -1068,12 +775,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1092,12 +793,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1116,12 +811,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveInside3() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1140,12 +829,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveInside4 () { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1164,12 +847,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1188,12 +865,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitPositiveOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1212,12 +883,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) the leftmost bit in a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitTopPositive() { byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; int aSign = 1; @@ -1236,12 +901,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) the leftmost bit in a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitLeftmostNegative() { byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; int aSign = -1; @@ -1260,12 +919,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeInside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1284,12 +937,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeInside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1308,12 +955,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) inside a negative number with all ones in bit representation */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeInside3() { String as = "-18446744073709551615"; String res = "-18446744073709551611"; @@ -1328,12 +969,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 2. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeInside4() { String as = "-4294967295"; int number = 0; @@ -1347,12 +982,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * with all ones in bit representation. * the resulting number's length is 3. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeInside5() { String as = "-18446744073709551615"; int number = 0; @@ -1364,12 +993,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeOutside1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1388,12 +1011,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * setBit(int n) outside a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitNegativeOutside2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1414,12 +1031,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * represented as n * 32 + 31, where n is an arbitrary integer. * Here 191 = 5 * 32 + 31 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for setBit method.", - method = "setBit", - args = {int.class} - ) public void testSetBitBug1331() { BigInteger result = BigInteger.valueOf(0L).setBit(191); assertEquals("incorrect value", "3138550867693340381917894711603833208051177722232017256448", result.toString()); @@ -1429,12 +1040,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftLeft(int n), n = 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftLeft method.", - method = "shiftLeft", - args = {int.class} - ) public void testShiftLeft1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1453,12 +1058,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftLeft(int n), n < 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftLeft method.", - method = "shiftLeft", - args = {int.class} - ) public void testShiftLeft2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1477,12 +1076,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftLeft(int n) a positive number, n > 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftLeft method.", - method = "shiftLeft", - args = {int.class} - ) public void testShiftLeft3() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1501,12 +1094,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftLeft(int n) a positive number, n > 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftLeft method.", - method = "shiftLeft", - args = {int.class} - ) public void testShiftLeft4() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1525,12 +1112,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftLeft(int n) a negative number, n > 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftLeft method.", - method = "shiftLeft", - args = {int.class} - ) public void testShiftLeft5() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1549,12 +1130,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftRight(int n), n = 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRight1() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1573,12 +1148,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftRight(int n), n < 0 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRight2() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1597,12 +1166,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftRight(int n), 0 < n < 32 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRight3() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1621,12 +1184,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftRight(int n), n > 32 */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRight4() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1645,12 +1202,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * shiftRight(int n), n is greater than bitLength() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRight5() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1671,12 +1222,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * shift distance is multiple of 32; * shifted bits are NOT zeroes. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRightNegNonZeroesMul32() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 1, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -1697,12 +1242,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * shift distance is NOT multiple of 32; * shifted bits are NOT zeroes. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRightNegNonZeroes() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -1723,12 +1262,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * shift distance is NOT multiple of 32; * shifted bits are zeroes. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRightNegZeroes() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -1749,12 +1282,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * shift distance is multiple of 32; * shifted bits are zeroes. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "shiftRight", - args = {int.class} - ) public void testShiftRightNegZeroesMul32() { byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0}; int aSign = -1; @@ -1773,12 +1300,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a negative n */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitException() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1795,12 +1316,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitPositive1() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1812,12 +1327,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitPositive2() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1829,12 +1338,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a positive number, n > bitLength() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitPositive3() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = 1; @@ -1846,12 +1349,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitNegative1() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1863,12 +1360,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a positive n */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitNegative2() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1880,12 +1371,6 @@ public class BigIntegerOperateBitsTest extends TestCase { /** * testBit(int n) of a positive n, n > bitLength() */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for shiftRight method.", - method = "testBit", - args = {int.class} - ) public void testTestBitNegative3() { byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; int aSign = -1; @@ -1900,12 +1385,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * @tests java.math.BigInteger#getLowestSetBit() getLowestSetBit for * negative BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for getLowestSetBit method.", - method = "getLowestSetBit", - args = {} - ) public void test_getLowestSetBitNeg() { byte aBytes[] = { -1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26 @@ -1921,12 +1400,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * @tests java.math.BigInteger#getLowestSetBit() getLowestSetBit for * positive BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for getLowestSetBit method.", - method = "getLowestSetBit", - args = {} - ) public void test_getLowestSetBitPos() { byte aBytes[] = { -1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26 @@ -1958,12 +1431,6 @@ public class BigIntegerOperateBitsTest extends TestCase { * @tests java.math.BigInteger#getLowestSetBit() getLowestSetBit for zero * BigInteger */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for getLowestSetBit method.", - method = "getLowestSetBit", - args = {} - ) public void test_getLowestSetBitZero() { byte[] aBytes = { 0 diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOrTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOrTest.java index 7b0e076..175a7a7 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOrTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerOrTest.java @@ -21,16 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: or @@ -39,12 +33,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for zero and a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testZeroPos() { byte aBytes[] = {0}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -65,12 +53,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for zero and a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testZeroNeg() { byte aBytes[] = {0}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -91,12 +73,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for a positive number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosZero() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {0}; @@ -117,12 +93,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for a negative number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegPos() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {0}; @@ -143,12 +113,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for zero and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testZeroZero() { byte aBytes[] = {0}; byte bBytes[] = {0}; @@ -169,12 +133,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for zero and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testZeroOne() { byte aBytes[] = {0}; byte bBytes[] = {1}; @@ -195,12 +153,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for one and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testOneOne() { byte aBytes[] = {1}; byte bBytes[] = {1}; @@ -221,12 +173,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two positive numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosPosSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -247,12 +193,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -273,12 +213,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two positive numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -299,12 +233,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two negative numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegNegSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -325,12 +253,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -351,12 +273,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -377,12 +293,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosNegSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -403,12 +313,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegPosSameLength() { byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -429,12 +333,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for a negative and a positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -455,12 +353,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for two negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -481,12 +373,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for a positive and a negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstLonger() { byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; @@ -507,12 +393,6 @@ public class BigIntegerOrTest extends TestCase { /** * Or for a positive and a negative number; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstShorter() { byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; @@ -530,13 +410,6 @@ public class BigIntegerOrTest extends TestCase { assertEquals("incorrect sign", -1, result.signum()); } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for or operation", - method = "or", - args = {java.math.BigInteger.class} - ) - @BrokenTest("Fails in CTS environment, but passes in CoreTestRunner") public void testRegression() { // Regression test for HARMONY-1996 BigInteger x = new BigInteger("-1023"); diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerSubtractTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerSubtractTest.java index 29d8405..1103a08 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerSubtractTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerSubtractTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: subtract @@ -39,12 +34,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two positive numbers of the same length. * The first is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase1() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; @@ -66,12 +55,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two positive numbers of the same length. * The second is greater. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase2() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -94,12 +77,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is positive. * The first is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase3() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; @@ -122,12 +99,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is positive. * The second is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase4() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -149,12 +120,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two negative numbers of the same length. * The first is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase5() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; @@ -176,12 +141,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two negative numbers of the same length. * The second is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase6() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -204,12 +163,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is negative. * The first is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase7() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; @@ -232,12 +185,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is negative. * The second is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase8() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -259,12 +206,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two positive numbers of different length. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase9() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -286,12 +227,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two positive numbers of different length. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase10() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -314,12 +249,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is positive. * The first is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase11() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -342,12 +271,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is positive. * The second is greater in absolute value. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase12() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -370,12 +293,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is negative. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase13() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -398,12 +315,6 @@ public class BigIntegerSubtractTest extends TestCase { * The first is negative. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase14() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -425,12 +336,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two negative numbers of different length. * The first is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase15() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; @@ -452,12 +357,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract two negative numbers of different length. * The second is longer. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase16() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; @@ -478,12 +377,6 @@ public class BigIntegerSubtractTest extends TestCase { /** * Subtract two positive equal in absolute value numbers. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase17() { byte aBytes[] = {-120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; byte bBytes[] = {-120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; @@ -505,12 +398,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract zero from a number. * The number is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase18() { byte aBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; byte bBytes[] = {0}; @@ -532,12 +419,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract a number from zero. * The number is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase19() { byte aBytes[] = {0}; byte bBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; @@ -558,12 +439,6 @@ public class BigIntegerSubtractTest extends TestCase { /** * Subtract zero from zero. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase20() { byte aBytes[] = {0}; byte bBytes[] = {0}; @@ -585,12 +460,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract ZERO from a number. * The number is positive. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase21() { byte aBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; @@ -610,12 +479,6 @@ public class BigIntegerSubtractTest extends TestCase { * Subtract a number from ZERO. * The number is negative. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase22() { byte bBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; @@ -634,12 +497,6 @@ public class BigIntegerSubtractTest extends TestCase { /** * Subtract ZERO from ZERO. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase23() { byte rBytes[] = {0}; BigInteger aNumber = BigInteger.ZERO; @@ -656,12 +513,6 @@ public class BigIntegerSubtractTest extends TestCase { /** * Subtract ONE from ONE. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase24() { byte rBytes[] = {0}; BigInteger aNumber = BigInteger.ONE; @@ -678,12 +529,6 @@ public class BigIntegerSubtractTest extends TestCase { /** * Subtract two numbers so that borrow is 1. */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for subtract method", - method = "subtract", - args = {java.math.BigInteger.class} - ) public void testCase25() { byte aBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; byte bBytes[] = {-128, -128, -128, -128, -128, -128, -128, -128, -128}; @@ -701,4 +546,3 @@ public class BigIntegerSubtractTest extends TestCase { assertEquals(-1, result.signum()); } } - diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerToStringTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerToStringTest.java index c405553..34b4b19 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerToStringTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerToStringTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: toString(int radix) @@ -38,12 +33,6 @@ public class BigIntegerToStringTest extends TestCase { /** * If 36 < radix < 2 it should be set to 10 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadixOutOfRange() { String value = "442429234853876401"; int radix = 10; @@ -55,12 +44,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test negative number of radix 2 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix2Neg() { String value = "-101001100010010001001010101110000101010110001010010101010101010101010101010101010101010101010010101"; int radix = 2; @@ -72,12 +55,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test positive number of radix 2 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix2Pos() { String value = "101000011111000000110101010101010101010001001010101010101010010101010101010000100010010"; int radix = 2; @@ -89,12 +66,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test negative number of radix 10 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix10Neg() { String value = "-2489756308572364789878394872984"; int radix = 16; @@ -106,12 +77,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test positive number of radix 10 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix10Pos() { String value = "2387627892347567398736473476"; int radix = 16; @@ -123,12 +88,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test negative number of radix 16 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix16Neg() { String value = "-287628a883451b800865c67e8d7ff20"; int radix = 16; @@ -140,12 +99,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test positive number of radix 16 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix16Pos() { String value = "287628a883451b800865c67e8d7ff20"; int radix = 16; @@ -157,12 +110,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test negative number of radix 24 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix24Neg() { String value = "-287628a88gmn3451b8ijk00865c67e8d7ff20"; int radix = 24; @@ -174,12 +121,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test positive number of radix 24 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix24Pos() { String value = "287628a883451bg80ijhk0865c67e8d7ff20"; int radix = 24; @@ -191,12 +132,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test negative number of radix 24 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix36Neg() { String value = "-uhguweut98iu4h3478tq3985pq98yeiuth33485yq4aiuhalai485yiaehasdkr8tywi5uhslei8"; int radix = 36; @@ -208,12 +143,6 @@ public class BigIntegerToStringTest extends TestCase { /** * test positive number of radix 24 */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {int.class} - ) public void testRadix36Pos() { String value = "23895lt45y6vhgliuwhgi45y845htsuerhsi4586ysuerhtsio5y68peruhgsil4568ypeorihtse48y6"; int radix = 36; @@ -227,12 +156,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString1() { String s = "0000000000"; @@ -244,12 +167,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString2() { String s = "1234567890987654321"; BigInteger bi = new BigInteger(s); @@ -260,12 +177,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString3() { String s = "-1234567890987654321"; BigInteger bi = new BigInteger(s); @@ -276,12 +187,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString4() { String s = "12345678901234"; long l = 12345678901234L; @@ -293,12 +198,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString5() { String s = "-12345678901234"; long l = -12345678901234L; @@ -310,12 +209,6 @@ public class BigIntegerToStringTest extends TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "This is a complete subset of tests for toString method", - method = "toString", - args = {} - ) public void test_toString() { byte aBytes[] = { 12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91 diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerXorTest.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerXorTest.java index 4e2dbcf..b55b60b 100644 --- a/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerXorTest.java +++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/BigIntegerXorTest.java @@ -21,15 +21,10 @@ package org.apache.harmony.math.tests.java.math; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - import java.math.BigInteger; import junit.framework.TestCase; -@TestTargetClass(BigInteger.class) + /** * Class: java.math.BigInteger * Method: xor @@ -38,12 +33,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for zero and a positive number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testZeroPos() { String numA = "0"; String numB = "27384627835298756289327365"; @@ -57,12 +46,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for zero and a negative number */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testZeroNeg() { String numA = "0"; String numB = "-27384627835298756289327365"; @@ -76,12 +59,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for a positive number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosZero() { String numA = "27384627835298756289327365"; String numB = "0"; @@ -95,12 +72,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for a negative number and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegPos() { String numA = "-27384627835298756289327365"; String numB = "0"; @@ -114,12 +85,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for zero and zero */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testZeroZero() { String numA = "0"; String numB = "0"; @@ -133,12 +98,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for zero and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testZeroOne() { String numA = "0"; String numB = "1"; @@ -152,12 +111,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for one and one */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testOneOne() { String numA = "1"; String numB = "1"; @@ -171,12 +124,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two positive numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosPosSameLength() { String numA = "283746278342837476784564875684767"; String numB = "293478573489347658763745839457637"; @@ -190,12 +137,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstLonger() { String numA = "2837462783428374767845648748973847593874837948575684767"; String numB = "293478573489347658763745839457637"; @@ -209,12 +150,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two positive numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosPosFirstShorter() { String numA = "293478573489347658763745839457637"; String numB = "2837462783428374767845648748973847593874837948575684767"; @@ -228,12 +163,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two negative numbers of the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegNegSameLength() { String numA = "-283746278342837476784564875684767"; String numB = "-293478573489347658763745839457637"; @@ -247,12 +176,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstLonger() { String numA = "-2837462783428374767845648748973847593874837948575684767"; String numB = "-293478573489347658763745839457637"; @@ -266,12 +189,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegNegFirstShorter() { String numA = "293478573489347658763745839457637"; String numB = "2837462783428374767845648748973847593874837948575684767"; @@ -285,12 +202,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosNegSameLength() { String numA = "283746278342837476784564875684767"; String numB = "-293478573489347658763745839457637"; @@ -304,12 +215,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two numbers of different signs and the same length */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegPosSameLength() { String numA = "-283746278342837476784564875684767"; String numB = "293478573489347658763745839457637"; @@ -323,12 +228,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for a negative and a positive numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstLonger() { String numA = "-2837462783428374767845648748973847593874837948575684767"; String numB = "293478573489347658763745839457637"; @@ -342,12 +241,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for two negative numbers; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testNegPosFirstShorter() { String numA = "-293478573489347658763745839457637"; String numB = "2837462783428374767845648748973847593874837948575684767"; @@ -361,12 +254,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for a positive and a negative numbers; the first is longer */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstLonger() { String numA = "2837462783428374767845648748973847593874837948575684767"; String numB = "-293478573489347658763745839457637"; @@ -380,12 +267,6 @@ public class BigIntegerXorTest extends TestCase { /** * Xor for a positive and a negative number; the first is shorter */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "This is a complete subset of tests for xor operation.", - method = "xor", - args = {java.math.BigInteger.class} - ) public void testPosNegFirstShorter() { String numA = "293478573489347658763745839457637"; String numB = "-2837462783428374767845648748973847593874837948575684767"; diff --git a/math/src/test/java/tests/api/java/math/AllTests.java b/math/src/test/java/tests/api/java/math/AllTests.java index 483e08a..a3fb664 100644 --- a/math/src/test/java/tests/api/java/math/AllTests.java +++ b/math/src/test/java/tests/api/java/math/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Math project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.math"); + TestSuite suite = new TestSuite("Tests for java.math"); // $JUnit-BEGIN$ suite.addTestSuite(BigDecimalTest.class); suite.addTestSuite(BigIntegerTest.class); diff --git a/math/src/test/java/tests/api/java/math/BigDecimalTest.java b/math/src/test/java/tests/api/java/math/BigDecimalTest.java index 29d68a2..a053cef 100644 --- a/math/src/test/java/tests/api/java/math/BigDecimalTest.java +++ b/math/src/test/java/tests/api/java/math/BigDecimalTest.java @@ -17,12 +17,6 @@ package tests.api.java.math; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.AndroidOnly; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; @@ -32,7 +26,6 @@ import java.math.BigInteger; import java.math.RoundingMode; import java.math.MathContext; -@TestTargetClass(BigDecimal.class) public class BigDecimalTest extends junit.framework.TestCase { BigInteger value = new BigInteger("12345908"); @@ -41,12 +34,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class} - ) public void test_ConstructorLjava_math_BigInteger() { BigDecimal big = new BigDecimal(value); assertTrue("the BigDecimal value is not initialized properly", big @@ -57,12 +44,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.math.BigInteger, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.math.BigInteger.class, int.class} - ) public void test_ConstructorLjava_math_BigIntegerI() { BigDecimal big = new BigDecimal(value2, 5); assertTrue("the BigDecimal value is not initialized properly", big @@ -75,12 +56,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(double) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = ".", - method = "BigDecimal", - args = {double.class} - ) public void test_ConstructorD() { // // These numbers have an exact representation as doubles: @@ -132,12 +107,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() throws NumberFormatException { BigDecimal big = new BigDecimal("345.23499600293850"); assertTrue("the BigDecimal value is not initialized properly", big @@ -158,12 +127,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "BigDecimal", - args = {double.class} - ) public void test_constructor_String_plus_exp() { /* * BigDecimal does not support a + sign in the exponent when converting @@ -181,12 +144,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checked.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void test_constructor_String_empty() { try { new BigDecimal(""); @@ -198,12 +155,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checked.", - method = "BigDecimal", - args = {java.lang.String.class} - ) public void test_constructor_String_plus_minus_exp() { try { new BigDecimal("+35e+-2"); @@ -221,12 +172,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#BigDecimal(char[]) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Exception checked.", - method = "BigDecimal", - args = {char[].class} - ) public void test_constructor_CC_plus_minus_exp() { try { new BigDecimal("+35e+-2".toCharArray()); @@ -244,12 +189,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#abs() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "abs", - args = {} - ) public void test_abs() { BigDecimal big = new BigDecimal("-1234"); BigDecimal bigabs = big.abs(); @@ -264,12 +203,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#add(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "add", - args = {java.math.BigDecimal.class} - ) public void test_addLjava_math_BigDecimal() { BigDecimal add1 = new BigDecimal("23.456"); BigDecimal add2 = new BigDecimal("3849.235"); @@ -287,12 +220,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#compareTo(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.math.BigDecimal.class} - ) public void test_compareToLjava_math_BigDecimal() { BigDecimal comp1 = new BigDecimal("1.00"); BigDecimal comp2 = new BigDecimal(1.000000D); @@ -309,12 +236,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "IllegalArgumentException checking missed. Used only ROUND_UP & ROUND_DOWN round modes.", - method = "divide", - args = {java.math.BigDecimal.class, int.class} - ) public void test_divideLjava_math_BigDecimalI() { BigDecimal divd1 = new BigDecimal(value, 2); BigDecimal divd2 = new BigDecimal("2.335"); @@ -342,12 +263,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "IllegalArgumentException checking missed. Used only ROUND_UP & ROUND_DOWN round modes.", - method = "divide", - args = {java.math.BigDecimal.class, int.class, int.class} - ) public void test_divideLjava_math_BigDecimalII() { BigDecimal divd1 = new BigDecimal(value2, 4); BigDecimal divd2 = new BigDecimal("0.0023"); @@ -372,12 +287,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#doubleValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Narrowing limitations of double representation are not checked.", - method = "doubleValue", - args = {} - ) public void test_doubleValue() { BigDecimal bigDB = new BigDecimal(-1.234E-112); // Commenting out this part because it causes an endless loop (see HARMONY-319 and HARMONY-329) @@ -409,12 +318,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#equals(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { BigDecimal equal1 = new BigDecimal(1.00D); BigDecimal equal2 = new BigDecimal("1.0"); @@ -442,12 +345,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#floatValue() */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Narrowing limitations of float representation are not checked.", - method = "floatValue", - args = {} - ) public void test_floatValue() { BigDecimal fl1 = new BigDecimal("234563782344567"); assertTrue("the float representation of bigDecimal 234563782344567", @@ -475,12 +372,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#hashCode() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) public void test_hashCode() { // anything that is equal must have the same hashCode BigDecimal hash = new BigDecimal("1.00"); @@ -509,12 +400,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#intValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "intValue", - args = {} - ) public void test_intValue() { BigDecimal int1 = new BigDecimal(value, 3); assertTrue("the int value of 12345.908 is not 12345", @@ -533,12 +418,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#longValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "longValue", - args = {} - ) public void test_longValue() { BigDecimal long1 = new BigDecimal(value2.negate(), 0); assertTrue("the long value of 12334560000 is not 12334560000", long1 @@ -557,12 +436,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#max(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "max", - args = {java.math.BigDecimal.class} - ) public void test_maxLjava_math_BigDecimal() { BigDecimal max1 = new BigDecimal(value2, 1); BigDecimal max2 = new BigDecimal(value2, 4); @@ -580,12 +453,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#min(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "min", - args = {java.math.BigDecimal.class} - ) public void test_minLjava_math_BigDecimal() { BigDecimal min1 = new BigDecimal(-12345.4D); BigDecimal min2 = new BigDecimal(-12345.39D); @@ -600,12 +467,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#movePointLeft(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "movePointLeft", - args = {int.class} - ) public void test_movePointLeftI() { BigDecimal movePtLeft = new BigDecimal("123456265.34"); BigDecimal alreadyMoved = movePtLeft.movePointLeft(5); @@ -635,12 +496,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#movePointRight(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed.", - method = "movePointRight", - args = {int.class} - ) public void test_movePointRightI() { BigDecimal movePtRight = new BigDecimal("-1.58796521458"); BigDecimal alreadyMoved = movePtRight.movePointRight(8); @@ -667,12 +522,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#multiply(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "multiply", - args = {java.math.BigDecimal.class} - ) public void test_multiplyLjava_math_BigDecimal() { BigDecimal multi1 = new BigDecimal(value, 5); BigDecimal multi2 = new BigDecimal(2.345D); @@ -708,12 +557,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#negate() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "negate", - args = {} - ) public void test_negate() { BigDecimal negate1 = new BigDecimal(value2, 7); assertTrue("the negate of 1233.4560000 is not -1233.4560000", negate1 @@ -729,12 +572,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#scale() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "scale", - args = {} - ) public void test_scale() { BigDecimal scale1 = new BigDecimal(value2, 8); assertTrue("the scale of the number 123.34560000 is wrong", scale1 @@ -758,12 +595,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#setScale(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setScale", - args = {int.class} - ) public void test_setScaleI() { // rounding mode defaults to zero BigDecimal setScale1 = new BigDecimal(value, 3); @@ -783,12 +614,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#setScale(int, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setScale", - args = {int.class, int.class} - ) public void test_setScaleII() { BigDecimal setScale1 = new BigDecimal(2.323E102); BigDecimal setScale2 = setScale1.setScale(4); @@ -924,12 +749,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#setScale(int, java.math.RoundingMode) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setScale", - args = {int.class, java.math.RoundingMode.class} - ) public void test_setScaleILjava_math_RoundingMode() { BigDecimal setScale1 = new BigDecimal(2.323E102); BigDecimal setScale2 = setScale1.setScale(4); @@ -1065,12 +884,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#signum() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "signum", - args = {} - ) public void test_signum() { BigDecimal sign = new BigDecimal(123E-104); assertTrue("123E-104 is not positive in signum()", sign.signum() == 1); @@ -1084,12 +897,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#subtract(java.math.BigDecimal) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "subtract", - args = {java.math.BigDecimal.class} - ) public void test_subtractLjava_math_BigDecimal() { BigDecimal sub1 = new BigDecimal("13948"); BigDecimal sub2 = new BigDecimal("2839.489"); @@ -1122,12 +929,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#toBigInteger() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toBigInteger", - args = {} - ) public void test_toBigInteger() { BigDecimal sub1 = new BigDecimal("-29830.989"); BigInteger result = sub1.toBigInteger(); @@ -1151,12 +952,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { BigDecimal toString1 = new BigDecimal("1234.000"); assertTrue("the toString representation of 1234.000 is wrong", @@ -1175,12 +970,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#unscaledValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "unscaledValue", - args = {} - ) public void test_unscaledValue() { BigDecimal unsVal = new BigDecimal("-2839485.000"); assertTrue("the unscaledValue of -2839485.000 is wrong", unsVal @@ -1201,12 +990,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#valueOf(long) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {long.class} - ) public void test_valueOfJ() { BigDecimal valueOfL = BigDecimal.valueOf(9223372036854775806L); assertTrue("the bigDecimal equivalent of 9223372036854775806 is wrong", @@ -1225,12 +1008,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#valueOf(long, int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {long.class, int.class} - ) public void test_valueOfJI() { BigDecimal valueOfJI = BigDecimal.valueOf(9223372036854775806L, 5); assertTrue( @@ -1260,12 +1037,6 @@ public class BigDecimalTest extends junit.framework.TestCase { } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Checks serialization", - method = "!SerializationSelf", - args = {} - ) public void test_BigDecimal_serialization() throws Exception { // Regression for HARMONY-1896 char[] in = { '1', '5', '6', '7', '8', '7', '.', '0', '0' }; @@ -1287,12 +1058,6 @@ public class BigDecimalTest extends junit.framework.TestCase { /** * @tests java.math.BigDecimal#stripTrailingZero(long) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "The RI fails the Zero Test: has scale 4 for BigDecimal('0.0000')", - method = "stripTrailingZeros", - args = {} - ) public void test_stripTrailingZero() { BigDecimal sixhundredtest = new BigDecimal("600.0"); assertTrue("stripTrailingZero failed for 600.0", @@ -1314,12 +1079,6 @@ public class BigDecimalTest extends junit.framework.TestCase { // END android-changed } - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "abs", - args = {MathContext.class} - ) public void testMathContextConstruction() { String a = "-12380945E+61"; BigDecimal aNumber = new BigDecimal(a); diff --git a/math/src/test/java/tests/api/java/math/BigIntegerTest.java b/math/src/test/java/tests/api/java/math/BigIntegerTest.java index b84aa17..77eabb4 100644 --- a/math/src/test/java/tests/api/java/math/BigIntegerTest.java +++ b/math/src/test/java/tests/api/java/math/BigIntegerTest.java @@ -17,16 +17,9 @@ package tests.api.java.math; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - import java.math.BigInteger; import java.util.Random; -@TestTargetClass(BigInteger.class) public class BigIntegerTest extends junit.framework.TestCase { BigInteger minusTwo = new BigInteger("-2", 10); @@ -87,12 +80,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(int, java.util.Random) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigInteger", - args = {int.class, java.util.Random.class} - ) public void test_ConstructorILjava_util_Random() { // regression test for HARMONY-1047 try { @@ -123,12 +110,7 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(int, int, java.util.Random) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "BigInteger", - args = {int.class, int.class, java.util.Random.class} - ) - @KnownFailure("BIGNUM returns no Primes smaller than 16 bits.") + // BIGNUM returns no Primes smaller than 16 bits. public void test_ConstructorIILjava_util_Random() { bi = new BigInteger(10, 5, rand); bi2 = new BigInteger(10, 5, rand); @@ -168,12 +150,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(byte[]) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "NumberFormatException checking missed", - method = "BigInteger", - args = {byte[].class} - ) public void test_Constructor$B() { byte[] myByteArray; myByteArray = new byte[] { (byte) 0x00, (byte) 0xFF, (byte) 0xFE }; @@ -188,12 +164,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(int, byte[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "BigInteger", - args = {int.class, byte[].class} - ) public void test_ConstructorI$B() { byte[] myByteArray; myByteArray = new byte[] { (byte) 0xFF, (byte) 0xFE }; @@ -218,12 +188,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Checks NumberFormatException", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_constructor_String_empty() { try { new BigInteger(""); @@ -235,12 +199,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#toByteArray() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toByteArray", - args = {} - ) public void test_toByteArray() { byte[] myByteArray, anotherByteArray; myByteArray = new byte[] { 97, 33, 120, 124, 50, 2, 0, 0, 0, 12, 124, @@ -274,20 +232,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#isProbablePrime(int) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isProbablePrime", - args = {int.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "probablePrime", - args = {int.class, java.util.Random.class} - ) - }) public void test_isProbablePrimeI() { int fails = 0; bi = new BigInteger(20, 20, rand); @@ -355,20 +299,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#nextProbablePrime() */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "nextProbablePrime", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isProbablePrime", - args = {int.class} - ) - }) public void test_nextProbablePrime() { largePrimesProduct( new BigInteger("2537895984043447429238717358455377929009126353874925049325287329295635198252046158619999217453233889378619619008359011789"), @@ -400,12 +330,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#probablePrime(int, java.util.Random) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "probablePrime", - args = {int.class, java.util.Random.class} - ) public void test_probablePrime() { for (int bitLength = 50; bitLength <= 1050; bitLength += 100) { BigInteger a = BigInteger.probablePrime(bitLength, rand); @@ -478,12 +402,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#equals(java.lang.Object) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) public void test_equalsLjava_lang_Object() { assertTrue("0=0", zero.equals(BigInteger.valueOf(0))); assertTrue("-123=-123", BigInteger.valueOf(-123).equals( @@ -499,12 +417,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#compareTo(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "compareTo", - args = {java.math.BigInteger.class} - ) public void test_compareToLjava_math_BigInteger() { assertTrue("Smaller number returned >= 0", one.compareTo(two) < 0); assertTrue("Larger number returned >= 0", two.compareTo(one) > 0); @@ -516,12 +428,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#intValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "intValue", - args = {} - ) public void test_intValue() { assertTrue("Incorrect intValue for 2**70", twoToTheSeventy.intValue() == 0); @@ -531,12 +437,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#longValue() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "longValue", - args = {} - ) public void test_longValue() { assertTrue("Incorrect longValue for 2**70", twoToTheSeventy.longValue() == 0); @@ -546,12 +446,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#valueOf(long) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {long.class} - ) public void test_valueOfJ() { assertTrue("Incurred number returned for 2", BigInteger.valueOf(2L) .equals(two)); @@ -562,12 +456,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#add(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Test is OK, but some cases listed below can be reasonable.", - method = "add", - args = {java.math.BigInteger.class} - ) public void test_addLjava_math_BigInteger() { assertTrue("Incorrect sum--wanted a zillion", aZillion.add(aZillion) .add(aZillion.negate()).equals(aZillion)); @@ -609,12 +497,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#negate() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "negate", - args = {} - ) public void test_negate() { assertTrue("Single negation of zero did not result in zero", zero .negate().equals(zero)); @@ -643,12 +525,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#signum() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "signum", - args = {} - ) public void test_signum() { assertTrue("Wrong positive signum", two.signum() == 1); assertTrue("Wrong zero signum", zero.signum() == 0); @@ -659,12 +535,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#abs() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "abs", - args = {} - ) public void test_abs() { assertTrue("Invalid number returned for zillion", aZillion.negate() .abs().equals(aZillion.abs())); @@ -678,12 +548,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#pow(int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checking missed", - method = "pow", - args = {int.class} - ) public void test_powI() { assertTrue("Incorrect exponent returned for 2**10", two.pow(10).equals( twoToTheTen)); @@ -696,12 +560,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#modInverse(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "modInverse", - args = {java.math.BigInteger.class} - ) public void test_modInverseLjava_math_BigInteger() { BigInteger a = zero, mod, inv; for (int j = 3; j < 50; j++) { @@ -751,12 +609,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#shiftRight(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "shiftRight", - args = {int.class} - ) public void test_shiftRightI() { assertTrue("1 >> 0", BigInteger.valueOf(1).shiftRight(0).equals( BigInteger.ONE)); @@ -814,12 +666,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#shiftLeft(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "shiftLeft", - args = {int.class} - ) public void test_shiftLeftI() { assertTrue("1 << 0", one.shiftLeft(0).equals(one)); assertTrue("1 << 1", one.shiftLeft(1).equals(two)); @@ -861,12 +707,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#multiply(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "multiply", - args = {java.math.BigInteger.class} - ) public void test_multiplyLjava_math_BigInteger() { assertTrue("Incorrect sum--wanted three zillion", aZillion .add(aZillion).add(aZillion).equals( @@ -893,12 +733,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#divide(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "divide", - args = {java.math.BigInteger.class} - ) public void test_divideLjava_math_BigInteger() { testAllDivs(bi33, bi3); testAllDivs(bi22, bi2); @@ -957,12 +791,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#remainder(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checked", - method = "remainder", - args = {java.math.BigInteger.class} - ) public void test_remainderLjava_math_BigInteger() { try { largePos.remainder(zero); @@ -992,12 +820,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#mod(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checked", - method = "mod", - args = {java.math.BigInteger.class} - ) public void test_modLjava_math_BigInteger() { try { largePos.mod(zero); @@ -1027,12 +849,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#divideAndRemainder(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "ArithmeticException checked", - method = "divideAndRemainder", - args = {java.math.BigInteger.class} - ) public void test_divideAndRemainderLjava_math_BigInteger() { try { largePos.divideAndRemainder(zero); @@ -1062,12 +878,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "NumberFormatException checking missed.", - method = "BigInteger", - args = {java.lang.String.class} - ) public void test_ConstructorLjava_lang_String() { assertTrue("new(0)", new BigInteger("0").equals(BigInteger.valueOf(0))); assertTrue("new(1)", new BigInteger("1").equals(BigInteger.valueOf(1))); @@ -1082,12 +892,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#BigInteger(java.lang.String, int) */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "NumberFormatException checking missed.", - method = "BigInteger", - args = {java.lang.String.class, int.class} - ) public void test_ConstructorLjava_lang_StringI() { assertTrue("new(0,16)", new BigInteger("0", 16).equals(BigInteger .valueOf(0))); @@ -1112,12 +916,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#toString() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) public void test_toString() { assertTrue("0.toString", "0".equals(BigInteger.valueOf(0).toString())); assertTrue("1.toString", "1".equals(BigInteger.valueOf(1).toString())); @@ -1132,12 +930,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#toString(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {int.class} - ) public void test_toStringI() { assertTrue("0.toString(16)", "0".equals(BigInteger.valueOf(0).toString( 16))); @@ -1156,12 +948,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#and(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "and", - args = {java.math.BigInteger.class} - ) public void test_andLjava_math_BigInteger() { for (BigInteger[] element : booleanPairs) { BigInteger i1 = element[0], i2 = element[1]; @@ -1178,12 +964,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#or(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "or", - args = {java.math.BigInteger.class} - ) public void test_orLjava_math_BigInteger() { for (BigInteger[] element : booleanPairs) { BigInteger i1 = element[0], i2 = element[1]; @@ -1200,12 +980,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#xor(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "xor", - args = {java.math.BigInteger.class} - ) public void test_xorLjava_math_BigInteger() { for (BigInteger[] element : booleanPairs) { BigInteger i1 = element[0], i2 = element[1]; @@ -1222,12 +996,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#not() */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "not", - args = {} - ) public void test_not() { for (BigInteger[] element : booleanPairs) { BigInteger i1 = element[0]; @@ -1242,12 +1010,6 @@ public class BigIntegerTest extends junit.framework.TestCase { /** * @tests java.math.BigInteger#andNot(java.math.BigInteger) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "andNot", - args = {java.math.BigInteger.class} - ) public void test_andNotLjava_math_BigInteger() { for (BigInteger[] element : booleanPairs) { BigInteger i1 = element[0], i2 = element[1]; @@ -1279,12 +1041,6 @@ public class BigIntegerTest extends junit.framework.TestCase { } - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test", - method = "clone", - args = {} - ) public void testClone() { // Regression test for HARMONY-1770 MyBigInteger myBigInteger = new MyBigInteger("12345"); diff --git a/math/src/test/java/tests/api/java/math/MathContextTest.java b/math/src/test/java/tests/api/java/math/MathContextTest.java index 0051b44..dadfd12 100644 --- a/math/src/test/java/tests/api/java/math/MathContextTest.java +++ b/math/src/test/java/tests/api/java/math/MathContextTest.java @@ -17,71 +17,15 @@ package tests.api.java.math; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; -@TestTargetClass(MathContext.class) public class MathContextTest extends junit.framework.TestCase { /** * @tests java.math.MathContext#MathContext(...) */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MathContext", - args = {int.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MathContext", - args = {int.class, java.math.RoundingMode.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "MathContext", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPrecision", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getRoundingMode", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - }) public void test_MathContextConstruction() { String a = "-12380945E+61"; BigDecimal aNumber = new BigDecimal(a); @@ -132,4 +76,4 @@ public class MathContextTest extends junit.framework.TestCase { res); } -}
\ No newline at end of file +} diff --git a/math/src/test/java/tests/api/java/math/RoundingModeTest.java b/math/src/test/java/tests/api/java/math/RoundingModeTest.java index e0946b3..1549301 100644 --- a/math/src/test/java/tests/api/java/math/RoundingModeTest.java +++ b/math/src/test/java/tests/api/java/math/RoundingModeTest.java @@ -17,26 +17,14 @@ package tests.api.java.math; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import java.math.BigDecimal; import java.math.RoundingMode; -@TestTargetClass(RoundingMode.class) public class RoundingModeTest extends junit.framework.TestCase { /** * @tests java.math.RoundingMode#valueOf(int) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "valueOf", - args = {int.class} - ) public void test_valueOfI() { assertEquals("valueOf failed for ROUND_CEILING", RoundingMode.valueOf(BigDecimal.ROUND_CEILING), RoundingMode.CEILING); assertEquals("valueOf failed for ROUND_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_DOWN), RoundingMode.DOWN); diff --git a/math/src/test/java/tests/math/AllTests.java b/math/src/test/java/tests/math/AllTests.java index 2773ad6..64fb60d 100644 --- a/math/src/test/java/tests/math/AllTests.java +++ b/math/src/test/java/tests/math/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Math project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Math test suites"); + TestSuite suite = new TestSuite("All Math test suites"); suite.addTest(tests.api.java.math.AllTests.suite()); suite.addTest(org.apache.harmony.math.tests.java.math.AllTests.suite()); diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java index 6bf13f1..e88de9a 100644 --- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java +++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java @@ -25,13 +25,8 @@ import junit.framework.TestSuite; * */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.nio"); + TestSuite suite = new TestSuite("Tests for java.nio"); //$JUnit-BEGIN$ suite.addTestSuite(BufferOverflowExceptionTest.class); suite.addTestSuite(BufferUnderflowExceptionTest.class); diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java index 069b056..d348c3d 100644 --- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java +++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java @@ -32,10 +32,6 @@ import junit.framework.TestCase; @TestTargetClass(ByteOrder.class) public class ByteOrderTest extends TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(ByteOrderTest.class); - } - @TestTargetNew( level = TestLevel.COMPLETE, notes = "", diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java index 8031c5f..29cd201 100644 --- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java +++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(AllTests.class.getName()); + TestSuite suite = new TestSuite(AllTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(AlreadyConnectedExceptionTest.class); suite.addTestSuite(AsynchronousCloseExceptionTest.class); diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java index 1b5e12e..bd94f8d 100644 --- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java +++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java @@ -22,8 +22,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "Test for tests.api.java.nio.channels.spi"); + TestSuite suite = new TestSuite("Test for tests.api.java.nio.channels.spi"); //$JUnit-BEGIN$ suite.addTestSuite(AbstractInterruptibleChannelTest.class); suite.addTestSuite(AbstractSelectorTest.class); diff --git a/nio/src/test/java/tests/nio/AllTests.java b/nio/src/test/java/tests/nio/AllTests.java index ff50aa5..07f0491 100644 --- a/nio/src/test/java/tests/nio/AllTests.java +++ b/nio/src/test/java/tests/nio/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Math project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Math test suites"); + TestSuite suite = new TestSuite("All Math test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.nio.tests.java.nio.AllTests.suite()); suite.addTest(org.apache.harmony.nio.tests.java.nio.channels.AllTests.suite()); diff --git a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java index 2bc537b..9c56d76 100644 --- a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java +++ b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java @@ -20,14 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "Test for org.apache.harmony.nio_char.tests.java.nio.charset"); + TestSuite suite = new TestSuite("Test for org.apache.harmony.nio_char.tests.java.nio.charset"); //$JUnit-BEGIN$ suite.addTestSuite(ASCIICharsetEncoderTest.class); suite.addTestSuite(CharacterCodingExceptionTest.class); diff --git a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java index 3e5f3a9..00ed64b 100644 --- a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java +++ b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java @@ -20,14 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "Suite of tests for the java.nio.charset.spi package."); + TestSuite suite = new TestSuite("Suite of tests for the java.nio.charset.spi package."); // $JUnit-BEGIN$ suite.addTestSuite(CharsetProviderTest.class); // $JUnit-END$ diff --git a/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java b/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java index f318960..933f341 100644 --- a/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java +++ b/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.nio.charset;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.nio.charset;"); suite.addTestSuite(CharsetProviderTest.class); suite.addTestSuite(CharsetTest.class); diff --git a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java index b9f9bc6..7f83414 100644 --- a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java +++ b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java @@ -192,7 +192,6 @@ public class Charset_MultiByte_GB2312 extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is not properly supported in Android!") @Override public void test_Decode() throws CharacterCodingException { super.test_Decode(); @@ -203,7 +202,6 @@ public class Charset_MultiByte_GB2312 extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is not properly supported in Android!") @Override public void test_Encode() throws CharacterCodingException { super.test_Encode(); @@ -214,7 +212,6 @@ public class Charset_MultiByte_GB2312 extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is mapped to GBK Android!") @Override public void test_nameMatch() { super.test_nameMatch(); diff --git a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java index 3f1afb5..bf070c0 100644 --- a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java +++ b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java @@ -385,7 +385,6 @@ public class Charset_MultiByte_ISO_2022_JP extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is not properly supported in Android!") @Override public void test_Decode() throws CharacterCodingException { super.test_Decode(); @@ -396,7 +395,6 @@ public class Charset_MultiByte_ISO_2022_JP extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is not properly supported in Android!") @Override public void test_Encode() throws CharacterCodingException { super.test_Encode(); diff --git a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java index 61685f1..39e7f31 100644 --- a/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java +++ b/nio_char/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java @@ -251,7 +251,6 @@ public class Charset_MultiByte_x_windows_950 extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is not properly supported in Android!") @Override public void test_Encode() throws CharacterCodingException { super.test_Encode(); @@ -262,7 +261,6 @@ public class Charset_MultiByte_x_windows_950 extends Charset_AbstractTest { method = "functionalCoDec_REPR", args = {} ) - @KnownFailure("This Characterset is mapped to Big5 Android!") @Override public void test_nameMatch() { super.test_nameMatch(); diff --git a/nio_char/src/test/java/tests/nio_char/AllTests.java b/nio_char/src/test/java/tests/nio_char/AllTests.java index 19a003c..4ab9247 100644 --- a/nio_char/src/test/java/tests/nio_char/AllTests.java +++ b/nio_char/src/test/java/tests/nio_char/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the NIO_Char project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All NIO_Char test suites"); + TestSuite suite = new TestSuite("All NIO_Char test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.AllTests.suite()); suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.spi.AllTests.suite()); diff --git a/openssl/src/main/java/org/openssl/NativeBN.java b/openssl/src/main/java/org/openssl/NativeBN.java index fd796f8..9691204 100644 --- a/openssl/src/main/java/org/openssl/NativeBN.java +++ b/openssl/src/main/java/org/openssl/NativeBN.java @@ -96,11 +96,8 @@ public class NativeBN { // op: 0 = reset; 1 = set; -1 = flip // uses BN_set_bit(), BN_clear_bit() and BN_is_bit_set() - public static native boolean BN_lshift(int r, int a, int n); - // int BN_lshift(BIGNUM *r, const BIGNUM *a, int n); -// public static native int BN_rshift(BigInteger r, BigInteger a, int n); - // int BN_rshift(BIGNUM *r, const BIGNUM *a, int n); - + public static native boolean BN_shift(int r, int a, int n); + // int BN_shift(BIGNUM *r, const BIGNUM *a, int n); public static native boolean BN_add_word(int a, int w); // ATTENTION: w is treated as unsigned. diff --git a/openssl/src/main/native/BNInterface.c b/openssl/src/main/native/BNInterface.c index ff2a2ae..8ac2395 100644 --- a/openssl/src/main/native/BNInterface.c +++ b/openssl/src/main/native/BNInterface.c @@ -509,72 +509,13 @@ static jboolean NativeBN_modifyBit(JNIEnv* env, jclass cls, BIGNUM* a, int n, in } /** - * public static native int BN_lshift(int, int, int) + * public static native int BN_shift(int, int, int) */ -static jboolean NativeBN_BN_lshift(JNIEnv* env, jclass cls, BIGNUM* r, BIGNUM* a, int n) { -// LOGD("NativeBN_BN_lshift %p %p %d", r, a, n); +static jboolean NativeBN_BN_shift(JNIEnv* env, jclass cls, BIGNUM* r, BIGNUM* a, int n) { if (!twoValidHandles(env, r, a)) return FALSE; - if (n >= 0) return BN_lshift(r, a, n); - - n = -n; -// return BN_rshift(r, a, n); -// Following code insourced from bn_shift.c in order to have bug fixed: -// FIXME: Should report to openssl team!!! - - int i,j,nw,lb,rb; - BN_ULONG *t,*f; - BN_ULONG l,tmp; - - bn_check_top(r); - bn_check_top(a); - - nw=n/BN_BITS2; - rb=n%BN_BITS2; - lb=BN_BITS2-rb; -// Changed "nw > a->top || a->top == 0" to nw >= a->top" as considering this a bug: - if (nw >= a->top) - { - BN_zero(r); - return(1); - } - if (r != a) - { - r->neg=a->neg; - if (bn_wexpand(r,a->top-nw+1) == NULL) return(0); - } - else - { - if (n == 0) - return 1; /* or the copying loop will go berserk */ - } - - f= &(a->d[nw]); - t=r->d; - j=a->top-nw; - r->top=j; - - if (rb == 0) - { - for (i=j; i != 0; i--) - *(t++)= *(f++); - } - else - { - l= *(f++); - for (i=j-1; i != 0; i--) - { - tmp =(l>>rb)&BN_MASK2; - l= *(f++); - *(t++) =(tmp|(l<<lb))&BN_MASK2; - } - *(t++) =(l>>rb)&BN_MASK2; - } - bn_correct_top(r); - bn_check_top(r); - return(1); + return (n >= 0) ? BN_lshift(r, a, n) : BN_rshift(r, a, -n); } - /** * public static native boolean BN_add_word(int, int) */ @@ -698,7 +639,7 @@ static jboolean NativeBN_BN_mod_inverse(JNIEnv* env, jclass cls, BIGNUM* ret, BI static jboolean NativeBN_BN_generate_prime_ex(JNIEnv* env, jclass cls, BIGNUM* ret, int bits, jboolean safe, BIGNUM* add, BIGNUM* rem, jint cb) { if (!oneValidHandle(env, ret)) return FALSE; - return BN_generate_prime_ex(ret, bits, safe, add, rem, cb); + return BN_generate_prime_ex(ret, bits, safe, add, rem, (BN_GENCB*) cb); } /** @@ -706,7 +647,7 @@ static jboolean NativeBN_BN_generate_prime_ex(JNIEnv* env, jclass cls, BIGNUM* r */ static jboolean NativeBN_BN_is_prime_ex(JNIEnv* env, jclass cls, BIGNUM* p, int nchecks, BN_CTX* ctx, jint cb) { if (!oneValidHandle(env, p)) return FALSE; - return BN_is_prime_ex(p, nchecks, ctx, cb); + return BN_is_prime_ex(p, nchecks, ctx, (BN_GENCB*) cb); } @@ -740,7 +681,7 @@ static JNINativeMethod METHODS[] = { { "bitLength", "(I)I", (void*)NativeBN_bitLength }, { "BN_is_bit_set", "(II)Z", (void*)NativeBN_BN_is_bit_set }, { "modifyBit", "(III)Z", (void*)NativeBN_modifyBit }, - { "BN_lshift", "(III)Z", (void*)NativeBN_BN_lshift }, + { "BN_shift", "(III)Z", (void*)NativeBN_BN_shift }, { "BN_add_word", "(II)Z", (void*)NativeBN_BN_add_word }, { "BN_sub_word", "(II)Z", (void*)NativeBN_BN_sub_word }, { "BN_mul_word", "(II)Z", (void*)NativeBN_BN_mul_word }, diff --git a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java index 29ff362..d2dd841 100644 --- a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java +++ b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Suite for org.apache.harmony.prefs.tests.java.util.prefs"); + TestSuite suite = new TestSuite("Suite for org.apache.harmony.prefs.tests.java.util.prefs"); // $JUnit-BEGIN$ suite.addTestSuite(NodeChangeListenerTest.class); suite.addTestSuite(PreferenceChangeListenerTest.class); diff --git a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/PreferencesTest.java b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/PreferencesTest.java index 122dacd..c6e0861 100644 --- a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/PreferencesTest.java +++ b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/PreferencesTest.java @@ -213,7 +213,6 @@ public class PreferencesTest extends TestCase { method = "importPreferences", args = {java.io.InputStream.class} ) - @KnownFailure("xml validation does not work") public void testImportPreferences2() throws Exception { InputStream in = PreferencesTest.class .getResourceAsStream("/prefs/java/util/prefs/userprefs-badtype.xml"); diff --git a/prefs/src/test/java/tests/prefs/AllTests.java b/prefs/src/test/java/tests/prefs/AllTests.java index b3f2ed6..4d99023 100644 --- a/prefs/src/test/java/tests/prefs/AllTests.java +++ b/prefs/src/test/java/tests/prefs/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Prefs test suites"); + TestSuite suite = new TestSuite("All Prefs test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.prefs.tests.java.util.prefs.AllTests.suite()); // $JUnit-END$ diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java index b69c401..55d3bf0 100644 --- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java +++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; * Provides a test suite for java.util.regex package. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util.regex"); + TestSuite suite = new TestSuite("Tests for java.util.regex"); //$JUnit-BEGIN$ suite.addTestSuite(Matcher2Test.class); diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java index 5e9137b..adb3bc7 100644 --- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java +++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java @@ -1464,8 +1464,4 @@ public class MatcherTest extends TestCase { assertTrue(pattern.matcher("14pt").matches()); } - public static void main(String[] args) { - junit.textui.TestRunner.run(MatcherTest.class); - } - } diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java index c21a81d..5b979cf 100644 --- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java +++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java @@ -2377,10 +2377,6 @@ public void testRestoreFlagsAfterGroup() { assertTrue(matcher.find()); } - public static void main(String[] args) { - junit.textui.TestRunner.run(PatternTest.class); - } - @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "The test doesn't verify Matcher and should be moved to PatterTest.", diff --git a/regex/src/test/java/tests/regex/AllTests.java b/regex/src/test/java/tests/regex/AllTests.java index d590d08..07feebc 100644 --- a/regex/src/test/java/tests/regex/AllTests.java +++ b/regex/src/test/java/tests/regex/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the regex project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All regex test suites"); + TestSuite suite = new TestSuite("All regex test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.regex.tests.java.util.regex.AllTests.suite()); // $JUnit-END$ diff --git a/run-core-tests b/run-core-tests index 3359dde..171ee21 100755 --- a/run-core-tests +++ b/run-core-tests @@ -1,3 +1,4 @@ +# -*- mode: bash -*- # # Copyright (C) 2007 The Android Open Source Project # @@ -13,24 +14,32 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Run all the tests contained in the core-tests library. -# -# To install this script and the tests on a device: -# $ make (only necessary once) -# $ make CtsCoreTests snod (to create a system.img containing these files) -# OR -# $ make CtsCoreTests && adb sync (to push these files to a running system) +# To run these tests: +# mmm -j14 dalvik snod +# adb reboot && fastboot flashall +# adb shell run-core-tests tmp=/data/core-tests.tmp mkdir $tmp chmod 777 $tmp +# Build the classpath by putting together the jar file for each module. +classpath="/system/framework/sqlite-jdbc.jar" # Bonus item for jdbc testing. +modules="annotation archive concurrent crypto dom icu json \ + logging luni-kernel luni math nio nio_char prefs regex security sql \ + suncompat support text x-net xml" +for module in $modules; do + classpath="$classpath:/system/framework/core-tests-$module.jar" +done + exec dalvikvm \ -Duser.name=root \ -Duser.language=en \ -Duser.region=US \ + -Duser.dir=$tmp \ + -Duser.home=$tmp \ -Djava.io.tmpdir=$tmp \ -Djavax.net.ssl.trustStore=/system/etc/security/cacerts.bks \ - -classpath /system/framework/core-tests.jar \ + -classpath $classpath \ -Xcheck:jni \ -Xmx64M com.google.coretests.Main "$@" diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java index a2008de..9825291 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java @@ -41,14 +41,6 @@ import junit.framework.TestCase; public class AccessControlExceptionTest extends TestCase { /** - * Entry point for standalone run. - * @param args command line arguments - */ - public static void main(String[] args) { - junit.textui.TestRunner.run(AccessControlExceptionTest.class); - } - - /** * Tests AccessControlException(String) */ @TestTargetNew( diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java index 1ff236a..69c994d 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java @@ -478,10 +478,6 @@ public class AlgorithmParameterGenerator1Test extends TestCase { } catch (NullPointerException e) { } } - - public static void main(String args[]) { - junit.textui.TestRunner.run(AlgorithmParameterGenerator1Test.class); - } } /** * Additional class to verify AlgorithmParameterGenerator constructor diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java index 5ec3d96..f65cc80 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java @@ -126,9 +126,5 @@ public class AlgorithmParametersSpiTest extends TestCase { } } - public static void main(String args[]) { - junit.textui.TestRunner.run(AlgorithmParametersSpiTest.class); - } - class MyAlgorithmParameterSpec implements AlgorithmParameterSpec {} } diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java index 089a7db..c0d5640 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.security.tests.java.security;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.security.tests.java.security;"); // $JUnit-BEGIN$ suite.addTestSuite(AccessControlException2Test.class); diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java index e29d9ac..f94cb27 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java @@ -41,15 +41,6 @@ import junit.framework.TestCase; */ public class CodeSignerTest extends TestCase { - - /** - * Entry point for standalone runs. - * @param args command line arguments - */ - public static void main(String[] args) { - junit.textui.TestRunner.run(CodeSignerTest.class); - } - private CertPath cpath = TestCertUtils.genCertPath(3, 0); private Date now = new Date(); diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java index 276dfd7..eeef8ac 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java @@ -47,16 +47,6 @@ import junit.framework.TestCase; */ public class CodeSourceTest extends TestCase { - /** - * - * Entry point for standalone runs. - * - * @param args command line arguments - */ - public static void main(String[] args) throws Exception { - junit.textui.TestRunner.run(CodeSourceTest.class); - } - private java.security.cert.Certificate[] chain = null; /* Below are various URLs used during the testing */ diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java index a1b0365..e717747 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java @@ -39,10 +39,6 @@ import junit.framework.TestCase; public class GuardedObjectTest extends TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(GuardedObjectTest.class); - } - /** Null guard imposes no restriction. */ @TestTargets({ @TestTargetNew( diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java index 5b1ea7f..c11f90a 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java @@ -51,10 +51,6 @@ public class IdentityScopeTest extends TestCase { } } - public static void main(String[] args) { - junit.textui.TestRunner.run(IdentityScopeTest.class); - } - IdentityScope is; /** diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java index dc7880f..0cb1400 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java @@ -231,10 +231,6 @@ public class KSPrivateKeyEntryTest extends TestCase { return new TestSuite(KSPrivateKeyEntryTest.class); } - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } - private static class tmpPrivateKey implements PrivateKey { private String alg = "My algorithm"; diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java index 742cc13..efa9bf0 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java @@ -650,8 +650,4 @@ public class KeyPairGenerator1Test extends TestCase { fail("Unexpected InvalidAlgorithmParameterException was thrown"); } } - - public static void main(String args[]) { - junit.textui.TestRunner.run(KeyPairGenerator1Test.class); - } } diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java index 9a8c5c5..5fe110c 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java @@ -505,7 +505,4 @@ public class KeyPairGenerator2Test extends TestCase { setProv(); GetInstance03(4); } - public static void main(String args[]) { - junit.textui.TestRunner.run(KeyPairGenerator2Test.class); - } } diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java index 69ec7a7..24867e7 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java @@ -191,10 +191,6 @@ public class KeyPairGenerator3Test extends TestCase { } } - public static void main(String args[]) { - junit.textui.TestRunner.run(KeyPairGenerator3Test.class); - } - /** * Additional class to verify KeyPairGenerator constructor */ diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java index 8d75921..689e6ce 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java @@ -104,9 +104,6 @@ public class KeyPairGeneratorSpiTest extends TestCase { KeyPair kp = keyPairGen.generateKeyPair(); assertNull("Not null KeyPair", kp); } - public static void main(String args[]) { - junit.textui.TestRunner.run(KeyPairGeneratorSpiTest.class); - } class MyAlgorithmParameterSpec implements AlgorithmParameterSpec {} diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java index 2ccca0e..9f25a7b 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java @@ -424,12 +424,6 @@ public class KeyStoreSpiTest extends TestCase { } catch (UnsupportedOperationException e) { } } - - public static void main(String args[]) { - junit.textui.TestRunner.run(KeyStoreSpiTest.class); - } - - } /** @@ -487,4 +481,4 @@ class MyCertificate extends Certificate { } }; } -}
\ No newline at end of file +} diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java index 13d4d62..f1a3cf3 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java @@ -36,11 +36,6 @@ import dalvik.annotation.TestTargetNew; */ public class PermissionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(PermissionTest.class); - } - // Bare extension to instantiate abstract Permission class static final class RealPermission extends Permission { diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java index 5680e2e..99d39f3 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java @@ -49,11 +49,6 @@ import junit.framework.TestCase; */ public class PermissionsTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(PermissionsTest.class); - } - /** * Can add any type of permissions. Cannot add if collection is read-only. */ diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java index ce57328..1f64d34 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java @@ -57,10 +57,6 @@ public class PolicyTest extends TestCase { public static final String JAVA_SECURITY_POLICY = "java.security.policy"; - public static void main(String[] args) { - junit.textui.TestRunner.run(PolicyTest.class); - } - @Override protected void tearDown() throws Exception { TestEnvironment.reset(); super.tearDown(); diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java index 99fce26..f1e1b42 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java @@ -38,14 +38,6 @@ import junit.framework.TestCase; public class PrivilegedActionExceptionTest extends TestCase { /** - * Entry point for standalone runs. - * @param args command line arguments - */ - public static void main(String[] args) { - junit.textui.TestRunner.run(PrivilegedActionExceptionTest.class); - } - - /** * Tests PrivilegedActionException(Exception) */ @TestTargetNew( @@ -89,4 +81,4 @@ public class PrivilegedActionExceptionTest extends TestCase { assertNotNull(new PrivilegedActionException(new Exception()).toString()); } -}
\ No newline at end of file +} diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java index 451cad4..7397a08 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java @@ -48,14 +48,6 @@ import junit.framework.TestCase; public class ProtectionDomainTest extends TestCase { - /** - * Entry point for standalone runs. - * @param args command line arguments - */ - public static void main(String[] args) { - junit.textui.TestRunner.run(ProtectionDomainTest.class); - } - private final AllPermission allperm = new AllPermission(); private URL url = null; diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java index 2531c81..fcda610 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java @@ -36,11 +36,6 @@ import junit.framework.TestCase; * */ public class SecurityPermissionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(SecurityPermissionTest.class); - } - /** * Check all constructors: an object is created with the specified valid name. * If name equal null then NPE should be thrown. diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java index 898ab17..267221c 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java @@ -57,10 +57,6 @@ public class SignerTest extends TestCase { if (denied!=null && denied.implies(permission)) throw new SecurityException(); } } - - public static void main(String[] args) { - junit.textui.TestRunner.run(SignerTest.class); - } /** * @tests java.security.Signer#toString() diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java index 1015521..f965337 100644 --- a/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java +++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java @@ -41,11 +41,6 @@ import junit.framework.TestCase; */ public class TimestampTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(TimestampTest.class); - } - private Date now = new Date(); private static final byte[] encoding = { 1, 2, 3 }; diff --git a/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java b/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java index e9fbdb0..f9bf52f 100644 --- a/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java +++ b/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java @@ -20,14 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "All tests for " + AllTests.class.getPackage()); + TestSuite suite = new TestSuite("All tests for " + AllTests.class.getPackage()); suite.addTestSuite(PKIXCertPathValidatorSpiTest.class); return suite; } diff --git a/security/src/test/java/tests/api/java/security/AllTests.java b/security/src/test/java/tests/api/java/security/AllTests.java index 679f860..7f83780 100644 --- a/security/src/test/java/tests/api/java/security/AllTests.java +++ b/security/src/test/java/tests/api/java/security/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.security;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.security;"); // $JUnit-BEGIN$ suite.addTestSuite(AccessControlContextTest.class); diff --git a/security/src/test/java/tests/api/javax/security/auth/AllTests.java b/security/src/test/java/tests/api/javax/security/auth/AllTests.java index b5b7f18..bd4ae74 100644 --- a/security/src/test/java/tests/api/javax/security/auth/AllTests.java +++ b/security/src/test/java/tests/api/javax/security/auth/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.javax.security.auth;"); + TestSuite suite = new TestSuite("All tests for package tests.api.javax.security.auth;"); // $JUnit-BEGIN$ suite.addTestSuite(AuthPermissionTest.class); diff --git a/security/src/test/java/tests/api/javax/security/cert/AllTests.java b/security/src/test/java/tests/api/javax/security/cert/AllTests.java index 4516bc1..30921bd 100644 --- a/security/src/test/java/tests/api/javax/security/cert/AllTests.java +++ b/security/src/test/java/tests/api/javax/security/cert/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.javax.security.cert;"); + TestSuite suite = new TestSuite("All tests for package tests.api.javax.security.cert;"); // $JUnit-BEGIN$ suite.addTestSuite(CertificateEncodingExceptionTest.class); diff --git a/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java b/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java index c4d10f6..38afce6 100644 --- a/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java +++ b/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java @@ -191,8 +191,4 @@ public class CertificateTest extends TestCase { public static Test suite() { return new TestSuite(CertificateTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java b/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java index 4af8dc8..79b7b00 100644 --- a/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java +++ b/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java @@ -904,8 +904,4 @@ public class X509CertificateTest extends TestCase { public static Test suite() { return new TestSuite(X509CertificateTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/security/src/test/java/tests/java/security/AllPermissionTest.java b/security/src/test/java/tests/java/security/AllPermissionTest.java index e9668ad..2db54b0 100644 --- a/security/src/test/java/tests/java/security/AllPermissionTest.java +++ b/security/src/test/java/tests/java/security/AllPermissionTest.java @@ -40,10 +40,6 @@ import junit.framework.TestCase; */ public class AllPermissionTest extends TestCase { - public static void main(String[] args) { - junit.textui.TestRunner.run(AllPermissionTest.class); - } - /** * Test all constructors: an object is created, name and actions are ignored */ diff --git a/security/src/test/java/tests/java/security/AllTests.java b/security/src/test/java/tests/java/security/AllTests.java index 61396df..6dadd07 100644 --- a/security/src/test/java/tests/java/security/AllTests.java +++ b/security/src/test/java/tests/java/security/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.java.security;"); + TestSuite suite = new TestSuite("All tests for package tests.java.security;"); // $JUnit-BEGIN$ suite.addTestSuite(AlgorithmParameterGeneratorSpiTest.class); diff --git a/security/src/test/java/tests/java/security/BasicPermissionTest.java b/security/src/test/java/tests/java/security/BasicPermissionTest.java index 4987ab4..75661ae 100644 --- a/security/src/test/java/tests/java/security/BasicPermissionTest.java +++ b/security/src/test/java/tests/java/security/BasicPermissionTest.java @@ -38,11 +38,6 @@ import junit.framework.TestCase; */ @TestTargetClass(BasicPermission.class) public class BasicPermissionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(BasicPermissionTest.class); - } - /** * Check all constructors: an object is created with the specified valid name. * If name equal null then NPE should be thrown. diff --git a/security/src/test/java/tests/java/security/IdentityTest.java b/security/src/test/java/tests/java/security/IdentityTest.java index 3566ecf..470936e 100644 --- a/security/src/test/java/tests/java/security/IdentityTest.java +++ b/security/src/test/java/tests/java/security/IdentityTest.java @@ -56,10 +56,6 @@ public class IdentityTest extends TestCase { } } - public static void main(String[] args) { - junit.textui.TestRunner.run(IdentityTest.class); - } - @TestTargetNew( level = TestLevel.PARTIAL, notes = "Method's returned variable is not checked", diff --git a/security/src/test/java/tests/java/security/SecureClassLoaderTest.java b/security/src/test/java/tests/java/security/SecureClassLoaderTest.java index 1dfaae6..6ce1659 100644 --- a/security/src/test/java/tests/java/security/SecureClassLoaderTest.java +++ b/security/src/test/java/tests/java/security/SecureClassLoaderTest.java @@ -64,16 +64,6 @@ import java.security.cert.Certificate; public class SecureClassLoaderTest extends TestCase { /** - * Entry point for stand alone runs. - * - * @param args - * command line parameters - */ - public static void main(String[] args) { - junit.textui.TestRunner.run(SecureClassLoaderTest.class); - } - - /** * A class name for the class presented as {@link #klassData bytecode below} */ private static final String klassName = "HiWorld"; diff --git a/security/src/test/java/tests/security/AllTests.java b/security/src/test/java/tests/security/AllTests.java index a88cc0e..7a790c9 100644 --- a/security/src/test/java/tests/security/AllTests.java +++ b/security/src/test/java/tests/security/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the security project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All security test suites"); + TestSuite suite = new TestSuite("All security test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.security.tests.java.security.AllTests.suite()); suite.addTest(org.bouncycastle.jce.provider.AllTests.suite()); diff --git a/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java b/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java index cfd0bb0..cbee130 100644 --- a/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java +++ b/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java @@ -37,11 +37,6 @@ import java.security.acl.AclNotFoundException; */ @TestTargetClass(AclNotFoundException.class) public class AclNotFoundExceptionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AclNotFoundExceptionTest.class); - } - /** * check default constructor */ diff --git a/security/src/test/java/tests/security/acl/AllTests.java b/security/src/test/java/tests/security/acl/AllTests.java index 4b93980..9a6f2b4 100644 --- a/security/src/test/java/tests/security/acl/AllTests.java +++ b/security/src/test/java/tests/security/acl/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.security.acl;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.security.acl;"); // $JUnit-BEGIN$ suite.addTestSuite(AclNotFoundException2Test.class); diff --git a/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java b/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java index b76f456..3cd14ff 100644 --- a/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java +++ b/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java @@ -22,11 +22,6 @@ package tests.security.acl; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import java.security.acl.LastOwnerException; @@ -35,18 +30,7 @@ import java.security.acl.LastOwnerException; * Unit test for LastOwnerException. * */ -@TestTargetClass(LastOwnerException.class) public class LastOwnerExceptionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(LastOwnerExceptionTest.class); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "LastOwnerException", - args = {} - ) public void testLastOwnerException() { assertNotNull(new LastOwnerException()); assertNull(new LastOwnerException().getMessage()); diff --git a/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java b/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java index c3dfe34..67ef38b 100644 --- a/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java +++ b/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java @@ -22,11 +22,6 @@ package tests.security.acl; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - import junit.framework.TestCase; import java.security.acl.NotOwnerException; @@ -35,18 +30,7 @@ import java.security.acl.NotOwnerException; * Unit test for NotOwnerException. * */ -@TestTargetClass(NotOwnerException.class) public class NotOwnerExceptionTest extends TestCase { - - public static void main(String[] args) { - junit.textui.TestRunner.run(NotOwnerExceptionTest.class); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "NotOwnerException", - args = {} - ) public void testNotOwnerException() { assertNotNull(new NotOwnerException()); assertNull(new NotOwnerException().getMessage()); diff --git a/security/src/test/java/tests/security/cert/AllTests.java b/security/src/test/java/tests/security/cert/AllTests.java index 749a5ab..e5b9d47 100644 --- a/security/src/test/java/tests/security/cert/AllTests.java +++ b/security/src/test/java/tests/security/cert/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.security.cert;"); + TestSuite suite = new TestSuite("All tests for package tests.api.java.security.cert;"); // $JUnit-BEGIN$ suite.addTestSuite(CRLExceptionTest.class); diff --git a/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java b/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java index 1c45e57..d472bc4 100644 --- a/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java +++ b/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java @@ -522,11 +522,6 @@ public class CertPathBuilder1Test extends TestCase { } } - - public static void main(String args[]) { - junit.textui.TestRunner.run(CertPathBuilder1Test.class); - } - } /** * Additional class to verify CertPathBuilder constructor diff --git a/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java b/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java index fcf235e..af9de90 100644 --- a/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java +++ b/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java @@ -265,9 +265,4 @@ public class CertPathBuilder2Test extends TestCase { checkResult(cerPB); } } - public static void main(String args[]) { - junit.textui.TestRunner.run(CertPathBuilder2Test.class); - } - - } diff --git a/security/src/test/java/tests/security/cert/CertPathValidator1Test.java b/security/src/test/java/tests/security/cert/CertPathValidator1Test.java index a76af78..101644d 100644 --- a/security/src/test/java/tests/security/cert/CertPathValidator1Test.java +++ b/security/src/test/java/tests/security/cert/CertPathValidator1Test.java @@ -526,10 +526,6 @@ public class CertPathValidator1Test extends TestCase { defaultProvider); } } - - public static void main(String args[]) { - junit.textui.TestRunner.run(CertPathValidator1Test.class); - } } /** * Additional class to verify CertPathValidator constructor diff --git a/security/src/test/java/tests/security/cert/CertStoreSpiTest.java b/security/src/test/java/tests/security/cert/CertStoreSpiTest.java index 3cac01f..4760871 100644 --- a/security/src/test/java/tests/security/cert/CertStoreSpiTest.java +++ b/security/src/test/java/tests/security/cert/CertStoreSpiTest.java @@ -97,10 +97,6 @@ public class CertStoreSpiTest extends TestCase { return new TestSuite(CertStoreSpiTest.class); } - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } - /** * Additional classes for verification CertStoreSpi class */ diff --git a/security/src/test/java/tests/security/cert/CertificateFactory1Test.java b/security/src/test/java/tests/security/cert/CertificateFactory1Test.java index 42677eb..04112a2 100644 --- a/security/src/test/java/tests/security/cert/CertificateFactory1Test.java +++ b/security/src/test/java/tests/security/cert/CertificateFactory1Test.java @@ -887,10 +887,6 @@ public class CertificateFactory1Test extends TestCase { fail("Unexpected exception" + e); } } - - public static void main(String[] args) { - junit.textui.TestRunner.run(CertificateFactory1Test.class); - } } /** * Additional class to verify CertificateFactory constructor diff --git a/security/src/test/java/tests/security/cert/X509CRLEntryTest.java b/security/src/test/java/tests/security/cert/X509CRLEntryTest.java index 1eec127..3f82f67 100644 --- a/security/src/test/java/tests/security/cert/X509CRLEntryTest.java +++ b/security/src/test/java/tests/security/cert/X509CRLEntryTest.java @@ -266,9 +266,5 @@ public class X509CRLEntryTest extends TestCase { public static Test suite() { return new TestSuite(X509CRLEntryTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/security/src/test/java/tests/security/cert/X509CRLTest.java b/security/src/test/java/tests/security/cert/X509CRLTest.java index c10494e..4dd98cb 100644 --- a/security/src/test/java/tests/security/cert/X509CRLTest.java +++ b/security/src/test/java/tests/security/cert/X509CRLTest.java @@ -457,9 +457,5 @@ public class X509CRLTest extends TestCase { public static Test suite() { return new TestSuite(X509CRLTest.class); } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } } diff --git a/security/src/test/java/tests/security/interfaces/AllTests.java b/security/src/test/java/tests/security/interfaces/AllTests.java index e665119..e180408 100644 --- a/security/src/test/java/tests/security/interfaces/AllTests.java +++ b/security/src/test/java/tests/security/interfaces/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.security.interfaces;"); + TestSuite suite = new TestSuite("All tests for package tests.security.interfaces;"); // $JUnit-BEGIN$ suite.addTestSuite(DSAKeyTest.class); diff --git a/security/src/test/java/tests/security/spec/AllTests.java b/security/src/test/java/tests/security/spec/AllTests.java index f643618..151e0a7 100644 --- a/security/src/test/java/tests/security/spec/AllTests.java +++ b/security/src/test/java/tests/security/spec/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.security.spec;"); + TestSuite suite = new TestSuite("All tests for package tests.security.spec;"); // $JUnit-BEGIN$ suite.addTestSuite(DSAParameterSpecTest.class); diff --git a/security/src/test/java/tests/targets/security/AllTests.java b/security/src/test/java/tests/targets/security/AllTests.java index 6bd6d05..7d5802d 100644 --- a/security/src/test/java/tests/targets/security/AllTests.java +++ b/security/src/test/java/tests/targets/security/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.targets.security;"); + TestSuite suite = new TestSuite("All tests for package tests.targets.security;"); // $JUnit-BEGIN$ suite.addTestSuite(MessageDigestTestMD2.class); @@ -75,4 +70,4 @@ public class AllTests { // $JUnit-END$ return suite; } -}
\ No newline at end of file +} diff --git a/security/src/test/java/tests/targets/security/cert/AllTests.java b/security/src/test/java/tests/targets/security/cert/AllTests.java index 50292e2..c0c411d 100644 --- a/security/src/test/java/tests/targets/security/cert/AllTests.java +++ b/security/src/test/java/tests/targets/security/cert/AllTests.java @@ -19,13 +19,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.targets.security.certs;"); + TestSuite suite = new TestSuite("All tests for package tests.targets.security.certs;"); // $JUnit-BEGIN$ suite.addTestSuite(CertificateTest.class); @@ -36,4 +31,4 @@ public class AllTests { // $JUnit-END$ return suite; } -}
\ No newline at end of file +} diff --git a/sql/src/main/java/SQLite/Constants.java b/sql/src/main/java/SQLite/Constants.java deleted file mode 100644 index 4e636b9..0000000 --- a/sql/src/main/java/SQLite/Constants.java +++ /dev/null @@ -1,157 +0,0 @@ -/* DO NOT EDIT */ - -package SQLite; - -/** - * Container for SQLite constants. - */ - -public final class Constants { - /* - * Error code: 0 - */ - public static final int SQLITE_OK = 0; - /* - * Error code: 1 - */ - public static final int SQLITE_ERROR = 1; - /* - * Error code: 2 - */ - public static final int SQLITE_INTERNAL = 2; - /* - * Error code: 3 - */ - public static final int SQLITE_PERM = 3; - /* - * Error code: 4 - */ - public static final int SQLITE_ABORT = 4; - /* - * Error code: 5 - */ - public static final int SQLITE_BUSY = 5; - /* - * Error code: 6 - */ - public static final int SQLITE_LOCKED = 6; - /* - * Error code: 7 - */ - public static final int SQLITE_NOMEM = 7; - /* - * Error code: 8 - */ - public static final int SQLITE_READONLY = 8; - /* - * Error code: 9 - */ - public static final int SQLITE_INTERRUPT = 9; - /* - * Error code: 10 - */ - public static final int SQLITE_IOERR = 10; - /* - * Error code: 11 - */ - public static final int SQLITE_CORRUPT = 11; - /* - * Error code: 12 - */ - public static final int SQLITE_NOTFOUND = 12; - /* - * Error code: 13 - */ - public static final int SQLITE_FULL = 13; - /* - * Error code: 14 - */ - public static final int SQLITE_CANTOPEN = 14; - /* - * Error code: 15 - */ - public static final int SQLITE_PROTOCOL = 15; - /* - * Error code: 16 - */ - public static final int SQLITE_EMPTY = 16; - /* - * Error code: 17 - */ - public static final int SQLITE_SCHEMA = 17; - /* - * Error code: 18 - */ - public static final int SQLITE_TOOBIG = 18; - /* - * Error code: 19 - */ - public static final int SQLITE_CONSTRAINT = 19; - /* - * Error code: 20 - */ - public static final int SQLITE_MISMATCH = 20; - /* - * Error code: 21 - */ - public static final int SQLITE_MISUSE = 21; - /* - * Error code: 22 - */ - public static final int SQLITE_NOLFS = 22; - /* - * Error code: 23 - */ - public static final int SQLITE_AUTH = 23; - /* - * Error code: 24 - */ - public static final int SQLITE_FORMAT = 24; - /* - * Error code: 25 - */ - public static final int SQLITE_RANGE = 25; - /* - * Error code: 26 - */ - public static final int SQLITE_NOTADB = 26; - public static final int SQLITE_ROW = 100; - public static final int SQLITE_DONE = 101; - 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; - public static final int SQLITE_TEXT = 3; - public static final int SQLITE2_TEXT = -2; - public static final int SQLITE_ARGS = -3; - public static final int SQLITE_COPY = 0; - public static final int SQLITE_CREATE_INDEX = 1; - public static final int SQLITE_CREATE_TABLE = 2; - public static final int SQLITE_CREATE_TEMP_INDEX = 3; - public static final int SQLITE_CREATE_TEMP_TABLE = 4; - public static final int SQLITE_CREATE_TEMP_TRIGGER = 5; - public static final int SQLITE_CREATE_TEMP_VIEW = 6; - public static final int SQLITE_CREATE_TRIGGER = 7; - public static final int SQLITE_CREATE_VIEW = 8; - public static final int SQLITE_DELETE = 9; - public static final int SQLITE_DROP_INDEX = 10; - public static final int SQLITE_DROP_TABLE = 11; - public static final int SQLITE_DROP_TEMP_INDEX = 12; - public static final int SQLITE_DROP_TEMP_TABLE = 13; - public static final int SQLITE_DROP_TEMP_TRIGGER = 14; - public static final int SQLITE_DROP_TEMP_VIEW = 15; - public static final int SQLITE_DROP_TRIGGER = 16; - public static final int SQLITE_DROP_VIEW = 17; - public static final int SQLITE_INSERT = 18; - public static final int SQLITE_PRAGMA = 19; - public static final int SQLITE_READ = 20; - public static final int SQLITE_SELECT = 21; - public static final int SQLITE_TRANSACTION = 22; - public static final int SQLITE_UPDATE = 23; - public static final int SQLITE_ATTACH = 24; - public static final int SQLITE_DETACH = 25; - public static final int SQLITE_DENY = 1; - public static final int SQLITE_IGNORE = 2; -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCConnection.java b/sql/src/main/java/SQLite/JDBC2y/JDBCConnection.java deleted file mode 100644 index 20c98e3..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCConnection.java +++ /dev/null @@ -1,452 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; -import java.util.*; - -public class JDBCConnection - implements java.sql.Connection, SQLite.BusyHandler { - - /** - * Open database. - */ - protected DatabaseX db; - - /** - * Database URL. - */ - protected String url; - - /** - * Character encoding. - */ - protected String enc; - - /** - * Autocommit flag, true means autocommit. - */ - protected boolean autocommit = true; - - /** - * In-transaction flag. - * Can be true only when autocommit false. - */ - protected boolean intrans = false; - - /** - * Timeout for Database.exec() - */ - protected int timeout = 1000000; - - /** - * File name of database. - */ - private String dbfile = null; - - /** - * Reference to meta data or null. - */ - private JDBCDatabaseMetaData meta = null; - - /** - * Base time value for timeout handling. - */ - private long t0; - - /** - * Database in readonly mode. - */ - private boolean readonly = false; - - - private boolean busy0(DatabaseX db, int count) { - if (count <= 1) { - t0 = System.currentTimeMillis(); - } - if (db != null) { - long t1 = System.currentTimeMillis(); - if (t1 - t0 > timeout) { - return false; - } - db.wait(100); - return true; - } - return false; - } - - public boolean busy(String table, int count) { - return busy0(db, count); - } - - protected boolean busy3(DatabaseX db, int count) { - if (count <= 1) { - t0 = System.currentTimeMillis(); - } - if (db != null) { - long t1 = System.currentTimeMillis(); - if (t1 - t0 > timeout) { - return false; - } - return true; - } - return false; - } - - private DatabaseX open(boolean readonly) throws SQLException { - DatabaseX db = null; - try { - db = new DatabaseX(); - db.open(dbfile, readonly ? 0444 : 0644); - db.set_encoding(enc); - } catch (SQLite.Exception e) { - throw new SQLException(e.toString()); - } - int loop = 0; - while (true) { - try { - db.exec("PRAGMA short_column_names = off;", null); - db.exec("PRAGMA full_column_names = on;", null); - db.exec("PRAGMA empty_result_callbacks = on;", null); - if (SQLite.Database.version().compareTo("2.6.0") >= 0) { - db.exec("PRAGMA show_datatypes = on;", null); - } - } catch (SQLite.Exception e) { - if (db.last_error() != SQLite.Constants.SQLITE_BUSY || - !busy0(db, ++loop)) { - try { - db.close(); - } catch (SQLite.Exception ee) { - } - throw new SQLException(e.toString()); - } - continue; - } - break; - } - return db; - } - - public JDBCConnection(String url, String enc) throws SQLException { - if (url.startsWith("sqlite:/")) { - dbfile = url.substring(8); - } else if (url.startsWith("jdbc:sqlite:/")) { - dbfile = url.substring(13); - } else { - throw new SQLException("unsupported url"); - } - this.url = url; - this.enc = enc; - try { - db = open(readonly); - db.busy_handler(this); - } catch (SQLException e) { - if (db != null) { - try { - db.close(); - } catch (SQLite.Exception ee) { - } - } - throw e; - } - } - - /* non-standard */ - public SQLite.Database getSQLiteDatabase() { - return (SQLite.Database) db; - } - - public Statement createStatement() { - JDBCStatement s = new JDBCStatement(this); - return s; - } - - public Statement createStatement(int resultSetType, - int resultSetConcurrency) - throws SQLException { - JDBCStatement s = new JDBCStatement(this); - return s; - } - - public DatabaseMetaData getMetaData() throws SQLException { - if (meta == null) { - meta = new JDBCDatabaseMetaData(this); - } - return meta; - } - - public void close() throws SQLException { - try { - rollback(); - } catch (SQLException e) { - /* ignored */ - } - intrans = false; - if (db != null) { - try { - db.close(); - db = null; - } catch (SQLite.Exception e) { - throw new SQLException(e.toString()); - } - } - } - - public boolean isClosed() throws SQLException { - return db == null; - } - - public boolean isReadOnly() throws SQLException { - return readonly; - } - - public void clearWarnings() throws SQLException { - } - - public void commit() throws SQLException { - if (db == null) { - throw new SQLException("stale connection"); - } - if (!intrans) { - return; - } - try { - db.exec("COMMIT", null); - intrans = false; - } catch (SQLite.Exception e) { - throw new SQLException(e.toString()); - } - } - - public boolean getAutoCommit() throws SQLException { - return autocommit; - } - - public String getCatalog() throws SQLException { - return null; - } - - public int getTransactionIsolation() throws SQLException { - return TRANSACTION_SERIALIZABLE; - } - - public SQLWarning getWarnings() throws SQLException { - return null; - } - - public String nativeSQL(String sql) throws SQLException { - throw new SQLException("not supported"); - } - - public CallableStatement prepareCall(String sql) throws SQLException { - throw new SQLException("not supported"); - } - - public CallableStatement prepareCall(String sql, int x, int y) - throws SQLException { - throw new SQLException("not supported"); - } - - public PreparedStatement prepareStatement(String sql) throws SQLException { - JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql); - return s; - } - - public PreparedStatement prepareStatement(String sql, int resultSetType, - int resultSetConcurrency) - throws SQLException { - JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql); - return s; - } - - public void rollback() throws SQLException { - if (db == null) { - throw new SQLException("stale connection"); - } - if (!intrans) { - return; - } - try { - db.exec("ROLLBACK", null); - intrans = false; - } catch (SQLite.Exception e) { - throw new SQLException(e.toString()); - } - } - - public void setAutoCommit(boolean ac) throws SQLException { - if (ac && intrans && db != null) { - try { - db.exec("ROLLBACK", null); - } catch (SQLite.Exception e) { - throw new SQLException(e.toString()); - } - } - intrans = false; - autocommit = ac; - } - - public void setCatalog(String catalog) throws SQLException { - } - - public void setReadOnly(boolean ro) throws SQLException { - if (intrans) { - throw new SQLException("incomplete transaction"); - } - if (ro != readonly) { - DatabaseX db = null; - try { - db = open(ro); - this.db.close(); - this.db = db; - db = null; - readonly = ro; - } catch (SQLException e) { - throw e; - } catch (SQLite.Exception ee) { - if (db != null) { - try { - db.close(); - } catch (SQLite.Exception eee) { - } - } - throw new SQLException(ee.toString()); - } - } - } - - public void setTransactionIsolation(int level) throws SQLException { - if (level != TRANSACTION_SERIALIZABLE) { - throw new SQLException("not supported"); - } - } - - public java.util.Map<String, Class<?>> getTypeMap() throws SQLException { - throw new SQLException("not supported"); - } - - public void setTypeMap(java.util.Map map) throws SQLException { - throw new SQLException("not supported"); - } - - public int getHoldability() throws SQLException { - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - public void setHoldability(int holdability) throws SQLException { - if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) { - return; - } - throw new SQLException("not supported"); - } - - public Savepoint setSavepoint() throws SQLException { - throw new SQLException("not supported"); - } - - public Savepoint setSavepoint(String name) throws SQLException { - throw new SQLException("not supported"); - } - - public void rollback(Savepoint x) throws SQLException { - throw new SQLException("not supported"); - } - - public void releaseSavepoint(Savepoint x) throws SQLException { - throw new SQLException("not supported"); - } - - public Statement createStatement(int resultSetType, - int resultSetConcurrency, - int resultSetHoldability) - throws SQLException { - if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { - throw new SQLException("not supported"); - } - return createStatement(resultSetType, resultSetConcurrency); - } - - public PreparedStatement prepareStatement(String sql, int resultSetType, - int resultSetConcurrency, - int resultSetHoldability) - throws SQLException { - if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { - throw new SQLException("not supported"); - } - return prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - public CallableStatement prepareCall(String sql, int x, int y, int z) - throws SQLException { - throw new SQLException("not supported"); - } - - public PreparedStatement prepareStatement(String sql, int autokeys) - throws SQLException { - if (autokeys != Statement.NO_GENERATED_KEYS) { - throw new SQLException("not supported"); - } - return prepareStatement(sql); - } - - public PreparedStatement prepareStatement(String sql, int colIndexes[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public PreparedStatement prepareStatement(String sql, String columns[]) - throws SQLException { - throw new SQLException("not supported"); - } - -} - -class DatabaseX extends SQLite.Database { - - static Object lock = new Object(); - - public DatabaseX() { - super(); - } - - void wait(int ms) { - try { - synchronized (lock) { - lock.wait(ms); - } - } catch (java.lang.Exception e) { - } - } - - public void exec(String sql, SQLite.Callback cb) - throws SQLite.Exception { - super.exec(sql, cb); - synchronized (lock) { - lock.notifyAll(); - } - } - - public void exec(String sql, SQLite.Callback cb, String args[]) - throws SQLite.Exception { - super.exec(sql, cb, args); - synchronized (lock) { - lock.notifyAll(); - } - } - - public SQLite.TableResult get_table(String sql, String args[]) - throws SQLite.Exception { - SQLite.TableResult ret = super.get_table(sql, args); - synchronized (lock) { - lock.notifyAll(); - } - return ret; - } - - public void get_table(String sql, String args[], SQLite.TableResult tbl) - throws SQLite.Exception { - super.get_table(sql, args, tbl); - synchronized (lock) { - lock.notifyAll(); - } - } - -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java b/sql/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java deleted file mode 100644 index 8c14d1d..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java +++ /dev/null @@ -1,1578 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; -import java.util.Hashtable; - -public class JDBCDatabaseMetaData implements DatabaseMetaData { - - private JDBCConnection conn; - - public JDBCDatabaseMetaData(JDBCConnection conn) { - this.conn = conn; - } - - public boolean allProceduresAreCallable() throws SQLException { - return false; - } - - public boolean allTablesAreSelectable() throws SQLException { - return true; - } - - public String getURL() throws SQLException { - return conn.url; - } - - public String getUserName() throws SQLException { - return ""; - } - - public boolean isReadOnly() throws SQLException { - return false; - } - - public boolean nullsAreSortedHigh() throws SQLException { - return false; - } - - public boolean nullsAreSortedLow() throws SQLException { - return false; - } - - public boolean nullsAreSortedAtStart() throws SQLException { - return false; - } - - public boolean nullsAreSortedAtEnd() throws SQLException { - return false; - } - - public String getDatabaseProductName() throws SQLException { - return "SQLite"; - } - - public String getDatabaseProductVersion() throws SQLException { - return SQLite.Database.version(); - } - - public String getDriverName() throws SQLException { - return "SQLite/JDBC"; - } - - public String getDriverVersion() throws SQLException { - return "" + SQLite.JDBCDriver.MAJORVERSION + "." + - SQLite.JDBCDriver.MINORVERSION; - } - - public int getDriverMajorVersion() { - return SQLite.JDBCDriver.MAJORVERSION; - } - - public int getDriverMinorVersion() { - return SQLite.JDBCDriver.MINORVERSION; - } - - public boolean usesLocalFiles() throws SQLException { - return true; - } - - public boolean usesLocalFilePerTable() throws SQLException { - return false; - } - - public boolean supportsMixedCaseIdentifiers() throws SQLException { - return false; - } - - public boolean storesUpperCaseIdentifiers() throws SQLException { - return false; - } - - public boolean storesLowerCaseIdentifiers() throws SQLException { - return false; - } - - public boolean storesMixedCaseIdentifiers() throws SQLException { - return true; - } - - public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { - return false; - } - - public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { - return true; - } - - public String getIdentifierQuoteString() throws SQLException { - return "\""; - } - - public String getSQLKeywords() throws SQLException { - return "SELECT,UPDATE,CREATE,TABLE,VIEW,DELETE,FROM,WHERE" + - ",COMMIT,ROLLBACK,TRIGGER"; - } - - public String getNumericFunctions() throws SQLException { - return ""; - } - - public String getStringFunctions() throws SQLException { - return ""; - } - - public String getSystemFunctions() throws SQLException { - return ""; - } - - public String getTimeDateFunctions() throws SQLException { - return ""; - } - - public String getSearchStringEscape() throws SQLException { - return "\\"; - } - - public String getExtraNameCharacters() throws SQLException { - return ""; - } - - public boolean supportsAlterTableWithAddColumn() throws SQLException { - return false; - } - - public boolean supportsAlterTableWithDropColumn() throws SQLException { - return false; - } - - public boolean supportsColumnAliasing() throws SQLException { - return true; - } - - public boolean nullPlusNonNullIsNull() throws SQLException { - return false; - } - - public boolean supportsConvert() throws SQLException { - return false; - } - - public boolean supportsConvert(int fromType, int toType) - throws SQLException { - return false; - } - - public boolean supportsTableCorrelationNames() throws SQLException { - return true; - } - - public boolean supportsDifferentTableCorrelationNames() - throws SQLException { - return false; - } - - public boolean supportsExpressionsInOrderBy() throws SQLException { - return true; - } - - public boolean supportsOrderByUnrelated() throws SQLException { - return true; - } - - public boolean supportsGroupBy() throws SQLException { - return true; - } - - public boolean supportsGroupByUnrelated() throws SQLException { - return true; - } - - public boolean supportsGroupByBeyondSelect() throws SQLException { - return false; - } - - public boolean supportsLikeEscapeClause() throws SQLException { - return false; - } - - public boolean supportsMultipleResultSets() throws SQLException { - return false; - } - - public boolean supportsMultipleTransactions() throws SQLException { - return false; - } - - public boolean supportsNonNullableColumns() throws SQLException { - return true; - } - - public boolean supportsMinimumSQLGrammar() throws SQLException { - return true; - } - - public boolean supportsCoreSQLGrammar() throws SQLException { - return false; - } - - public boolean supportsExtendedSQLGrammar() throws SQLException { - return false; - } - - public boolean supportsANSI92EntryLevelSQL() throws SQLException { - return true; - } - - public boolean supportsANSI92IntermediateSQL() throws SQLException { - return false; - } - - public boolean supportsANSI92FullSQL() throws SQLException { - return false; - } - - public boolean supportsIntegrityEnhancementFacility() - throws SQLException { - return false; - } - - public boolean supportsOuterJoins() throws SQLException { - return false; - } - - public boolean supportsFullOuterJoins() throws SQLException { - return false; - } - - public boolean supportsLimitedOuterJoins() throws SQLException { - return false; - } - - public String getSchemaTerm() throws SQLException { - return ""; - } - - public String getProcedureTerm() throws SQLException { - return ""; - } - - public String getCatalogTerm() throws SQLException { - return ""; - } - - public boolean isCatalogAtStart() throws SQLException { - return false; - } - - public String getCatalogSeparator() throws SQLException { - return ""; - } - - public boolean supportsSchemasInDataManipulation() throws SQLException { - return false; - } - - public boolean supportsSchemasInProcedureCalls() throws SQLException { - return false; - } - - public boolean supportsSchemasInTableDefinitions() throws SQLException { - return false; - } - - public boolean supportsSchemasInIndexDefinitions() throws SQLException { - return false; - } - - public boolean supportsSchemasInPrivilegeDefinitions() - throws SQLException { - return false; - } - - public boolean supportsCatalogsInDataManipulation() throws SQLException { - return false; - } - - public boolean supportsCatalogsInProcedureCalls() throws SQLException { - return false; - } - - public boolean supportsCatalogsInTableDefinitions() throws SQLException { - return false; - } - - public boolean supportsCatalogsInIndexDefinitions() throws SQLException { - return false; - } - - public boolean supportsCatalogsInPrivilegeDefinitions() - throws SQLException { - return false; - } - - public boolean supportsPositionedDelete() throws SQLException { - return false; - } - - public boolean supportsPositionedUpdate() throws SQLException { - return false; - } - - public boolean supportsSelectForUpdate() throws SQLException { - return true; - } - - public boolean supportsStoredProcedures() throws SQLException { - return false; - } - - public boolean supportsSubqueriesInComparisons() throws SQLException { - return true; - } - - public boolean supportsSubqueriesInExists() throws SQLException { - return true; - } - - public boolean supportsSubqueriesInIns() throws SQLException { - return true; - } - - public boolean supportsSubqueriesInQuantifieds() throws SQLException { - return false; - } - - public boolean supportsCorrelatedSubqueries() throws SQLException { - return false; - } - - public boolean supportsUnion() throws SQLException { - return false; - } - - public boolean supportsUnionAll() throws SQLException { - return false; - } - - public boolean supportsOpenCursorsAcrossCommit() throws SQLException { - return false; - } - - public boolean supportsOpenCursorsAcrossRollback() throws SQLException { - return false; - } - - public boolean supportsOpenStatementsAcrossCommit() throws SQLException { - return false; - } - - public boolean supportsOpenStatementsAcrossRollback() throws SQLException { - return false; - } - - public int getMaxBinaryLiteralLength() throws SQLException { - return 0; - } - - public int getMaxCharLiteralLength() throws SQLException { - return 0; - } - - public int getMaxColumnNameLength() throws SQLException { - return 0; - } - - public int getMaxColumnsInGroupBy() throws SQLException { - return 0; - } - - public int getMaxColumnsInIndex() throws SQLException { - return 0; - } - - public int getMaxColumnsInOrderBy() throws SQLException { - return 0; - } - - public int getMaxColumnsInSelect() throws SQLException { - return 0; - } - - public int getMaxColumnsInTable() throws SQLException { - return 0; - } - - public int getMaxConnections() throws SQLException { - return 0; - } - - public int getMaxCursorNameLength() throws SQLException { - return 8; - } - - public int getMaxIndexLength() throws SQLException { - return 0; - } - - public int getMaxSchemaNameLength() throws SQLException { - return 0; - } - - public int getMaxProcedureNameLength() throws SQLException { - return 0; - } - - public int getMaxCatalogNameLength() throws SQLException { - return 0; - } - - public int getMaxRowSize() throws SQLException { - return 0; - } - - public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { - return true; - } - - public int getMaxStatementLength() throws SQLException { - return 0; - } - - public int getMaxStatements() throws SQLException { - return 0; - } - - public int getMaxTableNameLength() throws SQLException { - return 0; - } - - public int getMaxTablesInSelect() throws SQLException { - return 0; - } - - public int getMaxUserNameLength() throws SQLException { - return 0; - } - - public int getDefaultTransactionIsolation() throws SQLException { - return Connection.TRANSACTION_SERIALIZABLE; - } - - public boolean supportsTransactions() throws SQLException { - return true; - } - - public boolean supportsTransactionIsolationLevel(int level) - throws SQLException { - return level == Connection.TRANSACTION_SERIALIZABLE; - } - - public boolean supportsDataDefinitionAndDataManipulationTransactions() - throws SQLException { - return true; - } - - public boolean supportsDataManipulationTransactionsOnly() - throws SQLException { - return false; - } - - public boolean dataDefinitionCausesTransactionCommit() - throws SQLException { - return false; - } - - public boolean dataDefinitionIgnoredInTransactions() throws SQLException { - return false; - } - - public ResultSet getProcedures(String catalog, String schemaPattern, - String procedureNamePattern) - throws SQLException { - return null; - } - - public ResultSet getProcedureColumns(String catalog, - String schemaPattern, - String procedureNamePattern, - String columnNamePattern) - throws SQLException { - return null; - } - - public ResultSet getTables(String catalog, String schemaPattern, - String tableNamePattern, String types[]) - throws SQLException { - JDBCStatement s = new JDBCStatement(conn); - StringBuffer sb = new StringBuffer(); - sb.append("SELECT '' AS 'TABLE_CAT', " + - "'' AS 'TABLE_SCHEM', " + - "tbl_name AS 'TABLE_NAME', " + - "upper(type) AS 'TABLE_TYPE', " + - "'' AS REMARKS FROM sqlite_master " + - "WHERE tbl_name like "); - if (tableNamePattern != null) { - sb.append(SQLite.Shell.sql_quote(tableNamePattern)); - } else { - sb.append("'%'"); - } - sb.append(" AND "); - if (types == null || types.length == 0) { - sb.append("(type = 'table' or type = 'view')"); - } else { - sb.append("("); - String sep = ""; - for (int i = 0; i < types.length; i++) { - sb.append(sep); - sb.append("type = "); - sb.append(SQLite.Shell.sql_quote(types[i].toLowerCase())); - sep = " or "; - } - sb.append(")"); - } - ResultSet rs = null; - try { - rs = s.executeQuery(sb.toString()); - s.close(); - } catch (SQLException e) { - throw e; - } finally { - s.close(); - } - return rs; - } - - public ResultSet getSchemas() throws SQLException { - String cols[] = { "TABLE_SCHEM" }; - SQLite.TableResult tr = new SQLite.TableResult(); - tr.columns(cols); - String row[] = { "" }; - tr.newrow(row); - JDBCResultSet rs = new JDBCResultSet(tr, null); - return (ResultSet) rs; - } - - public ResultSet getCatalogs() throws SQLException { - String cols[] = { "TABLE_CAT" }; - SQLite.TableResult tr = new SQLite.TableResult(); - tr.columns(cols); - String row[] = { "" }; - tr.newrow(row); - JDBCResultSet rs = new JDBCResultSet(tr, null); - return (ResultSet) rs; - } - - public ResultSet getTableTypes() throws SQLException { - String cols[] = { "TABLE_TYPE" }; - SQLite.TableResult tr = new SQLite.TableResult(); - tr.columns(cols); - String row[] = new String[1]; - row[0] = "TABLE"; - tr.newrow(row); - row = new String[1]; - row[0] = "VIEW"; - tr.newrow(row); - JDBCResultSet rs = new JDBCResultSet(tr, null); - return (ResultSet) rs; - } - - public ResultSet getColumns(String catalog, String schemaPattern, - String tableNamePattern, - String columnNamePattern) - throws SQLException { - JDBCStatement s = new JDBCStatement(conn); - JDBCResultSet rs0 = null; - try { - rs0 = (JDBCResultSet) - (s.executeQuery("PRAGMA table_info(" + - SQLite.Shell.sql_quote(tableNamePattern) + - ")")); - s.close(); - } catch (SQLException e) { - throw e; - } finally { - s.close(); - } - String cols[] = { - "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", - "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", - "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_POINTS", - "NUM_PREC_RADIX", "NULLABLE", "REMARKS", - "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", - "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.SMALLINT, Types.VARCHAR, - Types.INTEGER, Types.INTEGER, Types.INTEGER, - Types.INTEGER, Types.INTEGER, Types.VARCHAR, - Types.VARCHAR, Types.INTEGER, Types.INTEGER, - Types.INTEGER, Types.INTEGER, Types.VARCHAR - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - Hashtable<String, Integer> h = new Hashtable<String, Integer>(); - for (int i = 0; i < rs0.tr.ncolumns; i++) { - h.put(rs0.tr.column[i], new Integer(i)); - } - if (columnNamePattern != null && - columnNamePattern.charAt(0) == '%') { - columnNamePattern = null; - } - for (int i = 0; i < rs0.tr.nrows; i++) { - String r0[] = (String [])(rs0.tr.rows.elementAt(i)); - int col = ((Integer) h.get("name")).intValue(); - if (columnNamePattern != null) { - if (r0[col].compareTo(columnNamePattern) != 0) { - continue; - } - } - String row[] = new String[cols.length]; - row[0] = ""; - row[1] = ""; - row[2] = tableNamePattern; - row[3] = r0[col]; - col = ((Integer) h.get("type")).intValue(); - String typeStr = r0[col]; - int type = mapSqlType(typeStr); - row[4] = "" + type; - row[5] = mapTypeName(type); - row[6] = "" + getD(typeStr, type); - row[7] = "" + getM(typeStr, type); - row[8] = "10"; - row[9] = "0"; - row[11] = null; - col = ((Integer) h.get("dflt_value")).intValue(); - row[12] = r0[col]; - row[13] = "0"; - row[14] = "0"; - row[15] = "65536"; - col = ((Integer) h.get("cid")).intValue(); - Integer cid = new Integer(r0[col]); - row[16] = "" + (cid.intValue() + 1); - col = ((Integer) h.get("notnull")).intValue(); - row[17] = (r0[col].charAt(0) == '0') ? "YES" : "NO"; - row[10] = (r0[col].charAt(0) == '0') ? "" + columnNullable : - "" + columnNoNulls; - tr.newrow(row); - } - } - return rs; - } - - public ResultSet getColumnPrivileges(String catalog, String schema, - String table, - String columnNamePattern) - throws SQLException { - String cols[] = { - "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", - "COLUMN_NAME", "GRANTOR", "GRANTEE", - "PRIVILEGE", "IS_GRANTABLE" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - return rs; - } - - public ResultSet getTablePrivileges(String catalog, String schemaPattern, - String tableNamePattern) - throws SQLException { - String cols[] = { - "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", - "COLUMN_NAME", "GRANTOR", "GRANTEE", - "PRIVILEGE", "IS_GRANTABLE" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - return rs; - } - - public ResultSet getBestRowIdentifier(String catalog, String schema, - String table, int scope, - boolean nullable) - throws SQLException { - JDBCStatement s0 = new JDBCStatement(conn); - JDBCResultSet rs0 = null; - JDBCStatement s1 = new JDBCStatement(conn); - JDBCResultSet rs1 = null; - try { - rs0 = (JDBCResultSet) - (s0.executeQuery("PRAGMA index_list(" + - SQLite.Shell.sql_quote(table) + ")")); - rs1 = (JDBCResultSet) - (s1.executeQuery("PRAGMA table_info(" + - SQLite.Shell.sql_quote(table) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s0.close(); - s1.close(); - } - String cols[] = { - "SCOPE", "COLUMN_NAME", "DATA_TYPE", - "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", - "DECIMAL_DIGITS", "PSEUDO_COLUMN" - }; - int types[] = { - Types.SMALLINT, Types.VARCHAR, Types.SMALLINT, - Types.VARCHAR, Types.INTEGER, Types.INTEGER, - Types.SMALLINT, Types.SMALLINT - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0 && - rs1 != null && rs1.tr != null && rs1.tr.nrows > 0) { - Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); - for (int i = 0; i < rs0.tr.ncolumns; i++) { - h0.put(rs0.tr.column[i], new Integer(i)); - } - Hashtable<String, Integer> h1 = new Hashtable<String, Integer>(); - for (int i = 0; i < rs1.tr.ncolumns; i++) { - h1.put(rs1.tr.column[i], new Integer(i)); - } - for (int i = 0; i < rs0.tr.nrows; i++) { - String r0[] = (String [])(rs0.tr.rows.elementAt(i)); - int col = ((Integer) h0.get("unique")).intValue(); - String uniq = r0[col]; - col = ((Integer) h0.get("name")).intValue(); - String iname = r0[col]; - if (uniq.charAt(0) == '0') { - continue; - } - JDBCStatement s2 = new JDBCStatement(conn); - JDBCResultSet rs2 = null; - try { - rs2 = (JDBCResultSet) - (s2.executeQuery("PRAGMA index_info(" + - SQLite.Shell.sql_quote(iname) + ")")); - } catch (SQLException e) { - } finally { - s2.close(); - } - if (rs2 == null || rs2.tr == null || rs2.tr.nrows <= 0) { - continue; - } - Hashtable<String, Integer> h2 = - new Hashtable<String, Integer>(); - for (int k = 0; k < rs2.tr.ncolumns; k++) { - h2.put(rs2.tr.column[k], new Integer(k)); - } - for (int k = 0; k < rs2.tr.nrows; k++) { - String r2[] = (String [])(rs2.tr.rows.elementAt(k)); - col = ((Integer) h2.get("name")).intValue(); - String cname = r2[col]; - for (int m = 0; m < rs1.tr.nrows; m++) { - String r1[] = (String [])(rs1.tr.rows.elementAt(m)); - col = ((Integer) h1.get("name")).intValue(); - if (cname.compareTo(r1[col]) == 0) { - String row[] = new String[cols.length]; - row[0] = "" + scope; - row[1] = cname; - row[2] = "" + Types.VARCHAR; - row[3] = "VARCHAR"; - row[4] = "65536"; - row[5] = "0"; - row[6] = "0"; - row[7] = "" + bestRowNotPseudo; - tr.newrow(row); - } - } - } - } - } - if (tr.nrows <= 0) { - String row[] = new String[cols.length]; - row[0] = "" + scope; - row[1] = "_ROWID_"; - row[2] = "" + Types.INTEGER; - row[3] = "INTEGER"; - row[4] = "10"; - row[5] = "0"; - row[6] = "0"; - row[7] = "" + bestRowPseudo; - tr.newrow(row); - } - return rs; - } - - public ResultSet getVersionColumns(String catalog, String schema, - String table) throws SQLException { - String cols[] = { - "SCOPE", "COLUMN_NAME", "DATA_TYPE", - "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", - "DECIMAL_DIGITS", "PSEUDO_COLUMN" - }; - int types[] = { - Types.SMALLINT, Types.VARCHAR, Types.SMALLINT, - Types.VARCHAR, Types.INTEGER, Types.INTEGER, - Types.SMALLINT, Types.SMALLINT - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - return rs; - } - - public ResultSet getPrimaryKeys(String catalog, String schema, - String table) throws SQLException { - JDBCStatement s0 = new JDBCStatement(conn); - JDBCResultSet rs0 = null; - try { - rs0 = (JDBCResultSet) - (s0.executeQuery("PRAGMA index_list(" + - SQLite.Shell.sql_quote(table) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s0.close(); - } - String cols[] = { - "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", - "COLUMN_NAME", "KEY_SEQ", "PK_NAME" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.SMALLINT, Types.VARCHAR - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); - for (int i = 0; i < rs0.tr.ncolumns; i++) { - h0.put(rs0.tr.column[i], new Integer(i)); - } - for (int i = 0; i < rs0.tr.nrows; i++) { - String r0[] = (String [])(rs0.tr.rows.elementAt(i)); - int col = ((Integer) h0.get("unique")).intValue(); - String uniq = r0[col]; - col = ((Integer) h0.get("name")).intValue(); - String iname = r0[col]; - if (uniq.charAt(0) == '0') { - continue; - } - JDBCStatement s1 = new JDBCStatement(conn); - JDBCResultSet rs1 = null; - try { - rs1 = (JDBCResultSet) - (s1.executeQuery("PRAGMA index_info(" + - SQLite.Shell.sql_quote(iname) + ")")); - } catch (SQLException e) { - } finally { - s1.close(); - } - if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) { - continue; - } - Hashtable<String, Integer> h1 = - new Hashtable<String, Integer>(); - for (int k = 0; k < rs1.tr.ncolumns; k++) { - h1.put(rs1.tr.column[k], new Integer(k)); - } - for (int k = 0; k < rs1.tr.nrows; k++) { - String r1[] = (String [])(rs1.tr.rows.elementAt(k)); - String row[] = new String[cols.length]; - row[0] = ""; - row[1] = ""; - row[2] = table; - col = ((Integer) h1.get("name")).intValue(); - row[3] = r1[col]; - col = ((Integer) h1.get("seqno")).intValue(); -// BEGIN android-changed - row[4] = "" + (Integer.parseInt(r1[col]) + 1); -// END android-changed - row[5] = iname; - tr.newrow(row); - } - } - } - JDBCStatement s1 = new JDBCStatement(conn); - try { - rs0 = (JDBCResultSet) - (s1.executeQuery("PRAGMA table_info(" + - SQLite.Shell.sql_quote(table) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s1.close(); - } - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); - for (int i = 0; i < rs0.tr.ncolumns; i++) { - h0.put(rs0.tr.column[i], new Integer(i)); - } - for (int i = 0; i < rs0.tr.nrows; i++) { - String r0[] = (String [])(rs0.tr.rows.elementAt(i)); - int col = ((Integer) h0.get("type")).intValue(); - String type = r0[col]; - if (!type.equalsIgnoreCase("integer")) { - continue; - } - col = ((Integer) h0.get("pk")).intValue(); - String pk = r0[col]; - if (pk.charAt(0) == '0') { - continue; - } - String row[] = new String[cols.length]; - row[0] = ""; - row[1] = ""; - row[2] = table; - col = ((Integer) h0.get("name")).intValue(); - row[3] = r0[col]; - col = ((Integer) h0.get("cid")).intValue(); -// BEGIN android-changed - row[4] = "" + (Integer.parseInt(r0[col]) + 1); -// END android-changed - row[5] = ""; - tr.newrow(row); - } - } - return rs; - } - - private void internalImportedKeys(String table, String pktable, - JDBCResultSet in, TableResultX out) { - Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); - for (int i = 0; i < in.tr.ncolumns; i++) { - h0.put(in.tr.column[i], new Integer(i)); - } - for (int i = 0; i < in.tr.nrows; i++) { - String r0[] = (String [])(in.tr.rows.elementAt(i)); - int col = ((Integer) h0.get("table")).intValue(); - String pktab = r0[col]; - if (pktable != null && !pktable.equalsIgnoreCase(pktab)) { - continue; - } - col = ((Integer) h0.get("from")).intValue(); - String pkcol = r0[col]; - col = ((Integer) h0.get("to")).intValue(); - String fkcol = r0[col]; - col = ((Integer) h0.get("seq")).intValue(); - String seq = r0[col]; - String row[] = new String[out.ncolumns]; - row[0] = ""; - row[1] = ""; - row[2] = pktab; - row[3] = pkcol; - row[4] = ""; - row[5] = ""; - row[6] = table; - row[7] = fkcol == null ? pkcol : fkcol; -// BEGIN android-changed - row[8] = "" + ((Integer.parseInt(seq)) + 1); -// END android-changed - row[9] = - "" + java.sql.DatabaseMetaData.importedKeyNoAction; - row[10] = - "" + java.sql.DatabaseMetaData.importedKeyNoAction; - row[11] = null; - row[12] = null; - row[13] = - "" + java.sql.DatabaseMetaData.importedKeyNotDeferrable; - out.newrow(row); - } - } - - public ResultSet getImportedKeys(String catalog, String schema, - String table) throws SQLException { - JDBCStatement s0 = new JDBCStatement(conn); - JDBCResultSet rs0 = null; - try { - rs0 = (JDBCResultSet) - (s0.executeQuery("PRAGMA foreign_key_list(" + - SQLite.Shell.sql_quote(table) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s0.close(); - } - String cols[] = { - "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", - "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", - "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", - "UPDATE_RULE", "DELETE_RULE", "FK_NAME", - "PK_NAME", "DEFERRABILITY" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, - Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, - Types.VARCHAR, Types.SMALLINT - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - internalImportedKeys(table, null, rs0, tr); - } - return rs; - } - - public ResultSet getExportedKeys(String catalog, String schema, - String table) throws SQLException { - String cols[] = { - "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", - "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", - "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", - "UPDATE_RULE", "DELETE_RULE", "FK_NAME", - "PK_NAME", "DEFERRABILITY" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, - Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, - Types.VARCHAR, Types.SMALLINT - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet(tr, null); - return rs; - } - - public ResultSet getCrossReference(String primaryCatalog, - String primarySchema, - String primaryTable, - String foreignCatalog, - String foreignSchema, - String foreignTable) - throws SQLException { - JDBCResultSet rs0 = null; - if (foreignTable != null && foreignTable.charAt(0) != '%') { - JDBCStatement s0 = new JDBCStatement(conn); - try { - rs0 = (JDBCResultSet) - (s0.executeQuery("PRAGMA foreign_key_list(" + - SQLite.Shell.sql_quote(foreignTable) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s0.close(); - } - } - String cols[] = { - "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", - "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", - "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", - "UPDATE_RULE", "DELETE_RULE", "FK_NAME", - "PK_NAME", "DEFERRABILITY" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, - Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, - Types.VARCHAR, Types.SMALLINT - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet(tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - String pktable = null; - if (primaryTable != null && primaryTable.charAt(0) != '%') { - pktable = primaryTable; - } - internalImportedKeys(foreignTable, pktable, rs0, tr); - } - return rs; - } - - public ResultSet getTypeInfo() throws SQLException { - String cols[] = { - "TYPE_NAME", "DATA_TYPE", "PRECISION", - "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS", - "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", - "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT", - "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE", - "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX" - }; - int types[] = { - Types.VARCHAR, Types.SMALLINT, Types.INTEGER, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.SMALLINT, Types.BIT, Types.SMALLINT, - Types.BIT, Types.BIT, Types.BIT, - Types.VARCHAR, Types.SMALLINT, Types.SMALLINT, - Types.INTEGER, Types.INTEGER, Types.INTEGER - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet(tr, null); - String row1[] = { - "VARCHAR", "" + Types.VARCHAR, "65536", - "'", "'", null, - "" + typeNullable, "1", "" + typeSearchable, - "0", "0", "0", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row1); - String row2[] = { - "INTEGER", "" + Types.INTEGER, "32", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "2" - }; - tr.newrow(row2); - String row3[] = { - "DOUBLE", "" + Types.DOUBLE, "16", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "10" - }; - tr.newrow(row3); - String row4[] = { - "FLOAT", "" + Types.FLOAT, "7", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "10" - }; - tr.newrow(row4); - String row5[] = { - "SMALLINT", "" + Types.SMALLINT, "16", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "2" - }; - tr.newrow(row5); - String row6[] = { - "BIT", "" + Types.BIT, "1", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "2" - }; - tr.newrow(row6); - String row7[] = { - "TIMESTAMP", "" + Types.TIMESTAMP, "30", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row7); - String row8[] = { - "DATE", "" + Types.DATE, "10", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row8); - String row9[] = { - "TIME", "" + Types.TIME, "8", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row9); - String row10[] = { - "BINARY", "" + Types.BINARY, "65536", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row10); - String row11[] = { - "VARBINARY", "" + Types.VARBINARY, "65536", - null, null, null, - "" + typeNullable, "0", "" + typeSearchable, - "0", "0", "1", - null, "0", "0", - "0", "0", "0" - }; - tr.newrow(row11); - return rs; - } - - public ResultSet getIndexInfo(String catalog, String schema, String table, - boolean unique, boolean approximate) - throws SQLException { - JDBCStatement s0 = new JDBCStatement(conn); - JDBCResultSet rs0 = null; - try { - rs0 = (JDBCResultSet) - (s0.executeQuery("PRAGMA index_list(" + - SQLite.Shell.sql_quote(table) + ")")); - } catch (SQLException e) { - throw e; - } finally { - s0.close(); - } - String cols[] = { - "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", - "NON_UNIQUE", "INDEX_QUALIFIER", "INDEX_NAME", - "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", - "ASC_OR_DESC", "CARDINALITY", "PAGES", - "FILTER_CONDITION" - }; - int types[] = { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, - Types.BIT, Types.VARCHAR, Types.VARCHAR, - Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, - Types.VARCHAR, Types.INTEGER, Types.INTEGER, - Types.VARCHAR - }; - TableResultX tr = new TableResultX(); - tr.columns(cols); - tr.sql_types(types); - JDBCResultSet rs = new JDBCResultSet(tr, null); - if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { - Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); - for (int i = 0; i < rs0.tr.ncolumns; i++) { - h0.put(rs0.tr.column[i], new Integer(i)); - } - for (int i = 0; i < rs0.tr.nrows; i++) { - String r0[] = (String [])(rs0.tr.rows.elementAt(i)); - int col = ((Integer) h0.get("unique")).intValue(); - String uniq = r0[col]; - col = ((Integer) h0.get("name")).intValue(); - String iname = r0[col]; - if (unique && uniq.charAt(0) == '0') { - continue; - } - JDBCStatement s1 = new JDBCStatement(conn); - JDBCResultSet rs1 = null; - try { - rs1 = (JDBCResultSet) - (s1.executeQuery("PRAGMA index_info(" + - SQLite.Shell.sql_quote(iname) + ")")); - } catch (SQLException e) { - } finally { - s1.close(); - } - if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) { - continue; - } - Hashtable<String, Integer> h1 = - new Hashtable<String, Integer>(); - for (int k = 0; k < rs1.tr.ncolumns; k++) { - h1.put(rs1.tr.column[k], new Integer(k)); - } - for (int k = 0; k < rs1.tr.nrows; k++) { - String r1[] = (String [])(rs1.tr.rows.elementAt(k)); - String row[] = new String[cols.length]; - row[0] = ""; - row[1] = ""; - row[2] = table; - row[3] = (uniq.charAt(0) != '0' || - (iname.charAt(0) == '(' && - iname.indexOf(" autoindex ") > 0)) ? "0" : "1"; - row[4] = ""; - row[5] = iname; - row[6] = "" + tableIndexOther; - col = ((Integer) h1.get("seqno")).intValue(); -// BEGIN android-changed - row[7] = "" + (Integer.parseInt(r1[col]) + 1); -// END android-changed - col = ((Integer) h1.get("name")).intValue(); - row[8] = r1[col]; - row[9] = "A"; - row[10] = "0"; - row[11] = "0"; - row[12] = null; - tr.newrow(row); - } - } - } - return rs; - } - - public boolean supportsResultSetType(int type) throws SQLException { - return type == ResultSet.CONCUR_READ_ONLY; - } - - public boolean supportsResultSetConcurrency(int type, int concurrency) - throws SQLException { - return false; - } - - public boolean ownUpdatesAreVisible(int type) throws SQLException { - return false; - } - - public boolean ownDeletesAreVisible(int type) throws SQLException { - return false; - } - - public boolean ownInsertsAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersUpdatesAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersDeletesAreVisible(int type) throws SQLException { - return false; - } - - public boolean othersInsertsAreVisible(int type) throws SQLException { - return false; - } - - public boolean updatesAreDetected(int type) throws SQLException { - return false; - } - - public boolean deletesAreDetected(int type) throws SQLException { - return false; - } - - public boolean insertsAreDetected(int type) throws SQLException { - return false; - } - - public boolean supportsBatchUpdates() throws SQLException { - return false; - } - - public ResultSet getUDTs(String catalog, String schemaPattern, - String typeNamePattern, int[] types) - throws SQLException { - return null; - } - - public Connection getConnection() throws SQLException { - return conn; - } - - static String mapTypeName(int type) { - switch (type) { - case Types.INTEGER: return "integer"; - case Types.SMALLINT: return "smallint"; - case Types.FLOAT: return "float"; - case Types.DOUBLE: return "double"; - case Types.TIMESTAMP: return "timestamp"; - case Types.DATE: return "date"; - case Types.TIME: return "time"; - case Types.BINARY: return "binary"; - case Types.VARBINARY: return "varbinary"; - } - return "varchar"; - } - - static int mapSqlType(String type) { - if (type == null) { - return Types.VARCHAR; - } - type = type.toLowerCase(); - if (type.startsWith("inter")) { - return Types.VARCHAR; - } - if (type.startsWith("numeric") || - type.startsWith("int")) { - return Types.INTEGER; - } - if (type.startsWith("tinyint") || - type.startsWith("smallint")) { - return Types.SMALLINT; - } - if (type.startsWith("float")) { - return Types.FLOAT; - } - if (type.startsWith("double")) { - return Types.DOUBLE; - } - if (type.startsWith("datetime") || - type.startsWith("timestamp")) { - return Types.TIMESTAMP; - } - if (type.startsWith("date")) { - return Types.DATE; - } - if (type.startsWith("time")) { - return Types.TIME; - } - if (type.startsWith("blob")) { - return Types.BINARY; - } - if (type.startsWith("binary")) { - return Types.BINARY; - } - if (type.startsWith("varbinary")) { - return Types.VARBINARY; - } - return Types.VARCHAR; - } - - static int getM(String typeStr, int type) { - int m = 65536; - switch (type) { - case Types.INTEGER: m = 11; break; - case Types.SMALLINT: m = 6; break; - case Types.FLOAT: m = 25; break; - case Types.DOUBLE: m = 54; break; - case Types.TIMESTAMP: return 30; - case Types.DATE: return 10; - case Types.TIME: return 8; - } - typeStr = typeStr.toLowerCase(); - int i1 = typeStr.indexOf('('); - if (i1 > 0) { - ++i1; - int i2 = typeStr.indexOf(',', i1); - if (i2 < 0) { - i2 = typeStr.indexOf(')', i1); - } - if (i2 - i1 > 0) { - String num = typeStr.substring(i1, i2); - try { - m = java.lang.Integer.parseInt(num, 10); - } catch (NumberFormatException e) { - } - } - } - return m; - } - - static int getD(String typeStr, int type) { - int d = 0; - switch (type) { - case Types.INTEGER: d = 10; break; - case Types.SMALLINT: d = 5; break; - case Types.FLOAT: d = 24; break; - case Types.DOUBLE: d = 53; break; - default: return getM(typeStr, type); - } - typeStr = typeStr.toLowerCase(); - int i1 = typeStr.indexOf('('); - if (i1 > 0) { - ++i1; - int i2 = typeStr.indexOf(',', i1); - if (i2 < 0) { - return getM(typeStr, type); - } - i1 = i2; - i2 = typeStr.indexOf(')', i1); - if (i2 - i1 > 0) { - String num = typeStr.substring(i1, i2); - try { - d = java.lang.Integer.parseInt(num, 10); - } catch (NumberFormatException e) { - } - } - } - return d; - } - - public boolean supportsSavepoints() { - return false; - } - - public boolean supportsNamedParameters() { - return false; - } - - public boolean supportsMultipleOpenResults() { - return false; - } - - public boolean supportsGetGeneratedKeys() { - return false; - } - - public boolean supportsResultSetHoldability(int x) { - return false; - } - - public boolean supportsStatementPooling() { - return false; - } - - public boolean locatorsUpdateCopy() throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSet getSuperTypes(String catalog, String schemaPattern, - String typeNamePattern) - throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSet getSuperTables(String catalog, String schemaPattern, - String tableNamePattern) - throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSet getAttributes(String catalog, String schemaPattern, - String typeNamePattern, - String attributeNamePattern) - throws SQLException { - throw new SQLException("not supported"); - } - - public int getResultSetHoldability() throws SQLException { - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - - public int getDatabaseMajorVersion() { - return SQLite.JDBCDriver.MAJORVERSION; - } - - public int getDatabaseMinorVersion() { - return SQLite.JDBCDriver.MINORVERSION; - } - - public int getJDBCMajorVersion() { - return 1; - } - - public int getJDBCMinorVersion() { - return 0; - } - - public int getSQLStateType() throws SQLException { - return sqlStateXOpen; - } - -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java b/sql/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java deleted file mode 100644 index ab81867..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java +++ /dev/null @@ -1,752 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; -import java.math.BigDecimal; -import java.util.*; - -class BatchArg { - String arg; - boolean blob; - - BatchArg(String arg, boolean blob) { - if (arg == null) { - this.arg = null; - } else { - this.arg = new String(arg); - } - this.blob = blob; - } -} - -public class JDBCPreparedStatement extends JDBCStatement - implements java.sql.PreparedStatement { - - private String sql; - private String args[]; - private boolean blobs[]; - private ArrayList<BatchArg> batch; - private static final boolean nullrepl = - SQLite.Database.version().compareTo("2.5.0") < 0; - - public JDBCPreparedStatement(JDBCConnection conn, String sql) { - super(conn); - this.args = null; - this.blobs = null; - this.batch = null; - this.sql = fixup(sql); - } - - private String fixup(String sql) { - StringBuffer sb = new StringBuffer(); - boolean inq = false; - int nparm = 0; - for (int i = 0; i < sql.length(); i++) { - char c = sql.charAt(i); - if (c == '\'') { - if (inq) { - char nextChar = 0; - if(i + 1 < sql.length()) { - nextChar = sql.charAt(i + 1); - } - if (nextChar == '\'') { - sb.append(c); - sb.append(nextChar); - i++; - } else { - inq = false; - sb.append(c); - } - } else { - inq = true; - sb.append(c); - } - } else if (c == '?') { - if (inq) { - sb.append(c); - } else { - ++nparm; - sb.append(nullrepl ? "'%q'" : "%Q"); - } - } else if (c == ';') { - if (!inq) { - break; - } - sb.append(c); - } else if (c == '%') { - sb.append("%%"); - } else { - sb.append(c); - } - } - args = new String[nparm]; - blobs = new boolean[nparm]; - try { - clearParameters(); - } catch (SQLException e) { - } - return sb.toString(); - } - - private String fixup2(String sql) { - if (!conn.db.is3()) { - return sql; - } - StringBuffer sb = new StringBuffer(); - int parm = -1; - for (int i = 0; i < sql.length(); i++) { - char c = sql.charAt(i); - if (c == '%') { - sb.append(c); - ++i; - c = sql.charAt(i); - if (c == 'Q') { - parm++; - if (blobs[parm]) { - c = 's'; - } - } - } - sb.append(c); - } - return sb.toString(); - } - - public ResultSet executeQuery() throws SQLException { - return executeQuery(fixup2(sql), args, false); - } - - public int executeUpdate() throws SQLException { - executeQuery(fixup2(sql), args, true); - return updcnt; - } - - public void setNull(int parameterIndex, int sqlType) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = nullrepl ? "" : null; - blobs[parameterIndex - 1] = false; - } - - public void setBoolean(int parameterIndex, boolean x) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = x ? "1" : "0"; - blobs[parameterIndex - 1] = false; - } - - public void setByte(int parameterIndex, byte x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setShort(int parameterIndex, short x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setInt(int parameterIndex, int x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setLong(int parameterIndex, long x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setFloat(int parameterIndex, float x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setDouble(int parameterIndex, double x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - args[parameterIndex - 1] = "" + x; - blobs[parameterIndex - 1] = false; - } - - public void setBigDecimal(int parameterIndex, BigDecimal x) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - args[parameterIndex - 1] = "" + x; - } - blobs[parameterIndex - 1] = false; - } - - public void setString(int parameterIndex, String x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - args[parameterIndex - 1] = x; - } - blobs[parameterIndex - 1] = false; - } - - public void setBytes(int parameterIndex, byte x[]) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - blobs[parameterIndex - 1] = false; - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - if (conn.db.is3()) { - args[parameterIndex - 1] = SQLite.StringEncoder.encodeX(x); - blobs[parameterIndex - 1] = true; - } else { - args[parameterIndex - 1] = SQLite.StringEncoder.encode(x); - } - } - } - - public void setDate(int parameterIndex, java.sql.Date x) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - args[parameterIndex - 1] = x.toString(); - } - blobs[parameterIndex - 1] = false; - } - - public void setTime(int parameterIndex, java.sql.Time x) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - args[parameterIndex - 1] = x.toString(); - } - blobs[parameterIndex - 1] = false; - } - - public void setTimestamp(int parameterIndex, java.sql.Timestamp x) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - args[parameterIndex - 1] = x.toString(); - } - blobs[parameterIndex - 1] = false; - } - - public void setAsciiStream(int parameterIndex, java.io.InputStream x, - int length) throws SQLException { - throw new SQLException("not supported"); - } - - @Deprecated - public void setUnicodeStream(int parameterIndex, java.io.InputStream x, - int length) throws SQLException { - throw new SQLException("not supported"); - } - - public void setBinaryStream(int parameterIndex, java.io.InputStream x, - int length) throws SQLException { - throw new SQLException("not supported"); - } - - public void clearParameters() throws SQLException { - for (int i = 0; i < args.length; i++) { - args[i] = nullrepl ? "" : null; - blobs[i] = false; - } - } - - public void setObject(int parameterIndex, Object x, int targetSqlType, - int scale) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - if (x instanceof byte[]) { - byte[] bx = (byte[]) x; - if (conn.db.is3()) { - args[parameterIndex - 1] = - SQLite.StringEncoder.encodeX(bx); - blobs[parameterIndex - 1] = true; - return; - } - args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); - } else { - args[parameterIndex - 1] = x.toString(); - } - } - blobs[parameterIndex - 1] = false; - } - - public void setObject(int parameterIndex, Object x, int targetSqlType) - throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - if (x instanceof byte[]) { - byte[] bx = (byte[]) x; - if (conn.db.is3()) { - args[parameterIndex - 1] = - SQLite.StringEncoder.encodeX(bx); - blobs[parameterIndex - 1] = true; - return; - } - args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); - } else { - args[parameterIndex - 1] = x.toString(); - } - } - blobs[parameterIndex - 1] = false; - } - - public void setObject(int parameterIndex, Object x) throws SQLException { - if (parameterIndex < 1 || parameterIndex > args.length) { - throw new SQLException("bad parameter index"); - } - if (x == null) { - args[parameterIndex - 1] = nullrepl ? "" : null; - } else { - if (x instanceof byte[]) { - byte[] bx = (byte[]) x; - if (conn.db.is3()) { - args[parameterIndex - 1] = - SQLite.StringEncoder.encodeX(bx); - blobs[parameterIndex - 1] = true; - return; - } - args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); - } else { - args[parameterIndex - 1] = x.toString(); - } - } - blobs[parameterIndex - 1] = false; - } - - public boolean execute() throws SQLException { - return executeQuery(fixup2(sql), args, false) != null; - } - - public void addBatch() throws SQLException { - if (batch == null) { - batch = new ArrayList<BatchArg>(args.length); - } - for (int i = 0; i < args.length; i++) { - batch.add(new BatchArg(args[i], blobs[i])); - } - } - - public int[] executeBatch() throws SQLException { - if (batch == null) { - return new int[0]; - } - int[] ret = new int[batch.size() / args.length]; - for (int i = 0; i < ret.length; i++) { - ret[i] = EXECUTE_FAILED; - } - int errs = 0; - int index = 0; - for (int i = 0; i < ret.length; i++) { - for (int k = 0; k < args.length; k++) { - BatchArg b = (BatchArg) batch.get(index++); - - args[i] = b.arg; - blobs[i] = b.blob; - } - try { - ret[i] = executeUpdate(); - } catch (SQLException e) { - ++errs; - } - } - if (errs > 0) { - throw new BatchUpdateException("batch failed", ret); - } - return ret; - } - - public void clearBatch() throws SQLException { - if (batch != null) { - batch.clear(); - batch = null; - } - } - - public void setCharacterStream(int parameterIndex, - java.io.Reader reader, - int length) throws SQLException { - throw new SQLException("not supported"); - } - - public void setRef(int i, Ref x) throws SQLException { - throw new SQLException("not supported"); - } - - public void setBlob(int i, Blob x) throws SQLException { - throw new SQLException("not supported"); - } - - public void setClob(int i, Clob x) throws SQLException { - throw new SQLException("not supported"); - } - - public void setArray(int i, Array x) throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSetMetaData getMetaData() throws SQLException { - return rs.getMetaData(); - } - - public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) - throws SQLException { - setDate(parameterIndex, x); - } - - public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) - throws SQLException { - setTime(parameterIndex, x); - } - - public void setTimestamp(int parameterIndex, java.sql.Timestamp x, - Calendar cal) throws SQLException { - setTimestamp(parameterIndex, x); - } - - public void setNull(int parameterIndex, int sqlType, String typeName) - throws SQLException { - setNull(parameterIndex, sqlType); - } - - public ParameterMetaData getParameterMetaData() throws SQLException { - throw new SQLException("not supported"); - } - - public void registerOutputParameter(String parameterName, int sqlType) - throws SQLException { - throw new SQLException("not supported"); - } - - public void registerOutputParameter(String parameterName, int sqlType, - int scale) - throws SQLException { - throw new SQLException("not supported"); - } - - public void registerOutputParameter(String parameterName, int sqlType, - String typeName) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.net.URL getURL(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public void setURL(int parameterIndex, java.net.URL url) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setNull(String parameterName, int sqlType) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setBoolean(String parameterName, boolean val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setByte(String parameterName, byte val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setShort(String parameterName, short val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setInt(String parameterName, int val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setLong(String parameterName, long val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setFloat(String parameterName, float val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setDouble(String parameterName, double val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setBigDecimal(String parameterName, BigDecimal val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setString(String parameterName, String val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setBytes(String parameterName, byte val[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setDate(String parameterName, java.sql.Date val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setTime(String parameterName, java.sql.Time val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setTimestamp(String parameterName, java.sql.Timestamp val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setAsciiStream(String parameterName, - java.io.InputStream s, int length) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setBinaryStream(String parameterName, - java.io.InputStream s, int length) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setObject(String parameterName, Object val, int targetSqlType, - int scale) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setObject(String parameterName, Object val, int targetSqlType) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setObject(String parameterName, Object val) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setCharacterStream(String parameterName, - java.io.Reader r, int length) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setDate(String parameterName, java.sql.Date val, - Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setTime(String parameterName, java.sql.Time val, - Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setTimestamp(String parameterName, java.sql.Timestamp val, - Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public void setNull(String parameterName, int sqlType, String typeName) - throws SQLException { - throw new SQLException("not supported"); - } - - public String getString(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public boolean getBoolean(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public byte getByte(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public short getShort(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public int getInt(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public long getLong(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public float getFloat(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public double getDouble(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public byte[] getBytes(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Date getDate(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Time getTime(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Timestamp getTimestamp(String parameterName) - throws SQLException { - throw new SQLException("not supported"); - } - - public Object getObject(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Object getObject(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public BigDecimal getBigDecimal(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Object getObject(String parameterName, Map map) - throws SQLException { - throw new SQLException("not supported"); - } - - public Object getObject(int parameterIndex, Map map) - throws SQLException { - throw new SQLException("not supported"); - } - - public Ref getRef(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public Ref getRef(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Blob getBlob(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Blob getBlob(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public Clob getClob(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Clob getClob(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public Array getArray(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - - public Array getArray(int parameterIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Date getDate(String parameterName, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Date getDate(int parameterIndex, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Time getTime(String parameterName, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Time getTime(int parameterIndex, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.net.URL getURL(String parameterName) throws SQLException { - throw new SQLException("not supported"); - } - -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCResultSet.java b/sql/src/main/java/SQLite/JDBC2y/JDBCResultSet.java deleted file mode 100644 index 06384eb..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCResultSet.java +++ /dev/null @@ -1,932 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; -import java.math.BigDecimal; - -public class JDBCResultSet implements java.sql.ResultSet { - - /** - * Current row to be retrieved. - */ - private int row; - - /** - * Table returned by Database.get_table() - */ - protected SQLite.TableResult tr; - - /** - * Statement from which result set was produced. - */ - private JDBCStatement s; - - /** - * Meta data for result set or null. - */ - private JDBCResultSetMetaData m; - - /** - * Last result cell retrieved or null. - */ - private String lastg; - - - public JDBCResultSet(SQLite.TableResult tr, JDBCStatement s) { - this.tr = tr; - this.s = s; - this.m = null; - this.lastg = null; - this.row = -1; - } - - public boolean next() throws SQLException { - if (tr == null) { - return false; - } - row++; - return row < tr.nrows; - } - - public int findColumn(String columnName) throws SQLException { - JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData(); - return m.findColByName(columnName); - } - - public int getRow() throws SQLException { - if (tr == null) { - throw new SQLException("no rows"); - } - return row + 1; - } - - public boolean previous() throws SQLException { - if (tr == null) { - return false; - } - if (row >= 0) { - row--; - } - return row >= 0; - } - - public boolean absolute(int row) throws SQLException { - if (tr == null) { - return false; - } - if (row < 0) { - row = tr.nrows + 1 + row; - } - row--; - if (row < 0 || row > tr.nrows) { - return false; - } - this.row = row; - return true; - } - - public boolean relative(int row) throws SQLException { - if (tr == null) { - return false; - } - if (this.row + row < 0 || this.row + row >= tr.nrows) { - return false; - } - this.row += row; - return true; - } - - public void setFetchDirection(int dir) throws SQLException { - throw new SQLException("not supported"); - } - - public int getFetchDirection() throws SQLException { - throw new SQLException("not supported"); - } - - public void setFetchSize(int fsize) throws SQLException { - throw new SQLException("not supported"); - } - - public int getFetchSize() throws SQLException { - throw new SQLException("not supported"); - } - - public String getString(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - return lastg; - } - - public String getString(String columnName) throws SQLException { - int col = findColumn(columnName); - return getString(col); - } - - public int getInt(int columnIndex) throws SQLException { - Integer i = internalGetInt(columnIndex); - if (i != null) { - return i.intValue(); - } - return 0; - } - - private Integer internalGetInt(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return Integer.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public int getInt(String columnName) throws SQLException { - int col = findColumn(columnName); - return getInt(col); - } - - public boolean getBoolean(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public boolean getBoolean(String columnName) throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSetMetaData getMetaData() throws SQLException { - if (m == null) { - m = new JDBCResultSetMetaData(this); - } - return m; - } - - public short getShort(int columnIndex) throws SQLException { - Short s = internalGetShort(columnIndex); - if (s != null) { - return s.shortValue(); - } - return 0; - } - - private Short internalGetShort(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return Short.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public short getShort(String columnName) throws SQLException { - int col = findColumn(columnName); - return getShort(col); - } - - public java.sql.Time getTime(int columnIndex) throws SQLException { - return internalGetTime(columnIndex, null); - } - - private java.sql.Time internalGetTime(int columnIndex, - java.util.Calendar cal) - throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return java.sql.Time.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public java.sql.Time getTime(String columnName) throws SQLException { - int col = findColumn(columnName); - return getTime(col); - } - - public java.sql.Time getTime(int columnIndex, java.util.Calendar cal) - throws SQLException { - return internalGetTime(columnIndex, cal); - } - - public java.sql.Time getTime(String columnName, java.util.Calendar cal) - throws SQLException{ - int col = findColumn(columnName); - return getTime(col, cal); - } - - public java.sql.Timestamp getTimestamp(int columnIndex) - throws SQLException{ - return internalGetTimestamp(columnIndex, null); - } - - private java.sql.Timestamp internalGetTimestamp(int columnIndex, - java.util.Calendar cal) - throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return java.sql.Timestamp.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public java.sql.Timestamp getTimestamp(String columnName) - throws SQLException{ - int col = findColumn(columnName); - return getTimestamp(col); - } - - public java.sql.Timestamp getTimestamp(int columnIndex, - java.util.Calendar cal) - throws SQLException { - return internalGetTimestamp(columnIndex, cal); - } - - public java.sql.Timestamp getTimestamp(String columnName, - java.util.Calendar cal) - throws SQLException { - int col = findColumn(columnName); - return getTimestamp(col, cal); - } - - public java.sql.Date getDate(int columnIndex) throws SQLException { - return internalGetDate(columnIndex, null); - } - - private java.sql.Date internalGetDate(int columnIndex, - java.util.Calendar cal) - throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return java.sql.Date.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public java.sql.Date getDate(String columnName) throws SQLException { - int col = findColumn(columnName); - return getDate(col); - } - - public java.sql.Date getDate(int columnIndex, java.util.Calendar cal) - throws SQLException{ - return internalGetDate(columnIndex, cal); - } - - public java.sql.Date getDate(String columnName, java.util.Calendar cal) - throws SQLException{ - int col = findColumn(columnName); - return getDate(col, cal); - } - - public double getDouble(int columnIndex) throws SQLException { - Double d = internalGetDouble(columnIndex); - if (d != null) { - return d.doubleValue(); - } - return 0; - } - - private Double internalGetDouble(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return Double.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public double getDouble(String columnName) throws SQLException { - int col = findColumn(columnName); - return getDouble(col); - } - - public float getFloat(int columnIndex) throws SQLException { - Float f = internalGetFloat(columnIndex); - if (f != null) { - return f.floatValue(); - } - return 0; - } - - private Float internalGetFloat(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return Float.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public float getFloat(String columnName) throws SQLException { - int col = findColumn(columnName); - return getFloat(col); - } - - public long getLong(int columnIndex) throws SQLException { - Long l = internalGetLong(columnIndex); - if (l != null) { - return l.longValue(); - } - return 0; - } - - private Long internalGetLong(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - try { - return Long.valueOf(lastg); - } catch (java.lang.Exception e) { - lastg = null; - } - return null; - } - - public long getLong(String columnName) throws SQLException { - int col = findColumn(columnName); - return getLong(col); - } - - @Deprecated - public java.io.InputStream getUnicodeStream(int columnIndex) - throws SQLException { - throw new SQLException("not supported"); - } - - @Deprecated - public java.io.InputStream getUnicodeStream(String columnName) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.InputStream getAsciiStream(String columnName) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.InputStream getAsciiStream(int columnIndex) - throws SQLException { - throw new SQLException("not supported"); - } - - public BigDecimal getBigDecimal(String columnName) - throws SQLException { - throw new SQLException("not supported"); - } - - @Deprecated - public BigDecimal getBigDecimal(String columnName, int scale) - throws SQLException { - throw new SQLException("not supported"); - } - - public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - @Deprecated - public BigDecimal getBigDecimal(int columnIndex, int scale) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.InputStream getBinaryStream(int columnIndex) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.InputStream getBinaryStream(String columnName) - throws SQLException { - throw new SQLException("not supported"); - } - - public byte getByte(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public byte getByte(String columnName) throws SQLException { - throw new SQLException("not supported"); - } - - public byte[] getBytes(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - byte ret[] = null; - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - if (lastg != null) { - ret = SQLite.StringEncoder.decode(lastg); - } - return ret; - } - - public byte[] getBytes(String columnName) throws SQLException { - int col = findColumn(columnName); - return getBytes(col); - } - - public String getCursorName() throws SQLException { - return null; - } - - public Object getObject(int columnIndex) throws SQLException { - if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { - throw new SQLException("column " + columnIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[columnIndex - 1]; - Object ret = lastg; - if (tr instanceof TableResultX) { - switch (((TableResultX) tr).sql_type[columnIndex - 1]) { - case Types.SMALLINT: - ret = internalGetShort(columnIndex); - break; - case Types.INTEGER: - ret = internalGetInt(columnIndex); - break; - case Types.DOUBLE: - ret = internalGetDouble(columnIndex); - break; - case Types.FLOAT: - ret = internalGetFloat(columnIndex); - break; - case Types.BIGINT: - ret = internalGetLong(columnIndex); - break; - case Types.BINARY: - case Types.VARBINARY: - case Types.LONGVARBINARY: - ret = getBytes(columnIndex); - break; - case Types.NULL: - ret = null; - break; - /* defaults to String below */ - } - } - return ret; - } - - public Object getObject(String columnName) throws SQLException { - int col = findColumn(columnName); - return getObject(col); - } - - public Object getObject(int columnIndex, java.util.Map map) - throws SQLException { - throw new SQLException("not supported"); - } - - public Object getObject(String columnIndex, java.util.Map map) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Ref getRef(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Ref getRef(String columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Blob getBlob(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Blob getBlob(String columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Clob getClob(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Clob getClob(String columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Array getArray(int columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.sql.Array getArray(String columnIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.Reader getCharacterStream(int columnIndex) - throws SQLException { - throw new SQLException("not supported"); - } - - public java.io.Reader getCharacterStream(String columnName) - throws SQLException { - throw new SQLException("not supported"); - } - - public SQLWarning getWarnings() throws SQLException { - throw new SQLException("not supported"); - } - - public boolean wasNull() throws SQLException { - return lastg == null; - } - - public void clearWarnings() throws SQLException { - throw new SQLException("not supported"); - } - - public boolean isFirst() throws SQLException { - if (tr == null) { - return true; - } - return row == 0; - } - - public boolean isBeforeFirst() throws SQLException { - if (tr == null || tr.nrows <= 0) { - return false; - } - return row < 0; - } - - public void beforeFirst() throws SQLException { - if (tr == null) { - return; - } - row = -1; - } - - public boolean first() throws SQLException { - if (tr == null || tr.nrows <= 0) { - return false; - } - row = 0; - return true; - } - - public boolean isAfterLast() throws SQLException { - if (tr == null || tr.nrows <= 0) { - return false; - } - return row >= tr.nrows; - } - - public void afterLast() throws SQLException { - if (tr == null) { - return; - } - row = tr.nrows; - } - - public boolean isLast() throws SQLException { - if (tr == null) { - return true; - } - return row == tr.nrows - 1; - } - - public boolean last() throws SQLException { - if (tr == null || tr.nrows <= 0) { - return false; - } - row = tr.nrows -1; - return true; - } - - public int getType() throws SQLException { - return TYPE_SCROLL_INSENSITIVE; - } - - public int getConcurrency() throws SQLException { - return CONCUR_READ_ONLY; - } - - public boolean rowUpdated() throws SQLException { - throw new SQLException("not supported"); - } - - public boolean rowInserted() throws SQLException { - throw new SQLException("not supported"); - } - - public boolean rowDeleted() throws SQLException { - throw new SQLException("not supported"); - } - - public void insertRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void updateRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void deleteRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void refreshRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void cancelRowUpdates() throws SQLException { - throw new SQLException("not supported"); - } - - public void moveToInsertRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void moveToCurrentRow() throws SQLException { - throw new SQLException("not supported"); - } - - public void updateNull(int colIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBoolean(int colIndex, boolean b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateByte(int colIndex, byte b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateShort(int colIndex, short b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateInt(int colIndex, int b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateLong(int colIndex, long b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateFloat(int colIndex, float f) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateDouble(int colIndex, double f) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBigDecimal(int colIndex, BigDecimal f) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateString(int colIndex, String s) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBytes(int colIndex, byte[] s) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateDate(int colIndex, java.sql.Date d) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateTime(int colIndex, java.sql.Time t) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateTimestamp(int colIndex, java.sql.Timestamp t) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateAsciiStream(int colIndex, java.io.InputStream in, int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBinaryStream(int colIndex, java.io.InputStream in, int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateCharacterStream(int colIndex, java.io.Reader in, int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateObject(int colIndex, Object obj) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateObject(int colIndex, Object obj, int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateNull(String colIndex) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBoolean(String colIndex, boolean b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateByte(String colIndex, byte b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateShort(String colIndex, short b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateInt(String colIndex, int b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateLong(String colIndex, long b) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateFloat(String colIndex, float f) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateDouble(String colIndex, double f) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBigDecimal(String colIndex, BigDecimal f) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateString(String colIndex, String s) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBytes(String colIndex, byte[] s) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateDate(String colIndex, java.sql.Date d) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateTime(String colIndex, java.sql.Time t) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateTimestamp(String colIndex, java.sql.Timestamp t) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateAsciiStream(String colIndex, java.io.InputStream in, - int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBinaryStream(String colIndex, java.io.InputStream in, - int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateCharacterStream(String colIndex, java.io.Reader in, - int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateObject(String colIndex, Object obj) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateObject(String colIndex, Object obj, int s) - throws SQLException { - throw new SQLException("not supported"); - } - - public Statement getStatement() throws SQLException { - if (s == null) { - throw new SQLException("stale result set"); - } - return s; - } - - public void close() throws SQLException { - s = null; - tr = null; - lastg = null; - row = -1; - } - - public java.net.URL getURL(int colIndex) throws SQLException { - if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { - throw new SQLException("column " + colIndex + " not found"); - } - String rd[] = (String []) tr.rows.elementAt(row); - lastg = rd[colIndex - 1]; - java.net.URL url = null; - if (lastg == null) { - return url; - } - try { - url = new java.net.URL(lastg); - } catch (java.lang.Exception e) { - url = null; - } - return url; - } - - public java.net.URL getURL(String colIndex) throws SQLException { - int col = findColumn(colIndex); - return getURL(col); - } - - public void updateRef(int colIndex, java.sql.Ref x) throws SQLException { - throw new SQLException("not supported"); - } - - public void updateRef(String colIndex, java.sql.Ref x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBlob(int colIndex, java.sql.Blob x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateBlob(String colIndex, java.sql.Blob x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateClob(int colIndex, java.sql.Clob x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateClob(String colIndex, java.sql.Clob x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateArray(int colIndex, java.sql.Array x) - throws SQLException { - throw new SQLException("not supported"); - } - - public void updateArray(String colIndex, java.sql.Array x) - throws SQLException { - throw new SQLException("not supported"); - } - -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java b/sql/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java deleted file mode 100644 index 934ca78..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java +++ /dev/null @@ -1,212 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; - -public class JDBCResultSetMetaData implements java.sql.ResultSetMetaData { - - private JDBCResultSet r; - - public JDBCResultSetMetaData(JDBCResultSet r) { - this.r = r; - } - - public String getCatalogName(int column) throws java.sql.SQLException { - return null; - } - - public String getColumnClassName(int column) throws java.sql.SQLException { - column--; - if (r != null && r.tr != null) { - if (column < 0 || column >= r.tr.ncolumns) { - return null; - } - if (r.tr instanceof TableResultX) { - switch (((TableResultX) r.tr).sql_type[column]) { - case Types.SMALLINT: return "java.lang.Short"; - case Types.INTEGER: return "java.lang.Integer"; - case Types.DOUBLE: return "java.lang.Double"; - case Types.FLOAT: return "java.lang.Float"; - case Types.BIGINT: return "java.lang.Long"; - case Types.DATE: return "java.sql.Date"; - case Types.TIME: return "java.sql.Time"; - case Types.TIMESTAMP: return "java.sql.Timestamp"; - case Types.BINARY: - case Types.VARBINARY: return "[B"; - /* defaults to varchar below */ - } - } - return "java.lang.String"; - } - return null; - } - - public int getColumnCount() throws java.sql.SQLException { - if (r != null && r.tr != null) { - return r.tr.ncolumns; - } - return 0; - } - - public int getColumnDisplaySize(int column) throws java.sql.SQLException { - return 0; - } - - public String getColumnLabel(int column) throws java.sql.SQLException { - column--; - String c = null; - if (r != null && r.tr != null) { - if (column < 0 || column >= r.tr.ncolumns) { - return c; - } - c = r.tr.column[column]; - } - return c; - } - - public String getColumnName(int column) throws java.sql.SQLException { - column--; - String c = null; - if (r != null && r.tr != null) { - if (column < 0 || column >= r.tr.ncolumns) { - return c; - } - c = r.tr.column[column]; - if (c != null) { - int i = c.indexOf('.'); - if (i > 0) { - return c.substring(i + 1); - } - } - } - return c; - } - - public int getColumnType(int column) throws java.sql.SQLException { - column--; - if (r != null && r.tr != null) { - if (column >= 0 && column < r.tr.ncolumns) { - if (r.tr instanceof TableResultX) { - return ((TableResultX) r.tr).sql_type[column]; - } - return Types.VARCHAR; - } - } - throw new SQLException("bad column index"); - } - - public String getColumnTypeName(int column) throws java.sql.SQLException { - column--; - if (r != null && r.tr != null) { - if (column >= 0 && column < r.tr.ncolumns) { - if (r.tr instanceof TableResultX) { - switch (((TableResultX) r.tr).sql_type[column]) { - case Types.SMALLINT: return "smallint"; - case Types.INTEGER: return "integer"; - case Types.DOUBLE: return "double"; - case Types.FLOAT: return "float"; - case Types.BIGINT: return "bigint"; - case Types.DATE: return "date"; - case Types.TIME: return "time"; - case Types.TIMESTAMP: return "timestamp"; - case Types.BINARY: return "binary"; - case Types.VARBINARY: return "varbinary"; - /* defaults to varchar below */ - } - } - return "varchar"; - } - } - throw new SQLException("bad column index"); - } - - public int getPrecision(int column) throws java.sql.SQLException { - return 0; - } - - public int getScale(int column) throws java.sql.SQLException { - return 0; - } - - public String getSchemaName(int column) throws java.sql.SQLException { - return null; - } - - public String getTableName(int column) throws java.sql.SQLException { - column--; - String c = null; - if (r != null && r.tr != null) { - if (column < 0 || column >= r.tr.ncolumns) { - return c; - } - c = r.tr.column[column]; - if (c != null) { - int i = c.indexOf('.'); - if (i > 0) { - return c.substring(0, i); - } - c = null; - } - } - return c; - } - - public boolean isAutoIncrement(int column) throws java.sql.SQLException { - return false; - } - - public boolean isCaseSensitive(int column) throws java.sql.SQLException { - return false; - } - - public boolean isCurrency(int column) throws java.sql.SQLException { - return false; - } - - public boolean isDefinitelyWritable(int column) - throws java.sql.SQLException { - return true; - } - - public int isNullable(int column) throws java.sql.SQLException { - return columnNullableUnknown; - } - - public boolean isReadOnly(int column) throws java.sql.SQLException { - return false; - } - - public boolean isSearchable(int column) throws java.sql.SQLException { - return true; - } - - public boolean isSigned(int column) throws java.sql.SQLException { - return false; - } - - public boolean isWritable(int column) throws java.sql.SQLException { - return true; - } - - int findColByName(String columnName) throws java.sql.SQLException { - String c = null; - if (r != null && r.tr != null) { - for (int i = 0; i < r.tr.ncolumns; i++) { - c = r.tr.column[i]; - if (c != null) { - if (c.compareToIgnoreCase(columnName) == 0) { - return i + 1; - } - int k = c.indexOf('.'); - if (k > 0) { - c = c.substring(k + 1); - if (c.compareToIgnoreCase(columnName) == 0) { - return i + 1; - } - } - } - c = null; - } - } - throw new SQLException("column " + columnName + " not found"); - } -} diff --git a/sql/src/main/java/SQLite/JDBC2y/JDBCStatement.java b/sql/src/main/java/SQLite/JDBC2y/JDBCStatement.java deleted file mode 100644 index 99d12d3..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/JDBCStatement.java +++ /dev/null @@ -1,287 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.*; -import java.util.*; - -public class JDBCStatement implements java.sql.Statement { - - protected JDBCConnection conn; - protected JDBCResultSet rs; - protected int updcnt; - private ArrayList<String> batch; - - public JDBCStatement(JDBCConnection conn) { - this.conn = conn; - this.updcnt = 0; - this.rs = null; - this.batch = null; - } - - public void setFetchSize(int fetchSize) throws SQLException { - throw new SQLException("not supported"); - } - - public int getFetchSize() throws SQLException { - return 1; - } - - public int getMaxRows() throws SQLException { - return 0; - } - - public void setMaxRows(int max) throws SQLException { - throw new SQLException("not supported"); - } - - public void setFetchDirection(int fetchDirection) throws SQLException { - throw new SQLException("not supported"); - } - - public int getFetchDirection() throws SQLException { - return ResultSet.FETCH_UNKNOWN; - } - - public int getResultSetConcurrency() throws SQLException { - return ResultSet.CONCUR_READ_ONLY; - } - - public int getResultSetType() throws SQLException { - return ResultSet.TYPE_SCROLL_INSENSITIVE; - } - - public void setQueryTimeout(int seconds) throws SQLException { - conn.timeout = seconds * 1000; - if (conn.timeout < 0) { - conn.timeout = 120000; - } else if (conn.timeout < 1000) { - conn.timeout = 5000; - } - } - - public int getQueryTimeout() throws SQLException { - return conn.timeout; - } - - public ResultSet getResultSet() throws SQLException { - return rs; - } - - ResultSet executeQuery(String sql, String args[], boolean updonly) - throws SQLException { - SQLite.TableResult tr = null; - if (rs != null) { - rs.close(); - rs = null; - } - updcnt = -1; - if (conn == null || conn.db == null) { - throw new SQLException("stale connection"); - } - int busy = 0; - boolean starttrans = !conn.autocommit && !conn.intrans; - while (true) { - try { - if (starttrans) { - conn.db.exec("BEGIN TRANSACTION", null); - conn.intrans = true; - } - if (args == null) { - if (updonly) { - conn.db.exec(sql, null); - } else { - tr = conn.db.get_table(sql); - } - } else { - if (updonly) { - conn.db.exec(sql, null, args); - } else { - tr = conn.db.get_table(sql, args); - } - } - updcnt = (int) conn.db.changes(); - } catch (SQLite.Exception e) { - if (conn.db.is3() && - conn.db.last_error() == SQLite.Constants.SQLITE_BUSY && - conn.busy3(conn.db, ++busy)) { - try { - if (starttrans && conn.intrans) { - conn.db.exec("ROLLBACK", null); - conn.intrans = false; - } - } catch (SQLite.Exception ee) { - } - try { - int ms = 20 + busy * 10; - if (ms > 1000) { - ms = 1000; - } - synchronized (this) { - this.wait(ms); - } - } catch (java.lang.Exception eee) { - } - continue; - } - throw new SQLException(e.toString()); - } - break; - } - if (!updonly && tr == null) { - throw new SQLException("no result set produced"); - } - if (!updonly && tr != null) { - rs = new JDBCResultSet(new TableResultX(tr), this); - } - return rs; - } - - public ResultSet executeQuery(String sql) throws SQLException { - return executeQuery(sql, null, false); - } - - public boolean execute(String sql) throws SQLException { - return executeQuery(sql) != null; - } - - public void cancel() throws SQLException { - if (conn == null || conn.db == null) { - throw new SQLException("stale connection"); - } - conn.db.interrupt(); - } - - public void clearWarnings() throws SQLException { - } - - public Connection getConnection() throws SQLException { - return conn; - } - - public void addBatch(String sql) throws SQLException { - if (batch == null) { - batch = new ArrayList<String>(1); - } - batch.add(sql); - } - - public int[] executeBatch() throws SQLException { - if (batch == null) { - return new int[0]; - } - int[] ret = new int[batch.size()]; - for (int i = 0; i < ret.length; i++) { - ret[i] = EXECUTE_FAILED; - } - int errs = 0; - for (int i = 0; i < ret.length; i++) { - try { - execute((String) batch.get(i)); - ret[i] = updcnt; - } catch (SQLException e) { - ++errs; - } - } - if (errs > 0) { - throw new BatchUpdateException("batch failed", ret); - } - return ret; - } - - public void clearBatch() throws SQLException { - if (batch != null) { - batch.clear(); - batch = null; - } - } - - public void close() throws SQLException { - clearBatch(); - conn = null; - } - - public int executeUpdate(String sql) throws SQLException { - executeQuery(sql, null, true); - return updcnt; - } - - public int getMaxFieldSize() throws SQLException { - return 0; - } - - public boolean getMoreResults() throws SQLException { - if (rs != null) { - rs.close(); - rs = null; - } - return false; - } - - public int getUpdateCount() throws SQLException { - return updcnt; - } - - public SQLWarning getWarnings() throws SQLException { - return null; - } - - public void setCursorName(String name) throws SQLException { - throw new SQLException("not supported"); - } - - public void setEscapeProcessing(boolean enable) throws SQLException { - throw new SQLException("not supported"); - } - - public void setMaxFieldSize(int max) throws SQLException { - throw new SQLException("not supported"); - } - - public boolean getMoreResults(int x) throws SQLException { - throw new SQLException("not supported"); - } - - public ResultSet getGeneratedKeys() throws SQLException { - throw new SQLException("not supported"); - } - - public int executeUpdate(String sql, int autokeys) - throws SQLException { - if (autokeys != Statement.NO_GENERATED_KEYS) { - throw new SQLException("not supported"); - } - return executeUpdate(sql); - } - - public int executeUpdate(String sql, int colIndexes[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public int executeUpdate(String sql, String colIndexes[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public boolean execute(String sql, int autokeys) - throws SQLException { - if (autokeys != Statement.NO_GENERATED_KEYS) { - throw new SQLException("not supported"); - } - return execute(sql); - } - - public boolean execute(String sql, int colIndexes[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public boolean execute(String sql, String colIndexes[]) - throws SQLException { - throw new SQLException("not supported"); - } - - public int getResultSetHoldability() throws SQLException { - return ResultSet.HOLD_CURSORS_OVER_COMMIT; - } - -} diff --git a/sql/src/main/java/SQLite/JDBC2y/TableResultX.java b/sql/src/main/java/SQLite/JDBC2y/TableResultX.java deleted file mode 100644 index 205372f..0000000 --- a/sql/src/main/java/SQLite/JDBC2y/TableResultX.java +++ /dev/null @@ -1,37 +0,0 @@ -package SQLite.JDBC2y; - -import java.sql.Types; -import java.util.Vector; - -public class TableResultX extends SQLite.TableResult { - public int sql_type[]; - - public TableResultX() { - super(); - sql_type = new int[this.ncolumns]; - for (int i = 0; i < this.ncolumns; i++) { - sql_type[i] = Types.VARCHAR; - } - } - - public TableResultX(SQLite.TableResult tr) { - this.column = tr.column; - this.rows = tr.rows; - this.ncolumns = tr.ncolumns; - this.nrows = tr.nrows; - this.types = tr.types; - sql_type = new int[tr.ncolumns]; - for (int i = 0; i < this.ncolumns; i++) { - sql_type[i] = Types.VARCHAR; - } - if (tr.types != null) { - for (int i = 0; i < tr.types.length; i++) { - sql_type[i] = JDBCDatabaseMetaData.mapSqlType(tr.types[i]); - } - } - } - - void sql_types(int types[]) { - sql_type = types; - } -} diff --git a/sql/src/main/java/SQLite/JDBCDriver.java b/sql/src/main/java/SQLite/JDBCDriver.java deleted file mode 100644 index 63b95ee..0000000 --- a/sql/src/main/java/SQLite/JDBCDriver.java +++ /dev/null @@ -1,109 +0,0 @@ -package SQLite; - -import java.sql.*; -import java.util.Properties; - -public class JDBCDriver implements java.sql.Driver { - - public static final int MAJORVERSION = 1; - public static final int MINORVERSION = 2; - - private static java.lang.reflect.Constructor makeConn = null; - - protected Connection conn; - - static { - try { - Class connClass = null; - Class args[] = new Class[2]; - args[0] = Class.forName("java.lang.String"); - args[1] = args[0]; - String jvers = java.lang.System.getProperty("java.version"); - String cvers; - if (jvers == null || jvers.startsWith("1.0")) { - throw new java.lang.Exception("unsupported java version"); - } else if (jvers.startsWith("1.1")) { - cvers = "SQLite.JDBC1.JDBCConnection"; - } else if (jvers.startsWith("1.2") || jvers.startsWith("1.3")) { - cvers = "SQLite.JDBC2.JDBCConnection"; - } else if (jvers.startsWith("1.4")) { - cvers = "SQLite.JDBC2x.JDBCConnection"; - } else if (jvers.startsWith("1.5")) { - cvers = "SQLite.JDBC2y.JDBCConnection"; - try { - Class.forName(cvers); - } catch (java.lang.Exception e) { - cvers = "SQLite.JDBC2x.JDBCConnection"; - } - } else { - cvers = "SQLite.JDBC2z.JDBCConnection"; - try { - Class.forName(cvers); - } catch (java.lang.Exception e) { - cvers = "SQLite.JDBC2y.JDBCConnection"; - try { - Class.forName(cvers); - } catch (java.lang.Exception ee) { - cvers = "SQLite.JDBC2x.JDBCConnection"; - } - } - } - connClass = Class.forName(cvers); - makeConn = connClass.getConstructor(args); - java.sql.DriverManager.registerDriver(new JDBCDriver()); - } catch (java.lang.Exception e) { - System.err.println(e); - } - } - - public JDBCDriver() { - } - - public boolean acceptsURL(String url) throws SQLException { - return url.startsWith("sqlite:/") || - url.startsWith("jdbc:sqlite:/"); - } - - public Connection connect(String url, Properties info) - throws SQLException { - if (!acceptsURL(url)) { - return null; - } - Object args[] = new Object[2]; - args[0] = url; - if (info != null) { - args[1] = info.getProperty("encoding"); - } - if (args[1] == null) { - args[1] = java.lang.System.getProperty("SQLite.encoding"); - } - try { - conn = (Connection) makeConn.newInstance(args); - } catch (java.lang.reflect.InvocationTargetException ie) { - throw new SQLException(ie.getTargetException().toString()); - } catch (java.lang.Exception e) { - throw new SQLException(e.toString()); - } - return conn; - } - - public int getMajorVersion() { - return MAJORVERSION; - } - - public int getMinorVersion() { - return MINORVERSION; - } - - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) - throws SQLException { - DriverPropertyInfo p[] = new DriverPropertyInfo[1]; - DriverPropertyInfo pp = new DriverPropertyInfo("encoding", ""); - p[0] = pp; - return p; - } - - public boolean jdbcCompliant() { - return false; - } -} diff --git a/sql/src/main/java/SQLite/Shell.java b/sql/src/main/java/SQLite/Shell.java deleted file mode 100644 index 78d37a1..0000000 --- a/sql/src/main/java/SQLite/Shell.java +++ /dev/null @@ -1,669 +0,0 @@ -package SQLite; - -import SQLite.*; -import java.io.*; -import java.util.*; - -/** - * SQLite command line shell. This is a partial reimplementaion - * of sqlite/src/shell.c and can be invoked by:<P> - * - * <verb> - * java SQLite.Shell [OPTIONS] database [SHELLCMD] - * or - * java -jar sqlite.jar [OPTIONS] database [SHELLCMD] - * </verb> - */ - -public class Shell implements Callback { - Database db; - boolean echo; - int count; - int mode; - boolean showHeader; - String tableName; - String sep; - String cols[]; - int colwidth[]; - String destTable; - PrintWriter pw; - PrintWriter err; - - static final int MODE_Line = 0; - static final int MODE_Column = 1; - static final int MODE_List = 2; - static final int MODE_Semi = 3; - static final int MODE_Html = 4; - static final int MODE_Insert = 5; - static final int MODE_Insert2 = 6; - - public Shell(PrintWriter pw, PrintWriter err) { - this.pw = pw; - this.err = err; - } - - public Shell(PrintStream ps, PrintStream errs) { - pw = new PrintWriter(ps); - err = new PrintWriter(errs); - } - - protected Object clone() { - Shell s = new Shell(this.pw, this.err); - s.db = db; - s.echo = echo; - s.mode = mode; - s.count = 0; - s.showHeader = showHeader; - s.tableName = tableName; - s.sep = sep; - s.colwidth = colwidth; - return s; - } - - static public String sql_quote_dbl(String str) { - if (str == null) { - return "NULL"; - } - int i, single = 0, dbl = 0; - for (i = 0; i < str.length(); i++) { - if (str.charAt(i) == '\'') { - single++; - } else if (str.charAt(i) == '"') { - dbl++; - } - } - if (dbl == 0) { - return "\"" + str + "\""; - } - StringBuffer sb = new StringBuffer("\""); - for (i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (c == '"') { - sb.append("\"\""); - } else { - sb.append(c); - } - } - return sb.toString(); - } - - static public String sql_quote(String str) { - if (str == null) { - return "NULL"; - } - int i, single = 0, dbl = 0; - for (i = 0; i < str.length(); i++) { - if (str.charAt(i) == '\'') { - single++; - } else if (str.charAt(i) == '"') { - dbl++; - } - } - if (single == 0) { - return "'" + str + "'"; - } - if (dbl == 0) { - return "\"" + str + "\""; - } - StringBuffer sb = new StringBuffer("'"); - for (i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (c == '\'') { - sb.append("''"); - } else { - sb.append(c); - } - } - return sb.toString(); - } - - static String html_quote(String str) { - if (str == null) { - return "NULL"; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (c == '<') { - sb.append("<"); - } else if (c == '>') { - sb.append(">"); - } else if (c == '&') { - sb.append("&"); - } else { - int x = c; - if (x < 32 || x > 127) { - sb.append("&#" + x + ";"); - } else { - sb.append(c); - } - } - } - return sb.toString(); - } - - static boolean is_numeric(String str) { - try { - Double d = Double.valueOf(str); - } catch (java.lang.Exception e) { - return false; - } - return true; - } - - void set_table_name(String str) { - if (str == null) { - tableName = ""; - return; - } - tableName = Shell.sql_quote(str); - } - - public void columns(String args[]) { - cols = args; - } - - public void types(String args[]) { - /* Empty body to satisfy SQLite.Callback interface. */ - } - - public boolean newrow(String args[]) { - int i; - String tname; - switch (mode) { - case Shell.MODE_Line: - if (args.length == 0) { - break; - } - if (count++ > 0) { - pw.println(""); - } - for (i = 0; i < args.length; i++) { - pw.println(cols[i] + " = " + - args[i] == null ? "NULL" : args[i]); - } - break; - case Shell.MODE_Column: - String csep = ""; - if (count++ == 0) { - colwidth = new int[args.length]; - for (i = 0; i < args.length; i++) { - int w, n; - w = cols[i].length(); - if (w < 10) { - w = 10; - } - colwidth[i] = w; - if (showHeader) { - pw.print(csep + cols[i]); - csep = " "; - } - } - if (showHeader) { - pw.println(""); - } - } - if (args.length == 0) { - break; - } - csep = ""; - for (i = 0; i < args.length; i++) { - pw.print(csep + (args[i] == null ? "NULL" : args[i])); - csep = " "; - } - pw.println(""); - break; - case Shell.MODE_Semi: - case Shell.MODE_List: - if (count++ == 0 && showHeader) { - for (i = 0; i < args.length; i++) { - pw.print(cols[i] + - (i == args.length - 1 ? "\n" : sep)); - } - } - if (args.length == 0) { - break; - } - for (i = 0; i < args.length; i++) { - pw.print(args[i] == null ? "NULL" : args[i]); - if (mode == Shell.MODE_Semi) { - pw.print(";"); - } else if (i < args.length - 1) { - pw.print(sep); - } - } - pw.println(""); - break; - case MODE_Html: - if (count++ == 0 && showHeader) { - pw.print("<TR>"); - for (i = 0; i < args.length; i++) { - pw.print("<TH>" + html_quote(cols[i]) + "</TH>"); - } - pw.println("</TR>"); - } - if (args.length == 0) { - break; - } - pw.print("<TR>"); - for (i = 0; i < args.length; i++) { - pw.print("<TD>" + html_quote(args[i]) + "</TD>"); - } - pw.println("</TR>"); - break; - case MODE_Insert: - if (args.length == 0) { - break; - } - tname = tableName; - if (destTable != null) { - tname = destTable; - } - pw.print("INSERT INTO " + tname + " VALUES("); - for (i = 0; i < args.length; i++) { - String tsep = i > 0 ? "," : ""; - if (args[i] == null) { - pw.print(tsep + "NULL"); - } else if (is_numeric(args[i])) { - pw.print(tsep + args[i]); - } else { - pw.print(tsep + sql_quote(args[i])); - } - } - pw.println(");"); - break; - case MODE_Insert2: - if (args.length == 0) { - break; - } - tname = tableName; - if (destTable != null) { - tname = destTable; - } - pw.print("INSERT INTO " + tname + " VALUES("); - for (i = 0; i < args.length; i++) { - String tsep = i > 0 ? "," : ""; - pw.print(tsep + args[i]); - } - pw.println(");"); - break; - } - return false; - } - - void do_meta(String line) { - StringTokenizer st = new StringTokenizer(line.toLowerCase()); - int n = st.countTokens(); - if (n <= 0) { - return; - } - String cmd = st.nextToken(); - String args[] = new String[n - 1]; - int i = 0; - while (st.hasMoreTokens()) { - args[i] = st.nextToken(); - ++i; - } - if (cmd.compareTo(".dump") == 0) { - new DBDump(this, args); - return; - } - if (cmd.compareTo(".echo") == 0) { - if (args.length > 0 && - (args[0].startsWith("y") || args[0].startsWith("on"))) { - echo = true; - } - return; - } - if (cmd.compareTo(".exit") == 0) { - try { - db.close(); - } catch (Exception e) { - } - System.exit(0); - } - if (cmd.compareTo(".header") == 0) { - if (args.length > 0 && - (args[0].startsWith("y") || args[0].startsWith("on"))) { - showHeader = true; - } - return; - } - if (cmd.compareTo(".help") == 0) { - pw.println(".dump ?TABLE? ... Dump database in text fmt"); - pw.println(".echo ON|OFF Command echo on or off"); - pw.println(".enc ?NAME? Change encoding"); - pw.println(".exit Exit program"); - pw.println(".header ON|OFF Display headers on or off"); - pw.println(".help This message"); - pw.println(".mode MODE Set output mode to\n" + - " line, column, insert\n" + - " list, or html"); - pw.println(".mode insert TABLE Generate SQL insert stmts"); - pw.println(".schema ?PATTERN? List table schema"); - pw.println(".separator STRING Set separator string"); - pw.println(".tables ?PATTERN? List table names"); - return; - } - if (cmd.compareTo(".mode") == 0) { - if (args.length > 0) { - if (args[0].compareTo("line") == 0) { - mode = Shell.MODE_Line; - } else if (args[0].compareTo("column") == 0) { - mode = Shell.MODE_Column; - } else if (args[0].compareTo("list") == 0) { - mode = Shell.MODE_List; - } else if (args[0].compareTo("html") == 0) { - mode = Shell.MODE_Html; - } else if (args[0].compareTo("insert") == 0) { - mode = Shell.MODE_Insert; - if (args.length > 1) { - destTable = args[1]; - } - } - } - return; - } - if (cmd.compareTo(".separator") == 0) { - if (args.length > 0) { - sep = args[0]; - } - return; - } - if (cmd.compareTo(".tables") == 0) { - TableResult t = null; - if (args.length > 0) { - try { - String qarg[] = new String[1]; - qarg[0] = args[0]; - t = db.get_table("SELECT name FROM sqlite_master " + - "WHERE type='table' AND " + - "name LIKE '%%%q%%' " + - "ORDER BY name", qarg); - } catch (Exception e) { - err.println("SQL Error: " + e); - err.flush(); - } - } else { - try { - t = db.get_table("SELECT name FROM sqlite_master " + - "WHERE type='table' ORDER BY name"); - } catch (Exception e) { - err.println("SQL Error: " + e); - err.flush(); - } - } - if (t != null) { - for (i = 0; i < t.nrows; i++) { - String tab = ((String[]) t.rows.elementAt(i))[0]; - if (tab != null) { - pw.println(tab); - } - } - } - return; - } - if (cmd.compareTo(".schema") == 0) { - if (args.length > 0) { - try { - String qarg[] = new String[1]; - qarg[0] = args[0]; - db.exec("SELECT sql FROM sqlite_master " + - "WHERE type!='meta' AND " + - "name LIKE '%%%q%%' AND " + - "sql NOTNULL " + - "ORDER BY type DESC, name", - this, qarg); - } catch (Exception e) { - err.println("SQL Error: " + e); - err.flush(); - } - } else { - try { - db.exec("SELECT sql FROM sqlite_master " + - "WHERE type!='meta' AND " + - "sql NOTNULL " + - "ORDER BY tbl_name, type DESC, name", - this); - } catch (Exception e) { - err.println("SQL Error: " + e); - err.flush(); - } - } - return; - } - if (cmd.compareTo(".enc") == 0) { - try { - db.set_encoding(args.length > 0 ? args[0] : null); - } catch (Exception e) { - err.println("" + e); - err.flush(); - } - return; - } - err.println("Unknown command '" + cmd + "'"); - err.flush(); - } - - String read_line(BufferedReader is, String prompt) { - try { - if (prompt != null) { - pw.print(prompt); - pw.flush(); - } - String line = is.readLine(); - return line; - } catch (IOException e) { - return null; - } - } - - void do_input(BufferedReader is) { - String line, sql = null; - String prompt = "SQLITE> "; - while ((line = read_line(is, prompt)) != null) { - if (echo) { - pw.println(line); - } - if (line.length() > 0 && line.charAt(0) == '.') { - do_meta(line); - } else { - if (sql == null) { - sql = line; - } else { - sql = sql + " " + line; - } - if (Database.complete(sql)) { - try { - db.exec(sql, this); - } catch (Exception e) { - if (!echo) { - err.println(sql); - } - err.println("SQL Error: " + e); - err.flush(); - } - sql = null; - prompt = "SQLITE> "; - } else { - prompt = "SQLITE? "; - } - } - pw.flush(); - } - if (sql != null) { - err.println("Incomplete SQL: " + sql); - err.flush(); - } - } - - void do_cmd(String sql) { - if (db == null) { - return; - } - if (sql.length() > 0 && sql.charAt(0) == '.') { - do_meta(sql); - } else { - try { - db.exec(sql, this); - } catch (Exception e) { - err.println("SQL Error: " + e); - err.flush(); - } - } - } - - public static void main(String args[]) { - Shell s = new Shell(System.out, System.err); - s.mode = Shell.MODE_List; - s.sep = "|"; - s.showHeader = false; - s.db = new Database(); - String dbname = null, sql = null; - for (int i = 0; i < args.length; i++) { - if(args[i].compareTo("-html") ==0) { - s.mode = Shell.MODE_Html; - } else if (args[i].compareTo("-list") == 0) { - s.mode = Shell.MODE_List; - } else if (args[i].compareTo("-line") == 0) { - s.mode = Shell.MODE_Line; - } else if (i < args.length - 1 && - args[i].compareTo("-separator") == 0) { - ++i; - s.sep = args[i]; - } else if (args[i].compareTo("-header") == 0) { - s.showHeader = true; - } else if (args[i].compareTo("-noheader") == 0) { - s.showHeader = false; - } else if (args[i].compareTo("-echo") == 0) { - s.echo = true; - } else if (dbname == null) { - dbname = args[i]; - } else if (sql == null) { - sql = args[i]; - } else { - System.err.println("Arguments: ?OPTIONS? FILENAME ?SQL?"); - System.exit(1); - } - } - if (dbname == null) { - System.err.println("No database file given"); - System.exit(1); - } - try { - s.db.open(dbname, 0); - } catch (Exception e) { - System.err.println("Unable to open database: " + e); - System.exit(1); - } - if (sql != null) { - s.do_cmd(sql); - } else { - // BEGIN android-modified - BufferedReader is = - new BufferedReader(new InputStreamReader(System.in), 8192); - // END android-modified - s.do_input(is); - } - try { - s.db.close(); - } catch (Exception ee) { - } - } -} - -/** - * Internal class for dumping an entire database. - * It contains a special callback interface to traverse the - * tables of the current database and output create SQL statements - * and for the data insert SQL statements. - */ - -class DBDump implements Callback { - Shell s; - - DBDump(Shell s, String tables[]) { - this.s = s; - s.pw.println("BEGIN TRANSACTION;"); - if (tables == null || tables.length == 0) { - try { - s.db.exec("SELECT name, type, sql FROM sqlite_master " + - "WHERE type!='meta' AND sql NOT NULL " + - "ORDER BY substr(type,2,1), name", this); - } catch (Exception e) { - s.err.println("SQL Error: " + e); - s.err.flush(); - } - } else { - String arg[] = new String[1]; - for (int i = 0; i < tables.length; i++) { - arg[0] = tables[i]; - try { - s.db.exec("SELECT name, type, sql FROM sqlite_master " + - "WHERE tbl_name LIKE '%q' AND type!='meta' " + - " AND sql NOT NULL " + - " ORDER BY substr(type,2,1), name", - this, arg); - } catch (Exception e) { - s.err.println("SQL Error: " + e); - s.err.flush(); - } - } - } - s.pw.println("COMMIT;"); - } - - public void columns(String col[]) { - /* Empty body to satisfy SQLite.Callback interface. */ - } - - public void types(String args[]) { - /* Empty body to satisfy SQLite.Callback interface. */ - } - - public boolean newrow(String args[]) { - if (args.length != 3) { - return true; - } - s.pw.println(args[2] + ";"); - if (args[1].compareTo("table") == 0) { - Shell s2 = (Shell) s.clone(); - s2.mode = Shell.MODE_Insert; - s2.set_table_name(args[0]); - String qargs[] = new String[1]; - qargs[0] = args[0]; - try { - if (s2.db.is3()) { - TableResult t = null; - t = s2.db.get_table("PRAGMA table_info('%q')", qargs); - String query; - if (t != null) { - StringBuffer sb = new StringBuffer(); - String sep = ""; - - sb.append("SELECT "); - for (int i = 0; i < t.nrows; i++) { - String col = ((String[]) t.rows.elementAt(i))[1]; - sb.append(sep + "quote(" + - Shell.sql_quote_dbl(col) + ")"); - sep = ","; - } - sb.append(" from '%q'"); - query = sb.toString(); - s2.mode = Shell.MODE_Insert2; - } else { - query = "SELECT * from '%q'"; - } - s2.db.exec(query, s2, qargs); - } else { - s2.db.exec("SELECT * from '%q'", s2, qargs); - } - } catch (Exception e) { - s.err.println("SQL Error: " + e); - s.err.flush(); - return true; - } - } - return false; - } -} diff --git a/sql/src/main/java/SQLite/StringEncoder.java b/sql/src/main/java/SQLite/StringEncoder.java deleted file mode 100644 index c2f20ad..0000000 --- a/sql/src/main/java/SQLite/StringEncoder.java +++ /dev/null @@ -1,201 +0,0 @@ -package SQLite; - -/** - * String encoder/decoder for SQLite. - * - * This module was kindly donated by Eric van der Maarel of Nedap N.V. - * - * This encoder was implemented based on an original idea from an anonymous - * author in the source code of the SQLite distribution. - * I feel obliged to provide a quote from the original C-source code: - * - * "The author disclaims copyright to this source code. In place of - * a legal notice, here is a blessing: - * - * May you do good and not evil. - * May you find forgiveness for yourself and forgive others. - * May you share freely, never taking more than you give." - * - */ - -public class StringEncoder { - - /** - * Encodes the given byte array into a string that can be used by - * the SQLite database. The database cannot handle null (0x00) and - * the character '\'' (0x27). The encoding consists of escaping - * these characters with a reserved character (0x01). The escaping - * is applied after determining and applying a shift that minimizes - * the number of escapes required. - * With this encoding the data of original size n is increased to a - * maximum of 1+(n*257)/254. - * For sufficiently large n the overhead is thus less than 1.2%. - * @param a the byte array to be encoded. A null reference is handled as - * an empty array. - * @return the encoded bytes as a string. When an empty array is - * provided a string of length 1 is returned, the value of - * which is bogus. - * When decoded with this class' <code>decode</code> method - * a string of size 1 will return an empty byte array. - */ - - public static String encode(byte[] a) { - // check input - if (a == null || a.length == 0) { - // bogus shift, no data - return "x"; - } - // determine count - int[] cnt = new int[256]; - for (int i = 0 ; i < a.length; i++) { - cnt[a[i] & 0xff]++; - } - // determine shift for minimum number of escapes - int shift = 1; - int nEscapes = a.length; - for (int i = 1; i < 256; i++) { - if (i == '\'') { - continue; - } - int sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff]; - if (sum < nEscapes) { - nEscapes = sum; - shift = i; - if (nEscapes == 0) { - // cannot become smaller - break; - } - } - } - // construct encoded output - int outLen = a.length + nEscapes + 1; - StringBuffer out = new StringBuffer(outLen); - out.append((char)shift); - for (int i = 0; i < a.length; i++) { - // apply shift - char c = (char)((a[i] - shift)&0xff); - // insert escapes - if (c == 0) { // forbidden - out.append((char)1); - out.append((char)1); - } else if (c == 1) { // escape character - out.append((char)1); - out.append((char)2); - } else if (c == '\'') { // forbidden - out.append((char)1); - out.append((char)3); - } else { - out.append(c); - } - } - return out.toString(); - } - - /** - * Decodes the given string that is assumed to be a valid encoding - * of a byte array. Typically the given string is generated by - * this class' <code>encode</code> method. - * @param s the given string encoding. - * @return the byte array obtained from the decoding. - * @throws IllegalArgumentException when the string given is not - * a valid encoded string for this encoder. - */ - - public static byte[] decode(String s) { - char[] a = s.toCharArray(); - if (a.length > 2 && a[0] == 'X' && - a[1] == '\'' && a[a.length-1] == '\'') { - // SQLite3 BLOB syntax - byte[] result = new byte[(a.length-3)/2]; - for (int i = 2, k = 0; i < a.length - 1; i += 2, k++) { - byte tmp = (byte) (a[i] - '0'); - if (tmp > 15) { - tmp -= 0x20; - } - result[k] = (byte) (tmp << 4); - tmp = (byte) (a[i+1] - '0'); - if (tmp > 15) { - tmp -= 0x20; - } - result[k] |= tmp; - } - return result; - } - // first element is the shift - byte[] result = new byte[a.length-1]; - int i = 0; - int shift = s.charAt(i++); - int j = 0; - while (i < s.length()) { - int c; - if ((c = s.charAt(i++)) == 1) { // escape character found - if ((c = s.charAt(i++)) == 1) { - c = 0; - } else if (c == 2) { - c = 1; - } else if (c == 3) { - c = '\''; - } else { - throw new IllegalArgumentException( - "invalid string passed to decoder: " + j); - } - } - // do shift - result[j++] = (byte)((c + shift) & 0xff); - } - int outLen = j; - // provide array of correct length - if (result.length != outLen) { - result = byteCopy(result, 0, outLen, new byte[outLen]); - } - return result; - } - - /** - * Copies count elements from source, starting at element with - * index offset, to the given target. - * @param source the source. - * @param offset the offset. - * @param count the number of elements to be copied. - * @param target the target to be returned. - * @return the target being copied to. - */ - - private static byte[] byteCopy(byte[] source, int offset, - int count, byte[] target) { - for (int i = offset, j = 0; i < offset + count; i++, j++) { - target[j] = source[i]; - } - return target; - } - - - static final char[] xdigits = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; - - /** - * Encodes the given byte array into SQLite3 blob notation, ie X'..' - * @param a the byte array to be encoded. A null reference is handled as - * an empty array. - * @return the encoded bytes as a string. - */ - - public static String encodeX(byte[] a) { - // check input - if (a == null || a.length == 0) { - return "X''"; - } - int outLen = a.length + 3; - StringBuffer out = new StringBuffer(outLen); - out.append('X'); - out.append('\''); - for (int i = 0; i < a.length; i++) { - out.append(xdigits[a[i] >> 4]); - out.append(xdigits[a[i] & 0x0F]); - } - out.append('\''); - return out.toString(); - } -} diff --git a/sql/src/main/native/sqlite_jni_registration.c b/sql/src/main/native/sqlite_jni_registration.c deleted file mode 100644 index 1ef5192..0000000 --- a/sql/src/main/native/sqlite_jni_registration.c +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright 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. - */ - -#include "JNIHelp.h" -#include "sqlite_jni.h" - -/* Methods for class SQLite_Database */ -extern JNIEXPORT void JNICALL Java_SQLite_Database__1open - (JNIEnv *, jobject, jstring, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1open_1aux_1file - (JNIEnv *, jobject, jstring); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1finalize - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1close - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1exec__Ljava_lang_String_2LSQLite_Callback_2 - (JNIEnv *, jobject, jstring, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1exec__Ljava_lang_String_2LSQLite_Callback_2_3Ljava_lang_String_2 - (JNIEnv *, jobject, jstring, jobject, jobjectArray); -extern JNIEXPORT jlong JNICALL Java_SQLite_Database__1last_1insert_1rowid - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1interrupt - (JNIEnv *, jobject); -extern JNIEXPORT jlong JNICALL Java_SQLite_Database__1changes - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1busy_1handler - (JNIEnv *, jobject, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1busy_1timeout - (JNIEnv *, jobject, jint); -extern JNIEXPORT jboolean JNICALL Java_SQLite_Database__1complete - (JNIEnv *, jclass, jstring); -extern JNIEXPORT jstring JNICALL Java_SQLite_Database_version - (JNIEnv *, jclass); -extern JNIEXPORT jstring JNICALL Java_SQLite_Database_dbversion - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1create_1function - (JNIEnv *, jobject, jstring, jint, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1create_1aggregate - (JNIEnv *, jobject, jstring, jint, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1function_1type - (JNIEnv *, jobject, jstring, jint); -extern JNIEXPORT jstring JNICALL Java_SQLite_Database__1errmsg - (JNIEnv *, jobject); -extern JNIEXPORT jstring JNICALL Java_SQLite_Database_error_1string - (JNIEnv *, jclass, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1set_1encoding - (JNIEnv *, jobject, jstring); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1set_1authorizer - (JNIEnv *, jobject, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1trace - (JNIEnv *, jobject, jobject); -extern JNIEXPORT jboolean JNICALL Java_SQLite_Database_is3 - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database_vm_1compile - (JNIEnv *, jobject, jstring, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database_vm_1compile_1args - (JNIEnv *, jobject, jstring, jobject, jobjectArray); -extern JNIEXPORT void JNICALL Java_SQLite_Database_stmt_1prepare - (JNIEnv *, jobject, jstring, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1open_1blob - (JNIEnv *, jobject, jstring, jstring, jstring, jlong, jboolean, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database__1progress_1handler - (JNIEnv *, jobject, jint, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Database_internal_1init - (JNIEnv *, jclass); - - -/* Methods for class SQLite_Vm */ - -extern JNIEXPORT jboolean JNICALL Java_SQLite_Vm_step - (JNIEnv *, jobject, jobject); -extern JNIEXPORT jboolean JNICALL Java_SQLite_Vm_compile - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Vm_stop - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Vm_finalize - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Vm_internal_1init - (JNIEnv *, jclass); - -/* Methods for class SQLite_FunctionContext */ - -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1result__Ljava_lang_String_2 - (JNIEnv *, jobject, jstring); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1result__I - (JNIEnv *, jobject, jint); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1result__D - (JNIEnv *, jobject, jdouble); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1error - (JNIEnv *, jobject, jstring); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1result___3B - (JNIEnv *, jobject, jbyteArray); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_set_1result_1zeroblob - (JNIEnv *, jobject, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_FunctionContext_count - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_FunctionContext_internal_1init - (JNIEnv *, jclass); - -/* Methods for class SQLite_Stmt */ - -extern JNIEXPORT jboolean JNICALL Java_SQLite_Stmt_prepare - (JNIEnv *, jobject); -extern JNIEXPORT jboolean JNICALL Java_SQLite_Stmt_step - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_close - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_reset - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_clear_1bindings - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__II - (JNIEnv *, jobject, jint, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__IJ - (JNIEnv *, jobject, jint, jlong); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__ID - (JNIEnv *, jobject, jint, jdouble); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__I_3B - (JNIEnv *, jobject, jint, jbyteArray); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__ILjava_lang_String_2 - (JNIEnv *, jobject, jint, jstring); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind__I - (JNIEnv *, jobject, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_bind_1zeroblob - (JNIEnv *, jobject, jint, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_Stmt_bind_1parameter_1count - (JNIEnv *, jobject); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_bind_1parameter_1name - (JNIEnv *, jobject, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_Stmt_bind_1parameter_1index - (JNIEnv *, jobject, jstring); -extern JNIEXPORT jint JNICALL Java_SQLite_Stmt_column_1int - (JNIEnv *, jobject, jint); -extern JNIEXPORT jlong JNICALL Java_SQLite_Stmt_column_1long - (JNIEnv *, jobject, jint); -extern JNIEXPORT jdouble JNICALL Java_SQLite_Stmt_column_1double - (JNIEnv *, jobject, jint); -extern JNIEXPORT jbyteArray JNICALL Java_SQLite_Stmt_column_1bytes - (JNIEnv *, jobject, jint); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_column_1string - (JNIEnv *, jobject, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_Stmt_column_1type - (JNIEnv *, jobject, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_Stmt_column_1count - (JNIEnv *, jobject); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_column_1table_1name - (JNIEnv *, jobject, jint); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_column_1database_1name - (JNIEnv *, jobject, jint); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_column_1decltype - (JNIEnv *, jobject, jint); -extern JNIEXPORT jstring JNICALL Java_SQLite_Stmt_column_1origin_1name - (JNIEnv *, jobject, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_finalize - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Stmt_internal_1init - (JNIEnv *, jclass); - -/* Methods for class SQLite_Blob */ - -extern JNIEXPORT void JNICALL Java_SQLite_Blob_close - (JNIEnv *, jobject); -extern JNIEXPORT jint JNICALL Java_SQLite_Blob_write - (JNIEnv *, jobject, jbyteArray, jint, jint, jint); -extern JNIEXPORT jint JNICALL Java_SQLite_Blob_read - (JNIEnv *, jobject, jbyteArray, jint, jint, jint); -extern JNIEXPORT void JNICALL Java_SQLite_Blob_finalize - (JNIEnv *, jobject); -extern JNIEXPORT void JNICALL Java_SQLite_Blob_internal_1init - (JNIEnv *, jclass); - -/* - * JNI registration - */ -static JNINativeMethod sqliteDatabaseMethods[] = { - /* name, signature, funcPtr */ -/* Header for class SQLite_Database */ -{ "_open", "(Ljava/lang/String;I)V", Java_SQLite_Database__1open}, -{ "_open_aux_file", "(Ljava/lang/String;)V", Java_SQLite_Database__1open_1aux_1file}, -{ "_finalize", "()V", Java_SQLite_Database__1finalize}, -{ "_close", "()V", Java_SQLite_Database__1close}, -{ "_exec", "(Ljava/lang/String;LSQLite/Callback;)V", Java_SQLite_Database__1exec__Ljava_lang_String_2LSQLite_Callback_2}, -{ "_exec", "(Ljava/lang/String;LSQLite/Callback;[Ljava/lang/String;)V", Java_SQLite_Database__1exec__Ljava_lang_String_2LSQLite_Callback_2_3Ljava_lang_String_2}, -{ "_last_insert_rowid", "()J", Java_SQLite_Database__1last_1insert_1rowid}, -{ "_interrupt", "()V", Java_SQLite_Database__1interrupt}, -{ "_changes", "()J", Java_SQLite_Database__1changes}, -{ "_busy_handler", "(LSQLite/BusyHandler;)V", Java_SQLite_Database__1busy_1handler}, -{ "_busy_timeout", "(I)V", Java_SQLite_Database__1busy_1timeout}, -{ "_complete", "(Ljava/lang/String;)Z", Java_SQLite_Database__1complete}, -{ "version", "()Ljava/lang/String;", Java_SQLite_Database_version}, -{ "dbversion", "()Ljava/lang/String;", Java_SQLite_Database_dbversion}, -{ "_create_function", "(Ljava/lang/String;ILSQLite/Function;)V", Java_SQLite_Database__1create_1function}, -{ "_create_aggregate", "(Ljava/lang/String;ILSQLite/Function;)V", Java_SQLite_Database__1create_1aggregate}, -{ "_function_type", "(Ljava/lang/String;I)V", Java_SQLite_Database__1function_1type}, -{ "_errmsg", "()Ljava/lang/String;", Java_SQLite_Database__1errmsg}, -{ "error_string", "(I)Ljava/lang/String;", Java_SQLite_Database_error_1string}, -{ "_set_encoding", "(Ljava/lang/String;)V", Java_SQLite_Database__1set_1encoding}, -{ "_set_authorizer", "(LSQLite/Authorizer;)V", Java_SQLite_Database__1set_1authorizer}, -{ "_trace", "(LSQLite/Trace;)V", Java_SQLite_Database__1trace}, -{ "is3", "()Z", Java_SQLite_Database_is3}, -{ "vm_compile", "(Ljava/lang/String;LSQLite/Vm;)V", Java_SQLite_Database_vm_1compile}, -{ "vm_compile_args", "(Ljava/lang/String;LSQLite/Vm;[Ljava/lang/String;)V", Java_SQLite_Database_vm_1compile_1args}, -{ "stmt_prepare", "(Ljava/lang/String;LSQLite/Stmt;)V", Java_SQLite_Database_stmt_1prepare}, -{ "_open_blob", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JZLSQLite/Blob;)V", Java_SQLite_Database__1open_1blob}, -{ "_progress_handler", "(ILSQLite/ProgressHandler;)V", Java_SQLite_Database__1progress_1handler}, -{ "internal_init", "()V", Java_SQLite_Database_internal_1init} -}; - -static JNINativeMethod sqliteVmMethods[] = { -/* Header for class SQLite_Vm */ -{ "step", "(LSQLite/Callback;)Z", Java_SQLite_Vm_step}, -{ "compile", "()Z", Java_SQLite_Vm_compile}, -{ "stop", "()V", Java_SQLite_Vm_stop}, -{ "finalize", "()V", Java_SQLite_Vm_finalize}, -{ "internal_init", "()V", Java_SQLite_Vm_internal_1init} -}; - -static JNINativeMethod sqliteFunctionContextMethods[] = { -/* Header for class SQLite_FunctionContext */ -{ "set_result", "(Ljava/lang/String;)V", Java_SQLite_FunctionContext_set_1result__Ljava_lang_String_2}, -{ "set_result", "(I)V", Java_SQLite_FunctionContext_set_1result__I}, -{ "set_result", "(D)V", Java_SQLite_FunctionContext_set_1result__D}, -{ "set_error", "(Ljava/lang/String;)V", Java_SQLite_FunctionContext_set_1error}, -{ "set_result", "([B)V", Java_SQLite_FunctionContext_set_1result___3B}, -{ "set_result_zeroblob", "(I)V", Java_SQLite_FunctionContext_set_1result_1zeroblob}, -{ "count", "()I", Java_SQLite_FunctionContext_count}, -{ "internal_init", "()V", Java_SQLite_FunctionContext_internal_1init} -}; - -static JNINativeMethod sqliteStmtMethods[] = { -/* Header for class SQLite_Stmt */ -{ "prepare", "()Z", Java_SQLite_Stmt_prepare}, -{ "step", "()Z", JNICALL Java_SQLite_Stmt_step}, -{ "close", "()V", Java_SQLite_Stmt_close}, -{ "reset", "()V", Java_SQLite_Stmt_reset}, -{ "clear_bindings", "()V", Java_SQLite_Stmt_clear_1bindings}, -{ "bind", "(II)V", Java_SQLite_Stmt_bind__II}, -{ "bind", "(IJ)V", Java_SQLite_Stmt_bind__IJ}, -{ "bind", "(ID)V", Java_SQLite_Stmt_bind__ID}, -{ "bind", "(I[B)V", Java_SQLite_Stmt_bind__I_3B}, -{ "bind", "(ILjava/lang/String;)V", Java_SQLite_Stmt_bind__ILjava_lang_String_2}, -{ "bind", "(I)V", Java_SQLite_Stmt_bind__I}, -{ "bind_zeroblob", "(II)V", Java_SQLite_Stmt_bind_1zeroblob}, -{ "bind_parameter_count", "()I", Java_SQLite_Stmt_bind_1parameter_1count}, -{ "bind_parameter_name", "(I)Ljava/lang/String;", Java_SQLite_Stmt_bind_1parameter_1name}, -{ "bind_parameter_index", "(Ljava/lang/String;)I", Java_SQLite_Stmt_bind_1parameter_1index}, -{ "column_int", "(I)I", Java_SQLite_Stmt_column_1int}, -{ "column_long", "(I)J", Java_SQLite_Stmt_column_1long}, -{ "column_double", "(I)D", Java_SQLite_Stmt_column_1double}, -{ "column_bytes", "(I)[B", Java_SQLite_Stmt_column_1bytes}, -{ "column_string", "(I)Ljava/lang/String;", Java_SQLite_Stmt_column_1string}, -{ "column_type", "(I)I", Java_SQLite_Stmt_column_1type}, -{ "column_count", "()I", Java_SQLite_Stmt_column_1count}, -{ "column_table_name", "(I)Ljava/lang/String;", Java_SQLite_Stmt_column_1table_1name}, -{ "column_database_name", "(I)Ljava/lang/String;", Java_SQLite_Stmt_column_1database_1name}, -{ "column_decltype", "(I)Ljava/lang/String;", Java_SQLite_Stmt_column_1decltype}, -{ "column_origin_name", "(I)Ljava/lang/String;", Java_SQLite_Stmt_column_1origin_1name}, -{ "finalize", "()V", Java_SQLite_Stmt_finalize}, -{ "internal_init", "()V", Java_SQLite_Stmt_internal_1init} -}; - -static JNINativeMethod sqliteBlobMethods[] = { -/* Header for class SQLite_Blob */ - -{ "close", "()V", Java_SQLite_Blob_close}, -{ "write", "([BIII)I", Java_SQLite_Blob_write}, -{ "read", "([BIII)I", Java_SQLite_Blob_read}, -{ "finalize", "()V", Java_SQLite_Blob_finalize}, -{ "internal_init", "()V", Java_SQLite_Blob_internal_1init} -}; - -int register_SQLite_Database(JNIEnv* env) { - return jniRegisterNativeMethods(env, "SQLite/Database", - sqliteDatabaseMethods, NELEM(sqliteDatabaseMethods)); -} - -int register_SQLite_Vm(JNIEnv* env) { - return jniRegisterNativeMethods(env, "SQLite/Vm", - sqliteVmMethods, NELEM(sqliteVmMethods)); -} - -int register_SQLite_FunctionContext(JNIEnv* env) { - return jniRegisterNativeMethods(env, "SQLite/FunctionContext", - sqliteFunctionContextMethods, NELEM(sqliteFunctionContextMethods)); -} - -int register_SQLite_Stmt(JNIEnv* env) { - return jniRegisterNativeMethods(env, "SQLite/Stmt", - sqliteStmtMethods, NELEM(sqliteStmtMethods)); -} - -int register_SQLite_Blob(JNIEnv* env) { - return jniRegisterNativeMethods(env, "SQLite/Blob", - sqliteBlobMethods, NELEM(sqliteBlobMethods)); -} diff --git a/sql/src/main/native/sub.mk b/sql/src/main/native/sub.mk deleted file mode 100644 index d84e0b6..0000000 --- a/sql/src/main/native/sub.mk +++ /dev/null @@ -1,19 +0,0 @@ -# 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 := \ - sqlite_jni.c \ - sqlite_jni_registration.c - -LOCAL_C_INCLUDES += \ - external/sqlite/dist - -# Any shared/static libs that are listed here must also -# be listed in libs/nativehelper/Android.mk. -# TODO: fix this requirement - -LOCAL_SHARED_LIBRARIES += \ - libsqlite - -LOCAL_STATIC_LIBRARIES += diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java index 58c670a..1b0bb59 100644 --- a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java +++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.sql.tests.java.sql;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.java.sql;"); // $JUnit-BEGIN$ suite.addTestSuite(BatchUpdateExceptionTest.class); diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java index d53f078..069d46f 100644 --- a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java +++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java @@ -383,16 +383,9 @@ public class DriverManagerTest extends TestCase { } // end while // Check that all the drivers are in the list... - // BEGIN android-changed - // We have a ClassLoader issue in the DriverManager: The - // Drivermanager loads the System drivers in a static initialisation - // method loadInitialDrivers. This initialisation happens in the cts - // environment before the test sets the drivers via the system property - // "jdbc.drivers". - // Therefore the system drivers are not returned via getDrivers() - final int noOfSystemDriversLoaded = 2; //DRIVER4 + DRIVER5 - assertEquals("testGetDrivers: Don't see all the loaded drivers - ", numberLoaded - noOfSystemDriversLoaded, i); - // END android-changed + // There might be other drivers loaded in other classes + assertTrue("testGetDrivers: Don't see all the loaded drivers - ", + i >= numberLoaded); } // end method testGetDrivers() static int timeout1 = 25; @@ -759,5 +752,3 @@ public class DriverManagerTest extends TestCase { } } // end class DriverManagerTest - - diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java index abbb8b0..8183bbf 100644 --- a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java +++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.apache.harmony.sql.tests.javax.sql;"); + TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.javax.sql;"); // $JUnit-BEGIN$ suite.addTestSuite(ConnectionEventTest.class); diff --git a/sql/src/test/java/tests/SQLite/AllTests.java b/sql/src/test/java/tests/SQLite/AllTests.java index 2cf0f61..ea8b841 100644 --- a/sql/src/test/java/tests/SQLite/AllTests.java +++ b/sql/src/test/java/tests/SQLite/AllTests.java @@ -23,12 +23,11 @@ public class AllTests { //All tests executed with sqlite3 only public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for SQLite"); + TestSuite suite = new TestSuite("Tests for SQLite"); //$JUnit-BEGIN$ suite.addTestSuite(DatabaseTest.class); suite.addTestSuite(JDBCDriverFunctionalTest.class); suite.addTestSuite(JDBCDriverTest.class); - suite.addTestSuite(ConstantsTest.class); suite.addTestSuite(BlobTest.class); suite.addTestSuite(StmtTest.class); suite.addTestSuite(ExceptionTest.class); diff --git a/sql/src/test/java/tests/SQLite/ConstantsTest.java b/sql/src/test/java/tests/SQLite/ConstantsTest.java deleted file mode 100644 index 2a4961f..0000000 --- a/sql/src/test/java/tests/SQLite/ConstantsTest.java +++ /dev/null @@ -1,110 +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 dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - -@TestTargetClass(Constants.class) -public class ConstantsTest extends TestCase { - - /** - * @tests Constants#Constants() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "constructor test", - method = "Constants", - args = {} - ) - public void testConstants() { - Constants c = new Constants(); - - assertNotNull(c); - assertEquals(c.SQLITE_OK, 0); - assertEquals(c.SQLITE_ERROR, 1); - assertEquals(c.SQLITE_INTERNAL, 2); - assertEquals(c.SQLITE_PERM, 3); - assertEquals(c.SQLITE_ABORT, 4); - assertEquals(c.SQLITE_BUSY, 5); - assertEquals(c.SQLITE_LOCKED, 6); - assertEquals(c.SQLITE_NOMEM, 7); - assertEquals(c.SQLITE_READONLY, 8); - assertEquals(c.SQLITE_INTERRUPT, 9); - assertEquals(c.SQLITE_IOERR, 10); - assertEquals(c.SQLITE_CORRUPT, 11); - assertEquals(c.SQLITE_NOTFOUND, 12); - assertEquals(c.SQLITE_FULL, 13); - assertEquals(c.SQLITE_CANTOPEN, 14); - assertEquals(c.SQLITE_PROTOCOL, 15); - assertEquals(c.SQLITE_EMPTY, 16); - assertEquals(c.SQLITE_SCHEMA, 17); - assertEquals(c.SQLITE_TOOBIG, 18); - assertEquals(c.SQLITE_CONSTRAINT, 19); - assertEquals(c.SQLITE_MISMATCH, 20); - assertEquals(c.SQLITE_MISUSE, 21); - assertEquals(c.SQLITE_NOLFS, 22); - assertEquals(c.SQLITE_AUTH, 23); - assertEquals(c.SQLITE_FORMAT, 24); - assertEquals(c.SQLITE_RANGE, 25); - assertEquals(c.SQLITE_NOTADB, 26); - assertEquals(c.SQLITE_ROW, 100); - assertEquals(c.SQLITE_DONE, 101); - assertEquals(c.SQLITE_INTEGER, 1); - assertEquals(c.SQLITE_FLOAT, 2); - assertEquals(c.SQLITE_BLOB, 4); - assertEquals(c.SQLITE_NULL, 5); - assertEquals(c.SQLITE3_TEXT, 3); - assertEquals(c.SQLITE_NUMERIC, -1); - assertEquals(c.SQLITE_TEXT, 3); - assertEquals(c.SQLITE2_TEXT, -2); - assertEquals(c.SQLITE_ARGS, -3); - assertEquals(c.SQLITE_COPY, 0); - assertEquals(c.SQLITE_CREATE_INDEX, 1); - assertEquals(c.SQLITE_CREATE_TABLE, 2); - assertEquals(c.SQLITE_CREATE_TEMP_INDEX, 3); - assertEquals(c.SQLITE_CREATE_TEMP_TABLE, 4); - assertEquals(c.SQLITE_CREATE_TEMP_TRIGGER, 5); - assertEquals(c.SQLITE_CREATE_TEMP_VIEW, 6); - assertEquals(c.SQLITE_CREATE_TRIGGER, 7); - assertEquals(c.SQLITE_CREATE_VIEW, 8); - assertEquals(c.SQLITE_DELETE, 9); - assertEquals(c.SQLITE_DROP_INDEX, 10); - assertEquals(c.SQLITE_DROP_TABLE, 11); - assertEquals(c.SQLITE_DROP_TEMP_INDEX, 12); - assertEquals(c.SQLITE_DROP_TEMP_TABLE, 13); - assertEquals(c.SQLITE_DROP_TEMP_TRIGGER, 14); - assertEquals(c.SQLITE_DROP_TEMP_VIEW, 15); - assertEquals(c.SQLITE_DROP_TRIGGER, 16); - assertEquals(c.SQLITE_DROP_VIEW, 17); - assertEquals(c.SQLITE_INSERT, 18); - assertEquals(c.SQLITE_PRAGMA, 19); - assertEquals(c.SQLITE_READ, 20); - assertEquals(c.SQLITE_SELECT, 21); - assertEquals(c.SQLITE_TRANSACTION, 22); - assertEquals(c.SQLITE_UPDATE, 23); - assertEquals(c.SQLITE_ATTACH, 24); - assertEquals(c.SQLITE_DETACH, 25); - assertEquals(c.SQLITE_DENY, 1); - assertEquals(c.SQLITE_IGNORE, 2); - } -} diff --git a/sql/src/test/java/tests/SQLite/DatabaseTest.java b/sql/src/test/java/tests/SQLite/DatabaseTest.java index 95ce7c8..12a556d 100644 --- a/sql/src/test/java/tests/SQLite/DatabaseTest.java +++ b/sql/src/test/java/tests/SQLite/DatabaseTest.java @@ -1069,7 +1069,7 @@ public class DatabaseTest extends SQLiteTest { 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.SQLITE_TEXT); + db.function_type("myaggfunc", Constants.SQLITE3_TEXT); db.exec("PRAGMA show_datatypes = on", null); assertFalse(aggFunction.functionCalled); @@ -1125,7 +1125,7 @@ public class DatabaseTest extends SQLiteTest { null); db.create_function("sin", 1, sinFunc); - db.function_type("sin", Constants.SQLITE_NUMERIC); + db.function_type("sin", Constants.SQLITE_FLOAT); res = db.get_table("select sin(res) from TEST WHERE res = " + Double.toString(input)); @@ -2036,4 +2036,3 @@ public class DatabaseTest extends SQLiteTest { } } - diff --git a/sql/src/test/java/tests/SQLite/StmtTest.java b/sql/src/test/java/tests/SQLite/StmtTest.java index cb71243..7a37154 100644 --- a/sql/src/test/java/tests/SQLite/StmtTest.java +++ b/sql/src/test/java/tests/SQLite/StmtTest.java @@ -982,17 +982,6 @@ public class StmtTest extends SQLiteTest { } } - /** - * @throws Exception - * @tests {@link Stmt#column_type(int)} - */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "method test", - method = "column_type", - args = {int.class} - ) - @KnownFailure("For numeric, float and blob wrong type is returned") public void testColumn_type() throws Exception { db.exec(createAllTypes, null); db.exec(insertAllTypes, null); @@ -1033,10 +1022,8 @@ public class StmtTest extends SQLiteTest { assertEquals(Constants.SQLITE_NULL, st.column_type(29)); // Failing tests - assertTrue("NUMERIC".equalsIgnoreCase(st.column_decltype(12))); - assertEquals(Constants.SQLITE_NUMERIC, st.column_type(12)); // NUMERIC - // -> got - // INTEGER + 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 -> diff --git a/sql/src/test/java/tests/java/sql/AllTests.java b/sql/src/test/java/tests/java/sql/AllTests.java index c6a2bff..5c9345b 100644 --- a/sql/src/test/java/tests/java/sql/AllTests.java +++ b/sql/src/test/java/tests/java/sql/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.java.sql;"); + TestSuite suite = new TestSuite("All tests for package tests.java.sql;"); // $JUnit-BEGIN$ suite.addTestSuite(MultiThreadAccessTest.class); diff --git a/sql/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java b/sql/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java index b09b779..c03bd6f 100644 --- a/sql/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java +++ b/sql/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java @@ -941,23 +941,14 @@ public class DatabaseMetaDataNotSupportedTest extends TestCase { meta.ownInsertsAreVisible(100)); } - /** - * @tests {@link java.sql.DatabaseMetaData#ownUpdatesAreVisible(int)} - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "not supported. Verification with invalid parameters missed.", - method = "ownUpdatesAreVisible", - args = {int.class} - ) public void test_ownUpdatesAreVisibleI() throws SQLException { - assertFalse( + assertTrue( "result set's own updates are visible for TYPE_FORWARD_ONLY type", meta.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY)); - assertFalse( + assertTrue( "result set's own updates are visible for TYPE_SCROLL_INSENSITIVE type", meta.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); - assertFalse( + assertTrue( "result set's own updates are visible for TYPE_SCROLL_SENSITIVE type", meta.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); assertFalse("result set's own updates are visible for unknown type", @@ -1090,18 +1081,8 @@ public class DatabaseMetaDataNotSupportedTest extends TestCase { } - /** - * @tests java.sql.DatabaseMetaData#supportsBatchUpdates() - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "not supported", - method = "supportsBatchUpdates", - args = {} - ) public void test_supportsBatchUpdates() throws SQLException { - // NOT_FEASIBLE: SQLITE does not implement this functionality - assertFalse(meta.supportsBatchUpdates()); + assertTrue(meta.supportsBatchUpdates()); } /** @@ -1792,32 +1773,12 @@ public class DatabaseMetaDataNotSupportedTest extends TestCase { assertFalse(meta.supportsTransactions()); } - /** - * @tests java.sql.DatabaseMetaData#supportsUnion() - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "not supported", - method = "supportsUnion", - args = {} - ) public void test_supportsUnion() throws SQLException { - // NOT_FEASIBLE: SQLITE does not implement this functionality - assertFalse(meta.supportsUnion()); + assertTrue(meta.supportsUnion()); } - /** - * @tests java.sql.DatabaseMetaData#supportsUnionAll() - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "not supported", - method = "supportsUnionAll", - args = {} - ) public void test_supportsUnionAll() throws SQLException { - // NOT_FEASIBLE: SQLITE does not implement this functionality - assertFalse(meta.supportsUnionAll()); + assertTrue(meta.supportsUnionAll()); } /** diff --git a/sql/src/test/java/tests/sql/AllTests.java b/sql/src/test/java/tests/sql/AllTests.java index 4d59cd4..6eda690 100644 --- a/sql/src/test/java/tests/sql/AllTests.java +++ b/sql/src/test/java/tests/sql/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Math project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All SQL test suites"); + TestSuite suite = new TestSuite("All SQL test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.sql.tests.java.sql.AllTests.suite()); suite.addTest(org.apache.harmony.sql.tests.javax.sql.AllTests.suite()); diff --git a/sql/src/test/java/tests/sql/PreparedStatementTest.java b/sql/src/test/java/tests/sql/PreparedStatementTest.java index 26147ed..1546d38 100755 --- a/sql/src/test/java/tests/sql/PreparedStatementTest.java +++ b/sql/src/test/java/tests/sql/PreparedStatementTest.java @@ -2981,16 +2981,6 @@ public class PreparedStatementTest extends SQLTest { } } - /** - * @test {@link java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, int)} - * - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "not supported", - method = "setCharacterStream", - args = {int.class, java.io.Reader.class, int.class} - ) public void testSetCharacterSteam() { ResultSet res = null; PreparedStatement ps = null; @@ -3002,9 +2992,6 @@ public class PreparedStatementTest extends SQLTest { assertNotNull("Error in test setup: file not found",file); Reader reader = new InputStreamReader(file); ps.setCharacterStream(1, reader, 100); - fail("Exception expected not supported"); - } catch (SQLException e) { - // ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); diff --git a/sql/src/test/java/tests/sql/ResultSetGetterTests.java b/sql/src/test/java/tests/sql/ResultSetGetterTests.java index 9b12fc1..fccfd94 100644 --- a/sql/src/test/java/tests/sql/ResultSetGetterTests.java +++ b/sql/src/test/java/tests/sql/ResultSetGetterTests.java @@ -299,7 +299,6 @@ public class ResultSetGetterTests extends SQLTest { method = "getBytes", args = {int.class} ) - @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") public void testGetBytesIntVarbinary() throws SQLException { Statement st = null; @@ -347,7 +346,6 @@ public class ResultSetGetterTests extends SQLTest { method = "getBytes", args = {int.class} ) - @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") public void testGetBytesIntBinary() throws SQLException { Statement st = null; @@ -511,18 +509,9 @@ public class ResultSetGetterTests extends SQLTest { } } - /** - * Test method for {@link java.sql.ResultSet#getConcurrency()}. - */ - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "Not fully supported: CONCUR_UPDATABLE not supported", - method = "getConcurrency", - args = {} - ) public void testGetConcurrency() { try { - assertEquals(ResultSet.CONCUR_READ_ONLY, res.getConcurrency()); + assertEquals(ResultSet.CONCUR_UPDATABLE, res.getConcurrency()); } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } diff --git a/sql/src/test/java/tests/sql/ResultSetTest.java b/sql/src/test/java/tests/sql/ResultSetTest.java index 796c6a4..5b6d74a 100644 --- a/sql/src/test/java/tests/sql/ResultSetTest.java +++ b/sql/src/test/java/tests/sql/ResultSetTest.java @@ -107,19 +107,6 @@ public class ResultSetTest extends SQLTest { } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } - - try { -// Go back in position with forward only cursor - assertEquals(ResultSet.TYPE_FORWARD_ONLY, target.getFetchDirection()); - target.absolute(2); - target.absolute(1); - fail("Should get SQLException"); - } catch (SQLException e) { - // ok - } - - - } /** @@ -598,42 +585,8 @@ public class ResultSetTest extends SQLTest { } - /** - * Test method for {@link java.sql.ResultSet#previous()}. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "tests SQLException", - method = "previous", - args = {} - ) - public void testPrevious() { - + public void testPrevious() throws SQLException { try { - assertEquals(ResultSet.FETCH_FORWARD, target.getFetchDirection()); - target.last(); - target.previous(); - fail("Should get SQLException"); - } catch (SQLException e) { - // ok - } - } - - /** - * Test method for {@link java.sql.ResultSet#previous()}. - * @throws SQLException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "not supported", - method = "previous", - args = {} - ) - @KnownFailure("not supported") - public void testPrevious2() throws SQLException { - try { - assertSame(ResultSet.TYPE_SCROLL_INSENSITIVE, scrollableTarget.getFetchDirection()); - target.first(); target.previous(); assertTrue(target.isBeforeFirst()); diff --git a/sql/src/test/java/tests/sql/StatementTest.java b/sql/src/test/java/tests/sql/StatementTest.java index f884782..55bd7ab 100755 --- a/sql/src/test/java/tests/sql/StatementTest.java +++ b/sql/src/test/java/tests/sql/StatementTest.java @@ -692,29 +692,28 @@ public class StatementTest extends SQLTest { } } - /** - * @test java.sql.Statement#setMaxRows(int max) - * TODO not supported - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "not supported", - method = "setMaxRows", - args = {int.class} - ) - public void testSetMaxRows() { + public void testMaxRows() { Statement st = null; try { st = conn.createStatement(); - st.execute("select * from zoo;"); - for (int i = 0; i < 300; i += 50) { + for (int i = 0; i < 300; i += 50) { try { st.setMaxRows(i); assertEquals(i, st.getMaxRows()); - fail("Revise test implemenation for feature impl. has changed"); + 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) { - assertEquals("not supported", sqle.getMessage()); -// fail("SQLException is thrown: " + sqle.getMessage()); + fail("SQLException is thrown: " + sqle.getMessage()); } } try { @@ -735,41 +734,6 @@ public class StatementTest extends SQLTest { } /** - * @test java.sql.Statement#getMaxRows() - * TODO not supported - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "not supported", - method = "getMaxRows", - args = {} - ) - public void testGetMaxRows() { - Statement st = null; - try { - st = conn.createStatement(); - for (int i = 200; i < 500; i += 50) { - try { - st.setMaxRows(i); - assertEquals(i, st.getMaxRows()); - 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(); - } catch (SQLException ee) { - } - } - } - - /** * @test java.sql.Statement#close() * not passed according to Java Docs: should release all resources * IMMEDIATELY diff --git a/sqlite-jdbc/Android.mk b/sqlite-jdbc/Android.mk new file mode 100644 index 0000000..2c3926a --- /dev/null +++ b/sqlite-jdbc/Android.mk @@ -0,0 +1,23 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := \ + src/main/native/sqlite_jni.c + +LOCAL_C_INCLUDES += \ + $(JNI_H_INCLUDE) \ + external/sqlite/dist + +LOCAL_SHARED_LIBRARIES += \ + libsqlite + +LOCAL_STATIC_LIBRARIES += + +# This name is dictated by the fact that the SQLite code calls +# loadLibrary("sqlite_jni"). +LOCAL_MODULE := libsqlite_jni + +TARGET_PRELINK_MODULE := false + +include $(BUILD_SHARED_LIBRARY) diff --git a/sql/MODULE_LICENSE_BSD_LIKE b/sqlite-jdbc/MODULE_LICENSE_BSD_LIKE index e69de29..e69de29 100644 --- a/sql/MODULE_LICENSE_BSD_LIKE +++ b/sqlite-jdbc/MODULE_LICENSE_BSD_LIKE diff --git a/sqlite-jdbc/VERSION b/sqlite-jdbc/VERSION new file mode 100644 index 0000000..23bd019 --- /dev/null +++ b/sqlite-jdbc/VERSION @@ -0,0 +1 @@ +20100131 diff --git a/sql/src/main/java/SQLite/Authorizer.java b/sqlite-jdbc/src/main/java/SQLite/Authorizer.java index cdc321d..24fc459 100644 --- a/sql/src/main/java/SQLite/Authorizer.java +++ b/sqlite-jdbc/src/main/java/SQLite/Authorizer.java @@ -20,6 +20,6 @@ public interface Authorizer { */ public int authorize(int what, String arg1, String arg2, String arg3, - String arg4); + String arg4); } diff --git a/sql/src/main/java/SQLite/Blob.java b/sqlite-jdbc/src/main/java/SQLite/Blob.java index 3de9f8a..3e28225 100644 --- a/sql/src/main/java/SQLite/Blob.java +++ b/sqlite-jdbc/src/main/java/SQLite/Blob.java @@ -26,8 +26,8 @@ class BlobR extends InputStream { */ BlobR(Blob blob) { - this.blob = blob; - this.pos = 0; + this.blob = blob; + this.pos = 0; } /** @@ -36,8 +36,8 @@ class BlobR extends InputStream { */ public int available() throws IOException { - int ret = blob.size - pos; - return (ret < 0) ? 0 : ret; + int ret = blob.size - pos; + return (ret < 0) ? 0 : ret; } /** @@ -60,7 +60,7 @@ class BlobR extends InputStream { */ public boolean markSupported() { - return false; + return false; } /** @@ -69,8 +69,8 @@ class BlobR extends InputStream { public void close() throws IOException { blob.close(); - blob = null; - pos = 0; + blob = null; + pos = 0; } /** @@ -78,17 +78,17 @@ class BlobR extends InputStream { */ public long skip(long n) throws IOException { - long ret = pos + n; - if (ret < 0) { - ret = 0; - pos = 0; - } else if (ret > blob.size) { - ret = blob.size; - pos = blob.size; - } else { - pos = (int) ret; - } - return ret; + long ret = pos + n; + if (ret < 0) { + ret = 0; + pos = 0; + } else if (ret > blob.size) { + ret = blob.size; + pos = blob.size; + } else { + pos = (int) ret; + } + return ret; } /** @@ -97,13 +97,13 @@ class BlobR extends InputStream { */ public int read() throws IOException { - byte b[] = new byte[1]; - int n = blob.read(b, 0, pos, b.length); - if (n > 0) { - pos += n; - return b[0]; - } - return -1; + byte b[] = new byte[1]; + int n = blob.read(b, 0, pos, b.length); + if (n > 0) { + pos += n; + return b[0]; + } + return -1; } /** @@ -113,12 +113,12 @@ class BlobR extends InputStream { */ public int read(byte b[]) throws IOException { - int n = blob.read(b, 0, pos, b.length); - if (n > 0) { - pos += n; - return n; - } - return -1; + int n = blob.read(b, 0, pos, b.length); + if (n > 0) { + pos += n; + return n; + } + return -1; } /** @@ -130,21 +130,21 @@ class BlobR extends InputStream { */ public int read(byte b[], int off, int len) throws IOException { - if (off + len > b.length) { - len = b.length - off; - } - if (len < 0) { - return -1; - } - if (len == 0) { - return 0; - } - int n = blob.read(b, off, pos, len); - if (n > 0) { - pos += n; - return n; - } - return -1; + if (off + len > b.length) { + len = b.length - off; + } + if (len < 0) { + return -1; + } + if (len == 0) { + return 0; + } + int n = blob.read(b, off, pos, len); + if (n > 0) { + pos += n; + return n; + } + return -1; } } @@ -172,8 +172,8 @@ class BlobW extends OutputStream { */ BlobW(Blob blob) { - this.blob = blob; - this.pos = 0; + this.blob = blob; + this.pos = 0; } /** @@ -189,8 +189,8 @@ class BlobW extends OutputStream { public void close() throws IOException { blob.close(); - blob = null; - pos = 0; + blob = null; + pos = 0; } /** @@ -199,9 +199,9 @@ class BlobW extends OutputStream { */ public void write(int v) throws IOException { - byte b[] = new byte[1]; - b[0] = (byte) v; - pos += blob.write(b, 0, pos, 1); + byte b[] = new byte[1]; + b[0] = (byte) v; + pos += blob.write(b, 0, pos, 1); } /** @@ -210,9 +210,9 @@ class BlobW extends OutputStream { */ public void write(byte[] b) throws IOException { - if (b != null && b.length > 0) { - pos += blob.write(b, 0, pos, b.length); - } + if (b != null && b.length > 0) { + pos += blob.write(b, 0, pos, b.length); + } } /** @@ -223,15 +223,15 @@ class BlobW extends OutputStream { */ public void write(byte[] b, int off, int len) throws IOException { - if (b != null) { - if (off + len > b.length) { - len = b.length - off; - } - if (len <= 0) { - return; - } - pos += blob.write(b, off, pos, len); - } + if (b != null) { + if (off + len > b.length) { + len = b.length - off; + } + if (len <= 0) { + return; + } + pos += blob.write(b, off, pos, len); + } } } @@ -265,7 +265,7 @@ public class Blob { */ public InputStream getInputStream() { - return (InputStream) new BlobR(this); + return (InputStream) new BlobR(this); } /** @@ -274,7 +274,7 @@ public class Blob { */ public OutputStream getOutputStream() { - return (OutputStream) new BlobW(this); + return (OutputStream) new BlobW(this); } /** @@ -318,6 +318,6 @@ public class Blob { private static native void internal_init(); static { - internal_init(); + internal_init(); } } diff --git a/sql/src/main/java/SQLite/BusyHandler.java b/sqlite-jdbc/src/main/java/SQLite/BusyHandler.java index c39b39d..c39b39d 100644 --- a/sql/src/main/java/SQLite/BusyHandler.java +++ b/sqlite-jdbc/src/main/java/SQLite/BusyHandler.java diff --git a/sql/src/main/java/SQLite/Callback.java b/sqlite-jdbc/src/main/java/SQLite/Callback.java index 3eeb605..3eeb605 100644 --- a/sql/src/main/java/SQLite/Callback.java +++ b/sqlite-jdbc/src/main/java/SQLite/Callback.java diff --git a/sqlite-jdbc/src/main/java/SQLite/Constants.java b/sqlite-jdbc/src/main/java/SQLite/Constants.java new file mode 100644 index 0000000..017c49c --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/Constants.java @@ -0,0 +1,201 @@ +/* DO NOT EDIT */ + +package SQLite; + +/** + * Container for SQLite constants. + * + * Usually generated by "native/mkconst.c". For Android, I pasted in the output of this one-liner: + * + * perl -ne '$_ =~ s/#define\s+(SQLITE\S+)\s+([0-9x]+)/ public static final int $1 = $2;/ && print $_;' external/sqlite/dist/sqlite3.h + */ +public final class Constants { + // Copied from VERSION. + public static final int drv_minor = 20100131; + // Generated by the one-liner above. + public static final int SQLITE_VERSION_NUMBER = 3006022; + public static final int SQLITE_OK = 0; /* Successful result */ + public static final int SQLITE_ERROR = 1; /* SQL error or missing database */ + public static final int SQLITE_INTERNAL = 2; /* Internal logic error in SQLite */ + public static final int SQLITE_PERM = 3; /* Access permission denied */ + public static final int SQLITE_ABORT = 4; /* Callback routine requested an abort */ + public static final int SQLITE_BUSY = 5; /* The database file is locked */ + public static final int SQLITE_LOCKED = 6; /* A table in the database is locked */ + public static final int SQLITE_NOMEM = 7; /* A malloc() failed */ + public static final int SQLITE_READONLY = 8; /* Attempt to write a readonly database */ + public static final int SQLITE_INTERRUPT = 9; /* Operation terminated by sqlite3_interrupt()*/ + public static final int SQLITE_IOERR = 10; /* Some kind of disk I/O error occurred */ + public static final int SQLITE_CORRUPT = 11; /* The database disk image is malformed */ + public static final int SQLITE_NOTFOUND = 12; /* NOT USED. Table or record not found */ + public static final int SQLITE_FULL = 13; /* Insertion failed because database is full */ + public static final int SQLITE_CANTOPEN = 14; /* Unable to open the database file */ + public static final int SQLITE_PROTOCOL = 15; /* NOT USED. Database lock protocol error */ + public static final int SQLITE_EMPTY = 16; /* Database is empty */ + public static final int SQLITE_SCHEMA = 17; /* The database schema changed */ + public static final int SQLITE_TOOBIG = 18; /* String or BLOB exceeds size limit */ + public static final int SQLITE_CONSTRAINT = 19; /* Abort due to constraint violation */ + public static final int SQLITE_MISMATCH = 20; /* Data type mismatch */ + public static final int SQLITE_MISUSE = 21; /* Library used incorrectly */ + public static final int SQLITE_NOLFS = 22; /* Uses OS features not supported on host */ + public static final int SQLITE_AUTH = 23; /* Authorization denied */ + public static final int SQLITE_FORMAT = 24; /* Auxiliary database format error */ + public static final int SQLITE_RANGE = 25; /* 2nd parameter to sqlite3_bind out of range */ + public static final int SQLITE_NOTADB = 26; /* File opened that is not a database file */ + public static final int SQLITE_ROW = 100; /* sqlite3_step() has another row ready */ + public static final int SQLITE_DONE = 101; /* sqlite3_step() has finished executing */ + public static final int SQLITE_OPEN_READONLY = 0x00000001; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_READWRITE = 0x00000002; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_CREATE = 0x00000004; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_DELETEONCLOSE = 0x00000008; /* VFS only */ + public static final int SQLITE_OPEN_EXCLUSIVE = 0x00000010; /* VFS only */ + public static final int SQLITE_OPEN_MAIN_DB = 0x00000100; /* VFS only */ + public static final int SQLITE_OPEN_TEMP_DB = 0x00000200; /* VFS only */ + public static final int SQLITE_OPEN_TRANSIENT_DB = 0x00000400; /* VFS only */ + public static final int SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; /* VFS only */ + public static final int SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; /* VFS only */ + public static final int SQLITE_OPEN_SUBJOURNAL = 0x00002000; /* VFS only */ + public static final int SQLITE_OPEN_MASTER_JOURNAL = 0x00004000; /* VFS only */ + public static final int SQLITE_OPEN_NOMUTEX = 0x00008000; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_FULLMUTEX = 0x00010000; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_SHAREDCACHE = 0x00020000; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_OPEN_PRIVATECACHE = 0x00040000; /* Ok for sqlite3_open_v2() */ + public static final int SQLITE_IOCAP_ATOMIC = 0x00000001; + public static final int SQLITE_IOCAP_ATOMIC512 = 0x00000002; + public static final int SQLITE_IOCAP_ATOMIC1K = 0x00000004; + public static final int SQLITE_IOCAP_ATOMIC2K = 0x00000008; + public static final int SQLITE_IOCAP_ATOMIC4K = 0x00000010; + public static final int SQLITE_IOCAP_ATOMIC8K = 0x00000020; + public static final int SQLITE_IOCAP_ATOMIC16K = 0x00000040; + public static final int SQLITE_IOCAP_ATOMIC32K = 0x00000080; + public static final int SQLITE_IOCAP_ATOMIC64K = 0x00000100; + public static final int SQLITE_IOCAP_SAFE_APPEND = 0x00000200; + public static final int SQLITE_IOCAP_SEQUENTIAL = 0x00000400; + public static final int SQLITE_LOCK_NONE = 0; + public static final int SQLITE_LOCK_SHARED = 1; + public static final int SQLITE_LOCK_RESERVED = 2; + public static final int SQLITE_LOCK_PENDING = 3; + public static final int SQLITE_LOCK_EXCLUSIVE = 4; + public static final int SQLITE_SYNC_NORMAL = 0x00002; + public static final int SQLITE_SYNC_FULL = 0x00003; + public static final int SQLITE_SYNC_DATAONLY = 0x00010; + public static final int SQLITE_FCNTL_LOCKSTATE = 1; + public static final int SQLITE_GET_LOCKPROXYFILE = 2; + public static final int SQLITE_SET_LOCKPROXYFILE = 3; + public static final int SQLITE_LAST_ERRNO = 4; + public static final int SQLITE_ACCESS_EXISTS = 0; + public static final int SQLITE_ACCESS_READWRITE = 1; + public static final int SQLITE_ACCESS_READ = 2; + public static final int SQLITE_CONFIG_SINGLETHREAD = 1; /* nil */ + public static final int SQLITE_CONFIG_MULTITHREAD = 2; /* nil */ + public static final int SQLITE_CONFIG_SERIALIZED = 3; /* nil */ + public static final int SQLITE_CONFIG_MALLOC = 4; /* sqlite3_mem_methods* */ + public static final int SQLITE_CONFIG_GETMALLOC = 5; /* sqlite3_mem_methods* */ + public static final int SQLITE_CONFIG_SCRATCH = 6; /* void*, int sz, int N */ + public static final int SQLITE_CONFIG_PAGECACHE = 7; /* void*, int sz, int N */ + public static final int SQLITE_CONFIG_HEAP = 8; /* void*, int nByte, int min */ + public static final int SQLITE_CONFIG_MEMSTATUS = 9; /* boolean */ + public static final int SQLITE_CONFIG_MUTEX = 10; /* sqlite3_mutex_methods* */ + public static final int SQLITE_CONFIG_GETMUTEX = 11; /* sqlite3_mutex_methods* */ + public static final int SQLITE_CONFIG_LOOKASIDE = 13; /* int int */ + public static final int SQLITE_CONFIG_PCACHE = 14; /* sqlite3_pcache_methods* */ + public static final int SQLITE_CONFIG_GETPCACHE = 15; /* sqlite3_pcache_methods* */ + public static final int SQLITE_DBCONFIG_LOOKASIDE = 1001; /* void* int int */ + public static final int SQLITE_DENY = 1; /* Abort the SQL statement with an error */ + public static final int SQLITE_IGNORE = 2; /* Don't allow access, but don't generate an error */ + public static final int SQLITE_CREATE_INDEX = 1; /* Index Name Table Name */ + public static final int SQLITE_CREATE_TABLE = 2; /* Table Name NULL */ + public static final int SQLITE_CREATE_TEMP_INDEX = 3; /* Index Name Table Name */ + public static final int SQLITE_CREATE_TEMP_TABLE = 4; /* Table Name NULL */ + public static final int SQLITE_CREATE_TEMP_TRIGGER = 5; /* Trigger Name Table Name */ + public static final int SQLITE_CREATE_TEMP_VIEW = 6; /* View Name NULL */ + public static final int SQLITE_CREATE_TRIGGER = 7; /* Trigger Name Table Name */ + public static final int SQLITE_CREATE_VIEW = 8; /* View Name NULL */ + public static final int SQLITE_DELETE = 9; /* Table Name NULL */ + public static final int SQLITE_DROP_INDEX = 10; /* Index Name Table Name */ + public static final int SQLITE_DROP_TABLE = 11; /* Table Name NULL */ + public static final int SQLITE_DROP_TEMP_INDEX = 12; /* Index Name Table Name */ + public static final int SQLITE_DROP_TEMP_TABLE = 13; /* Table Name NULL */ + public static final int SQLITE_DROP_TEMP_TRIGGER = 14; /* Trigger Name Table Name */ + public static final int SQLITE_DROP_TEMP_VIEW = 15; /* View Name NULL */ + public static final int SQLITE_DROP_TRIGGER = 16; /* Trigger Name Table Name */ + public static final int SQLITE_DROP_VIEW = 17; /* View Name NULL */ + public static final int SQLITE_INSERT = 18; /* Table Name NULL */ + public static final int SQLITE_PRAGMA = 19; /* Pragma Name 1st arg or NULL */ + public static final int SQLITE_READ = 20; /* Table Name Column Name */ + public static final int SQLITE_SELECT = 21; /* NULL NULL */ + public static final int SQLITE_TRANSACTION = 22; /* Operation NULL */ + public static final int SQLITE_UPDATE = 23; /* Table Name Column Name */ + public static final int SQLITE_ATTACH = 24; /* Filename NULL */ + public static final int SQLITE_DETACH = 25; /* Database Name NULL */ + public static final int SQLITE_ALTER_TABLE = 26; /* Database Name Table Name */ + public static final int SQLITE_REINDEX = 27; /* Index Name NULL */ + public static final int SQLITE_ANALYZE = 28; /* Table Name NULL */ + public static final int SQLITE_CREATE_VTABLE = 29; /* Table Name Module Name */ + public static final int SQLITE_DROP_VTABLE = 30; /* Table Name Module Name */ + public static final int SQLITE_FUNCTION = 31; /* NULL Function Name */ + public static final int SQLITE_SAVEPOINT = 32; /* Operation Savepoint Name */ + public static final int SQLITE_COPY = 0; /* No longer used */ + public static final int SQLITE_LIMIT_LENGTH = 0; + public static final int SQLITE_LIMIT_SQL_LENGTH = 1; + public static final int SQLITE_LIMIT_COLUMN = 2; + public static final int SQLITE_LIMIT_EXPR_DEPTH = 3; + public static final int SQLITE_LIMIT_COMPOUND_SELECT = 4; + public static final int SQLITE_LIMIT_VDBE_OP = 5; + public static final int SQLITE_LIMIT_FUNCTION_ARG = 6; + public static final int SQLITE_LIMIT_ATTACHED = 7; + public static final int SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8; + public static final int SQLITE_LIMIT_VARIABLE_NUMBER = 9; + public static final int SQLITE_LIMIT_TRIGGER_DEPTH = 10; + 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_UTF8 = 1; + public static final int SQLITE_UTF16LE = 2; + public static final int SQLITE_UTF16BE = 3; + public static final int SQLITE_UTF16 = 4; /* Use native byte order */ + public static final int SQLITE_ANY = 5; /* sqlite3_create_function only */ + public static final int SQLITE_UTF16_ALIGNED = 8; /* sqlite3_create_collation only */ + public static final int SQLITE_INDEX_CONSTRAINT_EQ = 2; + public static final int SQLITE_INDEX_CONSTRAINT_GT = 4; + public static final int SQLITE_INDEX_CONSTRAINT_LE = 8; + public static final int SQLITE_INDEX_CONSTRAINT_LT = 16; + public static final int SQLITE_INDEX_CONSTRAINT_GE = 32; + public static final int SQLITE_INDEX_CONSTRAINT_MATCH = 64; + public static final int SQLITE_MUTEX_FAST = 0; + public static final int SQLITE_MUTEX_RECURSIVE = 1; + public static final int SQLITE_MUTEX_STATIC_MASTER = 2; + public static final int SQLITE_MUTEX_STATIC_MEM = 3; /* sqlite3_malloc() */ + public static final int SQLITE_MUTEX_STATIC_MEM2 = 4; /* NOT USED */ + public static final int SQLITE_MUTEX_STATIC_OPEN = 4; /* sqlite3BtreeOpen() */ + public static final int SQLITE_MUTEX_STATIC_PRNG = 5; /* sqlite3_random() */ + public static final int SQLITE_MUTEX_STATIC_LRU = 6; /* lru page list */ + public static final int SQLITE_MUTEX_STATIC_LRU2 = 7; /* lru page list */ + public static final int SQLITE_TESTCTRL_FIRST = 5; + public static final int SQLITE_TESTCTRL_PRNG_SAVE = 5; + public static final int SQLITE_TESTCTRL_PRNG_RESTORE = 6; + public static final int SQLITE_TESTCTRL_PRNG_RESET = 7; + public static final int SQLITE_TESTCTRL_BITVEC_TEST = 8; + public static final int SQLITE_TESTCTRL_FAULT_INSTALL = 9; + public static final int SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = 10; + public static final int SQLITE_TESTCTRL_PENDING_BYTE = 11; + public static final int SQLITE_TESTCTRL_ASSERT = 12; + public static final int SQLITE_TESTCTRL_ALWAYS = 13; + public static final int SQLITE_TESTCTRL_RESERVE = 14; + public static final int SQLITE_TESTCTRL_OPTIMIZATIONS = 15; + public static final int SQLITE_TESTCTRL_ISKEYWORD = 16; + public static final int SQLITE_TESTCTRL_LAST = 16; + public static final int SQLITE_STATUS_MEMORY_USED = 0; + public static final int SQLITE_STATUS_PAGECACHE_USED = 1; + public static final int SQLITE_STATUS_PAGECACHE_OVERFLOW = 2; + public static final int SQLITE_STATUS_SCRATCH_USED = 3; + public static final int SQLITE_STATUS_SCRATCH_OVERFLOW = 4; + public static final int SQLITE_STATUS_MALLOC_SIZE = 5; + public static final int SQLITE_STATUS_PARSER_STACK = 6; + public static final int SQLITE_STATUS_PAGECACHE_SIZE = 7; + public static final int SQLITE_STATUS_SCRATCH_SIZE = 8; + public static final int SQLITE_DBSTATUS_LOOKASIDE_USED = 0; + public static final int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1; + public static final int SQLITE_STMTSTATUS_SORT = 2; +} diff --git a/sql/src/main/java/SQLite/Database.java b/sqlite-jdbc/src/main/java/SQLite/Database.java index dcaaf9d..200a9bf 100644 --- a/sql/src/main/java/SQLite/Database.java +++ b/sqlite-jdbc/src/main/java/SQLite/Database.java @@ -22,17 +22,102 @@ public class Database { * Open an SQLite database file. * * @param filename the name of the database file - * @param mode open mode, currently ignored + * @param mode open mode (e.g. SQLITE_OPEN_READONLY) */ public void open(String filename, int mode) throws SQLite.Exception { - synchronized(this) { - _open(filename, mode); + if ((mode & 0200) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READWRITE | + SQLite.Constants.SQLITE_OPEN_CREATE; + } else if ((mode & 0400) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READONLY; + } + synchronized(this) { + try { + _open4(filename, mode, null, false); + } catch (SQLite.Exception se) { + throw se; + } catch (java.lang.OutOfMemoryError me) { + throw me; + } catch (Throwable t) { + _open(filename, mode); + } + } } + + /** + * Open an SQLite database file. + * + * @param filename the name of the database file + * @param mode open mode (e.g. SQLITE_OPEN_READONLY) + * @param vfs VFS name (for SQLite >= 3.5) + */ + + public void open(String filename, int mode, String vfs) + throws SQLite.Exception { + if ((mode & 0200) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READWRITE | + SQLite.Constants.SQLITE_OPEN_CREATE; + } else if ((mode & 0400) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READONLY; + } + synchronized(this) { + try { + _open4(filename, mode, vfs, false); + } catch (SQLite.Exception se) { + throw se; + } catch (java.lang.OutOfMemoryError me) { + throw me; + } catch (Throwable t) { + _open(filename, mode); + } + } } + /** + * Open an SQLite database file. + * + * @param filename the name of the database file + * @param mode open mode (e.g. SQLITE_OPEN_READONLY) + * @param vfs VFS name (for SQLite >= 3.5) + * @param ver2 flag to force version on create (false = SQLite3, true = SQLite2) + */ + + public void open(String filename, int mode, String vfs, boolean ver2) + throws SQLite.Exception { + if ((mode & 0200) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READWRITE | + SQLite.Constants.SQLITE_OPEN_CREATE; + } else if ((mode & 0400) != 0) { + mode = SQLite.Constants.SQLITE_OPEN_READONLY; + } + synchronized(this) { + try { + _open4(filename, mode, vfs, ver2); + } catch (SQLite.Exception se) { + throw se; + } catch (java.lang.OutOfMemoryError me) { + throw me; + } catch (Throwable t) { + _open(filename, mode); + } + } + } + + /* + * For backward compatibility to older sqlite.jar, sqlite_jni + */ + private native void _open(String filename, int mode) - throws SQLite.Exception; + throws SQLite.Exception; + + /* + * Newer full interface + */ + + private native void _open4(String filename, int mode, String vfs, + boolean ver2) + throws SQLite.Exception; /** * Open SQLite auxiliary database file for temporary @@ -42,22 +127,22 @@ public class Database { */ public void open_aux_file(String filename) throws SQLite.Exception { - synchronized(this) { - _open_aux_file(filename); - } + synchronized(this) { + _open_aux_file(filename); + } } private native void _open_aux_file(String filename) - throws SQLite.Exception; + throws SQLite.Exception; /** * Destructor for object. */ protected void finalize() { - synchronized(this) { - _finalize(); - } + synchronized(this) { + _finalize(); + } } private native void _finalize(); @@ -66,14 +151,14 @@ public class Database { * Close the underlying SQLite database file. */ - public void close() throws SQLite.Exception { - synchronized(this) { - _close(); - } + public void close() throws SQLite.Exception { + synchronized(this) { + _close(); + } } private native void _close() - throws SQLite.Exception; + throws SQLite.Exception; /** * Execute an SQL statement and invoke callback methods @@ -88,13 +173,13 @@ public class Database { */ public void exec(String sql, SQLite.Callback cb) throws SQLite.Exception { - synchronized(this) { - _exec(sql, cb); - } + synchronized(this) { + _exec(sql, cb); + } } private native void _exec(String sql, SQLite.Callback cb) - throws SQLite.Exception; + throws SQLite.Exception; /** * Execute an SQL statement and invoke callback methods @@ -120,14 +205,14 @@ public class Database { */ public void exec(String sql, SQLite.Callback cb, - String args[]) throws SQLite.Exception { - synchronized(this) { - _exec(sql, cb, args); - } + String args[]) throws SQLite.Exception { + synchronized(this) { + _exec(sql, cb, args); + } } private native void _exec(String sql, SQLite.Callback cb, String args[]) - throws SQLite.Exception; + throws SQLite.Exception; /** * Return the row identifier of the last inserted @@ -135,9 +220,9 @@ public class Database { */ public long last_insert_rowid() { - synchronized(this) { - return _last_insert_rowid(); - } + synchronized(this) { + return _last_insert_rowid(); + } } private native long _last_insert_rowid(); @@ -147,9 +232,9 @@ public class Database { */ public void interrupt() { - synchronized(this) { - _interrupt(); - } + synchronized(this) { + _interrupt(); + } } private native void _interrupt(); @@ -159,9 +244,9 @@ public class Database { */ public long changes() { - synchronized(this) { - return _changes(); - } + synchronized(this) { + return _changes(); + } } private native long _changes(); @@ -174,9 +259,9 @@ public class Database { */ public void busy_handler(SQLite.BusyHandler bh) { - synchronized(this) { - _busy_handler(bh); - } + synchronized(this) { + _busy_handler(bh); + } } private native void _busy_handler(SQLite.BusyHandler bh); @@ -189,9 +274,9 @@ public class Database { */ public void busy_timeout(int ms) { - synchronized(this) { - _busy_timeout(ms); - } + synchronized(this) { + _busy_timeout(ms); + } } private native void _busy_timeout(int ms); @@ -201,25 +286,92 @@ public class Database { * set into memory. * * @param sql the SQL statement to be executed + * @param maxrows the max. number of rows to retrieve + * @return result set + */ + + public TableResult get_table(String sql, int maxrows) + throws SQLite.Exception { + TableResult ret = new TableResult(maxrows); + if (!is3()) { + try { + exec(sql, ret); + } catch (SQLite.Exception e) { + if (maxrows <= 0 || !ret.atmaxrows) { + throw e; + } + } + } else { + synchronized(this) { + /* only one statement !!! */ + Vm vm = compile(sql); + set_last_error(vm.error_code); + if (ret.maxrows > 0) { + while (ret.nrows < ret.maxrows && vm.step(ret)) { + set_last_error(vm.error_code); + } + } else { + while (vm.step(ret)) { + set_last_error(vm.error_code); + } + } + vm.finalize(); + } + } + return ret; + } + + /** + * Convenience method to retrieve an entire result + * set into memory. + * + * @param sql the SQL statement to be executed * @return result set */ public TableResult get_table(String sql) throws SQLite.Exception { - TableResult ret = new TableResult(); - if (!is3()) { - exec(sql, ret); - } else { - synchronized(this) { - /* only one statement !!! */ - Vm vm = compile(sql); - set_last_error(vm.error_code); - while (vm.step(ret)) { - set_last_error(vm.error_code); - } - vm.finalize(); - } + return get_table(sql, 0); } - return ret; + + /** + * Convenience method to retrieve an entire result + * set into memory. + * + * @param sql the SQL statement to be executed + * @param maxrows the max. number of rows to retrieve + * @param args arguments for the SQL statement, '%q' substitution + * @return result set + */ + + public TableResult get_table(String sql, int maxrows, String args[]) + throws SQLite.Exception { + TableResult ret = new TableResult(maxrows); + if (!is3()) { + try { + exec(sql, ret, args); + } catch (SQLite.Exception e) { + if (maxrows <= 0 || !ret.atmaxrows) { + throw e; + } + } + } else { + synchronized(this) { + /* only one statement !!! */ + Vm vm = compile(sql, args); + set_last_error(vm.error_code); + if (ret.maxrows > 0) { + while (ret.nrows < ret.maxrows && vm.step(ret)) { + set_last_error(vm.error_code); + } + } else { + while (vm.step(ret)) { + set_last_error(vm.error_code); + } + } + vm.finalize(); + } + } + return ret; } /** @@ -232,22 +384,8 @@ public class Database { */ public TableResult get_table(String sql, String args[]) - throws SQLite.Exception { - TableResult ret = new TableResult(); - if (!is3()) { - exec(sql, ret, args); - } else { - synchronized(this) { - /* only one statement !!! */ - Vm vm = compile(sql, args); - set_last_error(vm.error_code); - while (vm.step(ret)) { - set_last_error(vm.error_code); - } - vm.finalize(); - } - } - return ret; + throws SQLite.Exception { + return get_table(sql, 0, args); } /** @@ -261,19 +399,32 @@ public class Database { */ public void get_table(String sql, String args[], TableResult tbl) - throws SQLite.Exception { - tbl.clear(); - if (!is3()) { - exec(sql, tbl, args); - } else { - synchronized(this) { - /* only one statement !!! */ - Vm vm = compile(sql, args); - while (vm.step(tbl)) { - } - vm.finalize(); - } - } + throws SQLite.Exception { + tbl.clear(); + if (!is3()) { + try { + exec(sql, tbl, args); + } catch (SQLite.Exception e) { + if (tbl.maxrows <= 0 || !tbl.atmaxrows) { + throw e; + } + } + } else { + synchronized(this) { + /* only one statement !!! */ + Vm vm = compile(sql, args); + if (tbl.maxrows > 0) { + while (tbl.nrows < tbl.maxrows && vm.step(tbl)) { + set_last_error(vm.error_code); + } + } else { + while (vm.step(tbl)) { + set_last_error(vm.error_code); + } + } + vm.finalize(); + } + } } /** @@ -285,7 +436,7 @@ public class Database { */ public synchronized static boolean complete(String sql) { - return _complete(sql); + return _complete(sql); } private native static boolean _complete(String sql); @@ -314,9 +465,9 @@ public class Database { */ public void create_function(String name, int nargs, Function f) { - synchronized(this) { - _create_function(name, nargs, f); - } + synchronized(this) { + _create_function(name, nargs, f); + } } private native void _create_function(String name, int nargs, Function f); @@ -330,9 +481,9 @@ public class Database { */ public void create_aggregate(String name, int nargs, Function f) { - synchronized(this) { - _create_aggregate(name, nargs, f); - } + synchronized(this) { + _create_aggregate(name, nargs, f); + } } private native void _create_aggregate(String name, int nargs, Function f); @@ -346,9 +497,9 @@ public class Database { */ public void function_type(String name, int type) { - synchronized(this) { - _function_type(name, type); - } + synchronized(this) { + _function_type(name, type); + } } private native void _function_type(String name, int type); @@ -364,7 +515,7 @@ public class Database { */ public int last_error() { - return error_code; + return error_code; } /** @@ -373,7 +524,7 @@ public class Database { */ protected void set_last_error(int error_code) { - this.error_code = error_code; + this.error_code = error_code; } /** @@ -383,9 +534,9 @@ public class Database { */ public String error_message() { - synchronized(this) { - return _errmsg(); - } + synchronized(this) { + return _errmsg(); + } } private native String _errmsg(); @@ -405,13 +556,13 @@ public class Database { */ public void set_encoding(String enc) throws SQLite.Exception { - synchronized(this) { - _set_encoding(enc); - } + synchronized(this) { + _set_encoding(enc); + } } private native void _set_encoding(String enc) - throws SQLite.Exception; + throws SQLite.Exception; /** * Set authorizer function. Only available in SQLite 2.7.6 and @@ -421,9 +572,9 @@ public class Database { */ public void set_authorizer(Authorizer auth) { - synchronized(this) { - _set_authorizer(auth); - } + synchronized(this) { + _set_authorizer(auth); + } } private native void _set_authorizer(Authorizer auth); @@ -436,9 +587,9 @@ public class Database { */ public void trace(Trace tr) { - synchronized(this) { - _trace(tr); - } + synchronized(this) { + _trace(tr); + } } private native void _trace(Trace tr); @@ -452,11 +603,11 @@ public class Database { */ public Vm compile(String sql) throws SQLite.Exception { - synchronized(this) { - Vm vm = new Vm(); - vm_compile(sql, vm); - return vm; - } + synchronized(this) { + Vm vm = new Vm(); + vm_compile(sql, vm); + return vm; + } } /** @@ -469,11 +620,11 @@ public class Database { */ public Vm compile(String sql, String args[]) throws SQLite.Exception { - synchronized(this) { - Vm vm = new Vm(); - vm_compile_args(sql, vm, args); - return vm; - } + synchronized(this) { + Vm vm = new Vm(); + vm_compile_args(sql, vm, args); + return vm; + } } /** @@ -485,11 +636,11 @@ public class Database { */ public Stmt prepare(String sql) throws SQLite.Exception { - synchronized(this) { - Stmt stmt = new Stmt(); - stmt_prepare(sql, stmt); - return stmt; - } + synchronized(this) { + Stmt stmt = new Stmt(); + stmt_prepare(sql, stmt); + return stmt; + } } /** @@ -503,12 +654,12 @@ public class Database { */ public Blob open_blob(String db, String table, String column, - long row, boolean rw) throws SQLite.Exception { - synchronized(this) { - Blob blob = new Blob(); - _open_blob(db, table, column, row, rw, blob); - return blob; - } + long row, boolean rw) throws SQLite.Exception { + synchronized(this) { + Blob blob = new Blob(); + _open_blob(db, table, column, row, rw, blob); + return blob; + } } /** @@ -525,7 +676,7 @@ public class Database { */ private native void vm_compile(String sql, Vm vm) - throws SQLite.Exception; + throws SQLite.Exception; /** * Internal compile method, SQLite 3.0 only. @@ -535,7 +686,7 @@ public class Database { */ private native void vm_compile_args(String sql, Vm vm, String args[]) - throws SQLite.Exception; + throws SQLite.Exception; /** * Internal SQLite3 prepare method. @@ -544,7 +695,7 @@ public class Database { */ private native void stmt_prepare(String sql, Stmt stmt) - throws SQLite.Exception; + throws SQLite.Exception; /** * Internal SQLite open blob method. @@ -557,8 +708,8 @@ public class Database { */ private native void _open_blob(String db, String table, String column, - long row, boolean rw, Blob blob) - throws SQLite.Exception; + long row, boolean rw, Blob blob) + throws SQLite.Exception; /** * Establish a progress callback method which gets called after @@ -569,47 +720,185 @@ public class Database { */ public void progress_handler(int n, SQLite.ProgressHandler p) { - synchronized(this) { - _progress_handler(n, p); - } + synchronized(this) { + _progress_handler(n, p); + } } private native void _progress_handler(int n, SQLite.ProgressHandler p); /** + * Specify key for encrypted database. To be called + * right after open() on SQLite3 databases. + * Not available in public releases of SQLite. + * + * @param ekey the key as byte array + */ + + public void key(byte[] ekey) throws SQLite.Exception { + synchronized(this) { + _key(ekey); + } + } + + /** + * Specify key for encrypted database. To be called + * right after open() on SQLite3 databases. + * Not available in public releases of SQLite. + * + * @param skey the key as String + */ + + public void key(String skey) throws SQLite.Exception { + synchronized(this) { + byte ekey[] = null; + if (skey != null && skey.length() > 0) { + ekey = new byte[skey.length()]; + for (int i = 0; i< skey.length(); i++) { + char c = skey.charAt(i); + ekey[i] = (byte) ((c & 0xff) ^ (c >> 8)); + } + } + _key(ekey); + } + } + + private native void _key(byte[] ekey); + + /** + * Change the key of a encrypted database. The + * SQLite3 database must have been open()ed. + * Not available in public releases of SQLite. + * + * @param ekey the key as byte array + */ + + public void rekey(byte[] ekey) throws SQLite.Exception { + synchronized(this) { + _rekey(ekey); + } + } + + /** + * Change the key of a encrypted database. The + * SQLite3 database must have been open()ed. + * Not available in public releases of SQLite. + * + * @param skey the key as String + */ + + public void rekey(String skey) throws SQLite.Exception { + synchronized(this) { + byte ekey[] = null; + if (skey != null && skey.length() > 0) { + ekey = new byte[skey.length()]; + for (int i = 0; i< skey.length(); i++) { + char c = skey.charAt(i); + ekey[i] = (byte) ((c & 0xff) ^ (c >> 8)); + } + } + _rekey(ekey); + } + } + + private native void _rekey(byte[] ekey); + + /** + * Enable/disable shared cache mode (SQLite 3.x only). + * + * @param onoff boolean to enable or disable shared cache + * @return boolean when true, function supported/succeeded + */ + + protected static native boolean _enable_shared_cache(boolean onoff); + + /** * Internal native initializer. */ private static native void internal_init(); /** + * Make long value from julian date for java.lang.Date + * + * @param d double value (julian date in SQLite3 format) + * @return long + */ + + public static long long_from_julian(double d) { + d -= 2440587.5; + d *= 86400000.0; + return (long) d; + } + + /** + * Make long value from julian date for java.lang.Date + * + * @param s string (double value) (julian date in SQLite3 format) + * @return long + */ + + public static long long_from_julian(String s) throws SQLite.Exception { + try { + double d = Double.parseDouble(s); // android-changed: performance + return long_from_julian(d); + } catch (java.lang.Exception ee) { + throw new SQLite.Exception("not a julian date"); + } + } + + /** + * Make julian date value from java.lang.Date + * + * @param ms millisecond value of java.lang.Date + * @return double + */ + + public static double julian_from_long(long ms) { + double adj = (ms < 0) ? 0 : 0.5; + double d = (ms + adj) / 86400000.0 + 2440587.5; + return d; + } + + /** * Static initializer to load the native part. */ static { - try { -// String path = System.getProperty("SQLite.library.path"); -// if (path == null || path.length() == 0){ -// System.loadLibrary("sqlite_jni"); -// } else { -// try { -// java.lang.reflect.Method mapLibraryName; -// Class param[] = new Class[1]; -// param[0] = String.class; -// mapLibraryName = System.class.getMethod("mapLibraryName", -// param); -// Object args[] = new Object[1]; -// args[0] = "sqlite_jni"; -// String mapped = (String) mapLibraryName.invoke(null, args); -// System.load(path + java.io.File.separator + mapped); -// } catch (Throwable t) { -// System.loadLibrary("sqlite_jni"); -// } -// } - internal_init(); - } catch (Throwable t) { - System.err.println("Unable to load sqlite: " + t); - } + try { + String path = System.getProperty("SQLite.library.path"); + if (path == null || path.length() == 0) { + System.loadLibrary("sqlite_jni"); + } else { + try { + java.lang.reflect.Method mapLibraryName; + Class param[] = new Class[1]; + param[0] = String.class; + mapLibraryName = System.class.getMethod("mapLibraryName", + param); + Object args[] = new Object[1]; + args[0] = "sqlite_jni"; + String mapped = (String) mapLibraryName.invoke(null, args); + System.load(path + java.io.File.separator + mapped); + } catch (Throwable t) { + System.err.println("Unable to load sqlite_jni from" + + "SQLite.library.path=" + path + + ", trying system default: " + t); + System.loadLibrary("sqlite_jni"); + } + } + } catch (Throwable t) { + System.err.println("Unable to load sqlite_jni: " + t); + } + /* + * Call native initializer functions now, since the + * native part could have been linked statically, i.e. + * the try/catch above would have failed in that case. + */ + try { + internal_init(); + new FunctionContext(); + } catch (java.lang.Exception e) { + } } } - diff --git a/sql/src/main/java/SQLite/Exception.java b/sqlite-jdbc/src/main/java/SQLite/Exception.java index cc26b99..589fa4b 100644 --- a/sql/src/main/java/SQLite/Exception.java +++ b/sqlite-jdbc/src/main/java/SQLite/Exception.java @@ -13,6 +13,6 @@ public class Exception extends java.lang.Exception { */ public Exception(String string) { - super(string); + super(string); } } diff --git a/sql/src/main/java/SQLite/Function.java b/sqlite-jdbc/src/main/java/SQLite/Function.java index 5aa5e33..5aa5e33 100644 --- a/sql/src/main/java/SQLite/Function.java +++ b/sqlite-jdbc/src/main/java/SQLite/Function.java diff --git a/sql/src/main/java/SQLite/FunctionContext.java b/sqlite-jdbc/src/main/java/SQLite/FunctionContext.java index d0b5182..8509b4d 100644 --- a/sql/src/main/java/SQLite/FunctionContext.java +++ b/sqlite-jdbc/src/main/java/SQLite/FunctionContext.java @@ -77,6 +77,6 @@ public class FunctionContext { private static native void internal_init(); static { - internal_init(); + internal_init(); } } diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCConnection.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCConnection.java new file mode 100644 index 0000000..67e95da --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCConnection.java @@ -0,0 +1,516 @@ +package SQLite.JDBC2y; + +import java.sql.*; +import java.util.*; + +public class JDBCConnection + implements java.sql.Connection, SQLite.BusyHandler { + + /** + * Open database. + */ + protected DatabaseX db; + + /** + * Database URL. + */ + protected String url; + + /** + * Character encoding. + */ + protected String enc; + + /** + * SQLite 3 VFS to use. + */ + protected String vfs; + + /** + * Autocommit flag, true means autocommit. + */ + protected boolean autocommit = true; + + /** + * In-transaction flag. + * Can be true only when autocommit false. + */ + protected boolean intrans = false; + + /** + * Timeout for Database.exec() + */ + protected int timeout = 1000000; + + /** + * Use double/julian date representation. + */ + protected boolean useJulian = false; + + /** + * File name of database. + */ + private String dbfile = null; + + /** + * Reference to meta data or null. + */ + private JDBCDatabaseMetaData meta = null; + + /** + * Base time value for timeout handling. + */ + private long t0; + + /** + * Database in readonly mode. + */ + private boolean readonly = false; + + /** + * Transaction isolation mode. + */ + private int trmode = TRANSACTION_SERIALIZABLE; + + private boolean busy0(DatabaseX db, int count) { + if (count <= 1) { + t0 = System.currentTimeMillis(); + } + if (db != null) { + long t1 = System.currentTimeMillis(); + if (t1 - t0 > timeout) { + return false; + } + db.wait(100); + return true; + } + return false; + } + + public boolean busy(String table, int count) { + return busy0(db, count); + } + + protected boolean busy3(DatabaseX db, int count) { + if (count <= 1) { + t0 = System.currentTimeMillis(); + } + if (db != null) { + long t1 = System.currentTimeMillis(); + if (t1 - t0 > timeout) { + return false; + } + return true; + } + return false; + } + + private DatabaseX open(boolean readonly) throws SQLException { + DatabaseX dbx = null; + try { + dbx = new DatabaseX(); + dbx.open(dbfile, readonly ? SQLite.Constants.SQLITE_OPEN_READONLY : + (SQLite.Constants.SQLITE_OPEN_READWRITE | + SQLite.Constants.SQLITE_OPEN_CREATE), vfs); + dbx.set_encoding(enc); + } catch (SQLite.Exception e) { + throw new SQLException(e.toString()); + } + int loop = 0; + while (true) { + try { + dbx.exec("PRAGMA short_column_names = off;", null); + dbx.exec("PRAGMA full_column_names = on;", null); + dbx.exec("PRAGMA empty_result_callbacks = on;", null); + if (SQLite.Database.version().compareTo("2.6.0") >= 0) { + dbx.exec("PRAGMA show_datatypes = on;", null); + } + } catch (SQLite.Exception e) { + if (dbx.last_error() != SQLite.Constants.SQLITE_BUSY || + !busy0(dbx, ++loop)) { + try { + dbx.close(); + } catch (SQLite.Exception ee) { + } + throw new SQLException(e.toString()); + } + continue; + } + break; + } + return dbx; + } + + public JDBCConnection(String url, String enc, String pwd, String drep, + String vfs) + throws SQLException { + if (url.startsWith("sqlite:/")) { + dbfile = url.substring(8); + } else if (url.startsWith("jdbc:sqlite:/")) { + dbfile = url.substring(13); + } else { + throw new SQLException("unsupported url"); + } + this.url = url; + this.enc = enc; + this.vfs = vfs; + try { + db = open(readonly); + try { + if (pwd != null && pwd.length() > 0) { + db.key(pwd); + } + } catch (SQLite.Exception se) { + throw new SQLException("error while setting key"); + } + db.busy_handler(this); + } catch (SQLException e) { + if (db != null) { + try { + db.close(); + } catch (SQLite.Exception ee) { + } + } + throw e; + } + useJulian = drep != null && + (drep.startsWith("j") || drep.startsWith("J")); + } + + /* non-standard */ + public SQLite.Database getSQLiteDatabase() { + return (SQLite.Database) db; + } + + public Statement createStatement() { + JDBCStatement s = new JDBCStatement(this); + return s; + } + + public Statement createStatement(int resultSetType, + int resultSetConcurrency) + throws SQLException { + if (resultSetType != ResultSet.TYPE_FORWARD_ONLY && + resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE && + resultSetType != ResultSet.TYPE_SCROLL_SENSITIVE) { + throw new SQLException("unsupported result set type"); + } + if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY && + resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) { + throw new SQLException("unsupported result set concurrency"); + } + JDBCStatement s = new JDBCStatement(this); + return s; + } + + public DatabaseMetaData getMetaData() throws SQLException { + if (meta == null) { + meta = new JDBCDatabaseMetaData(this); + } + return meta; + } + + public void close() throws SQLException { + try { + rollback(); + } catch (SQLException e) { + /* ignored */ + } + intrans = false; + if (db != null) { + try { + db.close(); + db = null; + } catch (SQLite.Exception e) { + throw new SQLException(e.toString()); + } + } + } + + public boolean isClosed() throws SQLException { + return db == null; + } + + public boolean isReadOnly() throws SQLException { + return readonly; + } + + public void clearWarnings() throws SQLException { + } + + public void commit() throws SQLException { + if (db == null) { + throw new SQLException("stale connection"); + } + if (!intrans) { + return; + } + try { + db.exec("COMMIT", null); + intrans = false; + } catch (SQLite.Exception e) { + throw new SQLException(e.toString()); + } + } + + public boolean getAutoCommit() throws SQLException { + return autocommit; + } + + public String getCatalog() throws SQLException { + return null; + } + + public int getTransactionIsolation() throws SQLException { + return trmode; + } + + public SQLWarning getWarnings() throws SQLException { + return null; + } + + public String nativeSQL(String sql) throws SQLException { + throw new SQLException("not supported"); + } + + public CallableStatement prepareCall(String sql) throws SQLException { + throw new SQLException("not supported"); + } + + public CallableStatement prepareCall(String sql, int x, int y) + throws SQLException { + throw new SQLException("not supported"); + } + + public PreparedStatement prepareStatement(String sql) throws SQLException { + JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql); + return s; + } + + public PreparedStatement prepareStatement(String sql, int resultSetType, + int resultSetConcurrency) + throws SQLException { + if (resultSetType != ResultSet.TYPE_FORWARD_ONLY && + resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE && + resultSetType != ResultSet.TYPE_SCROLL_SENSITIVE) { + throw new SQLException("unsupported result set type"); + } + if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY && + resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) { + throw new SQLException("unsupported result set concurrency"); + } + JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql); + return s; + } + + public void rollback() throws SQLException { + if (db == null) { + throw new SQLException("stale connection"); + } + if (!intrans) { + return; + } + try { + db.exec("ROLLBACK", null); + intrans = false; + } catch (SQLite.Exception e) { + throw new SQLException(e.toString()); + } + } + + public void setAutoCommit(boolean ac) throws SQLException { + if (ac && intrans && db != null) { + try { + db.exec("ROLLBACK", null); + } catch (SQLite.Exception e) { + throw new SQLException(e.toString()); + } finally { + intrans = false; + } + } + autocommit = ac; + } + + public void setCatalog(String catalog) throws SQLException { + } + + public void setReadOnly(boolean ro) throws SQLException { + if (intrans) { + throw new SQLException("incomplete transaction"); + } + if (ro != readonly) { + DatabaseX dbx = null; + try { + dbx = open(ro); + db.close(); + db = dbx; + dbx = null; + readonly = ro; + } catch (SQLException e) { + throw e; + } catch (SQLite.Exception ee) { + if (dbx != null) { + try { + dbx.close(); + } catch (SQLite.Exception eee) { + } + } + throw new SQLException(ee.toString()); + } + } + } + + public void setTransactionIsolation(int level) throws SQLException { + if (db.is3() && SQLite.JDBCDriver.sharedCache) { + String flag = null; + if (level == TRANSACTION_READ_UNCOMMITTED && + trmode != TRANSACTION_READ_UNCOMMITTED) { + flag = "on"; + } else if (level == TRANSACTION_SERIALIZABLE && + trmode != TRANSACTION_SERIALIZABLE) { + flag = "off"; + } + if (flag != null) { + try { + db.exec("PRAGMA read_uncommitted = " + flag + ";", null); + trmode = level; + } catch (java.lang.Exception e) { + } + } + } + if (level != trmode) { + throw new SQLException("not supported"); + } + } + + public java.util.Map<String, Class<?>> getTypeMap() throws SQLException { + throw new SQLException("not supported"); + } + + public void setTypeMap(java.util.Map map) throws SQLException { + throw new SQLException("not supported"); + } + + public int getHoldability() throws SQLException { + return ResultSet.HOLD_CURSORS_OVER_COMMIT; + } + + public void setHoldability(int holdability) throws SQLException { + if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) { + return; + } + throw new SQLException("not supported"); + } + + public Savepoint setSavepoint() throws SQLException { + throw new SQLException("not supported"); + } + + public Savepoint setSavepoint(String name) throws SQLException { + throw new SQLException("not supported"); + } + + public void rollback(Savepoint x) throws SQLException { + throw new SQLException("not supported"); + } + + public void releaseSavepoint(Savepoint x) throws SQLException { + throw new SQLException("not supported"); + } + + public Statement createStatement(int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) + throws SQLException { + if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { + throw new SQLException("not supported"); + } + return createStatement(resultSetType, resultSetConcurrency); + } + + public PreparedStatement prepareStatement(String sql, int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) + throws SQLException { + if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { + throw new SQLException("not supported"); + } + return prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + public CallableStatement prepareCall(String sql, int x, int y, int z) + throws SQLException { + throw new SQLException("not supported"); + } + + public PreparedStatement prepareStatement(String sql, int autokeys) + throws SQLException { + if (autokeys != Statement.NO_GENERATED_KEYS) { + throw new SQLException("not supported"); + } + return prepareStatement(sql); + } + + public PreparedStatement prepareStatement(String sql, int colIndexes[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public PreparedStatement prepareStatement(String sql, String columns[]) + throws SQLException { + throw new SQLException("not supported"); + } + +} + +class DatabaseX extends SQLite.Database { + + static Object lock = new Object(); + + public DatabaseX() { + super(); + } + + void wait(int ms) { + try { + synchronized (lock) { + lock.wait(ms); + } + } catch (java.lang.Exception e) { + } + } + + public void exec(String sql, SQLite.Callback cb) + throws SQLite.Exception { + super.exec(sql, cb); + synchronized (lock) { + lock.notifyAll(); + } + } + + public void exec(String sql, SQLite.Callback cb, String args[]) + throws SQLite.Exception { + super.exec(sql, cb, args); + synchronized (lock) { + lock.notifyAll(); + } + } + + public SQLite.TableResult get_table(String sql, String args[]) + throws SQLite.Exception { + SQLite.TableResult ret = super.get_table(sql, args); + synchronized (lock) { + lock.notifyAll(); + } + return ret; + } + + public void get_table(String sql, String args[], SQLite.TableResult tbl) + throws SQLite.Exception { + super.get_table(sql, args, tbl); + synchronized (lock) { + lock.notifyAll(); + } + } + +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java new file mode 100644 index 0000000..2357c38 --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCDatabaseMetaData.java @@ -0,0 +1,1649 @@ +package SQLite.JDBC2y; + +import java.sql.*; +import java.util.Hashtable; + +public class JDBCDatabaseMetaData implements DatabaseMetaData { + + private JDBCConnection conn; + + public JDBCDatabaseMetaData(JDBCConnection conn) { + this.conn = conn; + } + + public boolean allProceduresAreCallable() throws SQLException { + return false; + } + + public boolean allTablesAreSelectable() throws SQLException { + return true; + } + + public String getURL() throws SQLException { + return conn.url; + } + + public String getUserName() throws SQLException { + return ""; + } + + public boolean isReadOnly() throws SQLException { + return false; + } + + public boolean nullsAreSortedHigh() throws SQLException { + return false; + } + + public boolean nullsAreSortedLow() throws SQLException { + return false; + } + + public boolean nullsAreSortedAtStart() throws SQLException { + return false; + } + + public boolean nullsAreSortedAtEnd() throws SQLException { + return false; + } + + public String getDatabaseProductName() throws SQLException { + return "SQLite"; + } + + public String getDatabaseProductVersion() throws SQLException { + return SQLite.Database.version(); + } + + public String getDriverName() throws SQLException { + return "SQLite/JDBC"; + } + + public String getDriverVersion() throws SQLException { + return "" + SQLite.JDBCDriver.MAJORVERSION + "." + + SQLite.Constants.drv_minor; + } + + public int getDriverMajorVersion() { + return SQLite.JDBCDriver.MAJORVERSION; + } + + public int getDriverMinorVersion() { + return SQLite.Constants.drv_minor; + } + + public boolean usesLocalFiles() throws SQLException { + return true; + } + + public boolean usesLocalFilePerTable() throws SQLException { + return false; + } + + public boolean supportsMixedCaseIdentifiers() throws SQLException { + return false; + } + + public boolean storesUpperCaseIdentifiers() throws SQLException { + return false; + } + + public boolean storesLowerCaseIdentifiers() throws SQLException { + return false; + } + + public boolean storesMixedCaseIdentifiers() throws SQLException { + return true; + } + + public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + return false; + } + + public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + return false; + } + + public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + return false; + } + + public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + return true; + } + + public String getIdentifierQuoteString() throws SQLException { + return "\""; + } + + public String getSQLKeywords() throws SQLException { + return "SELECT,UPDATE,CREATE,TABLE,VIEW,DELETE,FROM,WHERE" + + ",COMMIT,ROLLBACK,TRIGGER"; + } + + public String getNumericFunctions() throws SQLException { + return ""; + } + + public String getStringFunctions() throws SQLException { + return ""; + } + + public String getSystemFunctions() throws SQLException { + return ""; + } + + public String getTimeDateFunctions() throws SQLException { + return ""; + } + + public String getSearchStringEscape() throws SQLException { + return "\\"; + } + + public String getExtraNameCharacters() throws SQLException { + return ""; + } + + public boolean supportsAlterTableWithAddColumn() throws SQLException { + return false; + } + + public boolean supportsAlterTableWithDropColumn() throws SQLException { + return false; + } + + public boolean supportsColumnAliasing() throws SQLException { + return true; + } + + public boolean nullPlusNonNullIsNull() throws SQLException { + return false; + } + + public boolean supportsConvert() throws SQLException { + return false; + } + + public boolean supportsConvert(int fromType, int toType) + throws SQLException { + return false; + } + + public boolean supportsTableCorrelationNames() throws SQLException { + return true; + } + + public boolean supportsDifferentTableCorrelationNames() + throws SQLException { + return false; + } + + public boolean supportsExpressionsInOrderBy() throws SQLException { + return true; + } + + public boolean supportsOrderByUnrelated() throws SQLException { + return true; + } + + public boolean supportsGroupBy() throws SQLException { + return true; + } + + public boolean supportsGroupByUnrelated() throws SQLException { + return true; + } + + public boolean supportsGroupByBeyondSelect() throws SQLException { + return false; + } + + public boolean supportsLikeEscapeClause() throws SQLException { + return false; + } + + public boolean supportsMultipleResultSets() throws SQLException { + return false; + } + + public boolean supportsMultipleTransactions() throws SQLException { + return false; + } + + public boolean supportsNonNullableColumns() throws SQLException { + return true; + } + + public boolean supportsMinimumSQLGrammar() throws SQLException { + return true; + } + + public boolean supportsCoreSQLGrammar() throws SQLException { + return false; + } + + public boolean supportsExtendedSQLGrammar() throws SQLException { + return false; + } + + public boolean supportsANSI92EntryLevelSQL() throws SQLException { + return true; + } + + public boolean supportsANSI92IntermediateSQL() throws SQLException { + return false; + } + + public boolean supportsANSI92FullSQL() throws SQLException { + return false; + } + + public boolean supportsIntegrityEnhancementFacility() + throws SQLException { + return false; + } + + public boolean supportsOuterJoins() throws SQLException { + return false; + } + + public boolean supportsFullOuterJoins() throws SQLException { + return false; + } + + public boolean supportsLimitedOuterJoins() throws SQLException { + return false; + } + + public String getSchemaTerm() throws SQLException { + return ""; + } + + public String getProcedureTerm() throws SQLException { + return ""; + } + + public String getCatalogTerm() throws SQLException { + return ""; + } + + public boolean isCatalogAtStart() throws SQLException { + return false; + } + + public String getCatalogSeparator() throws SQLException { + return ""; + } + + public boolean supportsSchemasInDataManipulation() throws SQLException { + return false; + } + + public boolean supportsSchemasInProcedureCalls() throws SQLException { + return false; + } + + public boolean supportsSchemasInTableDefinitions() throws SQLException { + return false; + } + + public boolean supportsSchemasInIndexDefinitions() throws SQLException { + return false; + } + + public boolean supportsSchemasInPrivilegeDefinitions() + throws SQLException { + return false; + } + + public boolean supportsCatalogsInDataManipulation() throws SQLException { + return false; + } + + public boolean supportsCatalogsInProcedureCalls() throws SQLException { + return false; + } + + public boolean supportsCatalogsInTableDefinitions() throws SQLException { + return false; + } + + public boolean supportsCatalogsInIndexDefinitions() throws SQLException { + return false; + } + + public boolean supportsCatalogsInPrivilegeDefinitions() + throws SQLException { + return false; + } + + public boolean supportsPositionedDelete() throws SQLException { + return false; + } + + public boolean supportsPositionedUpdate() throws SQLException { + return false; + } + + public boolean supportsSelectForUpdate() throws SQLException { + return false; + } + + public boolean supportsStoredProcedures() throws SQLException { + return false; + } + + public boolean supportsSubqueriesInComparisons() throws SQLException { + return true; + } + + public boolean supportsSubqueriesInExists() throws SQLException { + return true; + } + + public boolean supportsSubqueriesInIns() throws SQLException { + return true; + } + + public boolean supportsSubqueriesInQuantifieds() throws SQLException { + return false; + } + + public boolean supportsCorrelatedSubqueries() throws SQLException { + return false; + } + + public boolean supportsUnion() throws SQLException { + return true; + } + + public boolean supportsUnionAll() throws SQLException { + return true; + } + + public boolean supportsOpenCursorsAcrossCommit() throws SQLException { + return false; + } + + public boolean supportsOpenCursorsAcrossRollback() throws SQLException { + return false; + } + + public boolean supportsOpenStatementsAcrossCommit() throws SQLException { + return false; + } + + public boolean supportsOpenStatementsAcrossRollback() throws SQLException { + return false; + } + + public int getMaxBinaryLiteralLength() throws SQLException { + return 0; + } + + public int getMaxCharLiteralLength() throws SQLException { + return 0; + } + + public int getMaxColumnNameLength() throws SQLException { + return 0; + } + + public int getMaxColumnsInGroupBy() throws SQLException { + return 0; + } + + public int getMaxColumnsInIndex() throws SQLException { + return 0; + } + + public int getMaxColumnsInOrderBy() throws SQLException { + return 0; + } + + public int getMaxColumnsInSelect() throws SQLException { + return 0; + } + + public int getMaxColumnsInTable() throws SQLException { + return 0; + } + + public int getMaxConnections() throws SQLException { + return 0; + } + + public int getMaxCursorNameLength() throws SQLException { + return 8; + } + + public int getMaxIndexLength() throws SQLException { + return 0; + } + + public int getMaxSchemaNameLength() throws SQLException { + return 0; + } + + public int getMaxProcedureNameLength() throws SQLException { + return 0; + } + + public int getMaxCatalogNameLength() throws SQLException { + return 0; + } + + public int getMaxRowSize() throws SQLException { + return 0; + } + + public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + return true; + } + + public int getMaxStatementLength() throws SQLException { + return 0; + } + + public int getMaxStatements() throws SQLException { + return 0; + } + + public int getMaxTableNameLength() throws SQLException { + return 0; + } + + public int getMaxTablesInSelect() throws SQLException { + return 0; + } + + public int getMaxUserNameLength() throws SQLException { + return 0; + } + + public int getDefaultTransactionIsolation() throws SQLException { + return Connection.TRANSACTION_SERIALIZABLE; + } + + public boolean supportsTransactions() throws SQLException { + return true; + } + + public boolean supportsTransactionIsolationLevel(int level) + throws SQLException { + return level == Connection.TRANSACTION_SERIALIZABLE; + } + + public boolean supportsDataDefinitionAndDataManipulationTransactions() + throws SQLException { + return true; + } + + public boolean supportsDataManipulationTransactionsOnly() + throws SQLException { + return false; + } + + public boolean dataDefinitionCausesTransactionCommit() + throws SQLException { + return false; + } + + public boolean dataDefinitionIgnoredInTransactions() throws SQLException { + return false; + } + + public ResultSet getProcedures(String catalog, String schemaPattern, + String procedureNamePattern) + throws SQLException { + return null; + } + + public ResultSet getProcedureColumns(String catalog, + String schemaPattern, + String procedureNamePattern, + String columnNamePattern) + throws SQLException { + return null; + } + + public ResultSet getTables(String catalog, String schemaPattern, + String tableNamePattern, String types[]) + throws SQLException { + JDBCStatement s = new JDBCStatement(conn); + StringBuffer sb = new StringBuffer(); + sb.append("SELECT '' AS 'TABLE_CAT', " + + "'' AS 'TABLE_SCHEM', " + + "tbl_name AS 'TABLE_NAME', " + + "upper(type) AS 'TABLE_TYPE', " + + "'' AS REMARKS FROM sqlite_master " + + "WHERE tbl_name like "); + if (tableNamePattern != null) { + sb.append(SQLite.Shell.sql_quote(tableNamePattern)); + } else { + sb.append("'%'"); + } + sb.append(" AND "); + if (types == null || types.length == 0) { + sb.append("(type = 'table' or type = 'view')"); + } else { + sb.append("("); + String sep = ""; + for (int i = 0; i < types.length; i++) { + sb.append(sep); + sb.append("type = "); + sb.append(SQLite.Shell.sql_quote(types[i].toLowerCase())); + sep = " or "; + } + sb.append(")"); + } + ResultSet rs = null; + try { + rs = s.executeQuery(sb.toString()); + s.close(); + } catch (SQLException e) { + throw e; + } finally { + s.close(); + } + return rs; + } + + public ResultSet getSchemas() throws SQLException { + String cols[] = { "TABLE_SCHEM" }; + SQLite.TableResult tr = new SQLite.TableResult(); + tr.columns(cols); + String row[] = { "" }; + tr.newrow(row); + JDBCResultSet rs = new JDBCResultSet(tr, null); + return (ResultSet) rs; + } + + public ResultSet getCatalogs() throws SQLException { + String cols[] = { "TABLE_CAT" }; + SQLite.TableResult tr = new SQLite.TableResult(); + tr.columns(cols); + String row[] = { "" }; + tr.newrow(row); + JDBCResultSet rs = new JDBCResultSet(tr, null); + return (ResultSet) rs; + } + + public ResultSet getTableTypes() throws SQLException { + String cols[] = { "TABLE_TYPE" }; + SQLite.TableResult tr = new SQLite.TableResult(); + tr.columns(cols); + String row[] = new String[1]; + row[0] = "TABLE"; + tr.newrow(row); + row = new String[1]; + row[0] = "VIEW"; + tr.newrow(row); + JDBCResultSet rs = new JDBCResultSet(tr, null); + return (ResultSet) rs; + } + + public ResultSet getColumns(String catalog, String schemaPattern, + String tableNamePattern, + String columnNamePattern) + throws SQLException { + // BEGIN android-changed: add missing error check. + if (conn.db == null) { + throw new SQLException("connection closed"); + } + // END android-changed + JDBCStatement s = new JDBCStatement(conn); + JDBCResultSet rs0 = null; + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s.executeQuery("PRAGMA table_info(" + + SQLite.Shell.sql_quote(tableNamePattern) + + ")")); + s.close(); + } catch (SQLException e) { + throw e; + } finally { + s.close(); + } + if (rs0.tr.nrows < 1) { + throw new SQLException("no such table: " + tableNamePattern); + } + String cols[] = { + "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", + "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", + "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", + "NUM_PREC_RADIX", "NULLABLE", "REMARKS", + "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", + "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.SMALLINT, Types.VARCHAR, + Types.INTEGER, Types.INTEGER, Types.INTEGER, + Types.INTEGER, Types.INTEGER, Types.VARCHAR, + Types.VARCHAR, Types.INTEGER, Types.INTEGER, + Types.INTEGER, Types.INTEGER, Types.VARCHAR + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + Hashtable<String, Integer> h = new Hashtable<String, Integer>(); + for (int i = 0; i < rs0.tr.ncolumns; i++) { + h.put(rs0.tr.column[i], new Integer(i)); + } + if (columnNamePattern != null && + columnNamePattern.charAt(0) == '%') { + columnNamePattern = null; + } + for (int i = 0; i < rs0.tr.nrows; i++) { + String r0[] = (String [])(rs0.tr.rows.elementAt(i)); + int col = ((Integer) h.get("name")).intValue(); + if (columnNamePattern != null) { + if (r0[col].compareTo(columnNamePattern) != 0) { + continue; + } + } + String row[] = new String[cols.length]; + row[0] = ""; + row[1] = ""; + row[2] = tableNamePattern; + row[3] = r0[col]; + col = ((Integer) h.get("type")).intValue(); + String typeStr = r0[col]; + int type = mapSqlType(typeStr); + row[4] = "" + type; + row[5] = mapTypeName(type); + row[6] = "" + getD(typeStr, type); + row[7] = "" + getM(typeStr, type); + row[8] = "10"; + row[9] = "0"; + row[11] = null; + col = ((Integer) h.get("dflt_value")).intValue(); + row[12] = r0[col]; + row[13] = "0"; + row[14] = "0"; + row[15] = "65536"; + col = ((Integer) h.get("cid")).intValue(); + Integer cid = new Integer(r0[col]); + row[16] = "" + (cid.intValue() + 1); + col = ((Integer) h.get("notnull")).intValue(); + row[17] = (r0[col].charAt(0) == '0') ? "YES" : "NO"; + row[10] = (r0[col].charAt(0) == '0') ? "" + columnNullable : + "" + columnNoNulls; + tr.newrow(row); + } + } + return rs; + } + + public ResultSet getColumnPrivileges(String catalog, String schema, + String table, + String columnNamePattern) + throws SQLException { + String cols[] = { + "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", + "COLUMN_NAME", "GRANTOR", "GRANTEE", + "PRIVILEGE", "IS_GRANTABLE" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + return rs; + } + + public ResultSet getTablePrivileges(String catalog, String schemaPattern, + String tableNamePattern) + throws SQLException { + String cols[] = { + "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", + "COLUMN_NAME", "GRANTOR", "GRANTEE", + "PRIVILEGE", "IS_GRANTABLE" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + return rs; + } + + public ResultSet getBestRowIdentifier(String catalog, String schema, + String table, int scope, + boolean nullable) + throws SQLException { + JDBCStatement s0 = new JDBCStatement(conn); + JDBCResultSet rs0 = null; + JDBCStatement s1 = new JDBCStatement(conn); + JDBCResultSet rs1 = null; + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s0.executeQuery("PRAGMA index_list(" + + SQLite.Shell.sql_quote(table) + ")")); + rs1 = (JDBCResultSet) + (s1.executeQuery("PRAGMA table_info(" + + SQLite.Shell.sql_quote(table) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s0.close(); + s1.close(); + } + String cols[] = { + "SCOPE", "COLUMN_NAME", "DATA_TYPE", + "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", + "DECIMAL_DIGITS", "PSEUDO_COLUMN" + }; + int types[] = { + Types.SMALLINT, Types.VARCHAR, Types.SMALLINT, + Types.VARCHAR, Types.INTEGER, Types.INTEGER, + Types.SMALLINT, Types.SMALLINT + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0 && + rs1 != null && rs1.tr != null && rs1.tr.nrows > 0) { + Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); + for (int i = 0; i < rs0.tr.ncolumns; i++) { + h0.put(rs0.tr.column[i], new Integer(i)); + } + Hashtable<String, Integer> h1 = new Hashtable<String, Integer>(); + for (int i = 0; i < rs1.tr.ncolumns; i++) { + h1.put(rs1.tr.column[i], new Integer(i)); + } + for (int i = 0; i < rs0.tr.nrows; i++) { + String r0[] = (String [])(rs0.tr.rows.elementAt(i)); + int col = ((Integer) h0.get("unique")).intValue(); + String uniq = r0[col]; + col = ((Integer) h0.get("name")).intValue(); + String iname = r0[col]; + if (uniq.charAt(0) == '0') { + continue; + } + JDBCStatement s2 = new JDBCStatement(conn); + JDBCResultSet rs2 = null; + try { + rs2 = (JDBCResultSet) + (s2.executeQuery("PRAGMA index_info(" + + SQLite.Shell.sql_quote(iname) + ")")); + } catch (SQLException e) { + } finally { + s2.close(); + } + if (rs2 == null || rs2.tr == null || rs2.tr.nrows <= 0) { + continue; + } + Hashtable<String, Integer> h2 = + new Hashtable<String, Integer>(); + for (int k = 0; k < rs2.tr.ncolumns; k++) { + h2.put(rs2.tr.column[k], new Integer(k)); + } + for (int k = 0; k < rs2.tr.nrows; k++) { + String r2[] = (String [])(rs2.tr.rows.elementAt(k)); + col = ((Integer) h2.get("name")).intValue(); + String cname = r2[col]; + for (int m = 0; m < rs1.tr.nrows; m++) { + String r1[] = (String [])(rs1.tr.rows.elementAt(m)); + col = ((Integer) h1.get("name")).intValue(); + if (cname.compareTo(r1[col]) == 0) { + String row[] = new String[cols.length]; + row[0] = "" + scope; + row[1] = cname; + row[2] = "" + Types.VARCHAR; + row[3] = "VARCHAR"; + row[4] = "65536"; + row[5] = "0"; + row[6] = "0"; + row[7] = "" + bestRowNotPseudo; + tr.newrow(row); + } + } + } + } + } + if (tr.nrows <= 0) { + String row[] = new String[cols.length]; + row[0] = "" + scope; + row[1] = "_ROWID_"; + row[2] = "" + Types.INTEGER; + row[3] = "INTEGER"; + row[4] = "10"; + row[5] = "0"; + row[6] = "0"; + row[7] = "" + bestRowPseudo; + tr.newrow(row); + } + return rs; + } + + public ResultSet getVersionColumns(String catalog, String schema, + String table) throws SQLException { + String cols[] = { + "SCOPE", "COLUMN_NAME", "DATA_TYPE", + "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", + "DECIMAL_DIGITS", "PSEUDO_COLUMN" + }; + int types[] = { + Types.SMALLINT, Types.VARCHAR, Types.SMALLINT, + Types.VARCHAR, Types.INTEGER, Types.INTEGER, + Types.SMALLINT, Types.SMALLINT + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + return rs; + } + + public ResultSet getPrimaryKeys(String catalog, String schema, + String table) throws SQLException { + JDBCStatement s0 = new JDBCStatement(conn); + JDBCResultSet rs0 = null; + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s0.executeQuery("PRAGMA index_list(" + + SQLite.Shell.sql_quote(table) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s0.close(); + } + String cols[] = { + "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", + "COLUMN_NAME", "KEY_SEQ", "PK_NAME" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.SMALLINT, Types.VARCHAR + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); + for (int i = 0; i < rs0.tr.ncolumns; i++) { + h0.put(rs0.tr.column[i], new Integer(i)); + } + for (int i = 0; i < rs0.tr.nrows; i++) { + String r0[] = (String [])(rs0.tr.rows.elementAt(i)); + int col = ((Integer) h0.get("unique")).intValue(); + String uniq = r0[col]; + col = ((Integer) h0.get("name")).intValue(); + String iname = r0[col]; + if (uniq.charAt(0) == '0') { + continue; + } + JDBCStatement s1 = new JDBCStatement(conn); + JDBCResultSet rs1 = null; + try { + rs1 = (JDBCResultSet) + (s1.executeQuery("PRAGMA index_info(" + + SQLite.Shell.sql_quote(iname) + ")")); + } catch (SQLException e) { + } finally { + s1.close(); + } + if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) { + continue; + } + Hashtable<String, Integer> h1 = + new Hashtable<String, Integer>(); + for (int k = 0; k < rs1.tr.ncolumns; k++) { + h1.put(rs1.tr.column[k], new Integer(k)); + } + for (int k = 0; k < rs1.tr.nrows; k++) { + String r1[] = (String [])(rs1.tr.rows.elementAt(k)); + String row[] = new String[cols.length]; + row[0] = ""; + row[1] = ""; + row[2] = table; + col = ((Integer) h1.get("name")).intValue(); + row[3] = r1[col]; + col = ((Integer) h1.get("seqno")).intValue(); + row[4] = Integer.toString(Integer.parseInt(r1[col]) + 1); // android-changed: performance + row[5] = iname; + tr.newrow(row); + } + } + } + if (tr.nrows > 0) { + return rs; + } + JDBCStatement s1 = new JDBCStatement(conn); + try { + rs0 = (JDBCResultSet) + (s1.executeQuery("PRAGMA table_info(" + + SQLite.Shell.sql_quote(table) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s1.close(); + } + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); + for (int i = 0; i < rs0.tr.ncolumns; i++) { + h0.put(rs0.tr.column[i], new Integer(i)); + } + for (int i = 0; i < rs0.tr.nrows; i++) { + String r0[] = (String [])(rs0.tr.rows.elementAt(i)); + int col = ((Integer) h0.get("type")).intValue(); + String type = r0[col]; + if (!type.equalsIgnoreCase("integer")) { + continue; + } + col = ((Integer) h0.get("pk")).intValue(); + String pk = r0[col]; + if (pk.charAt(0) == '0') { + continue; + } + String row[] = new String[cols.length]; + row[0] = ""; + row[1] = ""; + row[2] = table; + col = ((Integer) h0.get("name")).intValue(); + row[3] = r0[col]; + col = ((Integer) h0.get("cid")).intValue(); + row[4] = Integer.toString(Integer.parseInt(r0[col]) + 1); // android-changed: performance + row[5] = ""; + tr.newrow(row); + } + } + return rs; + } + + private void internalImportedKeys(String table, String pktable, + JDBCResultSet in, TableResultX out) { + Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); + for (int i = 0; i < in.tr.ncolumns; i++) { + h0.put(in.tr.column[i], new Integer(i)); + } + for (int i = 0; i < in.tr.nrows; i++) { + String r0[] = (String [])(in.tr.rows.elementAt(i)); + int col = ((Integer) h0.get("table")).intValue(); + String pktab = r0[col]; + if (pktable != null && !pktable.equalsIgnoreCase(pktab)) { + continue; + } + col = ((Integer) h0.get("from")).intValue(); + String fkcol = r0[col]; + col = ((Integer) h0.get("to")).intValue(); + String pkcol = r0[col]; + col = ((Integer) h0.get("seq")).intValue(); + String seq = r0[col]; + String row[] = new String[out.ncolumns]; + row[0] = ""; + row[1] = ""; + row[2] = pktab; + row[3] = pkcol; + row[4] = ""; + row[5] = ""; + row[6] = table; + row[7] = fkcol == null ? pkcol : fkcol; + row[8] = Integer.toString(Integer.parseInt(seq) + 1); // android-changed: performance + row[9] = + "" + java.sql.DatabaseMetaData.importedKeyNoAction; + row[10] = + "" + java.sql.DatabaseMetaData.importedKeyNoAction; + row[11] = null; + row[12] = null; + row[13] = + "" + java.sql.DatabaseMetaData.importedKeyNotDeferrable; + out.newrow(row); + } + } + + public ResultSet getImportedKeys(String catalog, String schema, + String table) throws SQLException { + JDBCStatement s0 = new JDBCStatement(conn); + JDBCResultSet rs0 = null; + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s0.executeQuery("PRAGMA foreign_key_list(" + + SQLite.Shell.sql_quote(table) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s0.close(); + } + String cols[] = { + "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", + "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", + "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", + "UPDATE_RULE", "DELETE_RULE", "FK_NAME", + "PK_NAME", "DEFERRABILITY" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, + Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, + Types.VARCHAR, Types.SMALLINT + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet((SQLite.TableResult) tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + internalImportedKeys(table, null, rs0, tr); + } + return rs; + } + + public ResultSet getExportedKeys(String catalog, String schema, + String table) throws SQLException { + String cols[] = { + "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", + "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", + "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", + "UPDATE_RULE", "DELETE_RULE", "FK_NAME", + "PK_NAME", "DEFERRABILITY" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, + Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, + Types.VARCHAR, Types.SMALLINT + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet(tr, null); + return rs; + } + + public ResultSet getCrossReference(String primaryCatalog, + String primarySchema, + String primaryTable, + String foreignCatalog, + String foreignSchema, + String foreignTable) + throws SQLException { + JDBCResultSet rs0 = null; + if (foreignTable != null && foreignTable.charAt(0) != '%') { + JDBCStatement s0 = new JDBCStatement(conn); + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s0.executeQuery("PRAGMA foreign_key_list(" + + SQLite.Shell.sql_quote(foreignTable) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s0.close(); + } + } + String cols[] = { + "PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", + "PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM", + "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", + "UPDATE_RULE", "DELETE_RULE", "FK_NAME", + "PK_NAME", "DEFERRABILITY" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, + Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, + Types.VARCHAR, Types.SMALLINT + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet(tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + String pktable = null; + if (primaryTable != null && primaryTable.charAt(0) != '%') { + pktable = primaryTable; + } + internalImportedKeys(foreignTable, pktable, rs0, tr); + } + return rs; + } + + public ResultSet getTypeInfo() throws SQLException { + String cols[] = { + "TYPE_NAME", "DATA_TYPE", "PRECISION", + "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS", + "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", + "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT", + "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE", + "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX" + }; + int types[] = { + Types.VARCHAR, Types.SMALLINT, Types.INTEGER, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.SMALLINT, Types.BIT, Types.SMALLINT, + Types.BIT, Types.BIT, Types.BIT, + Types.VARCHAR, Types.SMALLINT, Types.SMALLINT, + Types.INTEGER, Types.INTEGER, Types.INTEGER + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet(tr, null); + String row1[] = { + "VARCHAR", "" + Types.VARCHAR, "65536", + "'", "'", null, + "" + typeNullable, "1", "" + typeSearchable, + "0", "0", "0", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row1); + String row2[] = { + "INTEGER", "" + Types.INTEGER, "32", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "2" + }; + tr.newrow(row2); + String row3[] = { + "DOUBLE", "" + Types.DOUBLE, "16", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "10" + }; + tr.newrow(row3); + String row4[] = { + "FLOAT", "" + Types.FLOAT, "7", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "10" + }; + tr.newrow(row4); + String row5[] = { + "SMALLINT", "" + Types.SMALLINT, "16", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "2" + }; + tr.newrow(row5); + String row6[] = { + "BIT", "" + Types.BIT, "1", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "2" + }; + tr.newrow(row6); + String row7[] = { + "TIMESTAMP", "" + Types.TIMESTAMP, "30", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row7); + String row8[] = { + "DATE", "" + Types.DATE, "10", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row8); + String row9[] = { + "TIME", "" + Types.TIME, "8", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row9); + String row10[] = { + "BINARY", "" + Types.BINARY, "65536", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row10); + String row11[] = { + "VARBINARY", "" + Types.VARBINARY, "65536", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "0" + }; + tr.newrow(row11); + String row12[] = { + "REAL", "" + Types.REAL, "16", + null, null, null, + "" + typeNullable, "0", "" + typeSearchable, + "0", "0", "1", + null, "0", "0", + "0", "0", "10" + }; + tr.newrow(row12); + return rs; + } + + public ResultSet getIndexInfo(String catalog, String schema, String table, + boolean unique, boolean approximate) + throws SQLException { + JDBCStatement s0 = new JDBCStatement(conn); + JDBCResultSet rs0 = null; + try { + try { + conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null); + } catch (SQLite.Exception se) { + throw new SQLException("schema reload failed"); + } + rs0 = (JDBCResultSet) + (s0.executeQuery("PRAGMA index_list(" + + SQLite.Shell.sql_quote(table) + ")")); + } catch (SQLException e) { + throw e; + } finally { + s0.close(); + } + String cols[] = { + "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", + "NON_UNIQUE", "INDEX_QUALIFIER", "INDEX_NAME", + "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", + "ASC_OR_DESC", "CARDINALITY", "PAGES", + "FILTER_CONDITION" + }; + int types[] = { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, + Types.BIT, Types.VARCHAR, Types.VARCHAR, + Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, + Types.VARCHAR, Types.INTEGER, Types.INTEGER, + Types.VARCHAR + }; + TableResultX tr = new TableResultX(); + tr.columns(cols); + tr.sql_types(types); + JDBCResultSet rs = new JDBCResultSet(tr, null); + if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) { + Hashtable<String, Integer> h0 = new Hashtable<String, Integer>(); + for (int i = 0; i < rs0.tr.ncolumns; i++) { + h0.put(rs0.tr.column[i], new Integer(i)); + } + for (int i = 0; i < rs0.tr.nrows; i++) { + String r0[] = (String [])(rs0.tr.rows.elementAt(i)); + int col = ((Integer) h0.get("unique")).intValue(); + String uniq = r0[col]; + col = ((Integer) h0.get("name")).intValue(); + String iname = r0[col]; + if (unique && uniq.charAt(0) == '0') { + continue; + } + JDBCStatement s1 = new JDBCStatement(conn); + JDBCResultSet rs1 = null; + try { + rs1 = (JDBCResultSet) + (s1.executeQuery("PRAGMA index_info(" + + SQLite.Shell.sql_quote(iname) + ")")); + } catch (SQLException e) { + } finally { + s1.close(); + } + if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) { + continue; + } + Hashtable<String, Integer> h1 = + new Hashtable<String, Integer>(); + for (int k = 0; k < rs1.tr.ncolumns; k++) { + h1.put(rs1.tr.column[k], new Integer(k)); + } + for (int k = 0; k < rs1.tr.nrows; k++) { + String r1[] = (String [])(rs1.tr.rows.elementAt(k)); + String row[] = new String[cols.length]; + row[0] = ""; + row[1] = ""; + row[2] = table; + row[3] = (uniq.charAt(0) != '0' || + (iname.charAt(0) == '(' && + iname.indexOf(" autoindex ") > 0)) ? "0" : "1"; + row[4] = ""; + row[5] = iname; + row[6] = "" + tableIndexOther; + col = ((Integer) h1.get("seqno")).intValue(); + row[7] = Integer.toString(Integer.parseInt(r1[col]) + 1); // android-changed: performance + col = ((Integer) h1.get("name")).intValue(); + row[8] = r1[col]; + row[9] = "A"; + row[10] = "0"; + row[11] = "0"; + row[12] = null; + tr.newrow(row); + } + } + } + return rs; + } + + public boolean supportsResultSetType(int type) throws SQLException { + return type == ResultSet.TYPE_FORWARD_ONLY || + type == ResultSet.TYPE_SCROLL_INSENSITIVE || + type == ResultSet.TYPE_SCROLL_SENSITIVE; + } + + public boolean supportsResultSetConcurrency(int type, int concurrency) + throws SQLException { + if (type == ResultSet.TYPE_FORWARD_ONLY || + type == ResultSet.TYPE_SCROLL_INSENSITIVE || + type == ResultSet.TYPE_SCROLL_SENSITIVE) { + return concurrency == ResultSet.CONCUR_READ_ONLY || + concurrency == ResultSet.CONCUR_UPDATABLE; + } + return false; + } + + public boolean ownUpdatesAreVisible(int type) throws SQLException { + if (type == ResultSet.TYPE_FORWARD_ONLY || + type == ResultSet.TYPE_SCROLL_INSENSITIVE || + type == ResultSet.TYPE_SCROLL_SENSITIVE) { + return true; + } + return false; + } + + public boolean ownDeletesAreVisible(int type) throws SQLException { + if (type == ResultSet.TYPE_FORWARD_ONLY || + type == ResultSet.TYPE_SCROLL_INSENSITIVE || + type == ResultSet.TYPE_SCROLL_SENSITIVE) { + return true; + } + return false; + } + + public boolean ownInsertsAreVisible(int type) throws SQLException { + if (type == ResultSet.TYPE_FORWARD_ONLY || + type == ResultSet.TYPE_SCROLL_INSENSITIVE || + type == ResultSet.TYPE_SCROLL_SENSITIVE) { + return true; + } + return false; + } + + public boolean othersUpdatesAreVisible(int type) throws SQLException { + return false; + } + + public boolean othersDeletesAreVisible(int type) throws SQLException { + return false; + } + + public boolean othersInsertsAreVisible(int type) throws SQLException { + return false; + } + + public boolean updatesAreDetected(int type) throws SQLException { + return false; + } + + public boolean deletesAreDetected(int type) throws SQLException { + return false; + } + + public boolean insertsAreDetected(int type) throws SQLException { + return false; + } + + public boolean supportsBatchUpdates() throws SQLException { + return true; + } + + public ResultSet getUDTs(String catalog, String schemaPattern, + String typeNamePattern, int[] types) + throws SQLException { + return null; + } + + public Connection getConnection() throws SQLException { + return conn; + } + + static String mapTypeName(int type) { + switch (type) { + case Types.INTEGER: return "integer"; + case Types.SMALLINT: return "smallint"; + case Types.FLOAT: return "float"; + case Types.DOUBLE: return "double"; + case Types.TIMESTAMP: return "timestamp"; + case Types.DATE: return "date"; + case Types.TIME: return "time"; + case Types.BINARY: return "binary"; + case Types.VARBINARY: return "varbinary"; + case Types.REAL: return "real"; + } + return "varchar"; + } + + static int mapSqlType(String type) { + if (type == null) { + return Types.VARCHAR; + } + type = type.toLowerCase(); + if (type.startsWith("inter")) { + return Types.VARCHAR; + } + if (type.startsWith("numeric") || + type.startsWith("int")) { + return Types.INTEGER; + } + if (type.startsWith("tinyint") || + type.startsWith("smallint")) { + return Types.SMALLINT; + } + if (type.startsWith("float")) { + return Types.FLOAT; + } + if (type.startsWith("double")) { + return Types.DOUBLE; + } + if (type.startsWith("datetime") || + type.startsWith("timestamp")) { + return Types.TIMESTAMP; + } + if (type.startsWith("date")) { + return Types.DATE; + } + if (type.startsWith("time")) { + return Types.TIME; + } + if (type.startsWith("blob")) { + return Types.BINARY; + } + if (type.startsWith("binary")) { + return Types.BINARY; + } + if (type.startsWith("varbinary")) { + return Types.VARBINARY; + } + if (type.startsWith("real")) { + return Types.REAL; + } + return Types.VARCHAR; + } + + static int getM(String typeStr, int type) { + int m = 65536; + switch (type) { + case Types.INTEGER: m = 11; break; + case Types.SMALLINT: m = 6; break; + case Types.FLOAT: m = 25; break; + case Types.REAL: + case Types.DOUBLE: m = 54; break; + case Types.TIMESTAMP: return 30; + case Types.DATE: return 10; + case Types.TIME: return 8; + } + typeStr = typeStr.toLowerCase(); + int i1 = typeStr.indexOf('('); + if (i1 > 0) { + ++i1; + int i2 = typeStr.indexOf(',', i1); + if (i2 < 0) { + i2 = typeStr.indexOf(')', i1); + } + if (i2 - i1 > 0) { + String num = typeStr.substring(i1, i2); + try { + m = java.lang.Integer.parseInt(num, 10); + } catch (NumberFormatException e) { + } + } + } + return m; + } + + static int getD(String typeStr, int type) { + int d = 0; + switch (type) { + case Types.INTEGER: d = 10; break; + case Types.SMALLINT: d = 5; break; + case Types.FLOAT: d = 24; break; + case Types.REAL: + case Types.DOUBLE: d = 53; break; + default: return getM(typeStr, type); + } + typeStr = typeStr.toLowerCase(); + int i1 = typeStr.indexOf('('); + if (i1 > 0) { + ++i1; + int i2 = typeStr.indexOf(',', i1); + if (i2 < 0) { + return getM(typeStr, type); + } + i1 = i2; + i2 = typeStr.indexOf(')', i1); + if (i2 - i1 > 0) { + String num = typeStr.substring(i1, i2); + try { + d = java.lang.Integer.parseInt(num, 10); + } catch (NumberFormatException e) { + } + } + } + return d; + } + + public boolean supportsSavepoints() { + return false; + } + + public boolean supportsNamedParameters() { + return false; + } + + public boolean supportsMultipleOpenResults() { + return false; + } + + public boolean supportsGetGeneratedKeys() { + return false; + } + + public boolean supportsResultSetHoldability(int x) { + return false; + } + + public boolean supportsStatementPooling() { + return false; + } + + public boolean locatorsUpdateCopy() throws SQLException { + throw new SQLException("not supported"); + } + + public ResultSet getSuperTypes(String catalog, String schemaPattern, + String typeNamePattern) + throws SQLException { + throw new SQLException("not supported"); + } + + public ResultSet getSuperTables(String catalog, String schemaPattern, + String tableNamePattern) + throws SQLException { + throw new SQLException("not supported"); + } + + public ResultSet getAttributes(String catalog, String schemaPattern, + String typeNamePattern, + String attributeNamePattern) + throws SQLException { + throw new SQLException("not supported"); + } + + public int getResultSetHoldability() throws SQLException { + return ResultSet.HOLD_CURSORS_OVER_COMMIT; + } + + public int getDatabaseMajorVersion() { + return SQLite.JDBCDriver.MAJORVERSION; + } + + public int getDatabaseMinorVersion() { + return SQLite.Constants.drv_minor; + } + + public int getJDBCMajorVersion() { + return 1; + } + + public int getJDBCMinorVersion() { + return 0; + } + + public int getSQLStateType() throws SQLException { + return sqlStateXOpen; + } + +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java new file mode 100644 index 0000000..3d5b045 --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCPreparedStatement.java @@ -0,0 +1,781 @@ +package SQLite.JDBC2y; + +import java.sql.*; +import java.math.BigDecimal; +import java.util.*; + +class BatchArg { + String arg; + boolean blob; + + BatchArg(String arg, boolean blob) { + if (arg == null) { + this.arg = null; + } else { + this.arg = new String(arg); + } + this.blob = blob; + } +} + +public class JDBCPreparedStatement extends JDBCStatement + implements java.sql.PreparedStatement { + + private String sql; + private String args[]; + private boolean blobs[]; + private ArrayList<BatchArg> batch; + private static final boolean nullrepl = + SQLite.Database.version().compareTo("2.5.0") < 0; + + public JDBCPreparedStatement(JDBCConnection conn, String sql) { + super(conn); + this.args = null; + this.blobs = null; + this.batch = null; + this.sql = fixup(sql); + } + + private String fixup(String sql) { + StringBuffer sb = new StringBuffer(); + boolean inq = false; + int nparm = 0; + for (int i = 0; i < sql.length(); i++) { + char c = sql.charAt(i); + if (c == '\'') { + if (inq) { + char nextChar = 0; + if(i + 1 < sql.length()) { + nextChar = sql.charAt(i + 1); + } + if (nextChar == '\'') { + sb.append(c); + sb.append(nextChar); + i++; + } else { + inq = false; + sb.append(c); + } + } else { + inq = true; + sb.append(c); + } + } else if (c == '?') { + if (inq) { + sb.append(c); + } else { + ++nparm; + sb.append(nullrepl ? "'%q'" : "%Q"); + } + } else if (c == ';') { + if (!inq) { + break; + } + sb.append(c); + } else if (c == '%') { + sb.append("%%"); + } else { + sb.append(c); + } + } + args = new String[nparm]; + blobs = new boolean[nparm]; + try { + clearParameters(); + } catch (SQLException e) { + } + return sb.toString(); + } + + private String fixup2(String sql) { + if (!conn.db.is3()) { + return sql; + } + StringBuffer sb = new StringBuffer(); + int parm = -1; + for (int i = 0; i < sql.length(); i++) { + char c = sql.charAt(i); + if (c == '%') { + sb.append(c); + ++i; + c = sql.charAt(i); + if (c == 'Q') { + parm++; + if (blobs[parm]) { + c = 's'; + } + } + } + sb.append(c); + } + return sb.toString(); + } + + public ResultSet executeQuery() throws SQLException { + return executeQuery(fixup2(sql), args, false); + } + + public int executeUpdate() throws SQLException { + executeQuery(fixup2(sql), args, true); + return updcnt; + } + + public void setNull(int parameterIndex, int sqlType) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = nullrepl ? "" : null; + blobs[parameterIndex - 1] = false; + } + + public void setBoolean(int parameterIndex, boolean x) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = x ? "1" : "0"; + blobs[parameterIndex - 1] = false; + } + + public void setByte(int parameterIndex, byte x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setShort(int parameterIndex, short x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setInt(int parameterIndex, int x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setLong(int parameterIndex, long x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setFloat(int parameterIndex, float x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setDouble(int parameterIndex, double x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + args[parameterIndex - 1] = "" + x; + blobs[parameterIndex - 1] = false; + } + + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + args[parameterIndex - 1] = "" + x; + } + blobs[parameterIndex - 1] = false; + } + + public void setString(int parameterIndex, String x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + args[parameterIndex - 1] = x; + } + blobs[parameterIndex - 1] = false; + } + + public void setBytes(int parameterIndex, byte x[]) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + blobs[parameterIndex - 1] = false; + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (conn.db.is3()) { + args[parameterIndex - 1] = SQLite.StringEncoder.encodeX(x); + blobs[parameterIndex - 1] = true; + } else { + args[parameterIndex - 1] = SQLite.StringEncoder.encode(x); + } + } + } + + public void setDate(int parameterIndex, java.sql.Date x) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (conn.useJulian) { + args[parameterIndex - 1] = java.lang.Double.toString(SQLite.Database.julian_from_long(x.getTime())); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public void setTime(int parameterIndex, java.sql.Time x) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (conn.useJulian) { + args[parameterIndex - 1] = java.lang.Double.toString(SQLite.Database.julian_from_long(x.getTime())); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (conn.useJulian) { + args[parameterIndex - 1] = java.lang.Double.toString(SQLite.Database.julian_from_long(x.getTime())); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public void setAsciiStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + throw new SQLException("not supported"); + } + + @Deprecated + public void setUnicodeStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + throw new SQLException("not supported"); + } + + public void setBinaryStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + try { + byte[] data = new byte[length]; + x.read(data, 0, length); + setBytes(parameterIndex, data); + } catch (java.io.IOException e) { + throw new SQLException("I/O failed"); + } + } + + public void clearParameters() throws SQLException { + for (int i = 0; i < args.length; i++) { + args[i] = nullrepl ? "" : null; + blobs[i] = false; + } + } + + public void setObject(int parameterIndex, Object x, int targetSqlType, + int scale) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (x instanceof byte[]) { + byte[] bx = (byte[]) x; + if (conn.db.is3()) { + args[parameterIndex - 1] = + SQLite.StringEncoder.encodeX(bx); + blobs[parameterIndex - 1] = true; + return; + } + args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public void setObject(int parameterIndex, Object x, int targetSqlType) + throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (x instanceof byte[]) { + byte[] bx = (byte[]) x; + if (conn.db.is3()) { + args[parameterIndex - 1] = + SQLite.StringEncoder.encodeX(bx); + blobs[parameterIndex - 1] = true; + return; + } + args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public void setObject(int parameterIndex, Object x) throws SQLException { + if (parameterIndex < 1 || parameterIndex > args.length) { + throw new SQLException("bad parameter index"); + } + if (x == null) { + args[parameterIndex - 1] = nullrepl ? "" : null; + } else { + if (x instanceof byte[]) { + byte[] bx = (byte[]) x; + if (conn.db.is3()) { + args[parameterIndex - 1] = + SQLite.StringEncoder.encodeX(bx); + blobs[parameterIndex - 1] = true; + return; + } + args[parameterIndex - 1] = SQLite.StringEncoder.encode(bx); + } else { + args[parameterIndex - 1] = x.toString(); + } + } + blobs[parameterIndex - 1] = false; + } + + public boolean execute() throws SQLException { + return executeQuery(fixup2(sql), args, false) != null; + } + + public void addBatch() throws SQLException { + if (batch == null) { + batch = new ArrayList<BatchArg>(args.length); + } + for (int i = 0; i < args.length; i++) { + batch.add(new BatchArg(args[i], blobs[i])); + } + } + + public int[] executeBatch() throws SQLException { + if (batch == null) { + return new int[0]; + } + int[] ret = new int[batch.size() / args.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = EXECUTE_FAILED; + } + int errs = 0; + int index = 0; + for (int i = 0; i < ret.length; i++) { + for (int k = 0; k < args.length; k++) { + BatchArg b = (BatchArg) batch.get(index++); + + args[k] = b.arg; + blobs[k] = b.blob; + } + try { + ret[i] = executeUpdate(); + } catch (SQLException e) { + ++errs; + } + } + if (errs > 0) { + throw new BatchUpdateException("batch failed", ret); + } + return ret; + } + + public void clearBatch() throws SQLException { + if (batch != null) { + batch.clear(); + batch = null; + } + } + + public void close() throws SQLException { + clearBatch(); + super.close(); + } + + public void setCharacterStream(int parameterIndex, + java.io.Reader reader, + int length) throws SQLException { + try { + char[] data = new char[length]; + reader.read(data); + setString(parameterIndex, new String(data)); + } catch (java.io.IOException e) { + throw new SQLException("I/O failed"); + } + } + + public void setRef(int i, Ref x) throws SQLException { + throw new SQLException("not supported"); + } + + public void setBlob(int i, Blob x) throws SQLException { + throw new SQLException("not supported"); + } + + public void setClob(int i, Clob x) throws SQLException { + throw new SQLException("not supported"); + } + + public void setArray(int i, Array x) throws SQLException { + throw new SQLException("not supported"); + } + + public ResultSetMetaData getMetaData() throws SQLException { + return rs.getMetaData(); + } + + public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) + throws SQLException { + setDate(parameterIndex, x); + } + + public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) + throws SQLException { + setTime(parameterIndex, x); + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x, + Calendar cal) throws SQLException { + setTimestamp(parameterIndex, x); + } + + public void setNull(int parameterIndex, int sqlType, String typeName) + throws SQLException { + setNull(parameterIndex, sqlType); + } + + public ParameterMetaData getParameterMetaData() throws SQLException { + throw new SQLException("not supported"); + } + + public void registerOutputParameter(String parameterName, int sqlType) + throws SQLException { + throw new SQLException("not supported"); + } + + public void registerOutputParameter(String parameterName, int sqlType, + int scale) + throws SQLException { + throw new SQLException("not supported"); + } + + public void registerOutputParameter(String parameterName, int sqlType, + String typeName) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.net.URL getURL(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public void setURL(int parameterIndex, java.net.URL url) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setNull(String parameterName, int sqlType) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setBoolean(String parameterName, boolean val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setByte(String parameterName, byte val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setShort(String parameterName, short val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setInt(String parameterName, int val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setLong(String parameterName, long val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setFloat(String parameterName, float val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setDouble(String parameterName, double val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setBigDecimal(String parameterName, BigDecimal val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setString(String parameterName, String val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setBytes(String parameterName, byte val[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setDate(String parameterName, java.sql.Date val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setTime(String parameterName, java.sql.Time val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setTimestamp(String parameterName, java.sql.Timestamp val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setAsciiStream(String parameterName, + java.io.InputStream s, int length) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setBinaryStream(String parameterName, + java.io.InputStream s, int length) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setObject(String parameterName, Object val, int targetSqlType, + int scale) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setObject(String parameterName, Object val, int targetSqlType) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setObject(String parameterName, Object val) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setCharacterStream(String parameterName, + java.io.Reader r, int length) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setDate(String parameterName, java.sql.Date val, + Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setTime(String parameterName, java.sql.Time val, + Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setTimestamp(String parameterName, java.sql.Timestamp val, + Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public void setNull(String parameterName, int sqlType, String typeName) + throws SQLException { + throw new SQLException("not supported"); + } + + public String getString(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public boolean getBoolean(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public byte getByte(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public short getShort(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public int getInt(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public long getLong(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public float getFloat(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public double getDouble(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public byte[] getBytes(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Date getDate(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Time getTime(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Timestamp getTimestamp(String parameterName) + throws SQLException { + throw new SQLException("not supported"); + } + + public Object getObject(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Object getObject(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public BigDecimal getBigDecimal(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Object getObject(String parameterName, Map map) + throws SQLException { + throw new SQLException("not supported"); + } + + public Object getObject(int parameterIndex, Map map) + throws SQLException { + throw new SQLException("not supported"); + } + + public Ref getRef(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public Ref getRef(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Blob getBlob(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Blob getBlob(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public Clob getClob(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Clob getClob(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public Array getArray(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + + public Array getArray(int parameterIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Date getDate(String parameterName, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Date getDate(int parameterIndex, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Time getTime(String parameterName, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Time getTime(int parameterIndex, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.net.URL getURL(String parameterName) throws SQLException { + throw new SQLException("not supported"); + } + +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSet.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSet.java new file mode 100644 index 0000000..24e110f --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSet.java @@ -0,0 +1,1314 @@ +package SQLite.JDBC2y; + +import java.sql.*; +import java.math.BigDecimal; + +public class JDBCResultSet implements java.sql.ResultSet { + + /** + * Current row to be retrieved. + */ + private int row; + + /** + * Table returned by Database.get_table() + */ + protected SQLite.TableResult tr; + + /** + * Statement from which result set was produced. + */ + private JDBCStatement s; + + /** + * Meta data for result set or null. + */ + private JDBCResultSetMetaData md; + + /** + * Last result cell retrieved or null. + */ + private String lastg; + + /** + * Updatability of this result set. + */ + private int updatable; + + /** + * When updatable this is the table name. + */ + private String uptable; + + /** + * When updatable these are the PK column names of uptable. + */ + private String pkcols[]; + + /** + * When updatable these are the PK column indices (0-based) of uptable. + */ + private int pkcoli[]; + + /* + * Constants to reflect updateability. + */ + private final static int UPD_UNKNOWN = -1; + private final static int UPD_NO = 0; + private final static int UPD_INS = 1; + private final static int UPD_INSUPDDEL = 2; + + /** + * Flag for cursor being (not) on insert row. + */ + private boolean oninsrow; + + /** + * Row buffer for insert/update row. + */ + private String rowbuf[]; + + private static final boolean nullrepl = + SQLite.Database.version().compareTo("2.5.0") < 0; + + public JDBCResultSet(SQLite.TableResult tr, JDBCStatement s) { + this.tr = tr; + this.s = s; + this.md = null; + this.lastg = null; + this.row = -1; + this.updatable = UPD_UNKNOWN; + this.oninsrow = false; + this.rowbuf = null; + } + + public boolean isUpdatable() throws SQLException { + if (updatable == UPD_UNKNOWN) { + try { + JDBCResultSetMetaData m = + (JDBCResultSetMetaData) getMetaData(); + java.util.HashSet<String> h = new java.util.HashSet<String>(); + String lastt = null; + for (int i = 1; i <= tr.ncolumns; i++) { + lastt = m.getTableName(i); + h.add(lastt); + } + if (h.size() > 1 || lastt == null) { + updatable = UPD_NO; + throw new SQLException("view or join"); + } + updatable = UPD_INS; + uptable = lastt; + JDBCResultSet pk = (JDBCResultSet) + s.conn.getMetaData().getPrimaryKeys(null, null, uptable); + if (pk.tr.nrows > 0) { + boolean colnotfound = false; + pkcols = new String[pk.tr.nrows]; + pkcoli = new int[pk.tr.nrows]; + for (int i = 0; i < pk.tr.nrows; i++) { + String rd[] = (String []) pk.tr.rows.elementAt(i); + pkcols[i] = rd[3]; + try { + pkcoli[i] = findColumn(pkcols[i]) - 1; + } catch (SQLException ee) { + colnotfound = true; + } + } + if (!colnotfound) { + updatable = UPD_INSUPDDEL; + } + } + pk.close(); + } catch (SQLException e) { + updatable = UPD_NO; + } + } + if (updatable < UPD_INS) { + throw new SQLException("result set not updatable"); + } + return true; + } + + public void fillRowbuf() throws SQLException { + if (rowbuf == null) { + if (row < 0) { + throw new SQLException("cursor outside of result set"); + } + rowbuf = new String[tr.ncolumns]; + System.arraycopy((String []) tr.rows.elementAt(row), 0, + rowbuf, 0, tr.ncolumns); + } + } + + public boolean next() throws SQLException { + if (tr == null) { + return false; + } + row++; + return row < tr.nrows; + } + + public int findColumn(String columnName) throws SQLException { + JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData(); + return m.findColByName(columnName); + } + + public int getRow() throws SQLException { + if (tr == null) { + throw new SQLException("no rows"); + } + return row + 1; + } + + public boolean previous() throws SQLException { + if (tr == null) { + // BEGIN android-changed: throw rather than return false. + throw new SQLException("ResultSet already closed"); + // END android-changed + } + if (row >= 0) { + row--; + } + return row >= 0; + } + + public boolean absolute(int row) throws SQLException { + if (tr == null) { + return false; + } + if (row < 0) { + row = tr.nrows + 1 + row; + } + row--; + if (row < 0 || row > tr.nrows) { + return false; + } + this.row = row; + return true; + } + + public boolean relative(int row) throws SQLException { + if (tr == null) { + return false; + } + if (this.row + row < 0 || this.row + row >= tr.nrows) { + return false; + } + this.row += row; + return true; + } + + public void setFetchDirection(int dir) throws SQLException { + if (dir != ResultSet.FETCH_FORWARD) { + throw new SQLException("not supported"); + } + } + + public int getFetchDirection() throws SQLException { + return ResultSet.FETCH_FORWARD; + } + + public void setFetchSize(int fsize) throws SQLException { + if (fsize != 1) { + throw new SQLException("not supported"); + } + } + + public int getFetchSize() throws SQLException { + return 1; + } + + public String getString(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + return lastg; + } + + public String getString(String columnName) throws SQLException { + int col = findColumn(columnName); + return getString(col); + } + + public int getInt(int columnIndex) throws SQLException { + Integer i = internalGetInt(columnIndex); + if (i != null) { + return i.intValue(); + } + return 0; + } + + private Integer internalGetInt(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + return Integer.valueOf(lastg); + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public int getInt(String columnName) throws SQLException { + int col = findColumn(columnName); + return getInt(col); + } + + public boolean getBoolean(int columnIndex) throws SQLException { + return getInt(columnIndex) == 1 || + Boolean.parseBoolean(getString(columnIndex)); // android-changed: performance + } + + public boolean getBoolean(String columnName) throws SQLException { + int col = findColumn(columnName); + return getBoolean(col); + } + + public ResultSetMetaData getMetaData() throws SQLException { + if (md == null) { + md = new JDBCResultSetMetaData(this); + } + return md; + } + + public short getShort(int columnIndex) throws SQLException { + Short sh = internalGetShort(columnIndex); + if (sh != null) { + return sh.shortValue(); + } + return 0; + } + + private Short internalGetShort(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + return Short.valueOf(lastg); + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public short getShort(String columnName) throws SQLException { + int col = findColumn(columnName); + return getShort(col); + } + + public java.sql.Time getTime(int columnIndex) throws SQLException { + return internalGetTime(columnIndex, null); + } + + private java.sql.Time internalGetTime(int columnIndex, + java.util.Calendar cal) + throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + if (s.conn.useJulian) { + try { + return new java.sql.Time(SQLite.Database.long_from_julian(lastg)); + } catch (java.lang.Exception ee) { + return java.sql.Time.valueOf(lastg); + } + } else { + try { + return java.sql.Time.valueOf(lastg); + } catch (java.lang.Exception ee) { + return new java.sql.Time(SQLite.Database.long_from_julian(lastg)); + } + } + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public java.sql.Time getTime(String columnName) throws SQLException { + int col = findColumn(columnName); + return getTime(col); + } + + public java.sql.Time getTime(int columnIndex, java.util.Calendar cal) + throws SQLException { + return internalGetTime(columnIndex, cal); + } + + public java.sql.Time getTime(String columnName, java.util.Calendar cal) + throws SQLException{ + int col = findColumn(columnName); + return getTime(col, cal); + } + + public java.sql.Timestamp getTimestamp(int columnIndex) + throws SQLException{ + return internalGetTimestamp(columnIndex, null); + } + + private java.sql.Timestamp internalGetTimestamp(int columnIndex, + java.util.Calendar cal) + throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + if (s.conn.useJulian) { + try { + return new java.sql.Timestamp(SQLite.Database.long_from_julian(lastg)); + } catch (java.lang.Exception ee) { + return java.sql.Timestamp.valueOf(lastg); + } + } else { + try { + return java.sql.Timestamp.valueOf(lastg); + } catch (java.lang.Exception ee) { + return new java.sql.Timestamp(SQLite.Database.long_from_julian(lastg)); + } + } + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public java.sql.Timestamp getTimestamp(String columnName) + throws SQLException{ + int col = findColumn(columnName); + return getTimestamp(col); + } + + public java.sql.Timestamp getTimestamp(int columnIndex, + java.util.Calendar cal) + throws SQLException { + return internalGetTimestamp(columnIndex, cal); + } + + public java.sql.Timestamp getTimestamp(String columnName, + java.util.Calendar cal) + throws SQLException { + int col = findColumn(columnName); + return getTimestamp(col, cal); + } + + public java.sql.Date getDate(int columnIndex) throws SQLException { + return internalGetDate(columnIndex, null); + } + + private java.sql.Date internalGetDate(int columnIndex, + java.util.Calendar cal) + throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + if (s.conn.useJulian) { + try { + return new java.sql.Date(SQLite.Database.long_from_julian(lastg)); + } catch (java.lang.Exception ee) { + return java.sql.Date.valueOf(lastg); + } + } else { + try { + return java.sql.Date.valueOf(lastg); + } catch (java.lang.Exception ee) { + return new java.sql.Date(SQLite.Database.long_from_julian(lastg)); + } + } + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public java.sql.Date getDate(String columnName) throws SQLException { + int col = findColumn(columnName); + return getDate(col); + } + + public java.sql.Date getDate(int columnIndex, java.util.Calendar cal) + throws SQLException{ + return internalGetDate(columnIndex, cal); + } + + public java.sql.Date getDate(String columnName, java.util.Calendar cal) + throws SQLException{ + int col = findColumn(columnName); + return getDate(col, cal); + } + + public double getDouble(int columnIndex) throws SQLException { + Double d = internalGetDouble(columnIndex); + if (d != null) { + return d.doubleValue(); + } + return 0; + } + + private Double internalGetDouble(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + return Double.valueOf(lastg); + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public double getDouble(String columnName) throws SQLException { + int col = findColumn(columnName); + return getDouble(col); + } + + public float getFloat(int columnIndex) throws SQLException { + Float f = internalGetFloat(columnIndex); + if (f != null) { + return f.floatValue(); + } + return 0; + } + + private Float internalGetFloat(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + return Float.valueOf(lastg); + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public float getFloat(String columnName) throws SQLException { + int col = findColumn(columnName); + return getFloat(col); + } + + public long getLong(int columnIndex) throws SQLException { + Long l = internalGetLong(columnIndex); + if (l != null) { + return l.longValue(); + } + return 0; + } + + private Long internalGetLong(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + try { + return Long.valueOf(lastg); + } catch (java.lang.Exception e) { + lastg = null; + } + return null; + } + + public long getLong(String columnName) throws SQLException { + int col = findColumn(columnName); + return getLong(col); + } + + @Deprecated + public java.io.InputStream getUnicodeStream(int columnIndex) + throws SQLException { + throw new SQLException("not supported"); + } + + @Deprecated + public java.io.InputStream getUnicodeStream(String columnName) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.io.InputStream getAsciiStream(String columnName) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.io.InputStream getAsciiStream(int columnIndex) + throws SQLException { + throw new SQLException("not supported"); + } + + public BigDecimal getBigDecimal(String columnName) + throws SQLException { + throw new SQLException("not supported"); + } + + @Deprecated + public BigDecimal getBigDecimal(String columnName, int scale) + throws SQLException { + throw new SQLException("not supported"); + } + + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + @Deprecated + public BigDecimal getBigDecimal(int columnIndex, int scale) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.io.InputStream getBinaryStream(int columnIndex) + throws SQLException { + byte data[] = getBytes(columnIndex); + if (data != null) { + return new java.io.ByteArrayInputStream(data); + } + return null; + } + + public java.io.InputStream getBinaryStream(String columnName) + throws SQLException { + byte data[] = getBytes(columnName); + if (data != null) { + return new java.io.ByteArrayInputStream(data); + } + return null; + } + + public byte getByte(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public byte getByte(String columnName) throws SQLException { + throw new SQLException("not supported"); + } + + public byte[] getBytes(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + byte ret[] = null; + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + if (lastg != null) { + ret = SQLite.StringEncoder.decode(lastg); + } + return ret; + } + + public byte[] getBytes(String columnName) throws SQLException { + int col = findColumn(columnName); + return getBytes(col); + } + + public String getCursorName() throws SQLException { + return null; + } + + public Object getObject(int columnIndex) throws SQLException { + if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) { + throw new SQLException("column " + columnIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[columnIndex - 1]; + Object ret = lastg; + if (tr instanceof TableResultX) { + switch (((TableResultX) tr).sql_type[columnIndex - 1]) { + case Types.SMALLINT: + ret = internalGetShort(columnIndex); + break; + case Types.INTEGER: + ret = internalGetInt(columnIndex); + break; + case Types.DOUBLE: + ret = internalGetDouble(columnIndex); + break; + case Types.FLOAT: + ret = internalGetFloat(columnIndex); + break; + case Types.BIGINT: + ret = internalGetLong(columnIndex); + break; + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + ret = getBytes(columnIndex); + break; + case Types.NULL: + ret = null; + break; + /* defaults to String below */ + } + } + return ret; + } + + public Object getObject(String columnName) throws SQLException { + int col = findColumn(columnName); + return getObject(col); + } + + public Object getObject(int columnIndex, java.util.Map map) + throws SQLException { + throw new SQLException("not supported"); + } + + public Object getObject(String columnIndex, java.util.Map map) + throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Ref getRef(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Ref getRef(String columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Blob getBlob(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Blob getBlob(String columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Clob getClob(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Clob getClob(String columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Array getArray(int columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.sql.Array getArray(String columnIndex) throws SQLException { + throw new SQLException("not supported"); + } + + public java.io.Reader getCharacterStream(int columnIndex) + throws SQLException { + String data = getString(columnIndex); + if (data != null) { + char[] cdata = data.toCharArray(); + return new java.io.CharArrayReader(cdata); + } + return null; + } + + public java.io.Reader getCharacterStream(String columnName) + throws SQLException { + String data = getString(columnName); + if (data != null) { + char[] cdata = data.toCharArray(); + return new java.io.CharArrayReader(cdata); + } + return null; + } + + public SQLWarning getWarnings() throws SQLException { + throw new SQLException("not supported"); + } + + public boolean wasNull() throws SQLException { + return lastg == null; + } + + public void clearWarnings() throws SQLException { + throw new SQLException("not supported"); + } + + public boolean isFirst() throws SQLException { + if (tr == null) { + return true; + } + return row == 0; + } + + public boolean isBeforeFirst() throws SQLException { + if (tr == null || tr.nrows <= 0) { + return false; + } + return row < 0; + } + + public void beforeFirst() throws SQLException { + if (tr == null) { + return; + } + row = -1; + } + + public boolean first() throws SQLException { + if (tr == null || tr.nrows <= 0) { + return false; + } + row = 0; + return true; + } + + public boolean isAfterLast() throws SQLException { + if (tr == null || tr.nrows <= 0) { + return false; + } + return row >= tr.nrows; + } + + public void afterLast() throws SQLException { + if (tr == null) { + return; + } + row = tr.nrows; + } + + public boolean isLast() throws SQLException { + if (tr == null) { + return true; + } + return row == tr.nrows - 1; + } + + public boolean last() throws SQLException { + if (tr == null || tr.nrows <= 0) { + return false; + } + row = tr.nrows -1; + return true; + } + + public int getType() throws SQLException { + return TYPE_SCROLL_SENSITIVE; + } + + public int getConcurrency() throws SQLException { + return CONCUR_UPDATABLE; + } + + public boolean rowUpdated() throws SQLException { + return false; + } + + public boolean rowInserted() throws SQLException { + return false; + } + + public boolean rowDeleted() throws SQLException { + return false; + } + + public void insertRow() throws SQLException { + isUpdatable(); + if (!oninsrow || rowbuf == null) { + throw new SQLException("no insert data provided"); + } + JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData(); + StringBuffer sb = new StringBuffer(); + sb.append("INSERT INTO "); + sb.append(SQLite.Shell.sql_quote_dbl(uptable)); + sb.append("("); + for (int i = 0; i < tr.ncolumns; i++) { + sb.append(SQLite.Shell.sql_quote_dbl(m.getColumnName(i + 1))); + if (i < tr.ncolumns - 1) { + sb.append(","); + } + } + sb.append(") VALUES("); + for (int i = 0; i < tr.ncolumns; i++) { + sb.append(nullrepl ? "'%q'" : "%Q"); + if (i < tr.ncolumns - 1) { + sb.append(","); + } + } + sb.append(")"); + try { + this.s.conn.db.exec(sb.toString(), null, rowbuf); + } catch (SQLite.Exception e) { + throw new SQLException(e.getMessage()); + } + tr.newrow(rowbuf); + rowbuf = null; + oninsrow = false; + last(); + } + + public void updateRow() throws SQLException { + isUpdatable(); + if (rowbuf == null) { + throw new SQLException("no update data provided"); + } + if (oninsrow) { + throw new SQLException("cursor on insert row"); + } + if (updatable < UPD_INSUPDDEL) { + throw new SQLException("no primary key on table defined"); + } + String rd[] = (String []) tr.rows.elementAt(row); + JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData(); + String args[] = new String[tr.ncolumns + pkcols.length]; + StringBuffer sb = new StringBuffer(); + sb.append("UPDATE "); + sb.append(SQLite.Shell.sql_quote_dbl(uptable)); + sb.append(" SET "); + int i; + for (i = 0; i < tr.ncolumns; i++) { + sb.append(SQLite.Shell.sql_quote_dbl(m.getColumnName(i + 1))); + sb.append(" = " + (nullrepl ? "'%q'" : "%Q")); + if (i < tr.ncolumns - 1) { + sb.append(","); + } + args[i] = rowbuf[i]; + } + sb. append(" WHERE "); + for (int k = 0; k < pkcols.length; k++, i++) { + sb.append(SQLite.Shell.sql_quote_dbl(pkcols[k])); + sb.append(" = " + (nullrepl ? "'%q'" : "%Q")); + if (k < pkcols.length - 1) { + sb.append(" AND "); + } + args[i] = rd[pkcoli[k]]; + } + try { + this.s.conn.db.exec(sb.toString(), null, args); + } catch (SQLite.Exception e) { + throw new SQLException(e.getMessage()); + } + System.arraycopy(rowbuf, 0, rd, 0, rowbuf.length); + rowbuf = null; + } + + public void deleteRow() throws SQLException { + isUpdatable(); + if (oninsrow) { + throw new SQLException("cursor on insert row"); + } + if (updatable < UPD_INSUPDDEL) { + throw new SQLException("no primary key on table defined"); + } + fillRowbuf(); + StringBuffer sb = new StringBuffer(); + sb.append("DELETE FROM "); + sb.append(SQLite.Shell.sql_quote_dbl(uptable)); + sb.append(" WHERE "); + String args[] = new String[pkcols.length]; + for (int i = 0; i < pkcols.length; i++) { + sb.append(SQLite.Shell.sql_quote_dbl(pkcols[i])); + sb.append(" = " + (nullrepl ? "'%q'" : "%Q")); + if (i < pkcols.length - 1) { + sb.append(" AND "); + } + args[i] = rowbuf[pkcoli[i]]; + } + try { + this.s.conn.db.exec(sb.toString(), null, args); + } catch (SQLite.Exception e) { + throw new SQLException(e.getMessage()); + } + rowbuf = null; + } + + public void refreshRow() throws SQLException { + isUpdatable(); + if (oninsrow) { + throw new SQLException("cursor on insert row"); + } + if (updatable < UPD_INSUPDDEL) { + throw new SQLException("no primary key on table defined"); + } + JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData(); + String rd[] = (String []) tr.rows.elementAt(row); + StringBuffer sb = new StringBuffer(); + sb.append("SELECT "); + for (int i = 0; i < tr.ncolumns; i++) { + sb.append(SQLite.Shell.sql_quote_dbl(m.getColumnName(i + 1))); + if (i < tr.ncolumns - 1) { + sb.append(","); + } + } + sb.append(" FROM "); + sb.append(SQLite.Shell.sql_quote_dbl(uptable)); + sb.append(" WHERE "); + String args[] = new String[pkcols.length]; + for (int i = 0; i < pkcols.length; i++) { + sb.append(SQLite.Shell.sql_quote_dbl(pkcols[i])); + sb.append(" = " + (nullrepl ? "'%q'" : "%Q")); + if (i < pkcols.length - 1) { + sb.append(" AND "); + } + args[i] = rd[pkcoli[i]]; + } + SQLite.TableResult trnew = null; + try { + trnew = this.s.conn.db.get_table(sb.toString(), args); + } catch (SQLite.Exception e) { + throw new SQLException(e.getMessage()); + } + if (trnew.nrows != 1) { + throw new SQLException("wrong size of result set"); + } + rowbuf = null; + tr.rows.setElementAt(trnew.rows.elementAt(0), row); + } + + public void cancelRowUpdates() throws SQLException { + rowbuf = null; + } + + public void moveToInsertRow() throws SQLException { + isUpdatable(); + if (!oninsrow) { + oninsrow = true; + rowbuf = new String[tr.nrows]; + } + } + + public void moveToCurrentRow() throws SQLException { + if (oninsrow) { + oninsrow = false; + rowbuf = null; + } + } + + public void updateNull(int colIndex) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = null; + } + + public void updateBoolean(int colIndex, boolean b) throws SQLException { + updateString(colIndex, b ? "1" : "0"); + } + + public void updateByte(int colIndex, byte b) throws SQLException { + throw new SQLException("not supported"); + } + + public void updateShort(int colIndex, short b) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = Short.toString(b); + } + + public void updateInt(int colIndex, int b) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = Integer.toString(b); + } + + public void updateLong(int colIndex, long b) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = Long.toString(b); + } + + public void updateFloat(int colIndex, float f) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = Float.toString(f); + } + + public void updateDouble(int colIndex, double f) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = Double.toString(f); + } + + public void updateBigDecimal(int colIndex, BigDecimal f) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateString(int colIndex, String s) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = s; + } + + public void updateBytes(int colIndex, byte[] s) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + if (this.s.conn.db.is3()) { + rowbuf[colIndex - 1] = SQLite.StringEncoder.encodeX(s); + } else { + rowbuf[colIndex - 1] = SQLite.StringEncoder.encode(s); + } + } + + public void updateDate(int colIndex, java.sql.Date d) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = d.toString(); + } + + public void updateTime(int colIndex, java.sql.Time t) throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = t.toString(); + } + + public void updateTimestamp(int colIndex, java.sql.Timestamp t) + throws SQLException { + isUpdatable(); + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + fillRowbuf(); + rowbuf[colIndex - 1] = t.toString(); + } + + public void updateAsciiStream(int colIndex, java.io.InputStream in, int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateBinaryStream(int colIndex, java.io.InputStream in, int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateCharacterStream(int colIndex, java.io.Reader in, int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateObject(int colIndex, Object obj) throws SQLException { + updateString(colIndex, obj.toString()); + } + + public void updateObject(int colIndex, Object obj, int s) + throws SQLException { + updateString(colIndex, obj.toString()); + } + + public void updateNull(String colName) throws SQLException { + int col = findColumn(colName); + updateNull(col); + } + + public void updateBoolean(String colName, boolean b) throws SQLException { + int col = findColumn(colName); + updateBoolean(col, b); + } + + public void updateByte(String colName, byte b) throws SQLException { + throw new SQLException("not supported"); + } + + public void updateShort(String colName, short b) throws SQLException { + int col = findColumn(colName); + updateShort(col, b); + } + + public void updateInt(String colName, int b) throws SQLException { + int col = findColumn(colName); + updateInt(col, b); + } + + public void updateLong(String colName, long b) throws SQLException { + int col = findColumn(colName); + updateLong(col, b); + } + + public void updateFloat(String colName, float f) throws SQLException { + int col = findColumn(colName); + updateFloat(col, f); + } + + public void updateDouble(String colName, double f) throws SQLException { + int col = findColumn(colName); + updateDouble(col, f); + } + + public void updateBigDecimal(String colName, BigDecimal f) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateString(String colName, String s) throws SQLException { + int col = findColumn(colName); + updateString(col, s); + } + + public void updateBytes(String colName, byte[] s) throws SQLException { + int col = findColumn(colName); + updateBytes(col, s); + } + + public void updateDate(String colName, java.sql.Date d) + throws SQLException { + int col = findColumn(colName); + updateDate(col, d); + } + + public void updateTime(String colName, java.sql.Time t) + throws SQLException { + int col = findColumn(colName); + updateTime(col, t); + } + + public void updateTimestamp(String colName, java.sql.Timestamp t) + throws SQLException { + int col = findColumn(colName); + updateTimestamp(col, t); + } + + public void updateAsciiStream(String colName, java.io.InputStream in, + int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateBinaryStream(String colName, java.io.InputStream in, + int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateCharacterStream(String colName, java.io.Reader in, + int s) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateObject(String colName, Object obj) + throws SQLException { + int col = findColumn(colName); + updateObject(col, obj); + } + + public void updateObject(String colName, Object obj, int s) + throws SQLException { + int col = findColumn(colName); + updateObject(col, obj, s); + } + + public Statement getStatement() throws SQLException { + if (s == null) { + throw new SQLException("stale result set"); + } + return s; + } + + public void close() throws SQLException { + s = null; + tr = null; + lastg = null; + oninsrow = false; + rowbuf = null; + row = -1; + } + + public java.net.URL getURL(int colIndex) throws SQLException { + if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) { + throw new SQLException("column " + colIndex + " not found"); + } + String rd[] = (String []) tr.rows.elementAt(row); + lastg = rd[colIndex - 1]; + java.net.URL url = null; + if (lastg == null) { + return url; + } + try { + url = new java.net.URL(lastg); + } catch (java.lang.Exception e) { + url = null; + } + return url; + } + + public java.net.URL getURL(String colName) throws SQLException { + int col = findColumn(colName); + return getURL(col); + } + + public void updateRef(int colIndex, java.sql.Ref x) throws SQLException { + throw new SQLException("not supported"); + } + + public void updateRef(String colName, java.sql.Ref x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateBlob(int colIndex, java.sql.Blob x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateBlob(String colName, java.sql.Blob x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateClob(int colIndex, java.sql.Clob x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateClob(String colName, java.sql.Clob x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateArray(int colIndex, java.sql.Array x) + throws SQLException { + throw new SQLException("not supported"); + } + + public void updateArray(String colName, java.sql.Array x) + throws SQLException { + throw new SQLException("not supported"); + } + +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java new file mode 100644 index 0000000..40be126 --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCResultSetMetaData.java @@ -0,0 +1,214 @@ +package SQLite.JDBC2y; + +import java.sql.*; + +public class JDBCResultSetMetaData implements java.sql.ResultSetMetaData { + + private JDBCResultSet r; + + public JDBCResultSetMetaData(JDBCResultSet r) { + this.r = r; + } + + public String getCatalogName(int column) throws java.sql.SQLException { + return null; + } + + public String getColumnClassName(int column) throws java.sql.SQLException { + column--; + if (r != null && r.tr != null) { + if (column < 0 || column >= r.tr.ncolumns) { + return null; + } + if (r.tr instanceof TableResultX) { + switch (((TableResultX) r.tr).sql_type[column]) { + case Types.SMALLINT: return "java.lang.Short"; + case Types.INTEGER: return "java.lang.Integer"; + case Types.REAL: + case Types.DOUBLE: return "java.lang.Double"; + case Types.FLOAT: return "java.lang.Float"; + case Types.BIGINT: return "java.lang.Long"; + case Types.DATE: return "java.sql.Date"; + case Types.TIME: return "java.sql.Time"; + case Types.TIMESTAMP: return "java.sql.Timestamp"; + case Types.BINARY: + case Types.VARBINARY: return "[B"; + /* defaults to varchar below */ + } + } + return "java.lang.String"; + } + return null; + } + + public int getColumnCount() throws java.sql.SQLException { + if (r != null && r.tr != null) { + return r.tr.ncolumns; + } + return 0; + } + + public int getColumnDisplaySize(int column) throws java.sql.SQLException { + return 0; + } + + public String getColumnLabel(int column) throws java.sql.SQLException { + column--; + String c = null; + if (r != null && r.tr != null) { + if (column < 0 || column >= r.tr.ncolumns) { + return c; + } + c = r.tr.column[column]; + } + return c; + } + + public String getColumnName(int column) throws java.sql.SQLException { + column--; + String c = null; + if (r != null && r.tr != null) { + if (column < 0 || column >= r.tr.ncolumns) { + return c; + } + c = r.tr.column[column]; + if (c != null) { + int i = c.indexOf('.'); + if (i > 0) { + return c.substring(i + 1); + } + } + } + return c; + } + + public int getColumnType(int column) throws java.sql.SQLException { + column--; + if (r != null && r.tr != null) { + if (column >= 0 && column < r.tr.ncolumns) { + if (r.tr instanceof TableResultX) { + return ((TableResultX) r.tr).sql_type[column]; + } + return Types.VARCHAR; + } + } + throw new SQLException("bad column index"); + } + + public String getColumnTypeName(int column) throws java.sql.SQLException { + column--; + if (r != null && r.tr != null) { + if (column >= 0 && column < r.tr.ncolumns) { + if (r.tr instanceof TableResultX) { + switch (((TableResultX) r.tr).sql_type[column]) { + case Types.SMALLINT: return "smallint"; + case Types.INTEGER: return "integer"; + case Types.DOUBLE: return "double"; + case Types.FLOAT: return "float"; + case Types.BIGINT: return "bigint"; + case Types.DATE: return "date"; + case Types.TIME: return "time"; + case Types.TIMESTAMP: return "timestamp"; + case Types.BINARY: return "binary"; + case Types.VARBINARY: return "varbinary"; + case Types.REAL: return "real"; + /* defaults to varchar below */ + } + } + return "varchar"; + } + } + throw new SQLException("bad column index"); + } + + public int getPrecision(int column) throws java.sql.SQLException { + return 0; + } + + public int getScale(int column) throws java.sql.SQLException { + return 0; + } + + public String getSchemaName(int column) throws java.sql.SQLException { + return null; + } + + public String getTableName(int column) throws java.sql.SQLException { + column--; + String c = null; + if (r != null && r.tr != null) { + if (column < 0 || column >= r.tr.ncolumns) { + return c; + } + c = r.tr.column[column]; + if (c != null) { + int i = c.indexOf('.'); + if (i > 0) { + return c.substring(0, i); + } + c = null; + } + } + return c; + } + + public boolean isAutoIncrement(int column) throws java.sql.SQLException { + return false; + } + + public boolean isCaseSensitive(int column) throws java.sql.SQLException { + return false; + } + + public boolean isCurrency(int column) throws java.sql.SQLException { + return false; + } + + public boolean isDefinitelyWritable(int column) + throws java.sql.SQLException { + return true; + } + + public int isNullable(int column) throws java.sql.SQLException { + return columnNullableUnknown; + } + + public boolean isReadOnly(int column) throws java.sql.SQLException { + return false; + } + + public boolean isSearchable(int column) throws java.sql.SQLException { + return true; + } + + public boolean isSigned(int column) throws java.sql.SQLException { + return false; + } + + public boolean isWritable(int column) throws java.sql.SQLException { + return true; + } + + int findColByName(String columnName) throws java.sql.SQLException { + String c = null; + if (r != null && r.tr != null) { + for (int i = 0; i < r.tr.ncolumns; i++) { + c = r.tr.column[i]; + if (c != null) { + if (c.compareToIgnoreCase(columnName) == 0) { + return i + 1; + } + int k = c.indexOf('.'); + if (k > 0) { + c = c.substring(k + 1); + if (c.compareToIgnoreCase(columnName) == 0) { + return i + 1; + } + } + } + c = null; + } + } + throw new SQLException("column " + columnName + " not found"); + } +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCStatement.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCStatement.java new file mode 100644 index 0000000..0b5b26f --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/JDBCStatement.java @@ -0,0 +1,293 @@ +package SQLite.JDBC2y; + +import java.sql.*; +import java.util.*; + +public class JDBCStatement implements java.sql.Statement { + + protected JDBCConnection conn; + protected JDBCResultSet rs; + protected int updcnt; + protected int maxrows = 0; + private ArrayList<String> batch; + + public JDBCStatement(JDBCConnection conn) { + this.conn = conn; + this.updcnt = 0; + this.rs = null; + this.batch = null; + } + + public void setFetchSize(int fetchSize) throws SQLException { + throw new SQLException("not supported"); + } + + public int getFetchSize() throws SQLException { + return 1; + } + + public int getMaxRows() throws SQLException { + return maxrows; + } + + public void setMaxRows(int max) throws SQLException { + // BEGIN android-added: missing error checking. + if (max < 0) { + throw new SQLException("max must be >= 0 (was " + max + ")"); + } + // END android-added + maxrows = max; + } + + public void setFetchDirection(int fetchDirection) throws SQLException { + throw new SQLException("not supported"); + } + + public int getFetchDirection() throws SQLException { + return ResultSet.FETCH_UNKNOWN; + } + + public int getResultSetConcurrency() throws SQLException { + return ResultSet.CONCUR_READ_ONLY; + } + + public int getResultSetType() throws SQLException { + return ResultSet.TYPE_SCROLL_INSENSITIVE; + } + + public void setQueryTimeout(int seconds) throws SQLException { + conn.timeout = seconds * 1000; + if (conn.timeout < 0) { + conn.timeout = 120000; + } else if (conn.timeout < 1000) { + conn.timeout = 5000; + } + } + + public int getQueryTimeout() throws SQLException { + return conn.timeout; + } + + public ResultSet getResultSet() throws SQLException { + return rs; + } + + ResultSet executeQuery(String sql, String args[], boolean updonly) + throws SQLException { + SQLite.TableResult tr = null; + if (rs != null) { + rs.close(); + rs = null; + } + updcnt = -1; + if (conn == null || conn.db == null) { + throw new SQLException("stale connection"); + } + int busy = 0; + boolean starttrans = !conn.autocommit && !conn.intrans; + while (true) { + try { + if (starttrans) { + conn.db.exec("BEGIN TRANSACTION", null); + conn.intrans = true; + } + if (args == null) { + if (updonly) { + conn.db.exec(sql, null); + } else { + tr = conn.db.get_table(sql, maxrows); + } + } else { + if (updonly) { + conn.db.exec(sql, null, args); + } else { + tr = conn.db.get_table(sql, maxrows, args); + } + } + updcnt = (int) conn.db.changes(); + } catch (SQLite.Exception e) { + if (conn.db.is3() && + conn.db.last_error() == SQLite.Constants.SQLITE_BUSY && + conn.busy3(conn.db, ++busy)) { + try { + if (starttrans && conn.intrans) { + conn.db.exec("ROLLBACK", null); + conn.intrans = false; + } + } catch (SQLite.Exception ee) { + } + try { + int ms = 20 + busy * 10; + if (ms > 1000) { + ms = 1000; + } + synchronized (this) { + this.wait(ms); + } + } catch (java.lang.Exception eee) { + } + continue; + } + throw new SQLException(e.toString()); + } + break; + } + if (!updonly && tr == null) { + throw new SQLException("no result set produced"); + } + if (!updonly && tr != null) { + rs = new JDBCResultSet(new TableResultX(tr), this); + } + return rs; + } + + public ResultSet executeQuery(String sql) throws SQLException { + return executeQuery(sql, null, false); + } + + public boolean execute(String sql) throws SQLException { + return executeQuery(sql) != null; + } + + public void cancel() throws SQLException { + if (conn == null || conn.db == null) { + throw new SQLException("stale connection"); + } + conn.db.interrupt(); + } + + public void clearWarnings() throws SQLException { + } + + public Connection getConnection() throws SQLException { + return conn; + } + + public void addBatch(String sql) throws SQLException { + if (batch == null) { + batch = new ArrayList<String>(1); + } + batch.add(sql); + } + + public int[] executeBatch() throws SQLException { + if (batch == null) { + return new int[0]; + } + int[] ret = new int[batch.size()]; + for (int i = 0; i < ret.length; i++) { + ret[i] = EXECUTE_FAILED; + } + int errs = 0; + for (int i = 0; i < ret.length; i++) { + try { + execute((String) batch.get(i)); + ret[i] = updcnt; + } catch (SQLException e) { + ++errs; + } + } + if (errs > 0) { + throw new BatchUpdateException("batch failed", ret); + } + return ret; + } + + public void clearBatch() throws SQLException { + if (batch != null) { + batch.clear(); + batch = null; + } + } + + public void close() throws SQLException { + clearBatch(); + conn = null; + } + + public int executeUpdate(String sql) throws SQLException { + executeQuery(sql, null, true); + return updcnt; + } + + public int getMaxFieldSize() throws SQLException { + return 0; + } + + public boolean getMoreResults() throws SQLException { + if (rs != null) { + rs.close(); + rs = null; + } + return false; + } + + public int getUpdateCount() throws SQLException { + return updcnt; + } + + public SQLWarning getWarnings() throws SQLException { + return null; + } + + public void setCursorName(String name) throws SQLException { + throw new SQLException("not supported"); + } + + public void setEscapeProcessing(boolean enable) throws SQLException { + throw new SQLException("not supported"); + } + + public void setMaxFieldSize(int max) throws SQLException { + throw new SQLException("not supported"); + } + + public boolean getMoreResults(int x) throws SQLException { + throw new SQLException("not supported"); + } + + public ResultSet getGeneratedKeys() throws SQLException { + throw new SQLException("not supported"); + } + + public int executeUpdate(String sql, int autokeys) + throws SQLException { + if (autokeys != Statement.NO_GENERATED_KEYS) { + throw new SQLException("not supported"); + } + return executeUpdate(sql); + } + + public int executeUpdate(String sql, int colIndexes[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public int executeUpdate(String sql, String colIndexes[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public boolean execute(String sql, int autokeys) + throws SQLException { + if (autokeys != Statement.NO_GENERATED_KEYS) { + throw new SQLException("not supported"); + } + return execute(sql); + } + + public boolean execute(String sql, int colIndexes[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public boolean execute(String sql, String colIndexes[]) + throws SQLException { + throw new SQLException("not supported"); + } + + public int getResultSetHoldability() throws SQLException { + return ResultSet.HOLD_CURSORS_OVER_COMMIT; + } + +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBC2y/TableResultX.java b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/TableResultX.java new file mode 100644 index 0000000..1414fc0 --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBC2y/TableResultX.java @@ -0,0 +1,46 @@ +package SQLite.JDBC2y; + +import java.sql.Types; +import java.util.Vector; + +public class TableResultX extends SQLite.TableResult { + public int sql_type[]; + + public TableResultX() { + super(); + sql_type = new int[this.ncolumns]; + for (int i = 0; i < this.ncolumns; i++) { + sql_type[i] = Types.VARCHAR; + } + } + + public TableResultX(int maxrows) { + super(maxrows); + sql_type = new int[this.ncolumns]; + for (int i = 0; i < this.ncolumns; i++) { + sql_type[i] = Types.VARCHAR; + } + } + + public TableResultX(SQLite.TableResult tr) { + this.column = tr.column; + this.rows = tr.rows; + this.ncolumns = tr.ncolumns; + this.nrows = tr.nrows; + this.types = tr.types; + this.maxrows = tr.maxrows; + sql_type = new int[tr.ncolumns]; + for (int i = 0; i < this.ncolumns; i++) { + sql_type[i] = Types.VARCHAR; + } + if (tr.types != null) { + for (int i = 0; i < tr.types.length; i++) { + sql_type[i] = JDBCDatabaseMetaData.mapSqlType(tr.types[i]); + } + } + } + + void sql_types(int types[]) { + sql_type = types; + } +} diff --git a/sqlite-jdbc/src/main/java/SQLite/JDBCDriver.java b/sqlite-jdbc/src/main/java/SQLite/JDBCDriver.java new file mode 100644 index 0000000..c90035d --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/JDBCDriver.java @@ -0,0 +1,144 @@ +package SQLite; + +import java.sql.*; +import java.util.Properties; + +public class JDBCDriver implements java.sql.Driver { + + public static final int MAJORVERSION = 1; + + public static boolean sharedCache = false; + + public static String vfs = null; + + private static java.lang.reflect.Constructor makeConn = null; + + protected Connection conn; + + static { + try { + Class connClass = null; + Class args[] = new Class[5]; + args[0] = Class.forName("java.lang.String"); + args[1] = args[0]; + args[2] = args[0]; + args[3] = args[0]; + args[4] = args[0]; + String jvers = java.lang.System.getProperty("java.version"); + String cvers; + if (jvers == null || jvers.startsWith("1.0")) { + throw new java.lang.Exception("unsupported java version"); + } else if (jvers.startsWith("1.1")) { + cvers = "SQLite.JDBC1.JDBCConnection"; + } else if (jvers.startsWith("1.2") || jvers.startsWith("1.3")) { + cvers = "SQLite.JDBC2.JDBCConnection"; + } else if (jvers.startsWith("1.4")) { + cvers = "SQLite.JDBC2x.JDBCConnection"; + } else if (jvers.startsWith("1.5")) { + cvers = "SQLite.JDBC2y.JDBCConnection"; + try { + Class.forName(cvers); + } catch (java.lang.Exception e) { + cvers = "SQLite.JDBC2x.JDBCConnection"; + } + } else { + cvers = "SQLite.JDBC2z.JDBCConnection"; + try { + Class.forName(cvers); + } catch (java.lang.Exception e) { + cvers = "SQLite.JDBC2y.JDBCConnection"; + try { + Class.forName(cvers); + } catch (java.lang.Exception ee) { + cvers = "SQLite.JDBC2x.JDBCConnection"; + } + } + } + connClass = Class.forName(cvers); + makeConn = connClass.getConstructor(args); + java.sql.DriverManager.registerDriver(new JDBCDriver()); + try { + String shcache = + java.lang.System.getProperty("SQLite.sharedcache"); + if (shcache != null && + (shcache.startsWith("y") || shcache.startsWith("Y"))) { + sharedCache = SQLite.Database._enable_shared_cache(true); + } + } catch (java.lang.Exception e) { + } + try { + String tvfs = + java.lang.System.getProperty("SQLite.vfs"); + if (tvfs != null) { + vfs = tvfs; + } + } catch (java.lang.Exception e) { + } + } catch (java.lang.Exception e) { + System.err.println(e); + } + } + + public JDBCDriver() { + } + + public boolean acceptsURL(String url) throws SQLException { + return url.startsWith("sqlite:/") || + url.startsWith("jdbc:sqlite:/"); + } + + public Connection connect(String url, Properties info) + throws SQLException { + if (!acceptsURL(url)) { + return null; + } + Object args[] = new Object[5]; + args[0] = url; + if (info != null) { + args[1] = info.getProperty("encoding"); + args[2] = info.getProperty("password"); + args[3] = info.getProperty("daterepr"); + args[4] = info.getProperty("vfs"); + } + if (args[1] == null) { + args[1] = java.lang.System.getProperty("SQLite.encoding"); + } + if (args[4] == null) { + args[4] = vfs; + } + try { + conn = (Connection) makeConn.newInstance(args); + } catch (java.lang.reflect.InvocationTargetException ie) { + throw new SQLException(ie.getTargetException().toString()); + } catch (java.lang.Exception e) { + throw new SQLException(e.toString()); + } + return conn; + } + + public int getMajorVersion() { + return MAJORVERSION; + } + + public int getMinorVersion() { + return Constants.drv_minor; + } + + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) + throws SQLException { + DriverPropertyInfo p[] = new DriverPropertyInfo[4]; + DriverPropertyInfo pp = new DriverPropertyInfo("encoding", ""); + p[0] = pp; + pp = new DriverPropertyInfo("password", ""); + p[1] = pp; + pp = new DriverPropertyInfo("daterepr", "normal"); + p[2] = pp; + pp = new DriverPropertyInfo("vfs", vfs); + p[3] = pp; + return p; + } + + public boolean jdbcCompliant() { + return false; + } +} diff --git a/sql/src/main/java/SQLite/ProgressHandler.java b/sqlite-jdbc/src/main/java/SQLite/ProgressHandler.java index b2ec7c0..b2ec7c0 100644 --- a/sql/src/main/java/SQLite/ProgressHandler.java +++ b/sqlite-jdbc/src/main/java/SQLite/ProgressHandler.java diff --git a/sqlite-jdbc/src/main/java/SQLite/Shell.java b/sqlite-jdbc/src/main/java/SQLite/Shell.java new file mode 100644 index 0000000..b25e8ca --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/Shell.java @@ -0,0 +1,694 @@ +package SQLite; + +import SQLite.*; +import java.io.*; +import java.util.*; + +/** + * SQLite command line shell. This is a partial reimplementaion + * of sqlite/src/shell.c and can be invoked by:<P> + * + * <verb> + * java SQLite.Shell [OPTIONS] database [SHELLCMD] + * or + * java -jar sqlite.jar [OPTIONS] database [SHELLCMD] + * </verb> + */ + +public class Shell implements Callback { + Database db; + boolean echo; + int count; + int mode; + boolean showHeader; + String tableName; + String sep; + String cols[]; + int colwidth[]; + String destTable; + PrintWriter pw; + PrintWriter err; + + static final int MODE_Line = 0; + static final int MODE_Column = 1; + static final int MODE_List = 2; + static final int MODE_Semi = 3; + static final int MODE_Html = 4; + static final int MODE_Insert = 5; + static final int MODE_Insert2 = 6; + + public Shell(PrintWriter pw, PrintWriter err) { + this.pw = pw; + this.err = err; + } + + public Shell(PrintStream ps, PrintStream errs) { + pw = new PrintWriter(ps); + err = new PrintWriter(errs); + } + + protected Object clone() { + Shell s = new Shell(this.pw, this.err); + s.db = db; + s.echo = echo; + s.mode = mode; + s.count = 0; + s.showHeader = showHeader; + s.tableName = tableName; + s.sep = sep; + s.colwidth = colwidth; + return s; + } + + static public String sql_quote_dbl(String str) { + if (str == null) { + return "NULL"; + } + int i, single = 0, dbl = 0; + for (i = 0; i < str.length(); i++) { + if (str.charAt(i) == '\'') { + single++; + } else if (str.charAt(i) == '"') { + dbl++; + } + } + if (dbl == 0) { + return "\"" + str + "\""; + } + StringBuffer sb = new StringBuffer("\""); + for (i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c == '"') { + sb.append("\"\""); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + static public String sql_quote(String str) { + if (str == null) { + return "NULL"; + } + int i, single = 0, dbl = 0; + for (i = 0; i < str.length(); i++) { + if (str.charAt(i) == '\'') { + single++; + } else if (str.charAt(i) == '"') { + dbl++; + } + } + if (single == 0) { + return "'" + str + "'"; + } + if (dbl == 0) { + return "\"" + str + "\""; + } + StringBuffer sb = new StringBuffer("'"); + for (i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c == '\'') { + sb.append("''"); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + static String html_quote(String str) { + if (str == null) { + return "NULL"; + } + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c == '<') { + sb.append("<"); + } else if (c == '>') { + sb.append(">"); + } else if (c == '&') { + sb.append("&"); + } else { + int x = c; + if (x < 32 || x > 127) { + sb.append("&#" + x + ";"); + } else { + sb.append(c); + } + } + } + return sb.toString(); + } + + static boolean is_numeric(String str) { + try { + Double d = Double.valueOf(str); + } catch (java.lang.Exception e) { + return false; + } + return true; + } + + void set_table_name(String str) { + if (str == null) { + tableName = ""; + return; + } + if (db.is3()) { + tableName = Shell.sql_quote_dbl(str); + } else { + tableName = Shell.sql_quote(str); + } + } + + public void columns(String args[]) { + cols = args; + } + + public void types(String args[]) { + /* Empty body to satisfy SQLite.Callback interface. */ + } + + public boolean newrow(String args[]) { + int i; + String tname; + switch (mode) { + case Shell.MODE_Line: + if (args.length == 0) { + break; + } + if (count++ > 0) { + pw.println(""); + } + for (i = 0; i < args.length; i++) { + pw.println(cols[i] + " = " + + args[i] == null ? "NULL" : args[i]); + } + break; + case Shell.MODE_Column: + String csep = ""; + if (count++ == 0) { + colwidth = new int[args.length]; + for (i = 0; i < args.length; i++) { + int w, n; + w = cols[i].length(); + if (w < 10) { + w = 10; + } + colwidth[i] = w; + if (showHeader) { + pw.print(csep + cols[i]); + csep = " "; + } + } + if (showHeader) { + pw.println(""); + } + } + if (args.length == 0) { + break; + } + csep = ""; + for (i = 0; i < args.length; i++) { + pw.print(csep + (args[i] == null ? "NULL" : args[i])); + csep = " "; + } + pw.println(""); + break; + case Shell.MODE_Semi: + case Shell.MODE_List: + if (count++ == 0 && showHeader) { + for (i = 0; i < args.length; i++) { + pw.print(cols[i] + + (i == args.length - 1 ? "\n" : sep)); + } + } + if (args.length == 0) { + break; + } + for (i = 0; i < args.length; i++) { + pw.print(args[i] == null ? "NULL" : args[i]); + if (mode == Shell.MODE_Semi) { + pw.print(";"); + } else if (i < args.length - 1) { + pw.print(sep); + } + } + pw.println(""); + break; + case MODE_Html: + if (count++ == 0 && showHeader) { + pw.print("<TR>"); + for (i = 0; i < args.length; i++) { + pw.print("<TH>" + html_quote(cols[i]) + "</TH>"); + } + pw.println("</TR>"); + } + if (args.length == 0) { + break; + } + pw.print("<TR>"); + for (i = 0; i < args.length; i++) { + pw.print("<TD>" + html_quote(args[i]) + "</TD>"); + } + pw.println("</TR>"); + break; + case MODE_Insert: + if (args.length == 0) { + break; + } + tname = tableName; + if (destTable != null) { + tname = destTable; + } + pw.print("INSERT INTO " + tname + " VALUES("); + for (i = 0; i < args.length; i++) { + String tsep = i > 0 ? "," : ""; + if (args[i] == null) { + pw.print(tsep + "NULL"); + } else if (is_numeric(args[i])) { + pw.print(tsep + args[i]); + } else { + pw.print(tsep + sql_quote(args[i])); + } + } + pw.println(");"); + break; + case MODE_Insert2: + if (args.length == 0) { + break; + } + tname = tableName; + if (destTable != null) { + tname = destTable; + } + pw.print("INSERT INTO " + tname + " VALUES("); + for (i = 0; i < args.length; i++) { + String tsep = i > 0 ? "," : ""; + pw.print(tsep + args[i]); + } + pw.println(");"); + break; + } + return false; + } + + void do_meta(String line) { + StringTokenizer st = new StringTokenizer(line.toLowerCase()); + int n = st.countTokens(); + if (n <= 0) { + return; + } + String cmd = st.nextToken(); + String args[] = new String[n - 1]; + int i = 0; + while (st.hasMoreTokens()) { + args[i] = st.nextToken(); + ++i; + } + if (cmd.compareTo(".dump") == 0) { + new DBDump(this, args); + return; + } + if (cmd.compareTo(".echo") == 0) { + if (args.length > 0 && + (args[0].startsWith("y") || args[0].startsWith("on"))) { + echo = true; + } + return; + } + if (cmd.compareTo(".exit") == 0) { + try { + db.close(); + } catch (Exception e) { + } + System.exit(0); + } + if (cmd.compareTo(".header") == 0) { + if (args.length > 0 && + (args[0].startsWith("y") || args[0].startsWith("on"))) { + showHeader = true; + } + return; + } + if (cmd.compareTo(".help") == 0) { + pw.println(".dump ?TABLE? ... Dump database in text fmt"); + pw.println(".echo ON|OFF Command echo on or off"); + pw.println(".enc ?NAME? Change encoding"); + pw.println(".exit Exit program"); + pw.println(".header ON|OFF Display headers on or off"); + pw.println(".help This message"); + pw.println(".mode MODE Set output mode to\n" + + " line, column, insert\n" + + " list, or html"); + pw.println(".mode insert TABLE Generate SQL insert stmts"); + pw.println(".schema ?PATTERN? List table schema"); + pw.println(".separator STRING Set separator string"); + pw.println(".tables ?PATTERN? List table names"); + return; + } + if (cmd.compareTo(".mode") == 0) { + if (args.length > 0) { + if (args[0].compareTo("line") == 0) { + mode = Shell.MODE_Line; + } else if (args[0].compareTo("column") == 0) { + mode = Shell.MODE_Column; + } else if (args[0].compareTo("list") == 0) { + mode = Shell.MODE_List; + } else if (args[0].compareTo("html") == 0) { + mode = Shell.MODE_Html; + } else if (args[0].compareTo("insert") == 0) { + mode = Shell.MODE_Insert; + if (args.length > 1) { + destTable = args[1]; + } + } + } + return; + } + if (cmd.compareTo(".separator") == 0) { + if (args.length > 0) { + sep = args[0]; + } + return; + } + if (cmd.compareTo(".tables") == 0) { + TableResult t = null; + if (args.length > 0) { + try { + String qarg[] = new String[1]; + qarg[0] = args[0]; + t = db.get_table("SELECT name FROM sqlite_master " + + "WHERE type='table' AND " + + "name LIKE '%%%q%%' " + + "ORDER BY name", qarg); + } catch (Exception e) { + err.println("SQL Error: " + e); + err.flush(); + } + } else { + try { + t = db.get_table("SELECT name FROM sqlite_master " + + "WHERE type='table' ORDER BY name"); + } catch (Exception e) { + err.println("SQL Error: " + e); + err.flush(); + } + } + if (t != null) { + for (i = 0; i < t.nrows; i++) { + String tab = ((String[]) t.rows.elementAt(i))[0]; + if (tab != null) { + pw.println(tab); + } + } + } + return; + } + if (cmd.compareTo(".schema") == 0) { + if (args.length > 0) { + try { + String qarg[] = new String[1]; + qarg[0] = args[0]; + db.exec("SELECT sql FROM sqlite_master " + + "WHERE type!='meta' AND " + + "name LIKE '%%%q%%' AND " + + "sql NOTNULL " + + "ORDER BY type DESC, name", + this, qarg); + } catch (Exception e) { + err.println("SQL Error: " + e); + err.flush(); + } + } else { + try { + db.exec("SELECT sql FROM sqlite_master " + + "WHERE type!='meta' AND " + + "sql NOTNULL " + + "ORDER BY tbl_name, type DESC, name", + this); + } catch (Exception e) { + err.println("SQL Error: " + e); + err.flush(); + } + } + return; + } + if (cmd.compareTo(".enc") == 0) { + try { + db.set_encoding(args.length > 0 ? args[0] : null); + } catch (Exception e) { + err.println("" + e); + err.flush(); + } + return; + } + if (cmd.compareTo(".rekey") == 0) { + try { + db.rekey(args.length > 0 ? args[0] : null); + } catch (Exception e) { + err.println("" + e); + err.flush(); + } + return; + } + err.println("Unknown command '" + cmd + "'"); + err.flush(); + } + + String read_line(BufferedReader is, String prompt) { + try { + if (prompt != null) { + pw.print(prompt); + pw.flush(); + } + String line = is.readLine(); + return line; + } catch (IOException e) { + return null; + } + } + + void do_input(BufferedReader is) { + String line, sql = null; + String prompt = "SQLITE> "; + while ((line = read_line(is, prompt)) != null) { + if (echo) { + pw.println(line); + } + if (line.length() > 0 && line.charAt(0) == '.') { + do_meta(line); + } else { + if (sql == null) { + sql = line; + } else { + sql = sql + " " + line; + } + if (Database.complete(sql)) { + try { + db.exec(sql, this); + } catch (Exception e) { + if (!echo) { + err.println(sql); + } + err.println("SQL Error: " + e); + err.flush(); + } + sql = null; + prompt = "SQLITE> "; + } else { + prompt = "SQLITE? "; + } + } + pw.flush(); + } + if (sql != null) { + err.println("Incomplete SQL: " + sql); + err.flush(); + } + } + + void do_cmd(String sql) { + if (db == null) { + return; + } + if (sql.length() > 0 && sql.charAt(0) == '.') { + do_meta(sql); + } else { + try { + db.exec(sql, this); + } catch (Exception e) { + err.println("SQL Error: " + e); + err.flush(); + } + } + } + + public static void main(String args[]) { + String key = null; + Shell s = new Shell(System.out, System.err); + s.mode = Shell.MODE_List; + s.sep = "|"; + s.showHeader = false; + s.db = new Database(); + String dbname = null, sql = null; + for (int i = 0; i < args.length; i++) { + if(args[i].compareTo("-html") ==0) { + s.mode = Shell.MODE_Html; + } else if (args[i].compareTo("-list") == 0) { + s.mode = Shell.MODE_List; + } else if (args[i].compareTo("-line") == 0) { + s.mode = Shell.MODE_Line; + } else if (i < args.length - 1 && + args[i].compareTo("-separator") == 0) { + ++i; + s.sep = args[i]; + } else if (args[i].compareTo("-header") == 0) { + s.showHeader = true; + } else if (args[i].compareTo("-noheader") == 0) { + s.showHeader = false; + } else if (args[i].compareTo("-echo") == 0) { + s.echo = true; + } else if (args[i].compareTo("-key") == 0) { + ++i; + key = args[i]; + } else if (dbname == null) { + dbname = args[i]; + } else if (sql == null) { + sql = args[i]; + } else { + System.err.println("Arguments: ?OPTIONS? FILENAME ?SQL?"); + System.exit(1); + } + } + if (dbname == null) { + System.err.println("No database file given"); + System.exit(1); + } + try { + s.db.open(dbname, 0); + } catch (Exception e) { + System.err.println("Unable to open database: " + e); + System.exit(1); + } + if (key != null) { + try { + s.db.key(key); + } catch (Exception e) { + System.err.println("Unable to set key: " + e); + System.exit(1); + } + } + if (sql != null) { + s.do_cmd(sql); + s.pw.flush(); + } else { + BufferedReader is = + new BufferedReader(new InputStreamReader(System.in)); + s.do_input(is); + s.pw.flush(); + } + try { + s.db.close(); + } catch (Exception ee) { + } + } +} + +/** + * Internal class for dumping an entire database. + * It contains a special callback interface to traverse the + * tables of the current database and output create SQL statements + * and for the data insert SQL statements. + */ + +class DBDump implements Callback { + Shell s; + + DBDump(Shell s, String tables[]) { + this.s = s; + s.pw.println("BEGIN TRANSACTION;"); + if (tables == null || tables.length == 0) { + try { + s.db.exec("SELECT name, type, sql FROM sqlite_master " + + "WHERE type!='meta' AND sql NOT NULL " + + "ORDER BY substr(type,2,1), name", this); + } catch (Exception e) { + s.err.println("SQL Error: " + e); + s.err.flush(); + } + } else { + String arg[] = new String[1]; + for (int i = 0; i < tables.length; i++) { + arg[0] = tables[i]; + try { + s.db.exec("SELECT name, type, sql FROM sqlite_master " + + "WHERE tbl_name LIKE '%q' AND type!='meta' " + + " AND sql NOT NULL " + + " ORDER BY substr(type,2,1), name", + this, arg); + } catch (Exception e) { + s.err.println("SQL Error: " + e); + s.err.flush(); + } + } + } + s.pw.println("COMMIT;"); + } + + public void columns(String col[]) { + /* Empty body to satisfy SQLite.Callback interface. */ + } + + public void types(String args[]) { + /* Empty body to satisfy SQLite.Callback interface. */ + } + + public boolean newrow(String args[]) { + if (args.length != 3) { + return true; + } + s.pw.println(args[2] + ";"); + if (args[1].compareTo("table") == 0) { + Shell s2 = (Shell) s.clone(); + s2.mode = Shell.MODE_Insert; + s2.set_table_name(args[0]); + String qargs[] = new String[1]; + qargs[0] = args[0]; + try { + if (s2.db.is3()) { + TableResult t = null; + t = s2.db.get_table("PRAGMA table_info('%q')", qargs); + String query; + if (t != null) { + StringBuffer sb = new StringBuffer(); + String sep = ""; + + sb.append("SELECT "); + for (int i = 0; i < t.nrows; i++) { + String col = ((String[]) t.rows.elementAt(i))[1]; + sb.append(sep + "quote(" + + Shell.sql_quote_dbl(col) + ")"); + sep = ","; + } + sb.append(" from '%q'"); + query = sb.toString(); + s2.mode = Shell.MODE_Insert2; + } else { + query = "SELECT * from '%q'"; + } + s2.db.exec(query, s2, qargs); + } else { + s2.db.exec("SELECT * from '%q'", s2, qargs); + } + } catch (Exception e) { + s.err.println("SQL Error: " + e); + s.err.flush(); + return true; + } + } + return false; + } +} diff --git a/sql/src/main/java/SQLite/Stmt.java b/sqlite-jdbc/src/main/java/SQLite/Stmt.java index c4f72ed..d60e6b0 100644 --- a/sql/src/main/java/SQLite/Stmt.java +++ b/sqlite-jdbc/src/main/java/SQLite/Stmt.java @@ -141,7 +141,7 @@ public class Stmt { */ public native void bind_zeroblob(int pos, int length) - throws SQLite.Exception; + throws SQLite.Exception; /** * Return number of parameters in compiled SQLite3 statement. @@ -165,7 +165,7 @@ public class Stmt { */ public native int bind_parameter_index(String name) - throws SQLite.Exception; + throws SQLite.Exception; /** @@ -226,16 +226,16 @@ public class Stmt { public Object column(int col) throws SQLite.Exception { switch (column_type(col)) { - case Constants.SQLITE_INTEGER: - return new Long(column_long(col)); - case Constants.SQLITE_FLOAT: - return new Double(column_double(col)); - case Constants.SQLITE_BLOB: - return column_bytes(col); - case Constants.SQLITE3_TEXT: - return column_string(col); - } - return null; + case Constants.SQLITE_INTEGER: + return new Long(column_long(col)); + case Constants.SQLITE_FLOAT: + return new Double(column_double(col)); + case Constants.SQLITE_BLOB: + return column_bytes(col); + case Constants.SQLITE3_TEXT: + return column_string(col); + } + return null; } /** @@ -283,6 +283,6 @@ public class Stmt { private static native void internal_init(); static { - internal_init(); + internal_init(); } } diff --git a/sqlite-jdbc/src/main/java/SQLite/StringEncoder.java b/sqlite-jdbc/src/main/java/SQLite/StringEncoder.java new file mode 100644 index 0000000..f02e77b --- /dev/null +++ b/sqlite-jdbc/src/main/java/SQLite/StringEncoder.java @@ -0,0 +1,244 @@ +package SQLite; + +/** + * String encoder/decoder for SQLite. + * + * This module was kindly donated by Eric van der Maarel of Nedap N.V. + * + * This encoder was implemented based on an original idea from an anonymous + * author in the source code of the SQLite distribution. + * I feel obliged to provide a quote from the original C-source code: + * + * "The author disclaims copyright to this source code. In place of + * a legal notice, here is a blessing: + * + * May you do good and not evil. + * May you find forgiveness for yourself and forgive others. + * May you share freely, never taking more than you give." + * + */ + +public class StringEncoder { + + /** + * Encodes the given byte array into a string that can be used by + * the SQLite database. The database cannot handle null (0x00) and + * the character '\'' (0x27). The encoding consists of escaping + * these characters with a reserved character (0x01). The escaping + * is applied after determining and applying a shift that minimizes + * the number of escapes required. + * With this encoding the data of original size n is increased to a + * maximum of 1+(n*257)/254. + * For sufficiently large n the overhead is thus less than 1.2%. + * @param a the byte array to be encoded. A null reference is handled as + * an empty array. + * @return the encoded bytes as a string. When an empty array is + * provided a string of length 1 is returned, the value of + * which is bogus. + * When decoded with this class' <code>decode</code> method + * a string of size 1 will return an empty byte array. + */ + + public static String encode(byte[] a) { + // check input + if (a == null || a.length == 0) { + // bogus shift, no data + return "x"; + } + // determine count + int[] cnt = new int[256]; + for (int i = 0 ; i < a.length; i++) { + cnt[a[i] & 0xff]++; + } + // determine shift for minimum number of escapes + int shift = 1; + int nEscapes = a.length; + for (int i = 1; i < 256; i++) { + if (i == '\'') { + continue; + } + int sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff]; + if (sum < nEscapes) { + nEscapes = sum; + shift = i; + if (nEscapes == 0) { + // cannot become smaller + break; + } + } + } + // construct encoded output + int outLen = a.length + nEscapes + 1; + StringBuffer out = new StringBuffer(outLen); + out.append((char)shift); + for (int i = 0; i < a.length; i++) { + // apply shift + char c = (char)((a[i] - shift)&0xff); + // insert escapes + if (c == 0) { // forbidden + out.append((char)1); + out.append((char)1); + } else if (c == 1) { // escape character + out.append((char)1); + out.append((char)2); + } else if (c == '\'') { // forbidden + out.append((char)1); + out.append((char)3); + } else { + out.append(c); + } + } + return out.toString(); + } + + /** + * Decodes the given string that is assumed to be a valid encoding + * of a byte array. Typically the given string is generated by + * this class' <code>encode</code> method. + * @param s the given string encoding. + * @return the byte array obtained from the decoding. + * @throws IllegalArgumentException when the string given is not + * a valid encoded string for this encoder. + */ + + public static byte[] decode(String s) { + char[] a = s.toCharArray(); + if (a.length > 2 && a[0] == 'X' && + a[1] == '\'' && a[a.length-1] == '\'') { + // SQLite3 BLOB syntax + byte[] result = new byte[(a.length-3)/2]; + for (int i = 2, k = 0; i < a.length - 1; i += 2, k++) { + byte tmp; + switch (a[i]) { + case '0': tmp = 0; break; + case '1': tmp = 1; break; + case '2': tmp = 2; break; + case '3': tmp = 3; break; + case '4': tmp = 4; break; + case '5': tmp = 5; break; + case '6': tmp = 6; break; + case '7': tmp = 7; break; + case '8': tmp = 8; break; + case '9': tmp = 9; break; + case 'A': + case 'a': tmp = 10; break; + case 'B': + case 'b': tmp = 11; break; + case 'C': + case 'c': tmp = 12; break; + case 'D': + case 'd': tmp = 13; break; + case 'E': + case 'e': tmp = 14; break; + case 'F': + case 'f': tmp = 15; break; + default: tmp = 0; break; + } + result[k] = (byte) (tmp << 4); + switch (a[i+1]) { + case '0': tmp = 0; break; + case '1': tmp = 1; break; + case '2': tmp = 2; break; + case '3': tmp = 3; break; + case '4': tmp = 4; break; + case '5': tmp = 5; break; + case '6': tmp = 6; break; + case '7': tmp = 7; break; + case '8': tmp = 8; break; + case '9': tmp = 9; break; + case 'A': + case 'a': tmp = 10; break; + case 'B': + case 'b': tmp = 11; break; + case 'C': + case 'c': tmp = 12; break; + case 'D': + case 'd': tmp = 13; break; + case 'E': + case 'e': tmp = 14; break; + case 'F': + case 'f': tmp = 15; break; + default: tmp = 0; break; + } + result[k] |= tmp; + } + return result; + } + // first element is the shift + byte[] result = new byte[a.length-1]; + int i = 0; + int shift = s.charAt(i++); + int j = 0; + while (i < s.length()) { + int c; + if ((c = s.charAt(i++)) == 1) { // escape character found + if ((c = s.charAt(i++)) == 1) { + c = 0; + } else if (c == 2) { + c = 1; + } else if (c == 3) { + c = '\''; + } else { + throw new IllegalArgumentException( + "invalid string passed to decoder: " + j); + } + } + // do shift + result[j++] = (byte)((c + shift) & 0xff); + } + int outLen = j; + // provide array of correct length + if (result.length != outLen) { + result = byteCopy(result, 0, outLen, new byte[outLen]); + } + return result; + } + + /** + * Copies count elements from source, starting at element with + * index offset, to the given target. + * @param source the source. + * @param offset the offset. + * @param count the number of elements to be copied. + * @param target the target to be returned. + * @return the target being copied to. + */ + + private static byte[] byteCopy(byte[] source, int offset, + int count, byte[] target) { + for (int i = offset, j = 0; i < offset + count; i++, j++) { + target[j] = source[i]; + } + return target; + } + + + static final char[] xdigits = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + + /** + * Encodes the given byte array into SQLite3 blob notation, ie X'..' + * @param a the byte array to be encoded. A null reference is handled as + * an empty array. + * @return the encoded bytes as a string. + */ + + public static String encodeX(byte[] a) { + // check input + if (a == null || a.length == 0) { + return "X''"; + } + int outLen = a.length * 2 + 3; + StringBuffer out = new StringBuffer(outLen); + out.append('X'); + out.append('\''); + for (int i = 0; i < a.length; i++) { + out.append(xdigits[(a[i] >> 4) & 0x0F]); + out.append(xdigits[a[i] & 0x0F]); + } + out.append('\''); + return out.toString(); + } +} diff --git a/sql/src/main/java/SQLite/TableResult.java b/sqlite-jdbc/src/main/java/SQLite/TableResult.java index 1a7fb57..14337aa 100644 --- a/sql/src/main/java/SQLite/TableResult.java +++ b/sqlite-jdbc/src/main/java/SQLite/TableResult.java @@ -60,11 +60,32 @@ public class TableResult implements Callback { public Vector rows; /** + * Maximum number of rows to hold in the table. + */ + + public int maxrows = 0; + + /** + * Flag to indicate Maximum number of rows condition. + */ + + public boolean atmaxrows; + + /** * Create an empty result set. */ public TableResult() { - clear(); + clear(); + } + + /** + * Create an empty result set with maximum number of rows. + */ + + public TableResult(int maxrows) { + this.maxrows = maxrows; + clear(); } /** @@ -72,10 +93,11 @@ public class TableResult implements Callback { */ public void clear() { - column = new String[0]; - types = null; - rows = new Vector(); - ncolumns = nrows = 0; + column = new String[0]; + types = null; + rows = new Vector(); + ncolumns = nrows = 0; + atmaxrows = false; } /** @@ -83,8 +105,8 @@ public class TableResult implements Callback { */ public void columns(String coldata[]) { - column = coldata; - ncolumns = column.length; + column = coldata; + ncolumns = column.length; } /** @@ -92,7 +114,7 @@ public class TableResult implements Callback { */ public void types(String types[]) { - this.types = types; + this.types = types; } /** @@ -100,11 +122,15 @@ public class TableResult implements Callback { */ public boolean newrow(String rowdata[]) { - if (rowdata != null) { - rows.addElement(rowdata); - nrows++; - } - return false; + if (rowdata != null) { + if (maxrows > 0 && nrows >= maxrows) { + atmaxrows = true; + return true; + } + rows.addElement(rowdata); + nrows++; + } + return false; } /** @@ -112,22 +138,22 @@ public class TableResult implements Callback { */ public String toString() { - StringBuffer sb = new StringBuffer(); - int i; - for (i = 0; i < ncolumns; i++) { - sb.append(column[i] == null ? "NULL" : column[i]); - sb.append('|'); - } - sb.append('\n'); - for (i = 0; i < nrows; i++) { - int k; - String row[] = (String[]) rows.elementAt(i); - for (k = 0; k < ncolumns; k++) { - sb.append(row[k] == null ? "NULL" : row[k]); - sb.append('|'); - } - sb.append('\n'); - } - return sb.toString(); + StringBuffer sb = new StringBuffer(); + int i; + for (i = 0; i < ncolumns; i++) { + sb.append(column[i] == null ? "NULL" : column[i]); + sb.append('|'); + } + sb.append('\n'); + for (i = 0; i < nrows; i++) { + int k; + String row[] = (String[]) rows.elementAt(i); + for (k = 0; k < ncolumns; k++) { + sb.append(row[k] == null ? "NULL" : row[k]); + sb.append('|'); + } + sb.append('\n'); + } + return sb.toString(); } } diff --git a/sql/src/main/java/SQLite/Trace.java b/sqlite-jdbc/src/main/java/SQLite/Trace.java index 19ed2a1..19ed2a1 100644 --- a/sql/src/main/java/SQLite/Trace.java +++ b/sqlite-jdbc/src/main/java/SQLite/Trace.java diff --git a/sql/src/main/java/SQLite/Vm.java b/sqlite-jdbc/src/main/java/SQLite/Vm.java index 9856ed0..f47e12f 100644 --- a/sql/src/main/java/SQLite/Vm.java +++ b/sqlite-jdbc/src/main/java/SQLite/Vm.java @@ -73,6 +73,6 @@ public class Vm { private static native void internal_init(); static { - internal_init(); + internal_init(); } } diff --git a/sql/src/main/native/sqlite_jni.c b/sqlite-jdbc/src/main/native/sqlite_jni.c index 341ef2e..bb5e2da 100644 --- a/sql/src/main/native/sqlite_jni.c +++ b/sqlite-jdbc/src/main/native/sqlite_jni.c @@ -1,11 +1,10 @@ #include "JNIHelp.h" +#include "sqlite_jni_defs.h" #include <stdlib.h> #include <stdio.h> #include <string.h> -#include "sqlite_jni_defs.h" - #if HAVE_SQLITE2 #include "sqlite.h" #endif @@ -31,7 +30,9 @@ #define HAVE_BOTH_SQLITE 1 #endif -#define CANT_PASS_VALIST_AS_CHARPTR +#ifndef HAVE_SQLITE3_SHARED_CACHE +#define HAVE_SQLITE3_SHARED_CACHE 0 +#endif #include "sqlite_jni.h" @@ -182,7 +183,7 @@ jstrlen(const jchar *jstr) int len = 0; if (jstr) { - while (*jstr++) { + while (*jstr++) { len++; } } @@ -278,13 +279,23 @@ freep(char **strp) static void throwex(JNIEnv *env, const char *msg) { - jniThrowException(env, "SQLite/Exception", msg); + jclass except = (*env)->FindClass(env, "SQLite/Exception"); + + (*env)->ExceptionClear(env); + if (except) { + (*env)->ThrowNew(env, except, msg); + } } static void throwoom(JNIEnv *env, const char *msg) { - jniThrowException(env, "java/lang/OutOfMemoryError", msg); + jclass except = (*env)->FindClass(env, "java/lang/OutOfMemoryError"); + + (*env)->ExceptionClear(env); + if (except) { + (*env)->ThrowNew(env, except, msg); + } } static void @@ -297,7 +308,12 @@ throwclosed(JNIEnv *env) static void throwioex(JNIEnv *env, const char *msg) { - jniThrowException(env, "java/io/IOException", msg); + jclass except = (*env)->FindClass(env, "java/io/IOException"); + + (*env)->ExceptionClear(env); + if (except) { + (*env)->ThrowNew(env, except, msg); + } } #endif @@ -318,6 +334,7 @@ trans2iso(JNIEnv *env, int haveutf, jstring enc, jstring src, dest->result = 0; dest->tofree = 0; if (haveutf) { + // BEGIN android-changed: leak/error reporting/simplification/performance. const jsize utfLength = (*env)->GetStringUTFLength(env, src); dest->result = dest->tofree = malloc(utfLength + 1); if (!dest->tofree) { @@ -326,6 +343,7 @@ trans2iso(JNIEnv *env, int haveutf, jstring enc, jstring src, } (*env)->GetStringUTFRegion(env, src, 0, utfLength, dest->result); return dest->result; + // END android-changed } if (enc) { bytes = (*env)->CallObjectMethod(env, src, @@ -403,7 +421,7 @@ busyhandler(void *udata, const char *table, int count) "(Ljava/lang/String;I)Z"); if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return ret; } trans2utf(env, h->haveutf, h->enc, table, &tabstr); @@ -411,7 +429,7 @@ busyhandler(void *udata, const char *table, int count) (jint) count) != JNI_FALSE; (*env)->DeleteLocalRef(env, tabstr.jstr); - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak } return ret; } @@ -431,12 +449,12 @@ busyhandler3(void *udata, int count) "(Ljava/lang/String;I)Z"); if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return ret; } ret = (*env)->CallBooleanMethod(env, h->bh, mid, 0, (jint) count) != JNI_FALSE; - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak } return ret; } @@ -454,11 +472,11 @@ progresshandler(void *udata) jmethodID mid = (*env)->GetMethodID(env, cls, "progress", "()Z"); if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return ret; } ret = (*env)->CallBooleanMethod(env, h->ph, mid) != JNI_TRUE; - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak } return ret; } @@ -676,41 +694,39 @@ callback(void *udata, int ncol, char **data, char **cols) #endif #endif } - mid = (*env)->GetMethodID(env, cls, "newrow", - "([Ljava/lang/String;)Z"); - if (mid) { - jboolean rc; + if (data) { + mid = (*env)->GetMethodID(env, cls, "newrow", + "([Ljava/lang/String;)Z"); + if (mid) { + jboolean rc; - if (data) { arr = (*env)->NewObjectArray(env, ncol, C_java_lang_String, 0); - } else { - arr = 0; - } - for (i = 0; arr && i < ncol; i++) { - if (data[i]) { - transstr dats; + for (i = 0; arr && i < ncol; i++) { + if (data[i]) { + transstr dats; - trans2utf(env, h->haveutf, h->enc, data[i], &dats); - (*env)->SetObjectArrayElement(env, arr, i, dats.jstr); - exc = (*env)->ExceptionOccurred(env); - if (exc) { - (*env)->DeleteLocalRef(env, exc); - return 1; + trans2utf(env, h->haveutf, h->enc, data[i], &dats); + (*env)->SetObjectArrayElement(env, arr, i, dats.jstr); + exc = (*env)->ExceptionOccurred(env); + if (exc) { + (*env)->DeleteLocalRef(env, exc); + return 1; + } + (*env)->DeleteLocalRef(env, dats.jstr); } - (*env)->DeleteLocalRef(env, dats.jstr); } + rc = (*env)->CallBooleanMethod(env, h->cb, mid, arr); + exc = (*env)->ExceptionOccurred(env); + if (exc) { + (*env)->DeleteLocalRef(env, exc); + return 1; + } + if (arr) { + (*env)->DeleteLocalRef(env, arr); + } + (*env)->DeleteLocalRef(env, cls); + return rc != JNI_FALSE; } - rc = (*env)->CallBooleanMethod(env, h->cb, mid, arr); - exc = (*env)->ExceptionOccurred(env); - if (exc) { - (*env)->DeleteLocalRef(env, exc); - return 1; - } - if (arr) { - (*env)->DeleteLocalRef(env, arr); - } - (*env)->DeleteLocalRef(env, cls); - return rc != JNI_FALSE; } } return 0; @@ -789,7 +805,7 @@ doclose(JNIEnv *env, jobject obj, int final) bl->next = 0; bl->h = 0; if (bl->blob) { - sqlite3_blob_close(bl->blob); + sqlite3_blob_close(bl->blob); } bl->blob = 0; } @@ -982,13 +998,21 @@ Java_SQLite_Database__1interrupt(JNIEnv *env, jobject obj) } JNIEXPORT void JNICALL -Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) +Java_SQLite_Database__1open4(JNIEnv *env, jobject obj, jstring file, jint mode, + jstring vfs, jboolean ver2) { handle *h = gethandle(env, obj); jthrowable exc; char *err = 0; transstr filename; int maj, min, lev; +#if HAVE_SQLITE3_OPEN_V2 + transstr vfsname; + + vfsname.result = 0; + vfsname.tofree = 0; + vfsname.jstr = 0; +#endif if (h) { if (h->sqlite) { @@ -1052,6 +1076,17 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) (*env)->DeleteLocalRef(env, exc); return; } +#if HAVE_SQLITE3_OPEN_V2 + if (vfs) { + trans2iso(env, 1, h->enc, vfs, &vfsname); + exc = (*env)->ExceptionOccurred(env); + if (exc) { + transfree(&filename); + (*env)->DeleteLocalRef(env, exc); + return; + } + } +#endif #if HAVE_BOTH_SQLITE { FILE *f = fopen(filename.result, "rb"); @@ -1061,8 +1096,13 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) c_0 = fgetc(f); fclose(f); } - if (c_0 != '*') { + if (c_0 != '*' && ver2 == JNI_FALSE) { +#if HAVE_SQLITE3_OPEN_V2 + int rc = sqlite3_open_v2(filename.result, (sqlite3 **) &h->sqlite, + (int) mode, vfsname.result); +#else int rc = sqlite3_open(filename.result, (sqlite3 **) &h->sqlite); +#endif if (rc == SQLITE_OK) { h->is3 = 1; @@ -1080,7 +1120,13 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) h->sqlite = (void *) sqlite_open(filename.result, (int) mode, &err); #endif #if HAVE_SQLITE3 - if (sqlite3_open(filename.result, (sqlite3 **) &h->sqlite) != SQLITE_OK) { +#if HAVE_SQLITE3_OPEN_V2 + if (sqlite3_open_v2(filename.result, (sqlite3 **) &h->sqlite, + (int) mode, vfsname.result) != SQLITE_OK) +#else + if (sqlite3_open(filename.result, (sqlite3 **) &h->sqlite) != SQLITE_OK) +#endif + { if (h->sqlite) { sqlite3_close((sqlite3 *) h->sqlite); h->sqlite = 0; @@ -1089,6 +1135,9 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) #endif #endif transfree(&filename); +#if HAVE_SQLITE3_OPEN_V2 + transfree(&vfsname); +#endif exc = (*env)->ExceptionOccurred(env); if (exc) { (*env)->DeleteLocalRef(env, exc); @@ -1131,6 +1180,9 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) #if HAVE_BOTH_SQLITE if (h->is3) { sscanf(sqlite3_libversion(), "%d.%d.%d", &maj, &min, &lev); +#if HAVE_SQLITE3_LOAD_EXTENSION + sqlite3_enable_load_extension((sqlite3 *) h->sqlite, 1); +#endif } else { sscanf(sqlite_libversion(), "%d.%d.%d", &maj, &min, &lev); } @@ -1140,6 +1192,9 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) #endif #if HAVE_SQLITE3 sscanf(sqlite3_libversion(), "%d.%d.%d", &maj, &min, &lev); +#if HAVE_SQLITE3_LOAD_EXTENSION + sqlite3_enable_load_extension((sqlite3 *) h->sqlite, 1); +#endif #endif #endif h->ver = ((maj & 0xFF) << 16) | ((min & 0xFF) << 8) | (lev & 0xFF); @@ -1154,6 +1209,12 @@ Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) } JNIEXPORT void JNICALL +Java_SQLite_Database__1open(JNIEnv *env, jobject obj, jstring file, jint mode) +{ + Java_SQLite_Database__1open4(env, obj, file, mode, 0, 0); +} + +JNIEXPORT void JNICALL Java_SQLite_Database__1open_1aux_1file(JNIEnv *env, jobject obj, jstring file) { handle *h = gethandle(env, obj); @@ -1325,7 +1386,7 @@ Java_SQLite_Database__1exec__Ljava_lang_String_2LSQLite_Callback_2_3Ljava_lang_S jthrowable exc; int rc = SQLITE_ERROR, nargs, i; char *err = 0, *p; - const char *str = (*env)->GetStringUTFChars(env, sql, NULL); + const char *str = (*env)->GetStringUTFChars(env, sql, NULL); // android-changed: unused variable transstr sqlstr; struct args { char *arg; @@ -1601,7 +1662,7 @@ call_common(sqlite_func *sf, int isstep, int nargs, const char **args) int i; if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return; } arr = (*env)->NewObjectArray(env, nargs, C_java_lang_String, 0); @@ -1650,7 +1711,7 @@ call_final(sqlite_func *sf) jmethodID mid = (*env)->GetMethodID(env, cls, "last_step", "(LSQLite/FunctionContext;)V"); if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return; } f->sf = sf; @@ -1677,7 +1738,7 @@ call3_common(sqlite3_context *sf, int isstep, int nargs, sqlite3_value **args) int i; if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return; } arr = (*env)->NewObjectArray(env, nargs, C_java_lang_String, 0); @@ -1727,7 +1788,7 @@ call3_final(sqlite3_context *sf) jmethodID mid = (*env)->GetMethodID(env, cls, "last_step", "(LSQLite/FunctionContext;)V"); if (mid == 0) { - (*env)->DeleteLocalRef(env, cls); + (*env)->DeleteLocalRef(env, cls); // android-changed: plug leak return; } f->sf = sf; @@ -2506,7 +2567,8 @@ Java_SQLite_Vm_step(JNIEnv *env, jobject obj, jobject cb) if (v && v->vm && v->h) { jthrowable exc; - int ret, ncol = 0; + int ret, tmp; + long ncol = 0; #if HAVE_SQLITE3 freemem *freeproc = 0; const char **blob = 0; @@ -2517,7 +2579,29 @@ Java_SQLite_Vm_step(JNIEnv *env, jobject obj, jobject cb) #if HAVE_BOTH_SQLITE if (v->is3) { ret = sqlite3_step((sqlite3_stmt *) v->vm); - if (ret == SQLITE_ROW) { + if (ret == SQLITE_DONE && v->hh.row1) { + ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); + if (ncol > 0) { + data = calloc(ncol * 3 + 3 + 1, sizeof (char *)); + if (data) { + data[0] = (const char *) ncol; + ++data; + cols = data + ncol + 1; + blob = cols + ncol + 1; + freeproc = free_tab; + } else { + ret = SQLITE_NOMEM; + } + } + if (ret != SQLITE_NOMEM) { + int i; + + for (i = 0; i < ncol; i++) { + cols[i] = + sqlite3_column_name((sqlite3_stmt *) v->vm, i); + } + } + } else if (ret == SQLITE_ROW) { ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (ncol > 0) { data = calloc(ncol * 3 + 3 + 1, sizeof (char *)); @@ -2570,15 +2654,41 @@ Java_SQLite_Vm_step(JNIEnv *env, jobject obj, jobject cb) } } } else { - ret = sqlite_step((sqlite_vm *) v->vm, &ncol, &data, &cols); + tmp = 0; + ret = sqlite_step((sqlite_vm *) v->vm, &tmp, &data, &cols); + ncol = tmp; } #else #if HAVE_SQLITE2 - ret = sqlite_step((sqlite_vm *) v->vm, &ncol, &data, &cols); + tmp = 0; + ret = sqlite_step((sqlite_vm *) v->vm, &tmp, &data, &cols); + ncol = tmp; #endif #if HAVE_SQLITE3 ret = sqlite3_step((sqlite3_stmt *) v->vm); - if (ret == SQLITE_ROW) { + if (ret == SQLITE_DONE && v->hh.row1) { + ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); + if (ncol > 0) { + data = calloc(ncol * 3 + 3 + 1, sizeof (char *)); + if (data) { + data[0] = (const char *) ncol; + ++data; + cols = data + ncol + 1; + blob = cols + ncol + 1; + freeproc = free_tab; + } else { + ret = SQLITE_NOMEM; + } + } + if (ret != SQLITE_NOMEM) { + int i; + + for (i = 0; i < ncol; i++) { + cols[i] = + sqlite3_column_name((sqlite3_stmt *) v->vm, i); + } + } + } else if (ret == SQLITE_ROW) { ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (ncol > 0) { data = calloc(ncol * 3 + 3 + 1, sizeof (char *)); @@ -2656,6 +2766,29 @@ Java_SQLite_Vm_step(JNIEnv *env, jobject obj, jobject cb) return JNI_TRUE; } else if (ret == SQLITE_DONE) { dofin: + if (v->hh.row1 && cols) { + v->hh.cb = cb; + v->hh.env = env; +#if HAVE_BOTH_SQLITE + if (v->is3) { + v->hh.stmt = (sqlite3_stmt *) v->vm; + } +#else +#if HAVE_SQLITE3 + v->hh.stmt = (sqlite3_stmt *) v->vm; +#endif +#endif + callback((void *) &v->hh, ncol, (char **) 0, (char **) cols); +#if HAVE_SQLITE3 + if (data && freeproc) { + freeproc((void *) data); + } +#endif + exc = (*env)->ExceptionOccurred(env); + if (exc) { + (*env)->DeleteLocalRef(env, exc); + } + } #if HAVE_BOTH_SQLITE if (v->is3) { sqlite3_finalize((sqlite3_stmt *) v->vm); @@ -2706,6 +2839,9 @@ Java_SQLite_Vm_compile(JNIEnv *env, jobject obj) hvm *v = gethvm(env, obj); void *svm = 0; char *err = 0; +#ifdef HAVE_SQLITE2 + char *errfr = 0; +#endif const char *tail; int ret; @@ -2745,11 +2881,13 @@ Java_SQLite_Vm_compile(JNIEnv *env, jobject obj) sqlite3_finalize((sqlite3_stmt *) svm); svm = 0; } + err = (char *) sqlite3_errmsg((sqlite3 *) v->h->sqlite); } } else { ret = sqlite_compile((sqlite *) v->h->sqlite, v->tail, - &tail, (sqlite_vm **) &svm, &err); + &tail, (sqlite_vm **) &svm, &errfr); if (ret != SQLITE_OK) { + err = errfr; if (svm) { sqlite_finalize((sqlite_vm *) svm, 0); svm = 0; @@ -2759,8 +2897,9 @@ Java_SQLite_Vm_compile(JNIEnv *env, jobject obj) #else #if HAVE_SQLITE2 ret = sqlite_compile((sqlite *) v->h->sqlite, v->tail, - &tail, (sqlite_vm **) &svm, &err); + &tail, (sqlite_vm **) &svm, &errfr); if (ret != SQLITE_OK) { + err = errfr; if (svm) { sqlite_finalize((sqlite_vm *) svm, 0); svm = 0; @@ -2780,6 +2919,7 @@ Java_SQLite_Vm_compile(JNIEnv *env, jobject obj) sqlite3_finalize((sqlite3_stmt *) svm); svm = 0; } + err = (char *) sqlite3_errmsg((sqlite3 *) v->h->sqlite); } #endif #endif @@ -2788,15 +2928,15 @@ Java_SQLite_Vm_compile(JNIEnv *env, jobject obj) v->tail = 0; throwex(env, err ? err : "error in compile/prepare"); #if HAVE_SQLITE2 - if (err) { - sqlite_freemem(err); + if (errfr) { + sqlite_freemem(errfr); } #endif return JNI_FALSE; } #if HAVE_SQLITE2 - if (err) { - sqlite_freemem(err); + if (errfr) { + sqlite_freemem(errfr); } #endif if (!svm) { @@ -2824,6 +2964,9 @@ Java_SQLite_Database_vm_1compile(JNIEnv *env, jobject obj, jstring sql, void *svm = 0; hvm *v; char *err = 0; +#if HAVE_SQLITE2 + char *errfr = 0; +#endif const char *tail; transstr tr; jvalue vv; @@ -2863,11 +3006,13 @@ Java_SQLite_Database_vm_1compile(JNIEnv *env, jobject obj, jstring sql, sqlite3_finalize((sqlite3_stmt *) svm); svm = 0; } + err = (char *) sqlite3_errmsg((sqlite3 *) h->sqlite); } } else { ret = sqlite_compile((sqlite *) h->sqlite, tr.result, &tail, - (sqlite_vm **) &svm, &err); + (sqlite_vm **) &svm, &errfr); if (ret != SQLITE_OK) { + err = errfr; if (svm) { sqlite_finalize((sqlite_vm *) svm, 0); } @@ -2876,8 +3021,9 @@ Java_SQLite_Database_vm_1compile(JNIEnv *env, jobject obj, jstring sql, #else #if HAVE_SQLITE2 ret = sqlite_compile((sqlite *) h->sqlite, tr.result, &tail, - (sqlite_vm **) &svm, &err); + (sqlite_vm **) &svm, &errfr); if (ret != SQLITE_OK) { + err = errfr; if (svm) { sqlite_finalize((sqlite_vm *) svm, 0); svm = 0; @@ -2897,6 +3043,7 @@ Java_SQLite_Database_vm_1compile(JNIEnv *env, jobject obj, jstring sql, sqlite3_finalize((sqlite3_stmt *) svm); svm = 0; } + err = (char *) sqlite3_errmsg((sqlite3 *) h->sqlite); } #endif #endif @@ -2905,15 +3052,15 @@ Java_SQLite_Database_vm_1compile(JNIEnv *env, jobject obj, jstring sql, setvmerr(env, vm, ret); throwex(env, err ? err : "error in prepare/compile"); #if HAVE_SQLITE2 - if (err) { - sqlite_freemem(err); + if (errfr) { + sqlite_freemem(errfr); } #endif return; } #if HAVE_SQLITE2 - if (err) { - sqlite_freemem(err); + if (errfr) { + sqlite_freemem(errfr); } #endif if (!svm) { @@ -3005,7 +3152,7 @@ Java_SQLite_Database_vm_1compile_1args(JNIEnv *env, jthrowable exc; int rc = SQLITE_ERROR, nargs, i; char *p; - const char *str = (*env)->GetStringUTFChars(env, sql, NULL); + const char *str = (*env)->GetStringUTFChars(env, sql, NULL); // android-changed: unused variable const char *tail; transstr sqlstr; struct args { @@ -3394,7 +3541,7 @@ Java_SQLite_Database_stmt_1prepare(JNIEnv *env, jobject obj, jstring sql, return; } len16 = len16 + sizeof (jchar) - ((char *) tail - (char *) sql16); - if (len16 < (jsize) sizeof (jchar)) { + if (len16 < (jsize) sizeof (jchar)) { // android-changed: signed/unsigned comparison len16 = sizeof (jchar); } v = malloc(sizeof (hvm) + len16); @@ -3667,6 +3814,7 @@ Java_SQLite_Stmt_bind__ILjava_lang_String_2(JNIEnv *env, jobject obj, return; } if (val) { + // BEGIN android-changed: simplification/performance. const jsize charCount = (*env)->GetStringLength(env, val); len = charCount * sizeof(jchar); if (len > 0) { @@ -3683,6 +3831,7 @@ Java_SQLite_Stmt_bind__ILjava_lang_String_2(JNIEnv *env, jobject obj, ret = sqlite3_bind_text16((sqlite3_stmt *) v->vm, pos, "", 0, SQLITE_STATIC); } + // END android-changed } else { ret = sqlite3_bind_null((sqlite3_stmt *) v->vm, pos); } @@ -4298,6 +4447,108 @@ Java_SQLite_Blob_finalize(JNIEnv *env, jobject obj) #endif } +JNIEXPORT void +JNICALL Java_SQLite_Database__1key(JNIEnv *env, jobject obj, jbyteArray key) +{ + jsize len; + jbyte *data; +#if HAVE_SQLITE3_KEY + handle *h = gethandle(env, obj); +#endif + + len = (*env)->GetArrayLength(env, key); + data = (*env)->GetByteArrayElements(env, key, 0); + if (len == 0) { + data = 0; + } + if (!data) { + len = 0; + } +#if HAVE_SQLITE3_KEY + if (h && h->sqlite) { +#if HAVE_BOTH_SQLITE + if (!h->is3) { + if (data) { + memset(data, 0, len); + } + throwex(env, "unsupported"); + } +#endif + sqlite3_key((sqlite3 *) h->sqlite, data, len); + if (data) { + memset(data, 0, len); + } + } else { + if (data) { + memset(data, 0, len); + } + throwclosed(env); + } +#else + if (data) { + memset(data, 0, len); + } + /* no error */ +#endif +} + +JNIEXPORT void JNICALL +Java_SQLite_Database__1rekey(JNIEnv *env, jobject obj, jbyteArray key) +{ + jsize len; + jbyte *data; +#if HAVE_SQLITE3_KEY + handle *h = gethandle(env, obj); +#endif + + len = (*env)->GetArrayLength(env, key); + data = (*env)->GetByteArrayElements(env, key, 0); + if (len == 0) { + data = 0; + } + if (!data) { + len = 0; + } +#if HAVE_SQLITE3_KEY + if (h && h->sqlite) { +#if HAVE_BOTH_SQLITE + if (!h->is3) { + if (data) { + memset(data, 0, len); + } + throwex(env, "unsupported"); + } +#endif + sqlite3_rekey((sqlite3 *) h->sqlite, data, len); + if (data) { + memset(data, 0, len); + } + } else { + if (data) { + memset(data, 0, len); + } + throwclosed(env); + } +#else + if (data) { + memset(data, 0, len); + } + throwex(env, "unsupported"); +#endif +} + +JNIEXPORT jboolean JNICALL +Java_SQLite_Database__1enable_1shared_1cache(JNIEnv *env, jclass cls, + jboolean onoff) +{ +#if HAVE_SQLITE3_SHARED_CACHE + return (sqlite3_enable_shared_cache(onoff == JNI_TRUE) == SQLITE_OK) ? + JNI_TRUE : JNI_FALSE; +#else + return JNI_FALSE; +#endif +} + JNIEXPORT void JNICALL Java_SQLite_Stmt_internal_1init(JNIEnv *env, jclass cls) { @@ -4328,11 +4579,13 @@ Java_SQLite_Blob_internal_1init(JNIEnv *env, jclass cls) JNIEXPORT void JNICALL Java_SQLite_Database_internal_1init(JNIEnv *env, jclass cls) { -//#ifndef JNI_VERSION_1_2 - jclass jls = (*env)->FindClass(env, "java/lang/String"); +#if defined(DONT_USE_JNI_ONLOAD) || !defined(JNI_VERSION_1_2) + while (C_java_lang_String == 0) { + jclass jls = (*env)->FindClass(env, "java/lang/String"); - C_java_lang_String = (*env)->NewGlobalRef(env, jls); -//#endif + C_java_lang_String = (*env)->NewGlobalRef(env, jls); + } +#endif F_SQLite_Database_handle = (*env)->GetFieldID(env, cls, "handle", "J"); F_SQLite_Database_error_code = @@ -4349,7 +4602,7 @@ Java_SQLite_Database_internal_1init(JNIEnv *env, jclass cls) "([BLjava/lang/String;)V"); } -#ifdef JNI_VERSION_1_2 +#if !defined(DONT_USE_JNI_ONLOAD) && defined(JNI_VERSION_1_2) JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { @@ -4370,7 +4623,7 @@ JNI_OnLoad(JavaVM *vm, void *reserved) if (!cls) { return JNI_ERR; } - C_java_lang_String = (*env)->NewWeakGlobalRef(env, cls); + C_java_lang_String = (*env)->NewGlobalRef(env, cls); // android-changed: bug return JNI_VERSION_1_2; } @@ -4383,7 +4636,7 @@ JNI_OnUnload(JavaVM *vm, void *reserved) return; } if (C_java_lang_String) { - (*env)->DeleteWeakGlobalRef(env, C_java_lang_String); + (*env)->DeleteGlobalRef(env, C_java_lang_String); // android-changed: bug C_java_lang_String = 0; } } diff --git a/sql/src/main/native/sqlite_jni.h b/sqlite-jdbc/src/main/native/sqlite_jni.h index cdb7692..cdb7692 100644 --- a/sql/src/main/native/sqlite_jni.h +++ b/sqlite-jdbc/src/main/native/sqlite_jni.h diff --git a/sql/src/main/native/sqlite_jni_defs.h b/sqlite-jdbc/src/main/native/sqlite_jni_defs.h index 91b2378..d21bf16 100644 --- a/sql/src/main/native/sqlite_jni_defs.h +++ b/sqlite-jdbc/src/main/native/sqlite_jni_defs.h @@ -36,4 +36,4 @@ #define HAVE_SQLITE3_RESULT_ZEROBLOB 0 #define HAVE_SQLITE3_INCRBLOBIO 0 - +#define CANT_PASS_VALIST_AS_CHARPTR diff --git a/suncompat/src/test/java/sun/misc/AllTests.java b/suncompat/src/test/java/sun/misc/AllTests.java index 8ea3bcf..f2c4277 100644 --- a/suncompat/src/test/java/sun/misc/AllTests.java +++ b/suncompat/src/test/java/sun/misc/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for sun.misc"); + TestSuite suite = new TestSuite("Test for sun.misc"); // $JUnit-BEGIN$ diff --git a/suncompat/src/test/java/sun/misc/UnsafeTest.java b/suncompat/src/test/java/sun/misc/UnsafeTest.java index 338055b..462d39d 100644 --- a/suncompat/src/test/java/sun/misc/UnsafeTest.java +++ b/suncompat/src/test/java/sun/misc/UnsafeTest.java @@ -16,23 +16,13 @@ package sun.misc; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; import junit.framework.TestCase; import java.util.concurrent.Callable; import java.util.concurrent.Executors; -@TestTargetClass(Unsafe.class) public class UnsafeTest extends TestCase { - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "getUnsafe", - args = {} - ) public void test_getUnsafeForbidden() { try { Unsafe.getUnsafe(); @@ -45,12 +35,6 @@ public class UnsafeTest extends TestCase { * Regression for 2053217. We used to look one level higher than necessary * on the stack. */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "", - method = "getUnsafe", - args = {} - ) public void test_getUnsafeForbiddenWithSystemCaller() throws Exception { Callable<Object> callable = Executors.callable(new Runnable() { public void run() { diff --git a/suncompat/src/test/java/tests/suncompat/AllTests.java b/suncompat/src/test/java/tests/suncompat/AllTests.java index 0884517..e86889c 100644 --- a/suncompat/src/test/java/tests/suncompat/AllTests.java +++ b/suncompat/src/test/java/tests/suncompat/AllTests.java @@ -23,13 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the suncompat project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All suncompat test suites"); + TestSuite suite = new TestSuite("All suncompat test suites"); // $JUnit-BEGIN$ suite.addTest(sun.misc.AllTests.suite()); // $JUnit-END$ diff --git a/support/src/test/java/tests/support/Support_TestWebServer.java b/support/src/test/java/tests/support/Support_TestWebServer.java index 7d20237..6773f01 100644 --- a/support/src/test/java/tests/support/Support_TestWebServer.java +++ b/support/src/test/java/tests/support/Support_TestWebServer.java @@ -46,9 +46,6 @@ public class Support_TestWebServer implements Support_HttpConstants { /* timeout on client connections */ int timeout = 0; - /* Default port for this server to listen on */ - final static int DEFAULT_PORT = 8080; - /* Default socket timeout value */ final static int DEFAULT_TIMEOUT = 5000; @@ -100,49 +97,51 @@ public class Support_TestWebServer implements Support_HttpConstants { * Initialize a new server with default port and timeout. * @param log Set true if you want trace output */ - public void initServer(boolean log) throws Exception { - initServer(DEFAULT_PORT, DEFAULT_TIMEOUT, log); + public int initServer(boolean log) throws Exception { + return initServer(0, DEFAULT_TIMEOUT, log); } /** * Initialize a new server with default timeout. - * @param port Sets the server to listen on this port + * @param port Sets the server to listen on this port, or 0 to let the OS choose. + * Hard-coding ports is evil, so always pass 0. * @param log Set true if you want trace output */ - public void initServer(int port, boolean log) throws Exception { - initServer(port, DEFAULT_TIMEOUT, log); + public int initServer(int port, boolean log) throws Exception { + return initServer(port, DEFAULT_TIMEOUT, log); } /** * Initialize a new server with default timeout and disabled log. - * @param port Sets the server to listen on this port + * @param port Sets the server to listen on this port, or 0 to let the OS choose. + * Hard-coding ports is evil, so always pass 0. * @param servePath the path to the dynamic web test data * @param contentType the type of the dynamic web test data */ - public void initServer(int port, String servePath, String contentType) + public int initServer(int port, String servePath, String contentType) throws Exception { Support_TestWebData.initDynamicTestWebData(servePath, contentType); - initServer(port, DEFAULT_TIMEOUT, false); + return initServer(port, DEFAULT_TIMEOUT, false); } /** * Initialize a new server with default port and timeout. - * @param port Sets the server to listen on this port + * @param port Sets the server to listen on this port, or 0 to let the OS choose. + * Hard-coding ports is evil, so always pass 0. * @param timeout Indicates the period of time to wait until a socket is * closed * @param log Set true if you want trace output */ - public void initServer(int port, int timeout, boolean log) throws Exception { - mPort = port; + public int initServer(int port, int timeout, boolean log) throws Exception { mTimeout = timeout; mLog = log; keepAlive = true; - if (acceptT == null) { acceptT = new AcceptThread(); - acceptT.init(); + mPort = acceptT.init(port); acceptT.start(); } + return mPort; } /** @@ -246,27 +245,15 @@ public class Support_TestWebServer implements Support_HttpConstants { ServerSocket ss = null; boolean running = false; - public void init() { - // Networking code doesn't support ServerSocket(port) yet - InetSocketAddress ia = new InetSocketAddress(mPort); - while (true) { - try { - ss = new ServerSocket(); - // Socket timeout functionality is not available yet - //ss.setSoTimeout(5000); - ss.setReuseAddress(true); - ss.bind(ia); - break; - } catch (IOException e) { - log("IOException in AcceptThread.init()"); - // wait and retry - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - } - } + /** + * @param port the port to use, or 0 to let the OS choose. + * Hard-coding ports is evil, so always pass 0! + */ + public int init(int port) throws IOException { + ss = new ServerSocket(port); + ss.setSoTimeout(5000); + ss.setReuseAddress(true); + return ss.getLocalPort(); } /** diff --git a/text/src/main/java/java/text/Bidi.java b/text/src/main/java/java/text/Bidi.java index 7939dea..9195a0f 100644 --- a/text/src/main/java/java/text/Bidi.java +++ b/text/src/main/java/java/text/Bidi.java @@ -641,8 +641,8 @@ public final class Bidi { public String toString() { // BEGIN android-changed return super.toString() - + "[direction: " + direction + " baselevel: " + baseLevel //$NON-NLS-1$ //$NON-NLS-2$ - + " length: " + length + " runs: " + (unidirectional ? "null" : runs.toString()) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + "[direction: " + direction + " baseLevel: " + baseLevel + + " length: " + length + " runs: " + Arrays.toString(runs) + "]"; // END android-changed } } diff --git a/text/src/main/java/java/text/Collator.java b/text/src/main/java/java/text/Collator.java index e954b8b..f324231 100644 --- a/text/src/main/java/java/text/Collator.java +++ b/text/src/main/java/java/text/Collator.java @@ -157,29 +157,6 @@ public abstract class Collator implements Comparator<Object>, Cloneable { */ public static final int IDENTICAL = 3; - private static int CACHE_SIZE; - - static { - // CACHE_SIZE includes key and value, so needs to be double - String cacheSize = AccessController - .doPrivileged(new PrivilegedAction<String>() { - public String run() { - return System.getProperty("collator.cache"); //$NON-NLS-1$ - } - }); - if (cacheSize != null) { - try { - CACHE_SIZE = Integer.parseInt(cacheSize); - } catch (NumberFormatException e) { - CACHE_SIZE = 6; - } - } else { - CACHE_SIZE = 6; - } - } - - private static Vector<Collator> cache = new Vector<Collator>(CACHE_SIZE); - // Wrapper class of ICU4JNI Collator com.ibm.icu4jni.text.Collator icuColl; @@ -332,15 +309,9 @@ public abstract class Collator implements Comparator<Object>, Cloneable { * @return the collator for {@code locale}. */ public static Collator getInstance(Locale locale) { - String key = locale.toString(); - for (int i = cache.size() - 1; i >= 0; i -= 2) { - if (cache.elementAt(i).equals(key)) { - return (Collator) (cache.elementAt(i - 1)).clone(); - } - } - - return new RuleBasedCollator(com.ibm.icu4jni.text.Collator - .getInstance(locale)); + // BEGIN android-changed: removed non-functional cache. + return new RuleBasedCollator(com.ibm.icu4jni.text.Collator.getInstance(locale)); + // END android-changed } /** diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java index c968b38..d5c539e 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java @@ -21,14 +21,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "Suite org.apache.harmony.text.tests.java.text"); + TestSuite suite = new TestSuite("Suite org.apache.harmony.text.tests.java.text"); //$JUnit-BEGIN$ suite.addTestSuite(AnnotationTest.class); suite.addTestSuite(AttributedCharacterIteratorAttributeTest.class); diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/BidiTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/BidiTest.java index deef841..0360a94 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/BidiTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/BidiTest.java @@ -1778,7 +1778,6 @@ public class BidiTest extends TestCase { method = "createLineBidi", args = {int.class, int.class} ) - @KnownFailure("Is this a failure or just a different behaviour of ICU?") public void testCreateLineBidi_AndroidFailure() { Bidi bidi = new Bidi("str", Bidi.DIRECTION_RIGHT_TO_LEFT); bidi.createLineBidi(2, 2); @@ -1983,7 +1982,6 @@ public class BidiTest extends TestCase { method = "getRunLimit", args = {int.class} ) - @KnownFailure("Doesn't verify any int value between 0 and getRunCount().") public void testGetRunLimit() { bd = new Bidi("text", Bidi.DIRECTION_LEFT_TO_RIGHT); try { @@ -2061,7 +2059,6 @@ public class BidiTest extends TestCase { method = "Bidi", args = {java.text.AttributedCharacterIterator.class} ) - @KnownFailure("Doesn't verify any int value between 0 and getRunCount().") public void testBidiConstructor_Iterator() { AttributedString paragraph = new AttributedString("text"); bd = new Bidi(paragraph.getIterator()); diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/CollatorTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/CollatorTest.java index 161a2c5..71ee510 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/CollatorTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/CollatorTest.java @@ -353,7 +353,6 @@ public class CollatorTest extends junit.framework.TestCase { method = "setDecomposition", args = {int.class} ) - @KnownFailure("uses decomposition even if set to NO_DECOMPOSITION") public void test_setDecompositionI() { Collator c = Collator.getInstance(Locale.FRENCH); c.setStrength(Collator.IDENTICAL); diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatSymbolsTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatSymbolsTest.java index 7a615d5..0b6ba31 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatSymbolsTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatSymbolsTest.java @@ -554,7 +554,6 @@ public class DecimalFormatSymbolsTest extends TestCase { method = "setInternationalCurrencySymbol", args = {java.lang.String.class} ) - @KnownFailure("getCurrency() doesn't return null for bogus currency code.") public void test_setInternationalCurrencySymbolLjava_lang_String() { Locale locale = Locale.CANADA; DecimalFormatSymbols dfs = ((DecimalFormat) NumberFormat @@ -743,8 +742,6 @@ public class DecimalFormatSymbolsTest extends TestCase { method = "!SerializationGolden", args = {} ) - @KnownFailure("Deserialized object is not equal to the original object." + - "Test passes on RI.") public void test_RIHarmony_compatible() throws Exception { ObjectInputStream i = null; try { diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java index 92945ee..92aaf71 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java @@ -70,8 +70,6 @@ public class DecimalFormatTest extends TestCase { method = "formatToCharacterIterator", args = {java.lang.Object.class} ) - @KnownFailure("formatting numbers with more than ~300 digits doesn't work." - + " Also the third test doesn't round the string like the RI does") public void test_formatToCharacterIterator() throws Exception { AttributedCharacterIterator iterator; int[] runStarts; @@ -277,7 +275,6 @@ public class DecimalFormatTest extends TestCase { method = "parse", args = {java.lang.String.class, java.text.ParsePosition.class} ) - @KnownFailure("Something seems wrong with Android implementation, here!") public void test_parseLjava_lang_String_Ljava_text_ParsePosition() { DecimalFormat form = (DecimalFormat) DecimalFormat .getInstance(Locale.US); @@ -1514,7 +1511,6 @@ public class DecimalFormatTest extends TestCase { method = "format", args = {double.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} ) - @KnownFailure("Something seems wrong with Android implementation, here!") public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() { new Support_DecimalFormat( "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition") @@ -1752,7 +1748,6 @@ public class DecimalFormatTest extends TestCase { method = "format", args = {long.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} ) - @KnownFailure("Something seems wrong with Android implementation, here!") public void test_formatJLjava_lang_StringBufferLjava_text_FieldPosition() { int failCount = 0; BitSet failures = new BitSet(); @@ -1853,10 +1848,6 @@ public class DecimalFormatTest extends TestCase { method = "format", args = {double.class} ) - @KnownFailure("This test should take into account (inexact) double " + - "representation. Fails on Both RI and Android at different places." + - "There is ticket for this failure because of parseDouble method " + - "returns different values on Android and RI.") public void test_formatD() { DecimalFormat format = (DecimalFormat) NumberFormat .getInstance(Locale.ENGLISH); @@ -2144,7 +2135,6 @@ public class DecimalFormatTest extends TestCase { method = "parse", args = {java.lang.String.class, java.text.ParsePosition.class} ) - @KnownFailure("Something seems wrong with Android implementation, here!") public void test_parseLjava_lang_StringLjava_text_ParsePosition() { DecimalFormat format = (DecimalFormat) NumberFormat .getNumberInstance(Locale.ENGLISH); diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatFieldTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatFieldTest.java index 06c6922..e6c79cd 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatFieldTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatFieldTest.java @@ -60,7 +60,6 @@ public class NumberFormatFieldTest extends junit.framework.TestCase { method = "readResolve", args = {} ) - @KnownFailure("readResolve does not work properly") public void test_readResolve() { // test for method java.lang.Object readResolve() diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/RuleBasedCollatorTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/RuleBasedCollatorTest.java index 3c864a5..68452e66 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/RuleBasedCollatorTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/RuleBasedCollatorTest.java @@ -280,7 +280,6 @@ public class RuleBasedCollatorTest extends TestCase { method = "getCollationElementIterator", args = {java.text.CharacterIterator.class} ) - @KnownFailure("ICU seems to miss collation data") public void testGetCollationElementIteratorCharacterIterator() throws Exception { { Locale locale = new Locale("cs", "CZ", ""); diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/SimpleDateFormatTest.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/SimpleDateFormatTest.java index f96410f..0f77270 100644 --- a/text/src/test/java/org/apache/harmony/text/tests/java/text/SimpleDateFormatTest.java +++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/SimpleDateFormatTest.java @@ -468,10 +468,6 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { method = "format", args = {java.util.Date.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} ) - @KnownFailure("SimpleDateFormat.format(Date date, " + - "StringBuffer toAppendTo, FieldPosition pos) " + - "return incorrect week number for \" W\" pattern. " + - "Also Android doesn't support formatting of PST, EST, ...") public void test_formatLjava_util_DateLjava_lang_StringBufferLjava_text_FieldPosition() { // Test for method java.lang.StringBuffer // java.text.SimpleDateFormat.format(java.util.Date, @@ -672,7 +668,6 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { args = {java.lang.String.class} ) }) - @KnownFailure("Android doesn't support formatting of PST, EST, ...") public void test_timeZoneFormatting() { // tests specific to formatting of timezones Date summerDate = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, diff --git a/text/src/test/java/tests/text/AllTests.java b/text/src/test/java/tests/text/AllTests.java index a3eb66d..25066fb 100644 --- a/text/src/test/java/tests/text/AllTests.java +++ b/text/src/test/java/tests/text/AllTests.java @@ -25,13 +25,8 @@ import junit.framework.TestSuite; * */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All Text test suites"); + TestSuite suite = new TestSuite("All Text test suites"); // $JUnit-BEGIN$ suite.addTest(org.apache.harmony.text.tests.java.text.AllTests.suite()); // $JUnit-END$ diff --git a/tools/runner/expectations.txt b/tools/runner/expectations.txt index 4c9f8e1..0ea91d0 100644 --- a/tools/runner/expectations.txt +++ b/tools/runner/expectations.txt @@ -685,10 +685,6 @@ pattern .*got java\.lang\.StringIndexOutOfBoundsException: null - FAILED.* # We don't expose Java 6 APIs -test java.lang.String.IsEmpty -result COMPILE_FAILED -pattern .*cannot find symbol.*method isEmpty\(\).* - test java.lang.String.Exceptions result COMPILE_FAILED pattern .*cannot find symbol.*new String.* diff --git a/tools/runner/java/dalvik/runner/Mode.java b/tools/runner/java/dalvik/runner/Mode.java index 0ad7172..3b69cb2 100644 --- a/tools/runner/java/dalvik/runner/Mode.java +++ b/tools/runner/java/dalvik/runner/Mode.java @@ -72,7 +72,7 @@ abstract class Mode { // TODO: we should be able to work with a shipping SDK, not depend on out/... // dalvik/libcore/**/test/ for junit // TODO: jar up just the junit classes and drop the jar in our lib/ directory. - new File("out/target/common/obj/JAVA_LIBRARIES/core-tests_intermediates/classes.jar").getAbsoluteFile()); + new File("out/target/common/obj/JAVA_LIBRARIES/core-tests-luni_intermediates/classes.jar").getAbsoluteFile()); Mode(Environment environment, long timeoutSeconds, File sdkJar, PrintStream tee) { this.environment = environment; diff --git a/tools/runner/vogar b/tools/runner/vogar index e5a6ad0..fa23d80 100755 --- a/tools/runner/vogar +++ b/tools/runner/vogar @@ -17,5 +17,9 @@ # m core-tests junit caliper snod && adb reboot bootloader && fastboot flashall && adb wait-for-device # mmm dalvik/libcore/tools/runner -classpath=`dirname $0`/../../../../out/host/linux-x86/framework/dalvik_runner.jar -exec java -cp $classpath dalvik.runner.DalvikRunner "$@" +android_root=`dirname $0`/../../../.. +cd ${android_root} + +classpath=${android_root}/out/host/linux-x86/framework/dalvik_runner.jar +core_jar=${android_root}/out/target/common/obj/JAVA_LIBRARIES/core_intermediates/classes.jar +exec java -cp $classpath dalvik.runner.DalvikRunner --sdk ${core_jar} "$@" diff --git a/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp b/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp index 407ca0d..3075898 100644 --- a/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp +++ b/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp @@ -1653,11 +1653,11 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_accept(JNIEn */ int sslErrorCode = SSL_get_error(ssl, ret); if (sslErrorCode == SSL_ERROR_NONE || - (sslErrorCode == SSL_ERROR_SYSCALL && errno == 0)) { - throwIOExceptionStr(env, "Connection closed by peer"); + (sslErrorCode == SSL_ERROR_SYSCALL && errno == 0)) { + throwIOExceptionStr(env, "Connection closed by peer"); } else { - throwIOExceptionWithSslErrors(env, ret, sslErrorCode, - "Trouble accepting connection"); + throwIOExceptionWithSslErrors(env, ret, sslErrorCode, + "Trouble accepting connection"); } free_ssl(env, object); return; diff --git a/x-net/src/test/java/tests/api/javax/net/AllTests.java b/x-net/src/test/java/tests/api/javax/net/AllTests.java index 90c2a6a..35cd6f5 100644 --- a/x-net/src/test/java/tests/api/javax/net/AllTests.java +++ b/x-net/src/test/java/tests/api/javax/net/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.javax.net;"); + TestSuite suite = new TestSuite("All tests for package tests.api.javax.net;"); // $JUnit-BEGIN$ suite.addTestSuite(ServerSocketFactoryTest.class); diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java b/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java index ecfe83f..5f9c32d 100644 --- a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java +++ b/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.javax.net.ssl;"); + TestSuite suite = new TestSuite("All tests for package tests.api.javax.net.ssl;"); // $JUnit-BEGIN$ suite.addTestSuite(CertPathTrustManagerParametersTest.class); diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java index f659919..8205059 100644 --- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java +++ b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java @@ -62,10 +62,6 @@ public class SSLEngineTest extends TestCase { private HandshakeHandler clientEngine; private HandshakeHandler serverEngine; - public static void main(String[] args) { - junit.textui.TestRunner.run(SSLEngineTest.class); - } - @Override protected void setUp() throws Exception { super.setUp(); TestEnvironment.reset(); diff --git a/x-net/src/test/java/tests/xnet/AllTests.java b/x-net/src/test/java/tests/xnet/AllTests.java index 53b11dc..04a2ed6 100644 --- a/x-net/src/test/java/tests/xnet/AllTests.java +++ b/x-net/src/test/java/tests/xnet/AllTests.java @@ -23,14 +23,8 @@ import junit.framework.TestSuite; * Test suite that includes all tests for the Math project. */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite( - "All javax.net and javax.net.ssl test suites"); + TestSuite suite = new TestSuite("All javax.net and javax.net.ssl test suites"); // $JUnit-BEGIN$ suite.addTest(tests.api.javax.net.AllTests.suite()); suite.addTest(tests.api.javax.net.ssl.AllTests.suite()); diff --git a/xml/src/test/java/org/apache/harmony/xml/AllTests.java b/xml/src/test/java/org/apache/harmony/xml/AllTests.java index f7fac7c..c04c1b5 100644 --- a/xml/src/test/java/org/apache/harmony/xml/AllTests.java +++ b/xml/src/test/java/org/apache/harmony/xml/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(ExpatParserTest.class); return suite; } diff --git a/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java b/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java index 7dbfaea..3f0d2cb 100644 --- a/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java +++ b/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java @@ -21,7 +21,6 @@ import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -import junit.textui.TestRunner; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -135,7 +134,7 @@ public class XsltXPathConformanceTestSuite { } File catalogXml = new File(args[0]); - TestRunner.run(suite(catalogXml)); + // TestRunner.run(suite(catalogXml)); android-changed } public static Test suite() throws Exception { diff --git a/xml/src/test/java/org/kxml2/io/AllTests.java b/xml/src/test/java/org/kxml2/io/AllTests.java index f996d25..4fcc44a 100644 --- a/xml/src/test/java/org/kxml2/io/AllTests.java +++ b/xml/src/test/java/org/kxml2/io/AllTests.java @@ -21,7 +21,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(KXmlSerializerTest.class); return suite; } diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java b/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java index 6a22109..aecc746 100644 --- a/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java +++ b/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java @@ -25,13 +25,8 @@ import org.apache.harmony.xml.ExpatParserTest; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.javax.xml.parsers;"); + TestSuite suite = new TestSuite("All tests for package tests.api.javax.xml.parsers;"); // $JUnit-BEGIN$ suite.addTestSuite(DocumentBuilderFactoryTest.class); diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java b/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java index 80c6e3c..7356d3a 100644 --- a/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java +++ b/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java @@ -319,7 +319,6 @@ public class DocumentBuilderFactoryTest extends TestCase { args = {boolean.class} ) }) - @KnownFailure("Should handle XIncludeAware flag more gracefully") public void test_isSetXIncludeAware() { dbf.setXIncludeAware(true); assertTrue(dbf.isXIncludeAware()); diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java b/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java index ea7abed..ea77a65 100644 --- a/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java +++ b/xml/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java @@ -251,7 +251,6 @@ public class DocumentBuilderTest extends TestCase { method = "isXIncludeAware", args = {} ) - @KnownFailure("Should handle XIncludeAware flag more gracefully") public void testIsXIncludeAware() { try { dbf.setXIncludeAware(false); @@ -606,7 +605,6 @@ public class DocumentBuilderTest extends TestCase { method = "reset", args = { } ) - @KnownFailure("Android DocumentBuilder should implement reset() properly") public void testReset() { // Make sure EntityResolver gets reset InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes()); @@ -693,7 +691,6 @@ public class DocumentBuilderTest extends TestCase { method = "setEntityResolver", args = { EntityResolver.class } ) - @KnownFailure("Android DocumentBuilder should support entity resolving") public void testSetEntityResolver() { // Ordinary case InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes()); diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java b/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java index a918ac2..b573dbd 100644 --- a/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java +++ b/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java @@ -163,7 +163,6 @@ public class SAXParserFactoryTest extends TestCase { args = {boolean.class} ) }) - @KnownFailure("Should handle XIncludeAware flag more gracefully") public void test_setIsXIncludeAware() { spf.setXIncludeAware(true); assertTrue(spf.isXIncludeAware()); @@ -316,7 +315,6 @@ public class SAXParserFactoryTest extends TestCase { method = "setNamespaceAware", args = {boolean.class} ) - @KnownFailure("Error in namespace feature handling (for ExpatParser)") public void test_setNamespaceAwareZ() { spf.setNamespaceAware(true); diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java b/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java index e6d6481..d44107b 100644 --- a/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java +++ b/xml/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java @@ -327,7 +327,6 @@ public class SAXParserTest extends TestCase { method = "isXIncludeAware", args = {} ) - @KnownFailure("Should handle XIncludeAware flag more gracefully") public void testIsXIncludeAware() { try { spf.setXIncludeAware(false); @@ -1046,7 +1045,6 @@ public class SAXParserTest extends TestCase { method = "reset", args = { } ) - @KnownFailure("Android DocumentBuilder should implement reset() properly") public void testReset() { try { spf = SAXParserFactory.newInstance(); @@ -1102,7 +1100,6 @@ public class SAXParserTest extends TestCase { args = { String.class, Object.class } ) }) - @KnownFailure("ExpatParser should allow to clear properties") public void testSetGetProperty() { // Ordinary case String validName = "http://xml.org/sax/properties/lexical-handler"; diff --git a/xml/src/test/java/tests/api/org/xml/sax/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/AllTests.java index 9c29178..f7643e9 100644 --- a/xml/src/test/java/tests/api/org/xml/sax/AllTests.java +++ b/xml/src/test/java/tests/api/org/xml/sax/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for org.xml.sax package"); + TestSuite suite = new TestSuite("Tests for org.xml.sax package"); // $JUnit-BEGIN$ suite.addTestSuite(HandlerBaseTest.class); diff --git a/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java index f4b34b8..1334780 100644 --- a/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java +++ b/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for org.xml.sax.ext package"); + TestSuite suite = new TestSuite("Tests for org.xml.sax.ext package"); // $JUnit-BEGIN$ suite.addTestSuite(Attributes2ImplTest.class); diff --git a/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java index 5bf63bf..135496c 100644 --- a/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java +++ b/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java @@ -20,13 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for org.xml.sax.helpers package"); + TestSuite suite = new TestSuite("Tests for org.xml.sax.helpers package"); // $JUnit-BEGIN$ suite.addTestSuite(AttributeListImplTest.class); diff --git a/xml/src/test/java/tests/org/w3c/dom/AllTests.java b/xml/src/test/java/tests/org/w3c/dom/AllTests.java index a4299a7..5dba844 100644 --- a/xml/src/test/java/tests/org/w3c/dom/AllTests.java +++ b/xml/src/test/java/tests/org/w3c/dom/AllTests.java @@ -24,13 +24,8 @@ import junit.framework.TestSuite; */ public class AllTests { - - public static void main(String[] args) { - junit.textui.TestRunner.run(AllTests.suite()); - } - public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package org.w3c.dom;"); + TestSuite suite = new TestSuite("All tests for package org.w3c.dom;"); // $JUnit-BEGIN$ suite.addTestSuite(AttrGetOwnerElement.class); diff --git a/xml/src/test/java/tests/xml/AllTests.java b/xml/src/test/java/tests/xml/AllTests.java index 96b96c5..9be812d 100644 --- a/xml/src/test/java/tests/xml/AllTests.java +++ b/xml/src/test/java/tests/xml/AllTests.java @@ -22,7 +22,7 @@ import junit.framework.TestSuite; public class AllTests { public static Test suite() { - TestSuite suite = tests.TestSuiteFactory.createTestSuite(); + TestSuite suite = new TestSuite(); suite.addTestSuite(DeclarationTest.class); suite.addTestSuite(DomTest.class); @@ -35,7 +35,9 @@ public class AllTests { suite.addTest(tests.api.javax.xml.parsers.AllTests.suite()); suite.addTest(tests.api.org.xml.sax.AllTests.suite()); - suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); + // BEGIN android-changed: this is in the dom module! + // suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); + // END android-changed suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(org.apache.harmony.xml.AllTests.suite()); suite.addTest(org.kxml2.io.AllTests.suite()); |
