summaryrefslogtreecommitdiffstats
path: root/harmony-tests/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'harmony-tests/src/test/java')
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/internal/net/www/protocol/file/FileURLConnectionTest.java132
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedInputStreamTest.java562
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedOutputStreamTest.java849
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedReaderTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedWriterTest.java302
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayInputStreamTest.java180
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayOutputStreamTest.java213
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayReaderTest.java178
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayWriterTest.java233
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharConversionExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ComputeSerialVersionUIDTest.java86
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ConsoleTest.java106
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataInputStreamTest.java594
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataOutputStreamTest.java262
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/EOFExceptionTest.java52
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileDescriptorTest.java89
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileInputStreamTest.java482
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileNotFoundExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileOutputStreamTest.java394
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileReaderTest.java118
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileTest.java2191
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileWriterTest.java185
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterInputStreamTest.java209
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterOutputStreamTest.java138
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOErrorTest.java73
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOExceptionTest.java113
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamReaderTest.java529
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InterruptedIOExceptionTest.java47
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InvalidClassExceptionTest.java71
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberInputStreamTest.java167
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberReaderTest.java221
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotActiveExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotSerializableExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectInputStream2Test.java213
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStream2Test.java59
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStreamTest.java1323
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamClassTest.java223
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamConstantsTest.java45
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamFieldTest.java395
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OpenRandomFileTest.java58
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamTesterTest.java206
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamWriterTest.java701
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedInputStreamTest.java448
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedOutputStreamTest.java231
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedReaderTest.java399
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedWriterTest.java477
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintStreamTest.java673
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintWriterTest.java779
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackInputStreamTest.java256
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackReaderTest.java381
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/RandomAccessFileTest.java1059
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ReaderTest.java205
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SequenceInputStreamTest.java193
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest.java1022
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest1.java1657
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest2.java2101
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest3.java1670
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest4.java1969
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationTestClass.java337
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamCorruptedExceptionTest.java78
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamTokenizerTest.java448
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringBufferInputStreamTest.java99
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringReaderTest.java172
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringWriterTest.java211
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SyncFailedExceptionTest.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UTFDataFormatExceptionTest.java83
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UnsupportedEncodingExceptionTest.java68
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriteAbortedExceptionTest.java73
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTest.java147
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTesterTest.java213
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AbstractMethodErrorTest.java62
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArithmeticExceptionTest.java41
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java52
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayStoreExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AssertionErrorTest.java78
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/BooleanTest.java157
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ByteTest.java672
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterImplTest.java38
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterTest.java1637
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_SubsetTest.java49
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_UnicodeBlockTest.java822
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCastExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCircularityErrorTest.java40
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassFormatErrorTest.java43
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassLoaderTest.java158
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassNotFoundExceptionTest.java60
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassTest.java642
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CloneNotSupportedExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CompilerTest.java65
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/DoubleTest.java1444
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumConstantNotPresentExceptionTest.java45
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumTest.java261
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionInInitializerErrorTest.java53
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/FloatTest.java1077
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalArgumentExceptionTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalMonitorStateExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalStateExceptionTest.java95
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalThreadStateExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IncompatibleClassChangeErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IndexOutOfBoundsExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InheritableThreadLocalTest.java41
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IntegerTest.java1231
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InternalErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InterruptedExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LinkageErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LongTest.java1067
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MathTest.java1960
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum.java57
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum2.java61
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NegativeArraySizeExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoClassDefFoundErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NullPointerExceptionTest.java41
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberFormatExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberTest.java66
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ObjectTest.java388
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/OutOfMemoryErrorTest.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Process2Test.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessBuilderTest.java171
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessManagerTest.java221
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessTest.java135
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeExceptionTest.java59
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeTest.java128
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SecurityExceptionTest.java81
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ShortTest.java684
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StackOverflowErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StrictMathTest.java1490
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/String2Test.java978
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuffer2Test.java610
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBufferTest.java623
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuilderTest.java1986
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringTest.java697
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SystemTest.java413
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadDeathTest.java30
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadGroupTest.java795
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadLocalTest.java150
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadTest.java1011
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThrowableTest.java183
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/TypeNotPresentExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnknownErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsatisfiedLinkErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedClassVersionErrorTest.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedOperationExceptionTest.java100
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VerifyErrorTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VirtualMachineErrorTest.java45
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/PhantomReferenceTest.java141
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceQueueTest.java254
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceTest.java340
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/SoftReferenceTest.java141
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/WeakReferenceTest.java80
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/AccessibleObjectTest.java215
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ArrayTest.java1001
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/BoundedGenericMethodsTests.java128
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ConstructorTest.java442
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/FieldTest.java1639
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericArrayTypeTest.java64
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericMethodsTests.java121
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericReflectionTestsBase.java74
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericSignatureFormatErrorTest.java100
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/InvocationTargetExceptionTest.java305
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTest.java34
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java21
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MethodTest.java881
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ModifierTest.java435
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ParameterizedTypeTest.java77
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ProxyTest.java334
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/TypeVariableTest.java150
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTests.java53
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/WildcardTypeTest.java151
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalTest.java (renamed from harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerTest.java (renamed from harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/math/MathContextTest.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/math/OldBigIntegerTest.java372
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/math/RoundingModeTest.java49
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/BindExceptionTest.java67
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieHandlerTest.java62
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieManagerTest.java303
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookiePolicyTest.java112
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieStoreTest.java401
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramPacketTest.java338
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketImplTest.java152
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java940
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/HttpCookieTest.java978
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/IDNTest.java156
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet4AddressTest.java346
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet6AddressTest.java916
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressTest.java443
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressThreadTest.java175
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetSocketAddressTest.java131
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InterfaceAddressTest.java164
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/JarURLConnectionTest.java312
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MalformedURLExceptionTest.java72
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java929
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NetworkInterfaceTest.java496
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NoRouteToHostExceptionTest.java53
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/PasswordAuthenticationTest.java74
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProtocolExceptionTest.java67
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxySelectorTest.java562
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxyTest.java238
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ResponseCacheTest.java70
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SecureCacheResponseTest.java85
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ServerSocketTest.java950
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketExceptionTest.java51
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketImplTest.java155
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTest.java1634
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTimeoutExceptionTest.java67
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/TestServerSocketInit.java30
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URISyntaxExceptionTest.java115
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URITest.java1841
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLDecoderTest.java64
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLTest.java1155
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownHostExceptionTest.java68
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownServiceExceptionTest.java67
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/AbstractBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferOverflowExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferUnderflowExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteOrderTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/CharBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectCharBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateDirectByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateHeapByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateWrappedByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/FloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapCharBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/IntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/InvalidMarkExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/LongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/MappedByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyBufferExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyCharBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDirectByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapCharBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceDirectByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceHeapByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceWrappedByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedByteBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest1.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest2.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedDoubleBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedFloatBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedIntBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedLongBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedShortBufferTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AlreadyConnectedExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AsynchronousCloseExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/CancelledKeyExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java)12
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedByInterruptExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedChannelExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedSelectorExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ConnectionPendingExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java)1004
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelLockingTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockInterruptionExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalSelectorExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MapModeTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java)14
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockServerSocketChannel.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java)6
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockSocketChannel.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java)13
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NoConnectionPendingExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonReadableChannelExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonWritableChannelExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetBoundExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetConnectedExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/OverlappingFileLockExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/PipeTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectableChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java)9
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectorTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java)11
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java)251
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SinkChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java)348
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SourceChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnixSelectorTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnresolvedAddressExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectorTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/MockAbstractSelector.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCIICharsetEncoderTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java)152
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/AbstractCharsetTestCase.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharacterCodingExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoder2Test.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java)4
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoder2Test.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java)4
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java)12
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderMalfunctionErrorTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderResultTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CodingErrorActionTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/MalformedInputExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF8CharsetTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetDecoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetEncoderTest.java (renamed from harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnmappableCharacterExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AnnotationTest.java45
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorAttributeTest.java147
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorTest.java178
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedStringTest.java179
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BidiTest.java964
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BreakIteratorTest.java317
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ChoiceFormatTest.java469
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationElementIteratorTest.java224
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationKeyTest.java117
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollatorTest.java234
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DataFormatFieldTest.java223
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatSymbolsTest.java423
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatTest.java475
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatSymbolsTest.java552
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatTest.java2594
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/FieldPositionTest.java249
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/LoadLocaleProviderTestHelper.java48
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatFieldTest.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatTest.java953
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NormalizerTest.java183
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatFieldTest.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatTest.java295
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParseExceptionTest.java49
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParsePositionTest.java117
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/RuleBasedCollatorTest.java258
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/SimpleDateFormatTest.java835
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/StringCharacterIteratorTest.java521
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_DecimalFormat.java248
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_Format.java139
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_MessageFormat.java118
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_SimpleDateFormat.java258
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractCollectionTest.java345
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractListTest.java576
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractMapTest.java415
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractQueueTest.java323
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractSequentialListTest.java603
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayDequeTest.java932
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayListTest.java1071
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java472
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArraysTest.java4209
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/BitSetTest.java1361
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CalendarTest.java1099
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Collections2Test.java495
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CollectionsTest.java2385
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModTest.java667
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModificationExceptionTest.java107
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ControlTest.java682
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CurrencyTest.java405
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DateTest.java520
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DuplicateFormatFlagsExceptionTest.java94
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EmptyStackExceptionTest.java65
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumMapTest.java1175
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumSetTest.java2003
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EventObjectTest.java70
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java115
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormattableFlagsTest.java27
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterClosedExceptionTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterTest.java4244
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/GregorianCalendarTest.java753
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashMapTest.java755
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashSetTest.java253
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashtableTest.java935
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMap2Test.java467
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMapTest.java871
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatCodePointExceptionTest.java91
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatConversionExceptionTest.java115
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatFlagsExceptionTest.java94
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatPrecisionExceptionTest.java92
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatWidthExceptionTest.java93
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InputMismatchExceptionTest.java67
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InvalidPropertiesFormatExceptionTest.java50
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashMapTest.java736
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashSetTest.java351
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedListTest.java983
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ListResourceBundleTest.java76
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LocaleTest.java449
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatArgumentExceptionTest.java97
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatWidthExceptionTest.java95
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingResourceExceptionTest.java85
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/NoSuchElementExceptionTest.java73
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ObservableTest.java246
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PriorityQueueTest.java823
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertiesTest.java1157
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertyResourceBundleTest.java201
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RandomTest.java320
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RefSortedMap.java402
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ResourceBundleTest.java398
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SampleBundleClass.java43
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerParseLargeFileBenchmarkTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerParseLargeFileBenchmarkTest.java)47
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerTest.java)116
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ServiceConfigurationErrorTest.java78
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleEntryTest.java133
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleImmutableEntryTest.java146
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleTimeZoneTest.java838
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SortedMapTestBase.java369
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StackTest.java214
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StringTokenizerTest.java311
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimeZoneTest.java301
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTaskTest.java248
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTest.java986
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TooManyListenersExceptionTest.java64
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapExtendTest.java13581
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapRndTest.java28
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapTest.java1968
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeSetTest.java342
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UUIDTest.java (renamed from harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java)2
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatConversionExceptionTest.java96
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatFlagsExceptionTest.java94
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/VectorTest.java1406
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/WeakHashMapTest.java423
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesNameTest.java39
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesTest.java286
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarEntryTest.java182
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarExceptionTest.java53
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarFileTest.java1017
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarInputStreamTest.java406
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarOutputStreamTest.java91
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/ManifestTest.java456
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/AbstractPreferencesTest.java1699
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/BackingStoreExceptionTest.java62
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/FilePreferencesImplTest.java120
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/InvalidPreferencesFormatExceptionTest.java81
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockAbstractPreferences.java263
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockPreferencesFactory.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeEventTest.java63
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeListenerTest.java68
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeEventTest.java84
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeListenerTest.java52
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesFactoryTest.java59
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesTest.java420
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/regex/MatcherTest.java85
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/A.java13
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/B.java4
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/I.java5
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/P.java28
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/Adler32Test.java169
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CRC32Test.java186
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedInputStreamTest.java130
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedOutputStreamTest.java140
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterInputStreamTest.java426
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterOutputStreamTest.java402
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java1129
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPInputStreamTest.java301
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPOutputStreamTest.java187
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterInputStreamTest.java480
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterOutputStreamTest.java392
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterTest.java1135
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipEntryTest.java453
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipErrorTest.java50
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipFileTest.java421
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipInputStreamTest.java245
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipOutputStreamTest.java292
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ServerSocketFactoryTest.java129
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/SocketFactoryTest.java267
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertPathTrustManagerParametersTest.java78
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertificatesToPlayWith.java478
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HandshakeCompletedEventTest.java613
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HostnameVerifierTest.java290
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HttpsURLConnectionTest.java341
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory1Test.java532
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory2Test.java263
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactorySpiTest.java151
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyStoreBuilderParametersTest.java101
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext1Test.java599
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext2Test.java293
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContextSpiTest.java229
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java83
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultStatusTest.java90
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultTest.java217
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineTest.java1210
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLExceptionTest.java158
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLHandshakeExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLKeyExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLProtocolExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketFactoryTest.java106
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketTest.java431
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingEventTest.java236
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingListenerTest.java85
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionContextTest.java95
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionTest.java655
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketFactoryTest.java129
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketTest.java631
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory1Test.java519
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory2Test.java255
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactorySpiTest.java139
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509ExtendedKeyManagerTest.java176
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509KeyManagerTest.java753
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509TrustManagerTest.java149
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyFailedExceptionTest.java81
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyableTest.java64
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/LoginExceptionTest.java69
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/SubjectTest.java257
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/CallbackHandlerTest.java47
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/PasswordCallbackTest.java137
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/UnsupportedCallbackExceptionTest.java117
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/login/LoginExceptionTest.java83
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/x500/X500PrincipalTest.java3094
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateEncodingExceptionTest.java78
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExceptionTest.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExpiredExceptionTest.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateNotYetValidExceptionTest.java81
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateParsingExceptionTest.java80
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateTest.java159
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/X509CertificateTest.java785
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderFactoryTest.java975
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderTest.java637
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/FactoryConfigurationErrorTest.java99
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/ParserConfigurationExceptionTest.java39
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserFactoryTest.java415
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTest.java899
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTestSupport.java492
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/apache/harmony/kernel/dalvik/ThreadsTest.java285
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/HandlerBaseTest.java151
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/InputSourceTest.java168
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXExceptionTest.java101
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotRecognizedExceptionTest.java40
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotSupportedExceptionTest.java40
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXParseExceptionTest.java216
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Attributes2ImplTest.java392
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/DefaultHandler2Test.java153
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Locator2ImplTest.java113
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributeListImplTest.java205
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributesImplTest.java481
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/DefaultHandlerTest.java187
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/LocatorImplTest.java108
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/NamespaceSupportTest.java318
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserAdapterTest.java335
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserFactoryTest.java145
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLFilterImplTest.java484
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderAdapterTest.java314
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderFactoryTest.java146
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/BrokenInputStream.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingParser.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingXMLReader.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MethodLogger.java95
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockFilter.java89
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockHandler.java147
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockParser.java68
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockReader.java128
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockResolver.java47
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessParser.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessXMLReader.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceParser.java58
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceXMLReader.java82
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassParser.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassXMLReader.java79
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/pkg1/TestClass.java30
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/pkg2/TestClass.java29
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/support/A.java30
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/support/B.java21
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/support/I.java22
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/support/P.java45
617 files changed, 182395 insertions, 1073 deletions
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/internal/net/www/protocol/file/FileURLConnectionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/internal/net/www/protocol/file/FileURLConnectionTest.java
new file mode 100644
index 0000000..d6f2c01
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/internal/net/www/protocol/file/FileURLConnectionTest.java
@@ -0,0 +1,132 @@
+/*
+ * 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.tests.internal.net.www.protocol.file;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import junit.framework.TestCase;
+import libcore.io.Streams;
+import libcore.net.url.FileURLConnection;
+
+/**
+ * Tests for <code>FileURLConnection</code> class constructors and methods.
+ */
+public class FileURLConnectionTest extends TestCase {
+
+ private static final String RESOURCE_NAME = "resources/test.rtf";
+
+ private final ClassLoader loader = FileURLConnectionTest.class.getClassLoader();
+
+ private URL createTempFileWithContent(String resourceName) throws IOException {
+ InputStream is = null;
+ OutputStream os = null;
+ try {
+ final URL url = loader.getResource(resourceName);
+ assertNotNull("Cannot find test resource " + resourceName, url);
+ is = url.openStream();
+ File file = File.createTempFile("FileURLConnectionTest",
+ resourceName.substring(resourceName.indexOf(".")));
+ os = new BufferedOutputStream(new FileOutputStream(file));
+ Streams.copy(is, os);
+
+ return new URL("file://" + file.getAbsolutePath());
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+
+ if (os != null) {
+ os.close();
+ }
+ }
+ }
+
+ private String getContentType(String fileName) throws IOException {
+ String resourceName = "resources/" + fileName;
+ URL url = createTempFileWithContent(resourceName);
+ return new FileURLConnection(url).getContentType();
+ }
+
+ public void testGetContentType() throws IOException {
+ // Regression for HARMONY-4699
+ assertEquals("text/rtf", getContentType("test.rtf"));
+ // RI would return "content/unknown"
+ assertEquals("application/msword", getContentType("test.doc"));
+ assertEquals("text/html", getContentType("test.htx"));
+ assertEquals("text/xml", getContentType("test.xml"));
+ assertEquals("text/html",
+ new FileURLConnection(new URL("file:///")).getContentType());
+ }
+
+ public void testGetInputStream() throws IOException {
+ // Regression for Harmony-5737
+ URL url = createTempFileWithContent(RESOURCE_NAME);
+ assertNotNull(url);
+ URL anchorUrl = new URL(url, "#anchor");
+ assertNotNull("Cannot find test resource " + RESOURCE_NAME, anchorUrl);
+
+ FileURLConnection conn = new FileURLConnection(anchorUrl);
+ assertNotNull(conn.getInputStream());
+ }
+
+ public void testGetInputStream_localHost() throws IOException {
+ // Regression for Harmony-5779
+ URL url = createTempFileWithContent(RESOURCE_NAME);
+ String localURLString = "file://localhost/" + url.getFile();
+ URL localURL = new URL(localURLString);
+ FileURLConnection conn = new FileURLConnection(localURL);
+ assertNotNull(conn.getInputStream());
+ assertEquals("file", conn.getURL().getProtocol());
+ }
+
+ public void testHeaderFunctions() throws IOException {
+ URL url = createTempFileWithContent(RESOURCE_NAME);
+ FileURLConnection conn = new FileURLConnection(url);
+ assertNotNull(conn.getInputStream());
+ assertEquals(conn.getContentType(), conn.getHeaderField("content-type"));
+
+ url = createTempFileWithContent(RESOURCE_NAME);
+ conn = new FileURLConnection(url);
+
+ assertNotNull(conn.getInputStream());
+ assertEquals(conn.getContentType(), conn.getHeaderField("content-type"));
+ assertEquals(Integer.toString(conn.getContentLength()),
+ conn.getHeaderField("content-length"));
+ assertEquals(conn.getHeaderField(0), conn.getHeaderField("content-type"));
+ assertEquals(conn.getHeaderField(1), conn.getHeaderField("content-length"));
+ assertEquals(conn.getHeaderField(2), conn.getHeaderField("last-modified"));
+ assertEquals("last-modified", conn.getHeaderFieldKey(2));
+ assertEquals("content-length", conn.getHeaderFieldKey(1));
+ assertEquals("content-type", conn.getHeaderFieldKey(0));
+ }
+
+ public void testHeader_BoundaryCheck() throws IOException {
+ URL url = createTempFileWithContent(RESOURCE_NAME);
+ URLConnection urlConnection = url.openConnection();
+ assertNull(urlConnection.getHeaderField(Integer.MIN_VALUE));
+ assertNull(urlConnection.getHeaderField(Integer.MAX_VALUE));
+ assertNull(urlConnection.getHeaderFieldKey(Integer.MIN_VALUE));
+ assertNull(urlConnection.getHeaderFieldKey(Integer.MAX_VALUE));
+ assertNull(urlConnection.getHeaderField(null));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedInputStreamTest.java
new file mode 100644
index 0000000..a5ba9e1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedInputStreamTest.java
@@ -0,0 +1,562 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import junit.framework.TestCase;
+
+public class BufferedInputStreamTest extends TestCase {
+
+ private static final String INPUT =
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n" +
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n";
+
+ private BufferedInputStream is;
+ private InputStream isBytes;
+
+
+ /*
+ * java.io.BufferedInputStream(InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ try {
+ BufferedInputStream str = new BufferedInputStream(null);
+ str.read();
+ fail("Expected an IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /*
+ * java.io.BufferedInputStream(InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStreamI() throws IOException {
+ try {
+ BufferedInputStream str = new BufferedInputStream(null, 1);
+ str.read();
+ fail("Expected an IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ // Test for method java.io.BufferedInputStream(java.io.InputStream, int)
+
+ // Create buffer with hald size of file and fill it.
+ int bufferSize = INPUT.length() / 2;
+ is = new BufferedInputStream(isBytes, bufferSize);
+ // Ensure buffer gets filled by evaluating one read
+ is.read();
+ // Close underlying FileInputStream, all but 1 buffered bytes should
+ // still be available.
+ isBytes.close();
+ // Read the remaining buffered characters, no IOException should
+ // occur.
+ is.skip(bufferSize - 2);
+ is.read();
+ try {
+ // is.read should now throw an exception because it will have to
+ // be filled.
+ is.read();
+ fail("Exception should have been triggered by read()");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ // regression test for harmony-2407
+ new MockBufferedInputStream(null);
+ assertNotNull(MockBufferedInputStream.buf);
+ MockBufferedInputStream.buf = null;
+ new MockBufferedInputStream(null, 100);
+ assertNotNull(MockBufferedInputStream.buf);
+ }
+
+ static class MockBufferedInputStream extends BufferedInputStream {
+ static byte[] buf;
+
+ MockBufferedInputStream(InputStream is) throws IOException {
+ super(is);
+ buf = super.buf;
+ }
+
+ MockBufferedInputStream(InputStream is, int size) throws IOException {
+ super(is, size);
+ buf = super.buf;
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#available()
+ */
+ public void test_available() throws IOException {
+ assertTrue("Returned incorrect number of available bytes", is
+ .available() == INPUT.length());
+
+ // Test that a closed stream throws an IOE for available()
+ BufferedInputStream bis = new BufferedInputStream(
+ new ByteArrayInputStream(new byte[] { 'h', 'e', 'l', 'l', 'o',
+ ' ', 't', 'i', 'm' }));
+ int available = bis.available();
+ bis.close();
+ assertTrue(available != 0);
+
+ try {
+ bis.available();
+ fail("Expected test to throw IOE.");
+ } catch (IOException ex) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#close()
+ */
+ public void test_close() throws IOException {
+ new BufferedInputStream(isBytes).close();
+
+ // regression for HARMONY-667
+ BufferedInputStream buf = new BufferedInputStream(null, 5);
+ buf.close();
+
+ InputStream in = new InputStream() {
+ Object lock = new Object();
+
+ @Override
+ public int read() {
+ return 1;
+ }
+
+ @Override
+ public int read(byte[] buf, int offset, int length) {
+ synchronized (lock) {
+ try {
+ lock.wait(3000);
+ } catch (InterruptedException e) {
+ // Ignore
+ }
+ }
+ return 1;
+ }
+
+ @Override
+ public void close() {
+ synchronized (lock) {
+ lock.notifyAll();
+ }
+ }
+ };
+ final BufferedInputStream bufin = new BufferedInputStream(in);
+ Thread thread = new Thread(new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(1000);
+ bufin.close();
+ } catch (Exception e) {
+ // Ignored
+ }
+ }
+ });
+ thread.start();
+ try {
+ bufin.read(new byte[100], 0, 99);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#mark(int)
+ */
+ public void test_markI() throws IOException {
+ byte[] buf1 = new byte[100];
+ byte[] buf2 = new byte[100];
+ is.skip(50);
+ is.mark(500);
+ is.read(buf1, 0, buf1.length);
+ is.reset();
+ is.read(buf2, 0, buf2.length);
+ is.reset();
+ assertTrue("Failed to mark correct position", new String(buf1, 0,
+ buf1.length).equals(new String(buf2, 0, buf2.length)));
+
+ byte[] bytes = new byte[256];
+ for (int i = 0; i < 256; i++) {
+ bytes[i] = (byte) i;
+ }
+ InputStream in = new BufferedInputStream(
+ new ByteArrayInputStream(bytes), 12);
+ in.skip(6);
+ in.mark(14);
+ in.read(new byte[14], 0, 14);
+ in.reset();
+ assertTrue("Wrong bytes", in.read() == 6 && in.read() == 7);
+
+ in = new BufferedInputStream(new ByteArrayInputStream(bytes), 12);
+ in.skip(6);
+ in.mark(8);
+ in.skip(7);
+ in.reset();
+ assertTrue("Wrong bytes 2", in.read() == 6 && in.read() == 7);
+
+ BufferedInputStream buf = new BufferedInputStream(
+ new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 }), 2);
+ buf.mark(3);
+ bytes = new byte[3];
+ int result = buf.read(bytes);
+ assertEquals(3, result);
+ assertEquals("Assert 0:", 0, bytes[0]);
+ assertEquals("Assert 1:", 1, bytes[1]);
+ assertEquals("Assert 2:", 2, bytes[2]);
+ assertEquals("Assert 3:", 3, buf.read());
+
+ buf = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 0,
+ 1, 2, 3, 4 }), 2);
+ buf.mark(3);
+ bytes = new byte[4];
+ result = buf.read(bytes);
+ assertEquals(4, result);
+ assertEquals("Assert 4:", 0, bytes[0]);
+ assertEquals("Assert 5:", 1, bytes[1]);
+ assertEquals("Assert 6:", 2, bytes[2]);
+ assertEquals("Assert 7:", 3, bytes[3]);
+ assertEquals("Assert 8:", 4, buf.read());
+ assertEquals("Assert 9:", -1, buf.read());
+
+ buf = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 0,
+ 1, 2, 3, 4 }), 2);
+ buf.mark(Integer.MAX_VALUE);
+ buf.read();
+ buf.close();
+ }
+
+ /**
+ * java.io.BufferedInputStream#markSupported()
+ */
+ public void test_markSupported() {
+ assertTrue("markSupported returned incorrect value", is.markSupported());
+ }
+
+ /**
+ * java.io.BufferedInputStream#read()
+ */
+ public void test_read() throws IOException {
+ InputStreamReader isr = new InputStreamReader(is);
+ int c = isr.read();
+ assertEquals(INPUT.charAt(0), c);
+
+ byte[] bytes = new byte[256];
+ for (int i = 0; i < 256; i++) {
+ bytes[i] = (byte) i;
+ }
+ InputStream in = new BufferedInputStream(
+ new ByteArrayInputStream(bytes), 12);
+ assertEquals("Wrong initial byte", 0, in.read()); // Fill the
+ // buffer
+ byte[] buf = new byte[14];
+ in.read(buf, 0, 14); // Read greater than the buffer
+ assertTrue("Wrong block read data", new String(buf, 0, 14)
+ .equals(new String(bytes, 1, 14)));
+ assertEquals("Wrong bytes", 15, in.read()); // Check next byte
+ }
+
+ /**
+ * java.io.BufferedInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII_Exception() throws IOException {
+ BufferedInputStream bis = new BufferedInputStream(null);
+ try {
+ bis.read(null, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bis.read(new byte[0], -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bis.read(new byte[0], 1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bis.read(new byte[0], 1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bis.close();
+
+ try {
+ bis.read(null, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ byte[] buf1 = new byte[100];
+ is.skip(500);
+ is.mark(500);
+ is.read(buf1, 0, buf1.length);
+ assertTrue("Failed to read correct data", new String(buf1, 0,
+ buf1.length).equals(INPUT.substring(500, 600)));
+
+ BufferedInputStream bufin = new BufferedInputStream(new InputStream() {
+ int size = 2
+ ,
+ pos = 0;
+
+ byte[] contents = new byte[size];
+
+ @Override
+ public int read() throws IOException {
+ if (pos >= size) {
+ throw new IOException("Read past end of data");
+ }
+ return contents[pos++];
+ }
+
+ @Override
+ public int read(byte[] buf, int off, int len) throws IOException {
+ if (pos >= size) {
+ throw new IOException("Read past end of data");
+ }
+ int toRead = len;
+ if (toRead > available()) {
+ toRead = available();
+ }
+ System.arraycopy(contents, pos, buf, off, toRead);
+ pos += toRead;
+ return toRead;
+ }
+
+ @Override
+ public int available() {
+ return size - pos;
+ }
+ });
+ bufin.read();
+ int result = bufin.read(new byte[2], 0, 2);
+ assertTrue("Incorrect result: " + result, result == 1);
+ }
+
+ /**
+ * java.io.BufferedInputStream#reset()
+ */
+ public void test_reset() throws IOException {
+ byte[] buf1 = new byte[10];
+ byte[] buf2 = new byte[10];
+ is.mark(2000);
+ is.read(buf1, 0, 10);
+ is.reset();
+ is.read(buf2, 0, 10);
+ is.reset();
+ assertTrue("Reset failed", new String(buf1, 0, buf1.length)
+ .equals(new String(buf2, 0, buf2.length)));
+
+ BufferedInputStream bIn = new BufferedInputStream(
+ new ByteArrayInputStream("1234567890".getBytes()));
+ bIn.mark(10);
+ for (int i = 0; i < 11; i++) {
+ bIn.read();
+ }
+ bIn.reset();
+ }
+
+ /**
+ * java.io.BufferedInputStream#reset()
+ */
+ public void test_reset_Exception() throws IOException {
+ BufferedInputStream bis = new BufferedInputStream(null);
+
+ // throws IOException with message "Mark has been invalidated"
+ try {
+ bis.reset();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ // does not throw IOException
+ bis.mark(1);
+ bis.reset();
+
+ bis.close();
+
+ // throws IOException with message "stream is closed"
+ try {
+ bis.reset();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#reset()
+ */
+ public void test_reset_scenario1() throws IOException {
+ byte[] input = "12345678900".getBytes();
+ BufferedInputStream buffis = new BufferedInputStream(
+ new ByteArrayInputStream(input));
+ buffis.read();
+ buffis.mark(5);
+ buffis.skip(5);
+ buffis.reset();
+ }
+
+ /**
+ * java.io.BufferedInputStream#reset()
+ */
+ public void test_reset_scenario2() throws IOException {
+ byte[] input = "12345678900".getBytes();
+ BufferedInputStream buffis = new BufferedInputStream(
+ new ByteArrayInputStream(input));
+ buffis.mark(5);
+ buffis.skip(6);
+ buffis.reset();
+ }
+
+ /**
+ * java.io.BufferedInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ byte[] buf1 = new byte[10];
+ is.mark(2000);
+ is.skip(1000);
+ is.read(buf1, 0, buf1.length);
+ is.reset();
+ assertTrue("Failed to skip to correct position", new String(buf1, 0,
+ buf1.length).equals(INPUT.substring(1000, 1010)));
+
+ // regression for HARMONY-667
+ try {
+ BufferedInputStream buf = new BufferedInputStream(null, 5);
+ buf.skip(10);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.BufferedInputStream#skip(long)
+ */
+ public void test_skip_NullInputStream() throws IOException {
+ BufferedInputStream buf = new BufferedInputStream(null, 5);
+ assertEquals(0, buf.skip(0));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ @Override
+ protected void setUp() throws IOException {
+ File f = File.createTempFile("BufferedInputStreamTest", "tst");
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.write(INPUT.getBytes(StandardCharsets.US_ASCII));
+ fos.close();
+
+ isBytes = new FileInputStream(f.getAbsolutePath());
+ is = new BufferedInputStream(isBytes, INPUT.length() / 2);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ @Override
+ protected void tearDown() {
+ try {
+ is.close();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedOutputStreamTest.java
new file mode 100644
index 0000000..9c5bb2d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedOutputStreamTest.java
@@ -0,0 +1,849 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class BufferedOutputStreamTest extends junit.framework.TestCase {
+
+ private java.io.OutputStream os;
+
+ java.io.ByteArrayOutputStream baos;
+
+ java.io.ByteArrayInputStream bais;
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_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";
+
+ /**
+ * java.io.BufferedOutputStream#BufferedOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws IOException {
+ baos = new java.io.ByteArrayOutputStream();
+ os = new java.io.BufferedOutputStream(baos);
+ os.write(fileString.getBytes(), 0, 500);
+ }
+
+ /**
+ * java.io.BufferedOutputStream#BufferedOutputStream(java.io.OutputStream,
+ *int)
+ */
+ public void test_ConstructorLjava_io_OutputStreamI() throws IOException {
+ baos = new java.io.ByteArrayOutputStream();
+ os = new java.io.BufferedOutputStream(baos, 1024);
+ os.write(fileString.getBytes(), 0, 500);
+ }
+
+ public void test_flush_Constructor_NullStream() throws IOException {
+ BufferedOutputStream buffos = new java.io.BufferedOutputStream(null);
+ try {
+ buffos.flush();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ buffos.close();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ buffos = new java.io.BufferedOutputStream(null, 10);
+ try {
+ buffos.flush();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ buffos.close();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ new java.io.BufferedOutputStream(null, 0);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ new java.io.BufferedOutputStream(null, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#flush()
+ */
+ public void test_flush() throws IOException {
+ baos = new ByteArrayOutputStream();
+ os = new java.io.BufferedOutputStream(baos, 600);
+ os.write(fileString.getBytes(), 0, 500);
+ os.flush();
+ assertEquals("Bytes not written after flush", 500,
+ ((ByteArrayOutputStream) baos).size());
+ }
+
+ private static class MockOutputStream extends OutputStream {
+ byte[] written;
+ int count;
+
+ public MockOutputStream(int size) {
+ written = new byte[size];
+ count = 0;
+ }
+
+ public void write(int b) {
+ written[count++] = (byte) b;
+ }
+
+ public String getWritten() {
+ return new String(written, 0, count);
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ os = new BufferedOutputStream(baos = new ByteArrayOutputStream(), 512);
+ os.write(fileString.getBytes(), 0, 500);
+ bais = new ByteArrayInputStream(baos.toByteArray());
+ assertEquals("Bytes written, not buffered", 0, bais.available());
+ os.flush();
+ bais = new ByteArrayInputStream(baos.toByteArray());
+ assertEquals("Bytes not written after flush", 500, bais.available());
+ os.write(fileString.getBytes(), 500, 513);
+ bais = new ByteArrayInputStream(baos.toByteArray());
+ assertTrue("Bytes not written when buffer full",
+ bais.available() >= 1000);
+ byte[] wbytes = new byte[1013];
+ bais.read(wbytes, 0, 1013);
+ assertEquals("Incorrect bytes written", new String(wbytes, 0,
+ wbytes.length), fileString.substring(0, 1013));
+
+ // regression test for HARMONY-4177
+ MockOutputStream mos = new MockOutputStream(5);
+ BufferedOutputStream bos = new BufferedOutputStream(mos, 3);
+ bos.write("a".getBytes());
+ bos.write("bcde".getBytes());
+ assertEquals("Large data should be written directly", "abcde", mos
+ .getWritten());
+ mos = new MockOutputStream(4);
+ bos = new BufferedOutputStream(mos, 3);
+ bos.write("ab".getBytes());
+ bos.write("cd".getBytes());
+ assertEquals("Should flush before write", "ab", mos.getWritten());
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_Exception() throws IOException {
+ OutputStream bos = new BufferedOutputStream(new ByteArrayOutputStream());
+ byte[] nullByteArray = null;
+ byte[] byteArray = new byte[10];
+
+ try {
+ bos.write(nullByteArray, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, byteArray.length + 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 1, byteArray.length);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, byteArray.length);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, byteArray.length, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ bos.write(byteArray, byteArray.length, 0);
+ try {
+ bos.write(byteArray, byteArray.length, 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.write(byteArray, 0, 0);
+ bos.write(byteArray, 0, 1);
+ bos.write(byteArray, 1, byteArray.length - 1);
+ bos.write(byteArray, 0, byteArray.length);
+
+ try {
+ bos.write(byteArray, 1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.write(byteArray, 1, 0);
+ bos.write(byteArray, 1, 1);
+
+ bos.write(byteArray, byteArray.length, 0);
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.close();
+
+ try {
+ bos.write(byteArray, -1, -1);
+ fail();
+ } catch (IOException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bos.write(null, -1, -1);
+ fail();
+ } catch (IOException expected) {
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ bos.write(null, 0, 1);
+ fail();
+ } catch (IOException expected) {
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_NullStream_NullArray() throws IOException {
+ OutputStream bos = new BufferedOutputStream(null);
+ byte[] nullByteArray = null;
+
+ try {
+ bos.write(nullByteArray, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_NullStream_NullArray_Size() throws IOException {
+ OutputStream bos = new BufferedOutputStream(null, 1);
+ byte[] nullByteArray = null;
+
+ try {
+ bos.write(nullByteArray, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_NullStream() throws IOException {
+ BufferedOutputStream bos = new BufferedOutputStream(null);
+ byte[] byteArray = new byte[10];
+
+ try {
+ bos.write(byteArray, -1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.write(byteArray, 0, 0);
+
+ bos.write(byteArray, 1, 0);
+
+ bos.write(byteArray, byteArray.length, 0);
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.write(byteArray, 0, 1);
+ bos.write(byteArray, 1, 1);
+
+ bos.write(byteArray, 0, byteArray.length);
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_NullStream_Size() throws IOException {
+ BufferedOutputStream bos = new BufferedOutputStream(null, 1);
+ byte[] byteArray = new byte[10];
+
+ try {
+ bos.write(byteArray, -1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bos.write(byteArray, 0, 0);
+
+ bos.write(byteArray, 1, 0);
+
+ bos.write(byteArray, byteArray.length, 0);
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 0);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 0, byteArray.length);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bos.write(byteArray, byteArray.length + 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedOutputStream#write(int)
+ */
+ public void test_writeI() throws IOException {
+ baos = new java.io.ByteArrayOutputStream();
+ os = new java.io.BufferedOutputStream(baos);
+ os.write('t');
+ bais = new java.io.ByteArrayInputStream(baos.toByteArray());
+ assertEquals("Byte written, not buffered", 0, bais.available());
+ os.flush();
+ bais = new java.io.ByteArrayInputStream(baos.toByteArray());
+ assertEquals("Byte not written after flush", 1, bais.available());
+ byte[] wbytes = new byte[1];
+ bais.read(wbytes, 0, 1);
+ assertEquals("Incorrect byte written", 't', wbytes[0]);
+ }
+
+ public void test_write_Close() throws IOException {
+ BufferedOutputStream buffos = new BufferedOutputStream(
+ new ByteArrayOutputStream());
+ buffos.write(new byte[0]);
+ try {
+ buffos.write(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ byte[] buffer = "1234567890".getBytes();
+
+ buffos.write(Integer.MIN_VALUE);
+ buffos.write(Integer.MAX_VALUE);
+ buffos.write(buffer, 0, 10);
+ buffos.flush();
+
+ buffos.close();
+ }
+
+ public void test_write_Scenario1() throws IOException {
+ ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();
+ ByteArrayInputStream byteArrayis = null;
+ byte[] buffer = "1234567890".getBytes("UTF-8");
+
+ BufferedOutputStream buffos = new BufferedOutputStream(byteArrayos, 10);
+ buffos.write(buffer, 0, 10);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 10, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 10, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+
+ buffos.write(buffer, 0, 10);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 20, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 20, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+
+ buffos.write(buffer, 0, 10);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 30, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 30, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ }
+
+ public void test_write_Scenario2() throws IOException {
+ ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();
+ ByteArrayInputStream byteArrayis = null;
+ byte[] buffer = "1234567890".getBytes("UTF-8");
+
+ BufferedOutputStream buffos = new BufferedOutputStream(byteArrayos, 20);
+ buffos.write(buffer, 0, 10);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 0, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 10, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+
+ byte[] buffer2 = new byte[] { 'a', 'b', 'c', 'd' };
+ buffos.write(buffer2, 0, 4);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 10, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 14, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 4; i++) {
+ assertEquals(buffer2[i], byteArrayis.read());
+ }
+
+ byte[] buffer3 = new byte[] { 'e', 'f', 'g', 'h', 'i' };
+ buffos.write(buffer3, 0, 5);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 14, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 19, byteArrayis
+ .available());
+ for (int i = 0; i < 10; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 4; i++) {
+ assertEquals(buffer2[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 5; i++) {
+ assertEquals(buffer3[i], byteArrayis.read());
+ }
+
+ buffos.write(new byte[] { 'j', 'k' });
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 19, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 21, byteArrayis
+ .available());
+
+ buffos.close();
+ }
+
+ public void test_write_Scenario3() throws IOException {
+ ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();
+ ByteArrayInputStream byteArrayis = null;
+ byte[] buffer = "1234567890".getBytes("UTF-8");
+
+ BufferedOutputStream buffos = new BufferedOutputStream(byteArrayos, 5);
+ buffos.write(buffer, 0, 4);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 0, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 4, byteArrayis
+ .available());
+ for (int i = 0; i < 4; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+
+ buffos.write(buffer, 0, 5);
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes written, not buffered", 9, byteArrayis.available());
+ buffos.flush();
+ byteArrayis = new ByteArrayInputStream(byteArrayos.toByteArray());
+ assertEquals("Bytes not written after flush", 9, byteArrayis
+ .available());
+ for (int i = 0; i < 4; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ for (int i = 0; i < 5; i++) {
+ assertEquals(buffer[i], byteArrayis.read());
+ }
+ }
+
+ // Regression test for flush on closed stream
+ public void test_flush_on_closed_stream() throws IOException {
+ BufferedOutputStream bos = new BufferedOutputStream(new ByteArrayOutputStream());
+ bos.close();
+ try {
+ bos.flush(); // RI does not throw exception
+ } catch (IOException expected) { // but Android does
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws IOException {
+ if (bais != null) {
+ bais.close();
+ }
+ if (os != null) {
+ os.close();
+ }
+ if (baos != null) {
+ baos.close();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedReaderTest.java
index f101c73..1da9502 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedReaderTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.luni.tests.java.io;
+package org.apache.harmony.tests.java.io;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedWriterTest.java
new file mode 100644
index 0000000..d1bb971
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/BufferedWriterTest.java
@@ -0,0 +1,302 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+import tests.support.Support_StringWriter;
+
+public class BufferedWriterTest extends junit.framework.TestCase {
+
+ BufferedWriter bw;
+
+ Support_StringWriter sw;
+
+ public 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";
+
+ /**
+ * java.io.BufferedWriter#BufferedWriter(java.io.Writer)
+ */
+ public void test_ConstructorLjava_io_Writer() {
+ sw = new Support_StringWriter();
+ bw = new BufferedWriter(sw);
+ sw.write("Hi");
+ assertEquals("Constructor failed", "Hi", sw.toString());
+ }
+
+ /**
+ * java.io.BufferedWriter#BufferedWriter(java.io.Writer, int)
+ */
+ public void test_ConstructorLjava_io_WriterI() {
+ assertTrue("Used in tests", true);
+ }
+
+ private static class MockWriter extends Writer {
+ StringBuffer sb = new StringBuffer();
+ boolean flushCalled = false;
+
+ public void write(char[] buf, int off, int len) throws IOException {
+ for (int i = off; i < off + len; i++) {
+ sb.append(buf[i]);
+ }
+ }
+
+ public void close() throws IOException {
+ // Empty
+ }
+
+ public void flush() throws IOException {
+ flushCalled = true;
+ }
+
+ public String getWritten() {
+ return sb.toString();
+ }
+
+ public boolean isFlushCalled() {
+ return flushCalled;
+ }
+ }
+
+ /**
+ * java.io.BufferedWriter#close()
+ */
+ public void test_close() throws IOException {
+ try {
+ bw.close();
+ bw.write(testString);
+ fail("Writing to a closed stream should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ assertTrue("Write after close", !sw.toString().equals(testString));
+
+ // Regression test for HARMONY-4178
+ MockWriter mw = new MockWriter();
+ BufferedWriter bw = new BufferedWriter(mw);
+ bw.write('a');
+ bw.close();
+
+ // flush should not be called on underlying stream
+ assertFalse("Flush was called in the underlying stream", mw
+ .isFlushCalled());
+
+ // on the other hand the BufferedWriter itself should flush the
+ // buffer
+ assertEquals("BufferdWriter do not flush itself before close", "a", mw
+ .getWritten());
+ }
+
+ /**
+ * @throws IOException
+ * java.io.BufferedWriter#close()
+ */
+ public void test_close2() throws IOException {
+ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream()));
+ bw.close();
+ }
+
+ /**
+ * java.io.BufferedWriter#flush()
+ */
+ public void test_flush() throws Exception {
+ bw.write("This should not cause a flush");
+ assertTrue("Bytes written without flush", sw.toString().equals(""));
+ bw.flush();
+ assertEquals("Bytes not flushed", "This should not cause a flush", sw
+ .toString());
+ }
+
+ /**
+ * java.io.BufferedWriter#newLine()
+ */
+ public void test_newLine() throws Exception {
+ String separator = System.getProperty("line.separator");
+ bw.write("Hello");
+ bw.newLine();
+ bw.write("World");
+ bw.flush();
+ assertTrue("Incorrect string written: " + sw.toString(), sw.toString()
+ .equals("Hello" + separator + "World"));
+ }
+
+ /**
+ * java.io.BufferedWriter#write(char[], int, int)
+ */
+ public void test_write$CII() throws Exception {
+ char[] testCharArray = testString.toCharArray();
+ bw.write(testCharArray, 500, 1000);
+ bw.flush();
+ assertTrue("Incorrect string written", sw.toString().equals(
+ testString.substring(500, 1500)));
+ }
+
+ /**
+ * java.io.BufferedWriter#write(char[], int, int)
+ */
+ public void test_write_$CII_Exception() throws IOException {
+ BufferedWriter bWriter = new BufferedWriter(sw);
+ char[] nullCharArray = null;
+
+ try {
+ bWriter.write(nullCharArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bWriter.write(nullCharArray, -1, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bWriter.write(nullCharArray, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ bWriter.write(nullCharArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ char[] testCharArray = testString.toCharArray();
+
+ bWriter.write(testCharArray, 0, 0);
+
+ bWriter.write(testCharArray, testCharArray.length, 0);
+
+ try {
+ bWriter.write(testCharArray, testCharArray.length + 1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bWriter.close();
+
+ try {
+ bWriter.write(nullCharArray, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.BufferedWriter#write(int)
+ */
+ public void test_writeI() throws Exception {
+ bw.write('T');
+ assertTrue("Char written without flush", sw.toString().equals(""));
+ bw.flush();
+ assertEquals("Incorrect char written", "T", sw.toString());
+ }
+
+ /**
+ * java.io.BufferedWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() throws Exception {
+ bw.write(testString);
+ bw.flush();
+ assertTrue("Incorrect string written", sw.toString().equals(testString));
+ }
+
+ /**
+ * java.io.BufferedWriter#write(java.lang.String, int, int)
+ */
+ public void test_write_LStringII_Exception() throws IOException {
+ BufferedWriter bWriter = new BufferedWriter(sw);
+
+ bWriter.write((String) null, -1, -1);
+ bWriter.write((String) null, -1, 0);
+ bWriter.write((String) null, 0, -1);
+ bWriter.write((String) null, 0, 0);
+
+ try {
+ bWriter.write((String) null, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ bWriter.write(testString, 0, 0);
+ bWriter.write(testString, testString.length(), 0);
+ bWriter.write(testString, testString.length() + 1, 0);
+
+ try {
+ bWriter.write(testString, testString.length() + 1, 1);
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // expected
+ }
+
+ bWriter.close();
+
+ try {
+ bWriter.write((String) null, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ bWriter.write((String) null, -1, 1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ bWriter.write(testString, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ sw = new Support_StringWriter();
+ bw = new BufferedWriter(sw, 500);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ bw.close();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayInputStreamTest.java
new file mode 100644
index 0000000..4ab972d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayInputStreamTest.java
@@ -0,0 +1,180 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class ByteArrayInputStreamTest extends junit.framework.TestCase {
+
+ private InputStream is;
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
+
+ /**
+ * ByteArrayInputStream#ByteArrayInputStream(byte[])
+ */
+ public void test_Constructor$B() throws IOException {
+ InputStream bis = new ByteArrayInputStream(fileString.getBytes());
+
+ assertTrue("Unable to create ByteArrayInputStream",
+ bis.available() == fileString.length());
+ }
+
+ /**
+ * ByteArrayInputStream#ByteArrayInputStream(byte[], int, int)
+ */
+ public void test_Constructor$BII() throws IOException {
+ byte[] zz = fileString.getBytes();
+ InputStream bis = new ByteArrayInputStream(zz, 0, 100);
+
+ assertEquals("Unable to create ByteArrayInputStream", 100, bis
+ .available());
+
+ // Regression test for Harmony-2405
+ new SubByteArrayInputStream(new byte[] { 1, 2 }, 444, 13);
+ assertEquals(444, SubByteArrayInputStream.pos);
+ assertEquals(444, SubByteArrayInputStream.mark);
+ assertEquals(2, SubByteArrayInputStream.count);
+ }
+
+ static class SubByteArrayInputStream extends ByteArrayInputStream {
+ public static byte[] buf;
+
+ public static int mark, pos, count;
+
+ SubByteArrayInputStream(byte[] buf, int offset, int length)
+ throws IOException {
+ super(buf, offset, length);
+ buf = super.buf;
+ mark = super.mark;
+ pos = super.pos;
+ count = super.count;
+ }
+ }
+
+ /**
+ * ByteArrayInputStream#available()
+ */
+ public void test_available() throws IOException {
+ assertTrue("Returned incorrect number of available bytes", is
+ .available() == fileString.length());
+ }
+
+ /**
+ * ByteArrayInputStream#close()
+ */
+ public void test_close() throws IOException {
+ is.read();
+ is.close();
+ is.read(); // Should be able to read from a closed stream
+ }
+
+ /**
+ * ByteArrayInputStream#mark(int)
+ */
+ public void test_markI() throws IOException {
+ byte[] buf1 = new byte[100];
+ byte[] buf2 = new byte[100];
+ is.skip(3000);
+ is.mark(1000);
+ is.read(buf1, 0, buf1.length);
+ is.reset();
+ is.read(buf2, 0, buf2.length);
+ is.reset();
+ assertTrue("Failed to mark correct position", new String(buf1, 0,
+ buf1.length).equals(new String(buf2, 0, buf2.length)));
+ }
+
+ /**
+ * ByteArrayInputStream#markSupported()
+ */
+ public void test_markSupported() {
+ assertTrue("markSupported returned incorrect value", is.markSupported());
+ }
+
+ /**
+ * ByteArrayInputStream#read()
+ */
+ public void test_read() throws IOException {
+ InputStreamReader isr = new InputStreamReader(is);
+ int c = isr.read();
+ is.reset();
+ assertTrue("read returned incorrect char", c == fileString.charAt(0));
+ }
+
+ /**
+ * ByteArrayInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ byte[] buf1 = new byte[20];
+ is.skip(50);
+ is.mark(100);
+ is.read(buf1, 0, buf1.length);
+ assertTrue("Failed to read correct data", new String(buf1, 0,
+ buf1.length).equals(fileString.substring(50, 70)));
+ }
+
+ /**
+ * ByteArrayInputStream#reset()
+ */
+ public void test_reset() throws IOException {
+ byte[] buf1 = new byte[10];
+ byte[] buf2 = new byte[10];
+ is.mark(200);
+ is.read(buf1, 0, 10);
+ is.reset();
+ is.read(buf2, 0, 10);
+ is.reset();
+ assertTrue("Reset failed", new String(buf1, 0, buf1.length)
+ .equals(new String(buf2, 0, buf2.length)));
+ }
+
+ /**
+ * ByteArrayInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ byte[] buf1 = new byte[10];
+ is.skip(100);
+ is.read(buf1, 0, buf1.length);
+ assertTrue("Failed to skip to correct position", new String(buf1, 0,
+ buf1.length).equals(fileString.substring(100, 110)));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ is = new ByteArrayInputStream(fileString.getBytes());
+
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ is.close();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayOutputStreamTest.java
new file mode 100644
index 0000000..9e95de1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ByteArrayOutputStreamTest.java
@@ -0,0 +1,213 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+
+import junit.framework.TestCase;
+
+/**
+ * Automated Test Suite for class java.io.ByteArrayOutputStream
+ *
+ * @see java.io.ByteArrayOutputStream
+ */
+public class ByteArrayOutputStreamTest extends TestCase {
+
+ ByteArrayOutputStream bos = null;
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws Exception {
+ try {
+ bos.close();
+ } catch (Exception ignore) {
+ }
+ super.tearDown();
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#ByteArrayOutputStream(int)
+ */
+ public void test_ConstructorI() {
+ bos = new ByteArrayOutputStream(100);
+ assertEquals("Failed to create stream", 0, bos.size());
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#ByteArrayOutputStream()
+ */
+ public void test_Constructor() {
+ bos = new ByteArrayOutputStream();
+ assertEquals("Failed to create stream", 0, bos.size());
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#close()
+ */
+ public void test_close() {
+ // close() does nothing for this implementation of OutputSteam
+
+ // The spec seems to say that a closed output stream can't be written
+ // to. We don't throw an exception if attempt is made to write.
+ // Right now our implementation doesn't do anything testable but
+ // should we decide to throw an exception if a closed stream is
+ // written to, the appropriate test is commented out below.
+
+ /***********************************************************************
+ * java.io.ByteArrayOutputStream bos = new
+ * java.io.ByteArrayOutputStream(); bos.write (fileString.getBytes(), 0,
+ * 100); try { bos.close(); } catch (java.io.IOException e) {
+ * fail("IOException closing stream"); } try { bos.write
+ * (fileString.getBytes(), 0, 100); bos.toByteArray(); fail("Wrote to
+ * closed stream"); } catch (Exception e) { }
+ **********************************************************************/
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#reset()
+ */
+ public void test_reset() {
+ bos = new java.io.ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, 100);
+ bos.reset();
+ assertEquals("reset failed", 0, bos.size());
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#size()
+ */
+ public void test_size() {
+ bos = new java.io.ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, 100);
+ assertEquals("size test failed", 100, bos.size());
+ bos.reset();
+ assertEquals("size test failed", 0, bos.size());
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#toByteArray()
+ */
+ public void test_toByteArray() {
+ byte[] bytes;
+ byte[] sbytes = fileString.getBytes();
+ bos = new java.io.ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, fileString.length());
+ bytes = bos.toByteArray();
+ for (int i = 0; i < fileString.length(); i++) {
+ assertTrue("Error in byte array", bytes[i] == sbytes[i]);
+ }
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#toString(java.lang.String)
+ */
+ public void test_toStringLjava_lang_String() throws IOException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ bos.write(fileString.getBytes("UTF-8"), 0, fileString.length());
+ assertTrue("Returned incorrect 8859-1 String", bos.toString("8859_1")
+ .equals(fileString));
+
+ bos = new ByteArrayOutputStream();
+ bos.write(fileString.getBytes("UTF-8"), 0, fileString.length());
+ assertTrue("Returned incorrect 8859-2 String", bos.toString("8859_2")
+ .equals(fileString));
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#toString()
+ */
+ public void test_toString() {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, fileString.length());
+ assertTrue("Returned incorrect String", bos.toString().equals(
+ fileString));
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#toString(int)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_toStringI() {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, fileString.length());
+ assertTrue("Returned incorrect String",
+ bos.toString(5).length() == fileString.length());
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#write(int)
+ */
+ public void test_writeI() throws UnsupportedEncodingException {
+ bos = new ByteArrayOutputStream();
+ bos.write('t');
+ byte[] result = bos.toByteArray();
+ assertEquals("Wrote incorrect bytes", "t", new String(result, 0,
+ result.length, "UTF-8"));
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, 100);
+ byte[] result = bos.toByteArray();
+ assertTrue("Wrote incorrect bytes",
+ new String(result, 0, result.length).equals(fileString
+ .substring(0, 100)));
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII_2() {
+ // Regression for HARMONY-387
+ ByteArrayOutputStream obj = new ByteArrayOutputStream();
+ try {
+ obj.write(new byte[] { (byte) 0x00 }, -1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.ByteArrayOutputStream#writeTo(java.io.OutputStream)
+ */
+ public void test_writeToLjava_io_OutputStream() throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
+ bos.write(fileString.getBytes(), 0, 100);
+ bos.writeTo(bos2);
+ assertTrue("Returned incorrect String", bos2.toString().equals(
+ fileString.substring(0, 100)));
+
+ // Regression test for HARMONY-834
+ // no exception expected
+ new ByteArrayOutputStream().writeTo(new FileOutputStream(
+ new FileDescriptor()));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayReaderTest.java
new file mode 100644
index 0000000..8865332
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayReaderTest.java
@@ -0,0 +1,178 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.CharArrayReader;
+import java.io.IOException;
+
+public class CharArrayReaderTest extends junit.framework.TestCase {
+
+ char[] hw = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+
+ CharArrayReader cr;
+
+ /**
+ * java.io.CharArrayReader#CharArrayReader(char[])
+ */
+ public void test_Constructor$C() throws IOException {
+ cr = new CharArrayReader(hw);
+ assertTrue("Failed to create reader", cr.ready());
+ }
+
+ /**
+ * java.io.CharArrayReader#CharArrayReader(char[], int, int)
+ */
+ public void test_Constructor$CII() throws IOException {
+ cr = new CharArrayReader(hw, 5, 5);
+ assertTrue("Failed to create reader", cr.ready());
+
+ int c = cr.read();
+ assertTrue("Created incorrect reader--returned '" + (char) c
+ + "' intsead of 'W'", c == 'W');
+ }
+
+ /**
+ * java.io.CharArrayReader#close()
+ */
+ public void test_close() {
+ cr = new CharArrayReader(hw);
+ cr.close();
+ try {
+ cr.read();
+ fail("Failed to throw exception on read from closed stream");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ // No-op
+ cr.close();
+ }
+
+ /**
+ * java.io.CharArrayReader#mark(int)
+ */
+ public void test_markI() throws IOException {
+ cr = new CharArrayReader(hw);
+ cr.skip(5L);
+ cr.mark(100);
+ cr.read();
+ cr.reset();
+ assertEquals("Failed to mark correct position", 'W', cr.read());
+ }
+
+ /**
+ * java.io.CharArrayReader#markSupported()
+ */
+ public void test_markSupported() {
+ cr = new CharArrayReader(hw);
+ assertTrue("markSupported returned false", cr.markSupported());
+ }
+
+ /**
+ * java.io.CharArrayReader#read()
+ */
+ public void test_read() throws IOException {
+ cr = new CharArrayReader(hw);
+ assertEquals("Read returned incorrect char", 'H', cr.read());
+ cr = new CharArrayReader(new char[] { '\u8765' });
+ assertTrue("Incorrect double byte char", cr.read() == '\u8765');
+ }
+
+ /**
+ * java.io.CharArrayReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws IOException {
+ char[] c = new char[11];
+ cr = new CharArrayReader(hw);
+ cr.read(c, 1, 10);
+ assertTrue("Read returned incorrect chars", new String(c, 1, 10)
+ .equals(new String(hw, 0, 10)));
+ }
+
+ /**
+ * java.io.CharArrayReader#ready()
+ */
+ public void test_ready() throws IOException {
+ cr = new CharArrayReader(hw);
+ assertTrue("ready returned false", cr.ready());
+ cr.skip(1000);
+ assertTrue("ready returned true", !cr.ready());
+ cr.close();
+
+ try {
+ cr.ready();
+ fail("No exception 1");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ cr = new CharArrayReader(hw);
+ cr.close();
+ cr.ready();
+ fail("No exception 2");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.CharArrayReader#reset()
+ */
+ public void test_reset() throws IOException {
+ cr = new CharArrayReader(hw);
+ cr.skip(5L);
+ cr.mark(100);
+ cr.read();
+ cr.reset();
+ assertEquals("Reset failed to return to marker position", 'W', cr
+ .read());
+
+ // Regression for HARMONY-4357
+ String str = "offsetHello world!";
+ char[] data = new char[str.length()];
+ str.getChars(0, str.length(), data, 0);
+ int offsetLength = 6;
+ int length = data.length - offsetLength;
+
+ CharArrayReader reader = new CharArrayReader(data, offsetLength, length);
+ reader.reset();
+ for (int i = 0; i < length; i++) {
+ assertEquals(data[offsetLength + i], (char) reader.read());
+ }
+ }
+
+ /**
+ * java.io.CharArrayReader#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ cr = new CharArrayReader(hw);
+ long skipped = cr.skip(5L);
+
+ assertEquals("Failed to skip correct number of chars", 5L, skipped);
+ assertEquals("Skip skipped wrong chars", 'W', cr.read());
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ if (cr != null)
+ cr.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayWriterTest.java
new file mode 100644
index 0000000..951a1a1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharArrayWriterTest.java
@@ -0,0 +1,233 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.IOException;
+import java.io.StringWriter;
+
+public class CharArrayWriterTest extends junit.framework.TestCase {
+
+ char[] hw = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+
+ CharArrayWriter cw;
+
+ CharArrayReader cr;
+
+ /**
+ * java.io.CharArrayWriter#CharArrayWriter()
+ */
+ public void test_Constructor() {
+ cw = new CharArrayWriter(90);
+ assertEquals("Created incorrect writer", 0, cw.size());
+ }
+
+ /**
+ * java.io.CharArrayWriter#CharArrayWriter(int)
+ */
+ public void test_ConstructorI() {
+ cw = new CharArrayWriter();
+ assertEquals("Created incorrect writer", 0, cw.size());
+ }
+
+ /**
+ * java.io.CharArrayWriter#close()
+ */
+ public void test_close() {
+ cw.close();
+ }
+
+ /**
+ * java.io.CharArrayWriter#flush()
+ */
+ public void test_flush() {
+ cw.flush();
+ }
+
+ /**
+ * java.io.CharArrayWriter#reset()
+ */
+ public void test_reset() throws IOException {
+ cw.write("HelloWorld", 5, 5);
+ cw.reset();
+ cw.write("HelloWorld", 0, 5);
+ cr = new CharArrayReader(cw.toCharArray());
+ char[] c = new char[100];
+ cr.read(c, 0, 5);
+ assertEquals("Reset failed to reset buffer", "Hello", new String(c, 0,
+ 5));
+ }
+
+ /**
+ * java.io.CharArrayWriter#size()
+ */
+ public void test_size() {
+ assertEquals("Returned incorrect size", 0, cw.size());
+ cw.write(hw, 5, 5);
+ assertEquals("Returned incorrect size", 5, cw.size());
+ }
+
+ /**
+ * java.io.CharArrayWriter#toCharArray()
+ */
+ public void test_toCharArray() throws IOException {
+ cw.write("HelloWorld", 0, 10);
+ cr = new CharArrayReader(cw.toCharArray());
+ char[] c = new char[100];
+ cr.read(c, 0, 10);
+ assertEquals("toCharArray failed to return correct array",
+ "HelloWorld", new String(c, 0, 10));
+ }
+
+ /**
+ * java.io.CharArrayWriter#toString()
+ */
+ public void test_toString() {
+ cw.write("HelloWorld", 5, 5);
+ cr = new CharArrayReader(cw.toCharArray());
+ assertEquals("Returned incorrect string", "World", cw.toString());
+ }
+
+ /**
+ * java.io.CharArrayWriter#write(char[], int, int)
+ */
+ public void test_write$CII() throws IOException {
+ cw.write(hw, 5, 5);
+ cr = new CharArrayReader(cw.toCharArray());
+ char[] c = new char[100];
+ cr.read(c, 0, 5);
+ assertEquals("Writer failed to write correct chars", "World",
+ new String(c, 0, 5));
+ }
+
+ /**
+ * java.io.CharArrayWriter#write(char[], int, int)
+ */
+ public void test_write$CII_2() {
+ // Regression for HARMONY-387
+ CharArrayWriter obj = new CharArrayWriter();
+ try {
+ obj.write(new char[] { '0' }, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.CharArrayWriter#write(int)
+ */
+ public void test_writeI() throws IOException {
+ cw.write('T');
+ cr = new CharArrayReader(cw.toCharArray());
+ assertEquals("Writer failed to write char", 'T', cr.read());
+ }
+
+ /**
+ * java.io.CharArrayWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() throws IOException {
+ cw.write("HelloWorld", 5, 5);
+ cr = new CharArrayReader(cw.toCharArray());
+ char[] c = new char[100];
+ cr.read(c, 0, 5);
+ assertEquals("Writer failed to write correct chars", "World",
+ new String(c, 0, 5));
+ }
+
+ /**
+ * java.io.CharArrayWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII_2()
+ throws StringIndexOutOfBoundsException {
+ // Regression for HARMONY-387
+ CharArrayWriter obj = new CharArrayWriter();
+ try {
+ obj.write((String) null, -1, 0);
+ fail("NullPointerException expected");
+ } catch (NullPointerException t) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.CharArrayWriter#writeTo(java.io.Writer)
+ */
+ public void test_writeToLjava_io_Writer() throws IOException {
+ cw.write("HelloWorld", 0, 10);
+ StringWriter sw = new StringWriter();
+ cw.writeTo(sw);
+ assertEquals("Writer failed to write correct chars", "HelloWorld", sw
+ .toString());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ cw = new CharArrayWriter();
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ if (cr != null) {
+ cr.close();
+ }
+ cw.close();
+ }
+
+ /**
+ * java.io.CharArrayWriter#append(char)
+ */
+ public void test_appendChar() throws IOException {
+ char testChar = ' ';
+ CharArrayWriter writer = new CharArrayWriter(10);
+ writer.append(testChar);
+ writer.flush();
+ assertEquals(String.valueOf(testChar), writer.toString());
+ writer.close();
+ }
+
+ /**
+ * java.io.CharArrayWriter#append(CharSequence)
+ */
+ public void test_appendCharSequence() {
+ String testString = "My Test String";
+ CharArrayWriter writer = new CharArrayWriter(10);
+ writer.append(testString);
+ writer.flush();
+ assertEquals(testString, writer.toString());
+ writer.close();
+ }
+
+ /**
+ * java.io.CharArrayWriter#append(CharSequence, int, int)
+ */
+ public void test_appendCharSequenceIntInt() {
+ String testString = "My Test String";
+ CharArrayWriter writer = new CharArrayWriter(10);
+ writer.append(testString, 1, 3);
+ writer.flush();
+ assertEquals(testString.substring(1, 3), writer.toString());
+ writer.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharConversionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharConversionExceptionTest.java
new file mode 100644
index 0000000..c399793
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/CharConversionExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.CharConversionException;
+
+public class CharConversionExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.CharConversionException#CharConversionException()
+ */
+ public void test_Constructor() {
+ // Currently, there are no refs to CharConversionException so this is
+ // the best test we can do
+ try {
+ if (true) // BB: getting around LF
+ throw new CharConversionException();
+ fail("Exception not thrown");
+ } catch (CharConversionException e) {
+ assertNull(
+ "Exception defined with no message answers non-null to getMessage()",
+ e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.CharConversionException#CharConversionException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ if (true) // getting around LF
+ throw new CharConversionException("Blah");
+ fail("Exception not thrown");
+ } catch (CharConversionException e) {
+ assertEquals(
+ "Exception defined with no message answers non-null to getMessage()",
+ "Blah", e.getMessage());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ComputeSerialVersionUIDTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ComputeSerialVersionUIDTest.java
new file mode 100644
index 0000000..ee0e27d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ComputeSerialVersionUIDTest.java
@@ -0,0 +1,86 @@
+package org.apache.harmony.tests.java.io;
+
+import java.io.ObjectStreamClass;
+
+
+public class ComputeSerialVersionUIDTest extends junit.framework.TestCase {
+
+ public void testComputeSUIDClass() throws Exception {
+ assertEquals(-5877374382732244721L,
+ computeSerialVersionUID(SerializationTestClass.TestClassName1.class));
+ assertEquals(-2258784348609133821L,
+ computeSerialVersionUID(SerializationTestClass.TestClassName2T_T$T.class));
+ assertEquals(-5674447587118957354L,
+ computeSerialVersionUID(SerializationTestClass.TestClassModifierPublic.class));
+ assertEquals(8333249076871004334L,
+ computeSerialVersionUID(SerializationTestClass.TestClassModifierAbstract.class));
+ assertEquals(-6752991881983868187L,
+ computeSerialVersionUID(SerializationTestClass.TestClassModifierFinal.class));
+ assertEquals(-2046603329186110997L,
+ computeSerialVersionUID(SerializationTestClass.TestClassModifierInterface.class));
+ }
+
+ public void testComputeSUIDInterfaces() throws Exception {
+ assertEquals(2385879270919801624L, computeSerialVersionUID(SerializationTestClass.TestInterfaces.class));
+ assertEquals(-3876044724689092051L, computeSerialVersionUID(SerializationTestClass.TestInterfacesA.class));
+ assertEquals(6691168002125833763L, computeSerialVersionUID(SerializationTestClass.TestInterfacesAB.class));
+ assertEquals(-3862602835688739317L, computeSerialVersionUID(SerializationTestClass.TestInterfacesBA.class));
+ assertEquals(6153219913626150137L, computeSerialVersionUID(SerializationTestClass.TestInterfacesC.class));
+ assertEquals(-5230940296111061949L, computeSerialVersionUID(SerializationTestClass.TestInterfacesCA.class));
+ assertEquals(-561891731488612449L, computeSerialVersionUID(SerializationTestClass.TestInterfacesABC.class));
+ assertEquals(7173098887933679885L, computeSerialVersionUID(SerializationTestClass.TestInterfacesACB.class));
+ assertEquals(7417451177210251082L, computeSerialVersionUID(SerializationTestClass.TestInterfacesBAC.class));
+ assertEquals(6457265192863049241L, computeSerialVersionUID(SerializationTestClass.TestInterfacesBCA.class));
+ assertEquals( 5890948387530452778L, computeSerialVersionUID(SerializationTestClass.TestInterfacesCAB.class));
+ assertEquals(-7493935950381842313L, computeSerialVersionUID(SerializationTestClass.TestInterfacesCBA.class));
+ }
+
+
+ public void testComputeSUIDFields() throws Exception {
+ assertEquals(-30967666739349603L, computeSerialVersionUID(SerializationTestClass.TestFieldsNone.class));
+ assertEquals(8551211022820107208L, computeSerialVersionUID(SerializationTestClass.TestFieldsOneFinal.class));
+ assertEquals(-7774226929120968860L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoFinal.class));
+ assertEquals(-8196468848051541845L, computeSerialVersionUID(SerializationTestClass.TestFieldsOnePrivate.class));
+ assertEquals(-7861029019096564216L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoPrivate.class));
+ assertEquals(81248916710250820L, computeSerialVersionUID(SerializationTestClass.TestFieldsOneProtected.class));
+ assertEquals(280835377416490750L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoProtected.class));
+ assertEquals(-2290036437752730858L, computeSerialVersionUID(SerializationTestClass.TestFieldsOnePublic.class));
+ assertEquals(-6124932240571007214L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoPublic.class));
+ assertEquals(6101579853402497691L, computeSerialVersionUID(SerializationTestClass.TestFieldsOneStatic.class));
+ assertEquals(-7900976994549865116L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoStatic.class));
+ assertEquals(-4499355017417065560L, computeSerialVersionUID(SerializationTestClass.TestFieldsOneTransient.class));
+ assertEquals(3747907454018261619L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoTransient.class));
+ assertEquals(-4945042592592621725L, computeSerialVersionUID(SerializationTestClass.TestFieldsOneVolatile.class));
+ assertEquals(8983117060325881490L, computeSerialVersionUID(SerializationTestClass.TestFieldsTwoVolatile.class));
+ assertEquals(-8336483965186710722L, computeSerialVersionUID(SerializationTestClass.TestFieldSignatures.class));
+ }
+
+
+ public void testComputeSUIDConstructors() throws Exception {
+ assertEquals(-614706174292151857L, computeSerialVersionUID(SerializationTestClass.TestConstructorNone.class));
+ assertEquals(-3706135726712902027L, computeSerialVersionUID(SerializationTestClass.TestConstructorOne.class));
+ assertEquals(-8094991171016233719L, computeSerialVersionUID(SerializationTestClass.TestConstructorPrivate.class));
+ assertEquals(-8117933510362198687L, computeSerialVersionUID(SerializationTestClass.TestConstructorProtected.class));
+ assertEquals(9205589590060392077L, computeSerialVersionUID(SerializationTestClass.TestConstructorPublic.class));
+ assertEquals(5408111072458161992L, computeSerialVersionUID(SerializationTestClass.TestConstructorSignature.class));
+ assertEquals(625104530709630511L, computeSerialVersionUID(SerializationTestClass.TestConstructorTwo.class));
+ assertEquals(3737423569701135020L, computeSerialVersionUID(SerializationTestClass.TestConstructorTwoReverse.class));
+ }
+
+ public void testComputeSUIDMethods() throws Exception {
+ assertEquals(8872679581767836990L, computeSerialVersionUID(SerializationTestClass.TestMethodPrivate.class));
+ assertEquals(-4558121473827608582L, computeSerialVersionUID(SerializationTestClass.TestMethodAbstract.class));
+ assertEquals(4148772500508720405L, computeSerialVersionUID(SerializationTestClass.TestMethodFinal.class));
+ assertEquals(6329381817306256121L, computeSerialVersionUID(SerializationTestClass.TestMethodNative.class));
+ assertEquals(-2701115429311553102L, computeSerialVersionUID(SerializationTestClass.TestMethodProtected.class));
+ assertEquals(-4092306049997161465L, computeSerialVersionUID(SerializationTestClass.TestMethodPublic.class));
+ assertEquals(-7948580256486289776L, computeSerialVersionUID(SerializationTestClass.TestMethodStatic.class));
+ assertEquals(4085068229405300186L, computeSerialVersionUID(SerializationTestClass.TestMethodSignature.class));
+ assertEquals(-5743322978294773864L, computeSerialVersionUID(SerializationTestClass.TestMethodReturnSignature.class));
+ assertEquals(-6908429504335657476L, computeSerialVersionUID(SerializationTestClass.TestMethodSynchronized.class));
+ }
+
+ private static long computeSerialVersionUID(Class<?> clazz) {
+ return ObjectStreamClass.lookup(clazz).getSerialVersionUID();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ConsoleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ConsoleTest.java
new file mode 100644
index 0000000..99becf9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ConsoleTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestCase;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Console;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.lang.reflect.Constructor;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+
+/**
+ * This file is test for java.io.Console. Due to the redirect problem, it can
+ * only be run on Harmony.
+ *
+ * @since 1.6
+ */
+public class ConsoleTest extends TestCase {
+ private static final byte[] bytes = "hello world\n".getBytes();
+
+ private InputStream in = new ByteArrayInputStream(bytes);
+ private OutputStream out = new ByteArrayOutputStream();
+ private Console console = null;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ Constructor<Console> constructor =
+ Console.class.getDeclaredConstructor(InputStream.class, OutputStream.class);
+ constructor.setAccessible(true);
+ console = constructor.newInstance(in, out);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ console = null;
+ super.tearDown();
+ }
+
+ public void test_flush() {
+ console.flush();
+ assertFalse(console.writer().checkError());
+ }
+
+ public void test_format_LString_LObject() {
+ assertSame(console, console.format("%d %s", 1, "hello"));
+ String prompt = new String(((ByteArrayOutputStream) out).toByteArray());
+ assertEquals("1 hello", prompt);
+ }
+
+ public void test_printf_LString_LObject() {
+ Calendar c = new GregorianCalendar(1983, 2, 21);
+ assertSame(console, console.printf("%1$tm %1$te,%1$tY", c));
+ String prompt = new String(((ByteArrayOutputStream) out).toByteArray());
+ assertEquals("03 21,1983", prompt);
+ }
+
+ public void test_reader() throws IOException {
+ Reader reader1 = console.reader();
+ assertTrue(reader1.ready());
+ Reader reader2 = console.reader();
+ assertSame(reader1, reader2);
+ }
+
+ public void test_readLine() {
+ String line = console.readLine();
+ assertEquals("hello world", line);
+ }
+
+ public void test_readLine_LString_LObject() {
+ String line = console.readLine("%d %s", 2, "Please input a line of string to test:");
+ assertEquals("hello world", line);
+ String prompt = new String(((ByteArrayOutputStream) out).toByteArray());
+ assertEquals("2 Please input a line of string to test:", prompt);
+ }
+
+ /**
+ * {@link java.io.Console#writer()}
+ */
+ public void test_writer() {
+ PrintWriter writer1 = console.writer();
+ PrintWriter writer2 = console.writer();
+ assertSame(writer1, writer2);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataInputStreamTest.java
new file mode 100644
index 0000000..67a4e5f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataInputStreamTest.java
@@ -0,0 +1,594 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+
+public class DataInputStreamTest extends junit.framework.TestCase {
+
+ private DataOutputStream os;
+
+ private DataInputStream dis;
+
+ private ByteArrayOutputStream bos;
+
+ String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_DataInputStream\n";
+
+ /**
+ * java.io.DataInputStream#DataInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ try {
+ os.writeChar('t');
+ os.close();
+ openDataInputStream();
+ } finally {
+ dis.close();
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#read(byte[])
+ */
+ public void test_read$B() throws IOException {
+ os.write(fileString.getBytes());
+ os.close();
+ openDataInputStream();
+ byte rbytes[] = new byte[fileString.length()];
+ dis.read(rbytes);
+ assertTrue("Incorrect data read", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+ }
+
+ /**
+ * java.io.DataInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ os.write(fileString.getBytes());
+ os.close();
+ openDataInputStream();
+ byte rbytes[] = new byte[fileString.length()];
+ dis.read(rbytes, 0, rbytes.length);
+ assertTrue("Incorrect data read", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+ }
+
+ /**
+ * java.io.DataInputStream#readBoolean()
+ */
+ public void test_readBoolean() throws IOException {
+ os.writeBoolean(true);
+ os.close();
+ openDataInputStream();
+ assertTrue("Incorrect boolean written", dis.readBoolean());
+ }
+
+ /**
+ * java.io.DataInputStream#readByte()
+ */
+ public void test_readByte() throws IOException {
+ os.writeByte((byte) 127);
+ os.close();
+ openDataInputStream();
+ assertTrue("Incorrect byte read", dis.readByte() == (byte) 127);
+ }
+
+ /**
+ * java.io.DataInputStream#readChar()
+ */
+ public void test_readChar() throws IOException {
+ os.writeChar('t');
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect char read", 't', dis.readChar());
+ }
+
+ /**
+ * java.io.DataInputStream#readDouble()
+ */
+ public void test_readDouble() throws IOException {
+ os.writeDouble(2345.76834720202);
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect double read", 2345.76834720202, dis
+ .readDouble());
+ }
+
+ /**
+ * java.io.DataInputStream#readFloat()
+ */
+ public void test_readFloat() throws IOException {
+ os.writeFloat(29.08764f);
+ os.close();
+ openDataInputStream();
+ assertTrue("Incorrect float read", dis.readFloat() == 29.08764f);
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[])
+ */
+ public void test_readFully$B() throws IOException {
+ os.write(fileString.getBytes());
+ os.close();
+ openDataInputStream();
+ byte rbytes[] = new byte[fileString.length()];
+ dis.readFully(rbytes);
+ assertTrue("Incorrect data read", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII() throws IOException {
+ os.write(fileString.getBytes());
+ os.close();
+ openDataInputStream();
+ byte rbytes[] = new byte[fileString.length()];
+ dis.readFully(rbytes, 0, fileString.length());
+ assertTrue("Incorrect data read", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII_Exception() throws IOException {
+ DataInputStream is = new DataInputStream(new ByteArrayInputStream(
+ new byte[fileString.length()]));
+
+ byte[] byteArray = new byte[fileString.length()];
+
+ try {
+ is.readFully(byteArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(byteArray, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(byteArray, 1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ is.readFully(byteArray, -1, 0);
+ is.readFully(byteArray, 0, 0);
+ is.readFully(byteArray, 1, 0);
+
+ try {
+ is.readFully(byteArray, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ is.readFully(byteArray, 0, 1);
+ is.readFully(byteArray, 1, 1);
+ try {
+ is.readFully(byteArray, 0, Integer.MAX_VALUE);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII_NullArray() throws IOException {
+ DataInputStream is = new DataInputStream(new ByteArrayInputStream(
+ new byte[fileString.length()]));
+
+ byte[] nullByteArray = null;
+
+ try {
+ is.readFully(nullByteArray, -1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(nullByteArray, 1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ is.readFully(nullByteArray, -1, 0);
+ is.readFully(nullByteArray, 0, 0);
+ is.readFully(nullByteArray, 1, 0);
+
+ try {
+ is.readFully(nullByteArray, -1, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, Integer.MAX_VALUE);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII_NullStream() throws IOException {
+ DataInputStream is = new DataInputStream(null);
+ byte[] byteArray = new byte[fileString.length()];
+
+ try {
+ is.readFully(byteArray, -1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(byteArray, 0, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(byteArray, 1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ is.readFully(byteArray, -1, 0);
+ is.readFully(byteArray, 0, 0);
+ is.readFully(byteArray, 1, 0);
+
+ try {
+ is.readFully(byteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(byteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(byteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(byteArray, 0, Integer.MAX_VALUE);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII_NullStream_NullArray() throws IOException {
+ DataInputStream is = new DataInputStream(null);
+ byte[] nullByteArray = null;
+
+ try {
+ is.readFully(nullByteArray, -1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ is.readFully(nullByteArray, 1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ is.readFully(nullByteArray, -1, 0);
+ is.readFully(nullByteArray, 0, 0);
+ is.readFully(nullByteArray, 1, 0);
+
+ try {
+ is.readFully(nullByteArray, -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ is.readFully(nullByteArray, 0, Integer.MAX_VALUE);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#readInt()
+ */
+ public void test_readInt() throws IOException {
+ os.writeInt(768347202);
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect int read", 768347202, dis.readInt());
+ }
+
+ /**
+ * java.io.DataInputStream#readLine()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_readLine() throws IOException {
+ os.writeBytes("Hello");
+ os.close();
+ openDataInputStream();
+ String line = dis.readLine();
+ assertTrue("Incorrect line read: " + line, line.equals("Hello"));
+ }
+
+ /**
+ * java.io.DataInputStream#readLong()
+ */
+ public void test_readLong() throws IOException {
+ os.writeLong(9875645283333L);
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect long read", 9875645283333L, dis.readLong());
+ }
+
+ /**
+ * java.io.DataInputStream#readShort()
+ */
+ public void test_readShort() throws IOException {
+ os.writeShort(9875);
+ os.close();
+ openDataInputStream();
+ assertTrue("Incorrect short read", dis.readShort() == (short) 9875);
+ }
+
+ /**
+ * java.io.DataInputStream#readUnsignedByte()
+ */
+ public void test_readUnsignedByte() throws IOException {
+ os.writeByte((byte) -127);
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect byte read", 129, dis.readUnsignedByte());
+ }
+
+ /**
+ * java.io.DataInputStream#readUnsignedShort()
+ */
+ public void test_readUnsignedShort() throws IOException {
+ os.writeShort(9875);
+ os.close();
+ openDataInputStream();
+ assertEquals("Incorrect short read", 9875, dis.readUnsignedShort());
+ }
+
+ /**
+ * java.io.DataInputStream#readUTF()
+ */
+ public void test_readUTF() throws IOException {
+ os.writeUTF(unihw);
+ os.close();
+ openDataInputStream();
+ assertTrue("Failed to write string in UTF format",
+ dis.available() == unihw.length() + 2);
+ assertTrue("Incorrect string read", dis.readUTF().equals(unihw));
+ }
+
+ static class TestDataInputStream implements DataInput {
+ public boolean readBoolean() throws IOException {
+ return false;
+ }
+
+ public byte readByte() throws IOException {
+ return (byte) 0;
+ }
+
+ public char readChar() throws IOException {
+ return (char) 0;
+ }
+
+ public double readDouble() throws IOException {
+ return 0.0;
+ }
+
+ public float readFloat() throws IOException {
+ return (float) 0.0;
+ }
+
+ public void readFully(byte[] buffer) throws IOException {
+ }
+
+ public void readFully(byte[] buffer, int offset, int count)
+ throws IOException {
+ }
+
+ public int readInt() throws IOException {
+ return 0;
+ }
+
+ public String readLine() throws IOException {
+ return null;
+ }
+
+ public long readLong() throws IOException {
+ return (long) 0;
+ }
+
+ public short readShort() throws IOException {
+ return (short) 0;
+ }
+
+ public int readUnsignedByte() throws IOException {
+ return 0;
+ }
+
+ public int readUnsignedShort() throws IOException {
+ return 0;
+ }
+
+ public String readUTF() throws IOException {
+ return DataInputStream.readUTF(this);
+ }
+
+ public int skipBytes(int count) throws IOException {
+ return 0;
+ }
+ }
+
+ /**
+ * java.io.DataInputStream#readUTF(java.io.DataInput)
+ */
+ public void test_readUTFLjava_io_DataInput() throws IOException {
+ os.writeUTF(unihw);
+ os.close();
+ openDataInputStream();
+ assertTrue("Failed to write string in UTF format",
+ dis.available() == unihw.length() + 2);
+ assertTrue("Incorrect string read", DataInputStream.readUTF(dis)
+ .equals(unihw));
+
+ // Regression test for HARMONY-5336
+ new TestDataInputStream().readUTF();
+ }
+
+ /**
+ * java.io.DataInputStream#skipBytes(int)
+ */
+ public void test_skipBytesI() throws IOException {
+ byte fileBytes[] = fileString.getBytes();
+ os.write(fileBytes);
+ os.close();
+ openDataInputStream();
+ dis.skipBytes(100);
+ byte rbytes[] = new byte[fileString.length()];
+ dis.read(rbytes, 0, 50);
+ dis.close();
+ assertTrue("Incorrect data read", new String(rbytes, 0, 50)
+ .equals(fileString.substring(100, 150)));
+
+ int skipped = 0;
+ openDataInputStream();
+ try {
+ skipped = dis.skipBytes(50000);
+ } catch (EOFException e) {
+ }
+ assertTrue("Skipped should report " + fileString.length() + " not "
+ + skipped, skipped == fileString.length());
+ }
+
+ private void openDataInputStream() throws IOException {
+ dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ bos = new ByteArrayOutputStream();
+ os = new DataOutputStream(bos);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ os.close();
+ } catch (Exception e) {
+ }
+ try {
+ dis.close();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataOutputStreamTest.java
new file mode 100644
index 0000000..1f124f1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/DataOutputStreamTest.java
@@ -0,0 +1,262 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+public class DataOutputStreamTest extends junit.framework.TestCase {
+
+ private DataOutputStream os;
+
+ private DataInputStream dis;
+
+ private ByteArrayOutputStream bos;
+
+ String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
+
+ 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";
+
+ /**
+ * java.io.DataOutputStream#DataOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ assertTrue("Used in all tests", true);
+ }
+
+ /**
+ * java.io.DataOutputStream#flush()
+ */
+ public void test_flush() throws IOException {
+ os.writeInt(9087589);
+ os.flush();
+ openDataInputStream();
+ int c = dis.readInt();
+ dis.close();
+ assertEquals("Failed to flush correctly", 9087589, c);
+ }
+
+ /**
+ * java.io.DataOutputStream#size()
+ */
+ public void test_size() throws IOException {
+ os.write(fileString.getBytes(), 0, 150);
+ os.close();
+ openDataInputStream();
+ byte[] rbuf = new byte[150];
+ dis.read(rbuf, 0, 150);
+ dis.close();
+ assertEquals("Incorrect size returned", 150, os.size());
+ }
+
+ /**
+ * java.io.DataOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ os.write(fileString.getBytes(), 0, 150);
+ os.close();
+ openDataInputStream();
+ byte[] rbuf = new byte[150];
+ dis.read(rbuf, 0, 150);
+ dis.close();
+ assertTrue("Incorrect bytes written", new String(rbuf, 0, 150)
+ .equals(fileString.substring(0, 150)));
+ }
+
+ /**
+ * java.io.DataOutputStream#write(int)
+ */
+ public void test_writeI() throws IOException {
+ os.write((int) 't');
+ os.close();
+ openDataInputStream();
+ int c = dis.read();
+ dis.close();
+ assertTrue("Incorrect int written", (int) 't' == c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeBoolean(boolean)
+ */
+ public void test_writeBooleanZ() throws IOException {
+ os.writeBoolean(true);
+ os.close();
+ openDataInputStream();
+ boolean c = dis.readBoolean();
+ dis.close();
+ assertTrue("Incorrect boolean written", c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeByte(int)
+ */
+ public void test_writeByteI() throws IOException {
+ os.writeByte((byte) 127);
+ os.close();
+ openDataInputStream();
+ byte c = dis.readByte();
+ dis.close();
+ assertTrue("Incorrect byte written", c == (byte) 127);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeBytes(java.lang.String)
+ */
+ public void test_writeBytesLjava_lang_String() throws IOException {
+ os.write(fileString.getBytes());
+ os.close();
+ openDataInputStream();
+ byte[] rbuf = new byte[4000];
+ dis.read(rbuf, 0, fileString.length());
+ dis.close();
+ assertTrue("Incorrect bytes written", new String(rbuf, 0, fileString
+ .length()).equals(fileString));
+
+ // regression test for HARMONY-1101
+ new DataOutputStream(null).writeBytes("");
+ }
+
+ /**
+ * java.io.DataOutputStream#writeChar(int)
+ */
+ public void test_writeCharI() throws IOException {
+ os.writeChar('T');
+ os.close();
+ openDataInputStream();
+ char c = dis.readChar();
+ dis.close();
+ assertEquals("Incorrect char written", 'T', c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeChars(java.lang.String)
+ */
+ public void test_writeCharsLjava_lang_String() throws IOException {
+ os.writeChars("Test String");
+ os.close();
+ openDataInputStream();
+ char[] chars = new char[50];
+ int i, a = dis.available() / 2;
+ for (i = 0; i < a; i++)
+ chars[i] = dis.readChar();
+ assertEquals("Incorrect chars written", "Test String", new String(
+ chars, 0, i));
+ }
+
+ /**
+ * java.io.DataOutputStream#writeDouble(double)
+ */
+ public void test_writeDoubleD() throws IOException {
+ os.writeDouble(908755555456.98);
+ os.close();
+ openDataInputStream();
+ double c = dis.readDouble();
+ dis.close();
+ assertEquals("Incorrect double written", 908755555456.98, c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeFloat(float)
+ */
+ public void test_writeFloatF() throws IOException {
+ os.writeFloat(9087.456f);
+ os.close();
+ openDataInputStream();
+ float c = dis.readFloat();
+ dis.close();
+ assertTrue("Incorrect float written", c == 9087.456f);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeInt(int)
+ */
+ public void test_writeIntI() throws IOException {
+ os.writeInt(9087589);
+ os.close();
+ openDataInputStream();
+ int c = dis.readInt();
+ dis.close();
+ assertEquals("Incorrect int written", 9087589, c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeLong(long)
+ */
+ public void test_writeLongJ() throws IOException {
+ os.writeLong(908755555456L);
+ os.close();
+ openDataInputStream();
+ long c = dis.readLong();
+ dis.close();
+ assertEquals("Incorrect long written", 908755555456L, c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeShort(int)
+ */
+ public void test_writeShortI() throws IOException {
+ os.writeShort((short) 9087);
+ os.close();
+ openDataInputStream();
+ short c = dis.readShort();
+ dis.close();
+ assertEquals("Incorrect short written", 9087, c);
+ }
+
+ /**
+ * java.io.DataOutputStream#writeUTF(java.lang.String)
+ */
+ public void test_writeUTFLjava_lang_String() throws IOException {
+ os.writeUTF(unihw);
+ os.close();
+ openDataInputStream();
+ assertTrue("Failed to write string in UTF format",
+ dis.available() == unihw.length() + 2);
+ assertTrue("Incorrect string returned", dis.readUTF().equals(unihw));
+ }
+
+ private void openDataInputStream() throws IOException {
+ dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ bos = new ByteArrayOutputStream();
+ os = new DataOutputStream(bos);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ if (os != null)
+ os.close();
+ if (dis != null)
+ dis.close();
+ } catch (IOException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/EOFExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/EOFExceptionTest.java
new file mode 100644
index 0000000..1610816
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/EOFExceptionTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+
+public class EOFExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.EOFException#EOFException()
+ */
+ public void test_Constructor() throws Exception {
+ try {
+ new DataInputStream(new ByteArrayInputStream(new byte[1]))
+ .readShort();
+ fail("Failed to generate EOFException");
+ } catch (EOFException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.EOFException#EOFException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ try {
+ new DataInputStream(new ByteArrayInputStream(new byte[1]))
+ .readShort();
+ fail("Failed to generate EOFException");
+ } catch (EOFException e) {
+ // Expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileDescriptorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileDescriptorTest.java
new file mode 100644
index 0000000..5c18de3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileDescriptorTest.java
@@ -0,0 +1,89 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.charset.StandardCharsets;
+import junit.framework.TestCase;
+
+public class FileDescriptorTest extends TestCase {
+
+ public void test_sync() throws IOException {
+ File f = File.createTempFile("FileDescriptorText", "txt");
+
+ FileOutputStream fos = null;
+ FileInputStream fis = null;
+ RandomAccessFile raf = null;
+
+ try {
+ fos = new FileOutputStream(f.getAbsolutePath());
+ fos.write("Test String".getBytes(StandardCharsets.US_ASCII));
+
+ fis = new FileInputStream(f.getPath());
+ FileDescriptor fd = fos.getFD();
+ fd.sync();
+
+ int length = "Test String".length();
+ assertEquals(length, fis.available());
+
+ // Regression test for Harmony-1494
+ fd = fis.getFD();
+ fd.sync();
+ assertEquals(length, fis.available());
+
+ raf = new RandomAccessFile(f, "r");
+ fd = raf.getFD();
+ fd.sync();
+ } finally {
+ if (fos != null) {
+ fos.close();
+ }
+ if (fis != null) {
+ fis.close();
+ }
+ if (raf != null) {
+ raf.close();
+ }
+ }
+ }
+
+ /**
+ * java.io.FileDescriptor#valid()
+ */
+ public void test_valid() throws IOException {
+ File f = File.createTempFile("FileDescriptorText", "txt");
+
+ FileOutputStream fos = null;
+ try {
+ fos = new FileOutputStream(f.getAbsolutePath());
+ FileDescriptor fd = fos.getFD();
+ assertTrue(fd.valid());
+ fos.close();
+ assertFalse(fd.valid());
+ } finally {
+ if (fos != null) {
+ fos.close();
+ }
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileInputStreamTest.java
new file mode 100644
index 0000000..af54d4b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileInputStreamTest.java
@@ -0,0 +1,482 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import junit.framework.TestCase;
+
+public class FileInputStreamTest extends TestCase {
+
+ private String fileName;
+
+ private java.io.InputStream is;
+
+ private static final String INPUT =
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n" +
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n";
+
+ @Override
+ protected void setUp() throws IOException {
+ File f = File.createTempFile("FileInputStreamTest", "tst");
+
+ FileOutputStream fos = null;
+ try {
+ fos = new FileOutputStream(f.getAbsolutePath());
+ fos.write(INPUT.getBytes(StandardCharsets.US_ASCII));
+ } finally {
+ fos.close();
+ }
+
+ fileName = f.getAbsolutePath();
+ }
+
+ /**
+ * java.io.FileInputStream#FileInputStream(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() throws IOException {
+ java.io.File f = new File(fileName);
+ is = new FileInputStream(f);
+ is.close();
+ }
+
+ /**
+ * java.io.FileInputStream#FileInputStream(java.io.FileDescriptor)
+ */
+ public void test_ConstructorLjava_io_FileDescriptor() throws IOException {
+ FileOutputStream fos = new FileOutputStream(fileName);
+ FileInputStream fis = new FileInputStream(fos.getFD());
+ fos.close();
+ fis.close();
+ }
+
+ /**
+ * java.io.FileInputStream#FileInputStream(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ is = new FileInputStream(fileName);
+ is.close();
+ }
+
+ /**
+ * java.io.FileInputStream#FileInputStream(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String_I() throws IOException {
+ try {
+ is = new FileInputStream("");
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ try {
+ is = new FileInputStream(new File(""));
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#available()
+ */
+ public void test_available() throws IOException {
+ try {
+ is = new FileInputStream(fileName);
+ assertTrue(is.available() == INPUT.length());
+ } finally {
+ try {
+ is.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ public void test_close() throws IOException {
+ is = new FileInputStream(fileName);
+ is.close();
+ try {
+ is.read();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_close_shared_fd() throws IOException {
+ // Regression test for HARMONY-6642
+ FileInputStream fis1 = new FileInputStream(fileName);
+ FileInputStream fis2 = new FileInputStream(fis1.getFD());
+
+ try {
+ fis2.close();
+ // Should not throw, since the FD is owned by fis1.
+ fis1.read();
+ } finally {
+ try {
+ fis1.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#getFD()
+ */
+ public void test_getFD() throws IOException {
+ FileInputStream fis = new FileInputStream(fileName);
+ assertTrue("Returned invalid fd", fis.getFD().valid());
+ fis.close();
+ assertTrue("Returned invalid fd", !fis.getFD().valid());
+ }
+
+ /**
+ * java.io.FileInputStream#read()
+ */
+ public void test_read() throws IOException {
+ InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName));
+ int c = isr.read();
+ isr.close();
+ assertEquals(INPUT.charAt(0), c);
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[])
+ */
+ public void test_read$B() throws IOException {
+ byte[] buf1 = new byte[100];
+ is = new FileInputStream(fileName);
+ is.skip(500);
+ is.read(buf1);
+ is.close();
+ assertEquals(INPUT.substring(500, 600),
+ new String(buf1, 0, buf1.length, StandardCharsets.US_ASCII));
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ byte[] buf1 = new byte[100];
+ is = new FileInputStream(fileName);
+ is.skip(500);
+ is.read(buf1, 0, buf1.length);
+ is.close();
+ assertEquals(INPUT.substring(500, 600),
+ new String(buf1, 0, buf1.length, StandardCharsets.US_ASCII));
+
+ // Regression test for HARMONY-285
+ File tmpFile = File.createTempFile("FileOutputStream", "tmp");
+ FileInputStream in = new FileInputStream(tmpFile);
+ try {
+ in.read(null, 0, 0);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ } finally {
+ in.close();
+ tmpFile.delete();
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[], int, int)
+ */
+ public void test_read_$BII_IOException() throws IOException {
+ byte[] buf = new byte[1000];
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, 0, 1001);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, 1001, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, 500, 501);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.close();
+ is.read(buf, 0, 100);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+
+ try {
+ is = new FileInputStream(fileName);
+ is.close();
+ is.read(buf, 0, 0);
+ } finally {
+ is.close();
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[], int, int)
+ */
+ public void test_read_$BII_NullPointerException() throws IOException {
+ byte[] buf = null;
+ try {
+ is = new FileInputStream(fileName);
+ is.read(buf, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[], int, int)
+ */
+ public void test_read_$BII_IndexOutOfBoundsException() throws IOException {
+ byte[] buf = new byte[1000];
+ try {
+ is = new FileInputStream(fileName);
+ is.close();
+ is.read(buf, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+ }
+
+ /**
+ * java.io.FileInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ byte[] buf1 = new byte[10];
+ is = new FileInputStream(fileName);
+ is.skip(1000);
+ is.read(buf1, 0, buf1.length);
+ is.close();
+ assertEquals(INPUT.substring(1000, 1010),
+ new String(buf1, 0, buf1.length, StandardCharsets.US_ASCII));
+
+ }
+
+ /**
+ * java.io.FileInputStream#read(byte[], int, int))
+ */
+ public void test_regressionNNN() throws IOException {
+ // Regression for HARMONY-434
+ FileInputStream fis = new FileInputStream(fileName);
+
+ try {
+ fis.read(new byte[1], -1, 1);
+ fail("IndexOutOfBoundsException must be thrown if off <0");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ fis.read(new byte[1], 0, -1);
+ fail("IndexOutOfBoundsException must be thrown if len <0");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ fis.read(new byte[1], 0, 5);
+ fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ fis.read(new byte[10], Integer.MAX_VALUE, 5);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ fis.read(new byte[10], 5, Integer.MAX_VALUE);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ fis.close();
+ }
+
+ /**
+ * java.io.FileInputStream#skip(long)
+ */
+ public void test_skipNegativeArgumentJ() throws IOException {
+ FileInputStream fis = new FileInputStream(fileName);
+ try {
+ fis.skip(-5);
+ fail("IOException must be thrown if number of bytes to skip <0");
+ } catch (IOException e) {
+ // Expected IOException
+ } finally {
+ fis.close();
+ }
+ }
+
+ public void test_getChannel() throws Exception {
+ FileInputStream fis = new FileInputStream(fileName);
+ assertEquals(0, fis.getChannel().position());
+ int r;
+ int count = 1;
+ while ((r = fis.read()) != -1) {
+ assertEquals(count++, fis.getChannel().position());
+ }
+ fis.close();
+
+ try {
+ fis.getChannel().position();
+ fail("should throw ClosedChannelException");
+ } catch (java.nio.channels.ClosedChannelException e) {
+ // Expected
+ }
+
+ fis = new FileInputStream(fileName);
+ assertEquals(0, fis.getChannel().position());
+ byte[] bs = new byte[10];
+ r = fis.read(bs);
+ assertEquals(10, fis.getChannel().position());
+ fis.close();
+
+ fis = new FileInputStream(fileName);
+ assertEquals(0, fis.getChannel().position());
+ bs = new byte[10];
+ fis.skip(100);
+ assertEquals(100, fis.getChannel().position());
+ r = fis.read(bs);
+ assertEquals(110, fis.getChannel().position());
+ fis.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileNotFoundExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileNotFoundExceptionTest.java
new file mode 100644
index 0000000..a1772cd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileNotFoundExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.FileNotFoundException;
+
+import junit.framework.TestCase;
+
+public class FileNotFoundExceptionTest extends TestCase {
+
+ /**
+ * java.io.FileNotFoundException#FileNotFoundException()
+ */
+ public void test_Constructor() {
+ FileNotFoundException e = new FileNotFoundException();
+ assertNull(e.getMessage());
+ }
+
+ /**
+ * java.io.FileNotFoundException#FileNotFoundException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ String message = "Cannot found file: 9://0//l";
+ FileNotFoundException e = new FileNotFoundException(message);
+ assertSame(message, e.getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileOutputStreamTest.java
new file mode 100644
index 0000000..6263cc5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileOutputStreamTest.java
@@ -0,0 +1,394 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+public class FileOutputStreamTest extends TestCase {
+
+ private FileOutputStream fos;
+ private FileInputStream fis;
+ private File f;
+ private byte[] bytes;
+
+ 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_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() {
+ bytes = new byte[10];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = (byte) i;
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ if (f != null) {
+ f.delete();
+ }
+ if (fis != null) {
+ fis.close();
+ }
+ if (fos != null) {
+ fos.close();
+ }
+ }
+
+ /**
+ * java.io.FileOutputStream#FileOutputStream(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f);
+ }
+
+ /**
+ * java.io.FileOutputStream#FileOutputStream(java.io.FileDescriptor)
+ */
+ public void test_ConstructorLjava_io_FileDescriptor() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ String fileName = f.getAbsolutePath();
+ fos = new FileOutputStream(fileName);
+ fos.write('l');
+ fos.close();
+ fis = new FileInputStream(fileName);
+ fos = new FileOutputStream(fis.getFD());
+ fos.close();
+ fis.close();
+ }
+
+ /**
+ * java.io.FileOutputStream#FileOutputStream(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ String fileName = f.getAbsolutePath();
+ fos = new FileOutputStream(fileName);
+
+ // Harmony 4012.
+ fos = new FileOutputStream("/dev/null");
+ fos.close();
+ }
+
+ /**
+ * java.io.FileOutputStream#FileOutputStream(java.lang.String,
+ *boolean)
+ */
+ public void test_ConstructorLjava_lang_StringZ() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath(), false);
+ fos.write("HI".getBytes(), 0, 2);
+ fos.close();
+ fos = new FileOutputStream(f.getPath(), true);
+ fos.write(fileString.getBytes());
+ fos.close();
+ byte[] buf = new byte[fileString.length() + 2];
+ fis = new FileInputStream(f.getPath());
+ fis.read(buf, 0, buf.length);
+ assertTrue("Failed to create appending stream", new String(buf, 0,
+ buf.length).equals("HI" + fileString));
+ }
+
+ /**
+ * java.io.FileOutputStream#FileOutputStream(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String_I() throws IOException {
+ try {
+ fos = new FileOutputStream("");
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (fos != null) {
+ fos.close();
+ }
+ }
+ try {
+ fos = new FileOutputStream(new File(""));
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (fos != null) {
+ fos.close();
+ }
+ }
+ }
+
+ /**
+ * java.io.FileOutputStream#close()
+ */
+ public void test_close() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath());
+ fos.close();
+
+ try {
+ fos.write(fileString.getBytes());
+ fail("Close test failed - wrote to closed stream");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.FileOutputStream#getFD()
+ */
+ public void test_getFD() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ String fileName = f.getAbsolutePath();
+ fos = new FileOutputStream(f);
+ assertTrue("Returned invalid fd", fos.getFD().valid());
+ fos.close();
+ assertTrue("Returned invalid fd", !fos.getFD().valid());
+ }
+
+ /**
+ * java.io.FileOutputStream#write(byte[])
+ */
+ public void test_write$B() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath());
+ fos.write(fileString.getBytes());
+ fis = new FileInputStream(f.getPath());
+ byte rbytes[] = new byte[4000];
+ fis.read(rbytes, 0, fileString.length());
+ assertTrue("Incorrect string returned", new String(rbytes, 0,
+ fileString.length()).equals(fileString));
+ }
+
+ /**
+ * java.io.FileOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath());
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fis = new FileInputStream(f.getPath());
+ byte rbytes[] = new byte[4000];
+ fis.read(rbytes, 0, fileString.length());
+ assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+
+ // Regression test for HARMONY-285
+ File file = File.createTempFile("FileOutputStreamTest", ".tmp");
+ FileOutputStream out = new FileOutputStream(file);
+ try {
+ out.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+
+ } finally {
+ out.close();
+ file.delete();
+ }
+ }
+
+ /**
+ * java.io.FileOutputStream#write(int)
+ */
+ public void test_writeI() throws IOException {
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath());
+ fos.write('t');
+ fis = new FileInputStream(f.getPath());
+ assertEquals("Incorrect char written", 't', fis.read());
+ }
+
+ /**
+ * java.io.FileOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII2() throws IOException {
+ // Regression for HARMONY-437
+ f = File.createTempFile("FileOutputStreamTest", "tst");
+ fos = new FileOutputStream(f.getPath());
+
+ try {
+ fos.write(null, 1, 1);
+ fail("NullPointerException must be thrown");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ fos.write(new byte[1], -1, 1);
+ fail("IndexOutOfBoundsException must be thrown if off <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ fos.write(new byte[1], 0, -1);
+ fail("IndexOutOfBoundsException must be thrown if len <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ fos.write(new byte[1], 0, 5);
+ fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ fos.write(new byte[10], Integer.MAX_VALUE, 5);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ fos.write(new byte[10], 5, Integer.MAX_VALUE);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ fos.close();
+ }
+
+ /**
+ * java.io.FileOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII3() throws IOException {
+ // Regression for HARMONY-834
+ // no exception expected
+ new FileOutputStream(new FileDescriptor()).write(new byte[1], 0, 0);
+ }
+
+ /**
+ * java.io.FileOutputStream#getChannel()
+ */
+ public void test_getChannel() throws IOException {
+ // Regression for HARMONY-508
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile);
+ fos.write(bytes);
+ fos.flush();
+ fos.close();
+ FileOutputStream f = new FileOutputStream(tmpfile, true);
+ // Harmony expected 10, but the RI and Android report 0.
+ assertEquals(0, f.getChannel().position());
+ }
+
+ public void test_getChannel_Append() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, true);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(20, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(30, fos.getChannel().position());
+ fos.close();
+
+ try {
+ fos.getChannel().position();
+ fail("should throw ClosedChannelException");
+ } catch (java.nio.channels.ClosedChannelException e) {
+ // Expected
+ }
+ }
+
+ public void test_getChannel_UnAppend() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, false);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(20, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(30, fos.getChannel().position());
+ fos.close();
+
+ try {
+ fos.getChannel().position();
+ fail("should throw ClosedChannelException");
+ } catch (java.nio.channels.ClosedChannelException e) {
+ // Expected
+ }
+ }
+
+ public void test_getChannel_Unappend_Unappend() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, false);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.close();
+
+ fos = new FileOutputStream(tmpfile, false);
+ assertEquals(0, fos.getChannel().position());
+ fos.close();
+ }
+
+ public void test_getChannel_Unappend_Append() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, false);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.close();
+
+ fos = new FileOutputStream(tmpfile, true);
+ // Harmony expected 10, but the RI and Android report 0.
+ assertEquals(0, fos.getChannel().position());
+ fos.close();
+ }
+
+ public void test_getChannel_Append_Unappend() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, true);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.close();
+
+ fos = new FileOutputStream(tmpfile, false);
+ assertEquals(0, fos.getChannel().position());
+ fos.close();
+ }
+
+ public void test_getChanne_Append_Append() throws IOException {
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile, true);
+ assertEquals(0, fos.getChannel().position());
+ fos.write(bytes);
+ assertEquals(10, fos.getChannel().position());
+ fos.close();
+
+ fos = new FileOutputStream(tmpfile, true);
+ // Harmony expected 10, but the RI and Android report 0.
+ assertEquals(0, fos.getChannel().position());
+ fos.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileReaderTest.java
new file mode 100644
index 0000000..7f7c02c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileReaderTest.java
@@ -0,0 +1,118 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+public class FileReaderTest extends TestCase {
+
+ FileReader br;
+
+ BufferedWriter bw;
+
+ FileInputStream fis;
+
+ File f;
+
+ /**
+ * java.io.FileReader#FileReader(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() throws IOException {
+ bw = new BufferedWriter(new FileWriter(f.getPath()));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new FileReader(f);
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ assertEquals("Failed to read correct chars", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * java.io.FileReader#FileReader(java.io.FileDescriptor)
+ */
+ public void test_ConstructorLjava_io_FileDescriptor() throws IOException {
+ bw = new BufferedWriter(new FileWriter(f.getPath()));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ FileInputStream fis = new FileInputStream(f.getPath());
+ br = new FileReader(fis.getFD());
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ fis.close();
+ assertEquals("Failed to read correct chars", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * java.io.FileReader#FileReader(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ bw = new BufferedWriter(new FileWriter(f.getPath()));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new FileReader(f.getPath());
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ assertEquals("Failed to read correct chars", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() throws IOException {
+ f = File.createTempFile("FileReaderTest", "tst");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ bw.close();
+ } catch (Exception e) {
+ // Ignore
+ }
+ try {
+ br.close();
+ } catch (Exception e) {
+ // Ignore
+ }
+ try {
+ if (fis != null) {
+ fis.close();
+ }
+ } catch (Exception e) {
+ // Ignore
+ }
+ f.delete();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileTest.java
new file mode 100644
index 0000000..5cc88f4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileTest.java
@@ -0,0 +1,2191 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileFilter;
+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 libcore.io.Libcore;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class FileTest extends TestCase {
+
+ private static String platformId = "JDK"
+ + System.getProperty("java.vm.version").replace('.', '-');
+
+ private static void deleteTempFolder(File dir) {
+ String files[] = dir.list();
+ if (files != null) {
+ for (int i = 0; i < files.length; i++) {
+ File f = new File(dir, files[i]);
+ if (f.isDirectory()) {
+ deleteTempFolder(f);
+ } else {
+ f.delete();
+ }
+ }
+ }
+ dir.delete();
+ }
+
+ private static String addTrailingSlash(String path) {
+ if (File.separatorChar == path.charAt(path.length() - 1)) {
+ return path;
+ }
+ return path + File.separator;
+ }
+
+ /**
+ * Location to store tests in
+ */
+ private File tempDirectory;
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
+
+ protected void setUp() throws IOException {
+ /** Setup the temporary directory */
+ tempDirectory = new File(addTrailingSlash(System.getProperty("java.io.tmpdir")) + "harmony-test-" + getClass().getSimpleName() + File.separator);
+ tempDirectory.mkdirs();
+ }
+
+ protected void tearDown() {
+ if (tempDirectory != null) {
+ deleteTempFolder(tempDirectory);
+ tempDirectory = null;
+ }
+ }
+
+ /**
+ * java.io.File#File(java.io.File, java.lang.String)
+ */
+ public void test_ConstructorLjava_io_FileLjava_lang_String0() {
+ File f = new File(tempDirectory.getPath(), "input.tst");
+ assertEquals("Created Incorrect File ", addTrailingSlash(tempDirectory.getPath()) + "input.tst", f.getPath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String1() {
+ try {
+ new File(tempDirectory, null);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String2() throws IOException {
+ File f = new File((File) null, "input.tst");
+ assertEquals("Created Incorrect File",
+ new File("input.tst").getAbsolutePath(),
+ f.getAbsolutePath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String3() {
+ // Regression test for HARMONY-382
+ File f = new File("/abc");
+ File d = new File((File) null, "/abc");
+ assertEquals("Test3: Created Incorrect File",
+ d.getAbsolutePath(), f.getAbsolutePath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String4() {
+ // Regression test for HARMONY-21
+ File path = new File("/dir/file");
+ File root = new File("/");
+ File file = new File(root, "/dir/file");
+ assertEquals("Assert 1: wrong path result ", path.getPath(), file
+ .getPath());
+ if (File.separatorChar == '\\') {
+ assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b")
+ .isAbsolute());
+ } else {
+ assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b")
+ .isAbsolute());
+ }
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String5() {
+ // Test data used in a few places below
+ String dirName = tempDirectory.getPath();
+ String fileName = "input.tst";
+
+ // Check filename is preserved correctly
+ File d = new File(dirName);
+ File f = new File(d, fileName);
+ dirName = addTrailingSlash(dirName);
+ dirName += fileName;
+ assertEquals("Assert 1: Created incorrect file ",
+ dirName, f.getPath());
+
+ // Check null argument is handled
+ try {
+ f = new File(d, null);
+ fail("Assert 2: NullPointerException not thrown.");
+ } catch (NullPointerException e) {
+ // Expected.
+ }
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String6() {
+ // Regression for HARMONY-46
+ File f1 = new File("a");
+ File f2 = new File("a/");
+ assertEquals("Trailing slash file name is incorrect", f1, f2);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.io.File#File(java.lang.String, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException {
+ String dirName = null;
+ String fileName = "input.tst";
+ File f = new File(dirName, fileName);
+ assertEquals("Test 1: Created Incorrect File",
+ new File("input.tst").getAbsolutePath(),
+ f.getAbsolutePath());
+
+ dirName = tempDirectory.getPath();
+ fileName = null;
+ try {
+ f = new File(dirName, fileName);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ fileName = "input.tst";
+ f = new File(dirName, fileName);
+ assertEquals("Test 2: Created Incorrect File",
+ addTrailingSlash(tempDirectory.getPath()) + "input.tst",
+ f.getPath());
+
+ // Regression test for HARMONY-382
+ String s = null;
+ f = new File("/abc");
+ File d = new File(s, "/abc");
+ assertEquals("Test3: Created Incorrect File", d.getAbsolutePath(), f
+ .getAbsolutePath());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * java.io.File#createNewFile()
+ */
+ public void test_createNewFile_EmptyString() {
+ File f = new File("");
+ try {
+ f.createNewFile();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * 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;
+ // }
+ }
+
+ /**
+ * 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();
+ }
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+ }
+
+ /**
+ * 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.
+ // /**
+ // * 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);
+ // }
+
+ /**
+ * 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));
+
+ f1 = new File(tempDirectory, "casetest.tmp");
+ f2 = new File(tempDirectory, "CaseTest.tmp");
+ assertFalse(f1.equals(f2));
+ assertTrue(f1.createNewFile());
+ f1.delete();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.io.File#getParent()
+ */
+ public void test_getParent() {
+ File f = new File("p.tst");
+ assertNull("Incorrect path returned", f.getParent());
+ f = new File("/user/home/p.tst");
+ assertEquals("Incorrect path returned",
+ "/user/home", f.getParent());
+
+ 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());
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.io.File#getPath()
+ */
+ public void test_getPath() {
+ String base = System.getProperty("user.home");
+ String fname;
+ File f1;
+ if (!base.regionMatches((base.length() - 1), File.separator, 0, 1)) {
+ base += File.separator;
+ }
+ fname = base + "filechk.tst";
+ f1 = new File(base, "filechk.tst");
+ File f2 = new File("filechk.tst");
+ File f3 = new File("c:");
+ File f4 = new File(base + "a" + File.separator + File.separator + ".." + File.separator
+ + "filechk.tst");
+ assertEquals("getPath returned incorrect path(f1)",
+ fname, f1.getPath());
+ assertEquals("getPath returned incorrect path(f2)",
+ "filechk.tst", f2.getPath());
+ assertEquals("getPath returned incorrect path(f3)", "c:", f3.getPath());
+ assertEquals("getPath returned incorrect path(f4)",
+ base + "a" + File.separator + ".." + File.separator + "filechk.tst",
+ f4.getPath());
+ f1.delete();
+ f2.delete();
+ f3.delete();
+ f4.delete();
+
+ // Regression for HARMONY-444
+ File file;
+ String separator = File.separator;
+
+ file = new File((File) null, "x/y/z");
+ assertEquals("x" + separator + "y" + separator + "z", file.getPath());
+
+ file = new File((String) null, "x/y/z");
+ assertEquals("x" + separator + "y" + separator + "z", file.getPath());
+
+ // Regression for HARMONY-829
+ String f1ParentName = "01";
+ f1 = new File(f1ParentName, "");
+ assertEquals(f1ParentName, f1.getPath());
+
+ String f2ParentName = "0";
+ f2 = new File(f2ParentName, "");
+
+ assertEquals(-1, f2.compareTo(f1));
+ assertEquals(1, f1.compareTo(f2));
+
+ File parent = tempDirectory;
+ f3 = new File(parent, "");
+
+ assertEquals(parent.getPath(), f3.getPath());
+
+ File file0 = new File("");
+ assertEquals("", file0.getPath());
+
+ // Regression for HARMONY-3869
+ // Behavior here is system-dependent according to the RI javadoc.
+ String path1 = new File("", "").getPath();
+ assertTrue(path1.equals(File.separator) || path1.isEmpty());
+ String path2 = new File(new File(""), "").getPath();
+ assertTrue(path2.equals(File.separator) || path2.isEmpty());
+ }
+
+ /**
+ * java.io.File#hashCode()
+ */
+ public void test_hashCode() {
+ // Regression for HARMONY-53
+ File mfile = new File("SoMe FiLeNaMe"); // Mixed case
+ File lfile = new File("some filename"); // Lower case
+
+ if (mfile.equals(lfile)) {
+ assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile
+ .hashCode());
+ } else {
+ assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile
+ .hashCode());
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ public void test_isHidden() throws IOException, InterruptedException {
+ boolean onUnix = File.separatorChar == '/';
+ assertTrue(onUnix);
+
+ // On Unix hidden files are marked with a "." at the beginning
+ // of the file name.
+ File f1 = File.createTempFile("harmony-test-FileTest_notHidden_", ".tmp");
+ File f2 = File.createTempFile(".harmony-test-FileTest_isHidden_", ".tmp");
+ assertFalse(f1.isHidden());
+ assertTrue(f2.isHidden());
+ // We can still delete hidden files.
+ assertTrue(f2.delete());
+ f1.delete();
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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);
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * java.io.File#mkdir()
+ * <p/>
+ * 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());
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * 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();
+ }
+ }
+
+ /**
+ * java.io.File#setLastModified(long)
+ */
+ public void test_setLastModifiedJ() throws IOException {
+ File f1 = null;
+ try {
+ f1 = File.createTempFile("harmony-test-FileTest_setLastModified", ".tmp");
+ 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();
+ }
+ }
+ }
+
+ /**
+ * java.io.File#setReadOnly()
+ */
+ public void test_setReadOnly() throws Exception {
+ File f1 = null;
+ File f2 = null;
+ if (Libcore.os.getuid() == 0) {
+ System.err.println("Skipping #test_setReadOnly: test runner is root");
+ return;
+ }
+
+ 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());
+ assertTrue(f1.setReadOnly());
+ assertFalse(f1.canWrite());
+ // 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
+ }
+
+ Libcore.os.chmod(f1.getAbsolutePath(), 666);
+
+ // 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();
+ assertEquals(fileString.length(), f1.length());
+ assertTrue(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
+ }
+
+ Libcore.os.chmod(f2.getAbsolutePath(), 666);
+ assertTrue(f2.canWrite());
+ fos = new FileOutputStream(f2);
+ fos.write(fileString.getBytes());
+ fos.close();
+ f2.setReadOnly();
+ assertTrue(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();
+ }
+ }
+ }
+
+ /**
+ * java.io.File#toString()
+ */
+ public void test_toString() {
+ String fileName = System.getProperty("user.home");
+ if (!fileName.endsWith(File.separator)) {
+ fileName += File.separator;
+ }
+ fileName += "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);
+ }
+ }
+
+ /**
+ * 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("/"));
+ }
+
+ /**
+ * 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("/"));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * serialization
+ */
+ 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(System.getProperty("java.io.tmpdir")).getAbsoluteFile();
+ 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);
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void test_serialization_self() throws Exception {
+ File testFile = new File("test.ser");
+ SerializationTest.verifySelf(testFile);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void test_serialization_compatibility() throws Exception {
+ File file = new File("FileTest.golden.ser");
+ SerializationTest.verifyGolden(this, file);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileWriterTest.java
new file mode 100644
index 0000000..a3640b0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FileWriterTest.java
@@ -0,0 +1,185 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+public class FileWriterTest extends TestCase {
+ private FileInputStream fis;
+ private BufferedWriter bw;
+ private File f;
+ private FileOutputStream fos;
+ private BufferedReader br;
+
+ /**
+ * java.io.FileWriter#FileWriter(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() throws IOException {
+ fos = new FileOutputStream(f.getPath());
+ fos.write("Test String".getBytes());
+ fos.close();
+ bw = new BufferedWriter(new FileWriter(f));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new BufferedReader(new FileReader(f.getPath()));
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ assertEquals("Failed to write correct chars", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * java.io.FileWriter#FileWriter(java.io.File, boolean)
+ */
+ public void test_ConstructorLjava_io_FileZ() throws IOException {
+ FileWriter fileWriter = new FileWriter(f);
+
+ String first = "The first string for testing. ";
+ fileWriter.write(first);
+ fileWriter.close();
+
+ fileWriter = new FileWriter(f, true);
+ String second = "The second String for testing.";
+ fileWriter.write(second);
+ fileWriter.close();
+
+ FileReader fileReader = new FileReader(f);
+ char[] out = new char[first.length() + second.length() + 10];
+ int length = fileReader.read(out);
+ fileReader.close();
+ assertEquals(first + second, new String(out, 0, length));
+
+ fileWriter = new FileWriter(f);
+ first = "The first string for testing. ";
+ fileWriter.write(first);
+ fileWriter.close();
+
+ fileWriter = new FileWriter(f, false);
+ second = "The second String for testing.";
+ fileWriter.write(second);
+ fileWriter.close();
+
+ fileReader = new FileReader(f);
+ out = new char[first.length() + second.length() + 10];
+ length = fileReader.read(out);
+ fileReader.close();
+ assertEquals(second, new String(out, 0, length));
+ }
+
+ /**
+ * java.io.FileWriter#FileWriter(java.io.FileDescriptor)
+ */
+ public void test_ConstructorLjava_io_FileDescriptor() throws IOException {
+ fos = new FileOutputStream(f.getPath());
+ fos.write("Test String".getBytes());
+ fos.close();
+ fis = new FileInputStream(f.getPath());
+ br = new BufferedReader(new FileReader(fis.getFD()));
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ fis.close();
+ assertTrue("Failed to write correct chars: " + new String(buf, 0, r),
+ new String(buf, 0, r).equals("Test String"));
+ }
+
+ /**
+ * java.io.FileWriter#FileWriter(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ fos = new FileOutputStream(f.getPath());
+ fos.write("Test String".getBytes());
+ fos.close();
+ bw = new BufferedWriter(new FileWriter(f.getPath()));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new BufferedReader(new FileReader(f.getPath()));
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ assertEquals("Failed to write correct chars", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * java.io.FileWriter#FileWriter(java.lang.String, boolean)
+ */
+ public void test_ConstructorLjava_lang_StringZ() throws IOException {
+ fos = new FileOutputStream(f.getPath());
+ fos.write("Test String".getBytes());
+ fos.close();
+ bw = new BufferedWriter(new FileWriter(f.getPath(), true));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new BufferedReader(new FileReader(f.getPath()));
+ char[] buf = new char[100];
+ int r = br.read(buf);
+ br.close();
+ assertEquals("Failed to append to file",
+ "Test String After test string", new String(buf, 0, r));
+
+ fos = new FileOutputStream(f.getPath());
+ fos.write("Test String".getBytes());
+ fos.close();
+ bw = new BufferedWriter(new FileWriter(f.getPath(), false));
+ bw.write(" After test string", 0, 18);
+ bw.close();
+ br = new BufferedReader(new FileReader(f.getPath()));
+ buf = new char[100];
+ r = br.read(buf);
+ br.close();
+ assertEquals("Failed to overwrite file", " After test string",
+ new String(buf, 0, r));
+ }
+
+ /**
+ * 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 {
+ f = File.createTempFile("FileWriterTest", "tst");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ @Override
+ protected void tearDown() {
+ try {
+ bw.close();
+ } catch (Exception e) {
+ }
+ try {
+ fis.close();
+ } catch (Exception e) {
+ }
+ f.delete();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterInputStreamTest.java
new file mode 100644
index 0000000..1e42770
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterInputStreamTest.java
@@ -0,0 +1,209 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import junit.framework.TestCase;
+
+public class FilterInputStreamTest extends TestCase {
+
+ static class MyFilterInputStream extends FilterInputStream {
+ public MyFilterInputStream(InputStream is) {
+ super(is);
+ }
+ }
+
+ private String fileName;
+ private InputStream is;
+ private static final String INPUT =
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n" +
+ "Test_All_Tests\n" +
+ "Test_BufferedInputStream\n" +
+ "Test_java_io_BufferedOutputStream\n" +
+ "Test_java_io_ByteArrayInputStream\n" +
+ "Test_java_io_ByteArrayOutputStream\n" +
+ "Test_java_io_DataInputStream\n" +
+ "Test_java_io_File\n" +
+ "Test_java_io_FileDescriptor\n" +
+ "Test_java_io_FileInputStream\n" +
+ "Test_java_io_FileNotFoundException\n" +
+ "Test_java_io_FileOutputStream\n" +
+ "Test_java_io_FilterInputStream\n" +
+ "Test_java_io_FilterOutputStream\n" +
+ "Test_java_io_InputStream\n" +
+ "Test_java_io_IOException\n" +
+ "Test_java_io_OutputStream\n" +
+ "Test_java_io_PrintStream\n" +
+ "Test_java_io_RandomAccessFile\n" +
+ "Test_java_io_SyncFailedException\n" +
+ "Test_java_lang_AbstractMethodError\n" +
+ "Test_java_lang_ArithmeticException\n" +
+ "Test_java_lang_ArrayIndexOutOfBoundsException\n" +
+ "Test_java_lang_ArrayStoreException\n" +
+ "Test_java_lang_Boolean\n" +
+ "Test_java_lang_Byte\n" +
+ "Test_java_lang_Character\n";
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ @Override
+ protected void setUp() throws IOException {
+ File temp = File.createTempFile("FilterInputStreamTest", "tst");
+ fileName = temp.getAbsolutePath();
+ OutputStream fos = new FileOutputStream(temp.getAbsolutePath());
+ fos.write(INPUT.getBytes(StandardCharsets.US_ASCII));
+ fos.close();
+ is = new MyFilterInputStream(new java.io.FileInputStream(fileName));
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ @Override
+ protected void tearDown() {
+ try {
+ is.close();
+ } catch (Exception e) {
+ // Ignored
+ }
+ new File(fileName).delete();
+ }
+
+ /**
+ * java.io.FilterInputStream#available()
+ */
+ public void test_available() throws IOException {
+ assertTrue("Returned incorrect number of available bytes", is
+ .available() == INPUT.length());
+ }
+
+ /**
+ * java.io.FilterInputStream#close()
+ */
+ public void test_close() throws IOException {
+ is.close();
+
+ try {
+ is.read();
+ fail("Able to read from closed stream");
+ } catch (java.io.IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.FilterInputStream#mark(int)
+ */
+ public void test_markI() {
+ assertTrue("Mark not supported by parent InputStream", true);
+ }
+
+ /**
+ * java.io.FilterInputStream#markSupported()
+ */
+ public void test_markSupported() {
+ assertTrue("markSupported returned true", !is.markSupported());
+ }
+
+ /**
+ * java.io.FilterInputStream#read()
+ */
+ public void test_read() throws Exception {
+ int c = is.read();
+ assertTrue("read returned incorrect char", c == INPUT.charAt(0));
+ }
+
+ /**
+ * java.io.FilterInputStream#read(byte[])
+ */
+ public void test_read$B() throws Exception {
+ byte[] buf1 = new byte[100];
+ is.read(buf1);
+ assertTrue("Failed to read correct data", new String(buf1, 0,
+ buf1.length, "UTF-8").equals(INPUT.substring(0, 100)));
+ }
+
+ /**
+ * java.io.FilterInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws Exception {
+ byte[] buf1 = new byte[100];
+ is.skip(500);
+ is.mark(1000);
+ is.read(buf1, 0, buf1.length);
+ assertTrue("Failed to read correct data", new String(buf1, 0,
+ buf1.length, "UTF-8").equals(INPUT.substring(500, 600)));
+ }
+
+ /**
+ * java.io.FilterInputStream#reset()
+ */
+ public void test_reset() {
+ try {
+ is.reset();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.FilterInputStream#skip(long)
+ */
+ public void test_skipJ() throws Exception {
+ byte[] buf1 = new byte[10];
+ is.skip(1000);
+ is.read(buf1, 0, buf1.length);
+ assertTrue("Failed to skip to correct position", new String(buf1, 0,
+ buf1.length, "UTF-8").equals(INPUT.substring(1000, 1010)));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterOutputStreamTest.java
new file mode 100644
index 0000000..666955d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/FilterOutputStreamTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import junit.framework.TestCase;
+
+public class FilterOutputStreamTest extends TestCase {
+
+ private OutputStream os;
+
+ ByteArrayOutputStream bos;
+
+ ByteArrayInputStream bis;
+
+ byte[] ibuf = new byte[4096];
+
+ 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_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";
+
+ /**
+ * java.io.FilterOutputStream#FilterOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write('t');
+ }
+
+ /**
+ * java.io.FilterOutputStream#close()
+ */
+ public void test_close() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write(fileString.getBytes(), 0, 500);
+ os.flush();
+ assertEquals("Bytes not written after flush", 500, bos.size());
+ os.close();
+ }
+
+ /**
+ * java.io.FilterOutputStream#flush()
+ */
+ public void test_flush() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write(fileString.getBytes(), 0, 500);
+ os.flush();
+ assertEquals("Bytes not written after flush", 500, bos.size());
+ os.close();
+ }
+
+ /**
+ * java.io.FilterOutputStream#write(byte[])
+ */
+ public void test_write$B() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write(fileString.getBytes());
+ bis = new ByteArrayInputStream(bos.toByteArray());
+ os.flush();
+ assertTrue("Bytes not written after flush",
+ bis.available() == fileString.length());
+ byte[] wbytes = new byte[fileString.length()];
+ bis.read(wbytes, 0, fileString.length());
+ assertTrue("Incorrect bytes written", fileString.equals(new String(
+ wbytes, 0, wbytes.length)));
+ }
+
+ /**
+ * java.io.FilterOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write(fileString.getBytes(), 0, fileString.length());
+ bis = new ByteArrayInputStream(bos.toByteArray());
+ os.flush();
+ assertTrue("Bytes not written after flush",
+ bis.available() == fileString.length());
+ byte[] wbytes = new byte[fileString.length()];
+ bis.read(wbytes, 0, fileString.length());
+ assertTrue("Incorrect bytes written", fileString.equals(new String(
+ wbytes, 0, wbytes.length)));
+ }
+
+ /**
+ * java.io.FilterOutputStream#write(int)
+ */
+ public void test_writeI() throws IOException {
+ bos = new ByteArrayOutputStream();
+ os = new FilterOutputStream(bos);
+ os.write('t');
+ bis = new ByteArrayInputStream(bos.toByteArray());
+ os.flush();
+ assertEquals("Byte not written after flush", 1, bis.available());
+ byte[] wbytes = new byte[1];
+ bis.read(wbytes, 0, 1);
+ assertEquals("Incorrect byte written", 't', wbytes[0]);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ if (bos != null)
+ bos.close();
+ if (bis != null)
+ bis.close();
+ if (os != null)
+ os.close();
+ } catch (Exception e) {
+ // Ignored
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOErrorTest.java
new file mode 100644
index 0000000..b95adc9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOErrorTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOError;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+import junit.framework.TestCase;
+
+public class IOErrorTest extends TestCase {
+
+ /**
+ * java.io.IOError#IOError(java.lang.Throwable)
+ * @since 1.6
+ */
+ public void test_IOError_LThrowable() {
+ IOError e = new IOError(null);
+ assertNull(e.getCause());
+
+ String errorMsg = "java.io.IOError"; //$NON-NLS-1$
+ assertTrue(e.toString().contains(errorMsg));
+
+ errorMsg = "A dummy error"; //$NON-NLS-1$
+ e = new IOError(new Throwable(errorMsg));
+ assertTrue(e.toString().contains(errorMsg));
+
+ try {
+ throw new IOError(null);
+ } catch (IOError error) {
+ return;
+ } catch (Error error) {
+ fail("Error during IOException test" + error.toString()); //$NON-NLS-1$
+ }
+ fail("Failed to generate error"); //$NON-NLS-1$
+ }
+
+ /**
+ * serialization/deserialization.
+ * @since 1.6
+ */
+ public void testSerializationSelf() throws Exception {
+ String errorMsg = "java.io.IOError";
+ IOError e = new IOError(new Throwable(errorMsg));
+ SerializationTest.verifySelf(e);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ * @since 1.6
+ */
+ public void testSerializationCompatibility() throws Exception {
+ String errorMsg = "java.io.IOError";
+ IOError e = new IOError(new Throwable(errorMsg));
+ SerializationTest.verifyGolden(this, e);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOExceptionTest.java
new file mode 100644
index 0000000..d0b26db
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/IOExceptionTest.java
@@ -0,0 +1,113 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+public class IOExceptionTest extends TestCase {
+
+ /**
+ * java.io.IOException#IOException()
+ */
+ public void test_Constructor() {
+ try {
+ if (true) {
+ throw new IOException();
+ }
+ fail("Exception during IOException test");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.IOException#IOException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ if (true) {
+ throw new IOException("Some error message");
+ }
+ fail("Failed to generate exception");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.IOException#IOException(java.lang.String,
+ *java.lang.Throwable)
+ * @since 1.6
+ */
+ public void test_ConstructorLString_LThrowable() {
+ // Test for constructor java.io.IOException(java.lang.String, java.lang.Throwable)
+
+ IOException ioException = new IOException(
+ "A dummy IOException", new Throwable("A dummy Throwable")); //$NON-NLS-1$//$NON-NLS-2$
+ assertEquals("A dummy IOException", ioException.getMessage()); //$NON-NLS-1$
+
+ try {
+ throw new IOException(
+ "A dummy error", new Throwable("Some error message")); //$NON-NLS-1$ //$NON-NLS-2$
+ } catch (IOException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during IOException test" + e.toString()); //$NON-NLS-1$
+ }
+ fail("Failed to generate exception"); //$NON-NLS-1$
+ }
+
+ /**
+ * java.io.IOException#IOException(java.lang.Throwable)
+ * @since 1.6
+ */
+ public void test_Constructor_LThrowable() {
+ // Test for constructor java.io.IOException(java.lang.Throwable)
+ Throwable cause = new Throwable("A dummy Throwable"); //$NON-NLS-1$
+ IOException ioException = new IOException(cause);
+ assertEquals(cause.toString(), ioException.getMessage());
+
+ ioException = new IOException((Throwable) null);
+ assertNull(ioException.getMessage());
+
+ try {
+ throw new IOException(new Throwable("Some error message")); //$NON-NLS-1$
+ } catch (IOException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during IOException test" + e.toString()); //$NON-NLS-1$
+ }
+ fail("Failed to generate exception"); //$NON-NLS-1$
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamReaderTest.java
new file mode 100644
index 0000000..b84561a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamReaderTest.java
@@ -0,0 +1,529 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestCase;
+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;
+
+public class InputStreamReaderTest extends TestCase {
+
+ static class LimitedByteArrayInputStream extends ByteArrayInputStream {
+
+ // A ByteArrayInputStream that only returns a single byte per read
+ byte[] bytes;
+
+ int count;
+
+ public LimitedByteArrayInputStream(int type) {
+ super(new byte[0]);
+ switch (type) {
+ case 0:
+ bytes = new byte[] { 0x61, 0x72 };
+ break;
+ case 1:
+ bytes = new byte[] { (byte) 0xff, (byte) 0xfe, 0x61, 0x72 };
+ break;
+ case 2:
+ bytes = new byte[] { '\u001b', '$', 'B', '6', 'e', 'B', 'h',
+ '\u001b', '(', 'B' };
+ break;
+ }
+ count = bytes.length;
+ }
+
+ @Override
+ public int available() {
+ return count;
+ }
+
+ @Override
+ public int read() {
+ if (count == 0) {
+ return -1;
+ }
+ count--;
+ return bytes[bytes.length - count];
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int length) {
+ if (count == 0) {
+ return -1;
+ }
+ if (length == 0) {
+ return 0;
+ }
+ buffer[offset] = bytes[bytes.length - count];
+ count--;
+ return 1;
+ }
+ }
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
+
+ private InputStream fis;
+
+ private InputStream in;
+
+ private InputStreamReader is;
+
+ private InputStreamReader reader;
+
+ private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ in = new ByteArrayInputStream(source.getBytes("UTF-8"));
+ reader = new InputStreamReader(in, "UTF-8");
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ OutputStreamWriter osw = new OutputStreamWriter(bos);
+ char[] buf = new char[fileString.length()];
+ fileString.getChars(0, fileString.length(), buf, 0);
+ osw.write(buf);
+ osw.close();
+ fis = new ByteArrayInputStream(bos.toByteArray());
+ is = new InputStreamReader(fis);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ try {
+ in.close();
+ is.close();
+ fis.close();
+ } catch (IOException e) {
+ // Ignored
+ }
+
+ super.tearDown();
+ }
+
+ /**
+ * java.io.InputStreamReader#close()
+ */
+ public void test_close() throws IOException {
+ is.close();
+ try {
+ is.read();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ reader.close();
+ try {
+ reader.ready();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ // Should be a no-op
+ reader.close();
+
+ // Tests after reader closed
+ in = new BufferedInputStream(
+ this
+ .getClass()
+ .getClassLoader()
+ .getResourceAsStream(
+ "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt"));
+ reader = new InputStreamReader(in, "utf-8");
+ in.close();
+ try {
+ int count = reader.read(new char[1]);
+ fail("count:" + count);
+ } catch (IOException e) {
+ // Expected
+ }
+ try {
+ reader.read();
+ fail();
+ } catch (IOException e) {
+ // Expected
+ }
+
+ assertFalse(reader.ready());
+ Charset cs = Charset.forName("utf-8");
+ assertEquals(cs, Charset.forName(reader.getEncoding()));
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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) {
+ assertNotNull(e.getMessage());
+ }
+
+ 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * Unlike the RI, we return a canonical encoding name and not something
+ * java specific.
+ */
+ public void test_getEncoding() throws IOException {
+ InputStreamReader isr = new InputStreamReader(fis, "8859_1");
+ assertEquals("ISO-8859-1", isr.getEncoding());
+
+ isr = new InputStreamReader(fis, "ISO-8859-1");
+ assertEquals("ISO-8859-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("UTF-16BE", isr.getEncoding());
+ }
+
+ /**
+ * 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(
+ "tests/api/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(
+ "tests/api/java/io/testfile.txt");
+
+ reader = new InputStreamReader(in, "gb18030");
+ while ((c = reader.read()) != -1) {
+ sb.append((char) c);
+ }
+ assertEquals(source, sb.toString());
+ }
+
+ /**
+ * 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 {
+ reader.read(null, -1, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ reader.read(null, 0, -1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ reader.read(null, 0, 1);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], 1, 3);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ assertEquals(0, reader.read(new char[3], 3, 0));
+ char[] chars = new char[source.length()];
+ assertEquals(0, reader.read(chars, 0, 0));
+ assertEquals(0, chars[0]);
+ assertEquals(3, reader.read(chars, 0, 3));
+ assertEquals(5, reader.read(chars, 3, 5));
+ assertEquals(source.length() - 8, reader.read(chars, 8,
+ chars.length - 8));
+ assertTrue(Arrays.equals(chars, source.toCharArray()));
+ assertEquals(-1, reader.read(chars, 0, chars.length));
+ assertTrue(Arrays.equals(chars, source.toCharArray()));
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamTest.java
new file mode 100644
index 0000000..f2543c3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InputStreamTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import junit.framework.TestCase;
+
+public class InputStreamTest extends TestCase {
+ // Regression for HARMONY-4337
+ public void test1() throws IOException {
+ try {
+ InputStream in = new MockInputStream();
+ in.read(null, -1, 1);
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ class MockInputStream extends InputStream {
+ public int read() throws IOException {
+ return 0;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InterruptedIOExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InterruptedIOExceptionTest.java
new file mode 100644
index 0000000..5fc3d44
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InterruptedIOExceptionTest.java
@@ -0,0 +1,47 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.InterruptedIOException;
+
+import junit.framework.TestCase;
+
+public class InterruptedIOExceptionTest extends TestCase {
+
+ /**
+ * java.io.InterruptedIOException#InterruptedIOException()
+ */
+ public void test_Constructor() {
+ try {
+ throw new InterruptedIOException();
+ } catch (InterruptedIOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.InterruptedIOException#InterruptedIOException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ throw new InterruptedIOException("Some error message");
+ } catch (InterruptedIOException e) {
+ // Expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InvalidClassExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InvalidClassExceptionTest.java
new file mode 100644
index 0000000..f0d30f2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/InvalidClassExceptionTest.java
@@ -0,0 +1,71 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.InvalidClassException;
+
+import junit.framework.TestCase;
+
+public class InvalidClassExceptionTest extends TestCase {
+
+ /**
+ * java.io.InvalidClassException#InvalidClassException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ final String message = "A message";
+ try {
+ if (true) {
+ throw new InvalidClassException(message);
+ }
+ fail("Failed to throw exception");
+ } catch (InvalidClassException e) {
+ // correct
+ assertTrue("Incorrect message read", e.getMessage().equals(message));
+ }
+ }
+
+ /**
+ * java.io.InvalidClassException#InvalidClassException(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() {
+ final String message = "A message";
+ final String className = "Object";
+ try {
+ if (true) {
+ throw new InvalidClassException(className, message);
+ }
+ fail("Failed to throw exception");
+ } catch (InvalidClassException e) {
+ // correct
+ String returnedMessage = e.getMessage();
+ assertTrue("Incorrect message read: " + e.getMessage(),
+ returnedMessage.indexOf(className) >= 0
+ && returnedMessage.indexOf(message) >= 0);
+ }
+ }
+
+ /**
+ * java.io.InvalidClassException#getMessage()
+ */
+ public void test_getMessage() {
+ // Test for method java.lang.String
+ // java.io.InvalidClassException.getMessage()
+ // used to test
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberInputStreamTest.java
new file mode 100644
index 0000000..de345f1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberInputStreamTest.java
@@ -0,0 +1,167 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.LineNumberInputStream;
+import java.io.UnsupportedEncodingException;
+
+import junit.framework.TestCase;
+
+@SuppressWarnings("deprecation")
+public class LineNumberInputStreamTest extends TestCase {
+
+ String text = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501";
+
+ String dosText = "0\r\n1\r\n2";
+
+ LineNumberInputStream lnis;
+
+ LineNumberInputStream lnis2;
+
+ /**
+ * java.io.LineNumberInputStream#LineNumberInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ // Used in other tests
+ }
+
+ /**
+ * java.io.LineNumberInputStream#available()
+ */
+ public void test_available() throws IOException {
+ assertTrue("Returned incorrect number of available bytes", lnis
+ .available() == text.length() / 2);
+ }
+
+ /**
+ * java.io.LineNumberInputStream#getLineNumber()
+ */
+ public void test_getLineNumber() throws IOException {
+ assertEquals("New stream returned line number other than zero", 0, lnis
+ .getLineNumber());
+
+ lnis.read();
+ lnis.read();
+
+ assertEquals("stream returned incorrect line number after read", 1,
+ lnis.getLineNumber());
+
+ lnis.setLineNumber(89);
+ assertEquals("stream returned incorrect line number after set", 89,
+ lnis.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberInputStream#mark(int)
+ */
+ public void test_markI() throws IOException {
+ lnis.mark(40);
+ lnis.skip(4);
+ lnis.reset();
+ assertEquals("Failed to mark", 0, lnis.getLineNumber());
+ assertEquals("Failed to mark", '0', lnis.read());
+ }
+
+ /**
+ * java.io.LineNumberInputStream#read()
+ */
+ public void test_read() throws IOException {
+ assertEquals("Failed to read correct byte", '0', lnis.read());
+ assertEquals("Failed to read correct byte on dos text", '0', lnis2
+ .read());
+ assertTrue("Failed to read correct byte on dos text",
+ lnis2.read() == '\n');
+ assertEquals("Failed to read correct byte on dos text", '1', lnis2
+ .read());
+ assertTrue("Failed to read correct byte on dos text",
+ lnis2.read() == '\n');
+ assertEquals("Failed to read correct byte on dos text", '2', lnis2
+ .read());
+ }
+
+ /**
+ * java.io.LineNumberInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException, UnsupportedEncodingException {
+ byte[] buf = new byte[100];
+ lnis.read(buf, 0, 100);
+ assertTrue("Failed to read correct bytes on normal text", new String(
+ buf, 0, 100, "UTF-8").equals(text.substring(0, 100)));
+ }
+
+ /**
+ * java.io.LineNumberInputStream#reset()
+ */
+ public void test_reset() throws IOException {
+ lnis.mark(40);
+ lnis.skip(4);
+ lnis.reset();
+ assertEquals("Failed to reset", 0, lnis.getLineNumber());
+ assertEquals("Failed to reset", '0', lnis.read());
+ lnis.reset();
+
+ // see comment for setup
+ try {
+ lnis.mark(5);
+ lnis.skip(100);
+ lnis.reset();
+ fail("Failed to invalidate mark");
+ } catch (IOException e) {
+ // Correct mark has been invalidated
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.LineNumberInputStream#setLineNumber(int)
+ */
+ public void test_setLineNumberI() {
+ lnis.setLineNumber(89);
+ assertEquals("Failed to set line number", 89, lnis.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ lnis.skip(4);
+ assertEquals("Skip failed to increment lineNumber", 2, lnis
+ .getLineNumber());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() throws UnsupportedEncodingException {
+ /*
+ * In order for IOException to be thrown in reset(),the inputStream to
+ * the constructor cannot be a byteArrayInputstream because the reset()
+ * in byteArrayInputStream does not throw IOException. When
+ * BufferedInputStream is used, the size of the buffer must be smaller
+ * than the readlimit in mark inorder for IOException to be thrown
+ */
+ BufferedInputStream buftemp = new BufferedInputStream(
+ new ByteArrayInputStream(text.getBytes("UTF-8")), 4);
+ lnis = new LineNumberInputStream(buftemp);
+ lnis2 = new LineNumberInputStream(new ByteArrayInputStream(dosText
+ .getBytes("UTF-8")));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberReaderTest.java
new file mode 100644
index 0000000..d20b7af
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/LineNumberReaderTest.java
@@ -0,0 +1,221 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.LineNumberReader;
+import java.io.Reader;
+import java.io.StringReader;
+
+import junit.framework.TestCase;
+
+public class LineNumberReaderTest extends TestCase {
+
+ String text = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n";
+
+ LineNumberReader lnr;
+
+ /**
+ * java.io.LineNumberReader#LineNumberReader(java.io.Reader)
+ */
+ public void test_ConstructorLjava_io_Reader() {
+ lnr = new LineNumberReader(new StringReader(text), 4092);
+ assertEquals("Failed to create reader", 0, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#LineNumberReader(java.io.Reader, int)
+ */
+ public void test_ConstructorLjava_io_ReaderI() {
+ lnr = new LineNumberReader(new StringReader(text));
+ assertEquals("Failed to create reader", 0, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#getLineNumber()
+ */
+ public void test_getLineNumber() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ assertEquals("Returned incorrect line number--expected 0, got ", 0, lnr
+ .getLineNumber());
+
+ lnr.readLine();
+ lnr.readLine();
+
+ assertTrue("Returned incorrect line number--expected 2, got: "
+ + lnr.getLineNumber(), lnr.getLineNumber() == 2);
+ }
+
+ /**
+ * java.io.LineNumberReader#mark(int)
+ */
+ public void test_markI() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ String line;
+ lnr.skip(80);
+ lnr.mark(100);
+ line = lnr.readLine();
+ lnr.reset();
+ assertTrue("Failed to return to marked position", line.equals(lnr
+ .readLine()));
+ // The spec does not say the mark has to be invalidated
+ }
+
+ /**
+ * java.io.LineNumberReader#read()
+ */
+ public void test_read() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+
+ int c = lnr.read();
+ assertEquals("Read returned incorrect character", '0', c);
+
+ lnr.read();
+ assertEquals("Read failed to inc lineNumber", 1, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ char[] c = new char[100];
+ lnr.read(c, 0, 4);
+ assertTrue("Read returned incorrect characters", "0\n1\n"
+ .equals(new String(c, 0, 4)));
+ assertEquals("Read failed to inc lineNumber", 2, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#readLine()
+ */
+ public void test_readLine() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ assertEquals("Returned incorrect line number", 0, lnr.getLineNumber());
+ String line = null;
+ lnr.readLine();
+ line = lnr.readLine();
+
+ assertEquals("Returned incorrect string", "1", line);
+ assertTrue("Returned incorrect line number :" + lnr.getLineNumber(),
+ lnr.getLineNumber() == 2);
+
+ // Regression for HARMONY-4294
+ byte[] buffer = new byte[] { '\r', '\n' };
+ LineNumberReader reader = new LineNumberReader(new InputStreamReader(
+ new ByteArrayInputStream(buffer), "UTF-8"));
+ assertEquals('\n', reader.read());
+ assertEquals(-1, reader.read());
+ reader = new LineNumberReader(new InputStreamReader(
+ new ByteArrayInputStream(buffer), "UTF-8"));
+ assertNotNull(reader.readLine());
+ assertNull(reader.readLine());
+ }
+
+ /**
+ * java.io.LineNumberReader#reset()
+ */
+ public void test_reset() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ assertEquals("Returned incorrect line number", 0, lnr.getLineNumber());
+ String line = null;
+ lnr.mark(100);
+ lnr.readLine();
+ lnr.reset();
+ line = lnr.readLine();
+
+ assertEquals("Failed to reset reader", "0", line);
+ }
+
+ public void testReadLineSourceThrows() throws IOException {
+ lnr = new LineNumberReader(new Reader() {
+ private StringReader delegate = new StringReader("hello\nworld");
+ private int calls = 0;
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ @Override
+ public int read(char[] buf, int offset, int len) throws IOException {
+ if (calls++ < 2) {
+ throw new IOException();
+ } else {
+ return delegate.read(buf, offset, len);
+ }
+ }
+ });
+
+ assertEquals(0, lnr.getLineNumber());
+ try {
+ lnr.readLine();
+ fail();
+ } catch (IOException expected) {
+ }
+
+ assertEquals(0, lnr.getLineNumber());
+ try {
+ lnr.readLine();
+ fail();
+ } catch (IOException expected) {
+ }
+
+ assertEquals(0, lnr.getLineNumber());
+ assertEquals("hello", lnr.readLine());
+ assertEquals(1, lnr.getLineNumber());
+ assertEquals("world", lnr.readLine());
+ assertEquals(2, lnr.getLineNumber());
+ }
+
+ public void testGetLineNumberAfterEnd() throws IOException {
+ lnr = new LineNumberReader(new StringReader("hello\nworld"));
+ assertEquals(0, lnr.getLineNumber());
+ assertEquals("hello", lnr.readLine());
+ assertEquals(1, lnr.getLineNumber());
+ assertEquals("world", lnr.readLine());
+ assertEquals(2, lnr.getLineNumber());
+ assertEquals(null, lnr.readLine());
+ assertEquals(2, lnr.getLineNumber());
+ assertEquals(null, lnr.readLine());
+ assertEquals(2, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#setLineNumber(int)
+ */
+ public void test_setLineNumberI() {
+ lnr = new LineNumberReader(new StringReader(text));
+ lnr.setLineNumber(1001);
+ assertEquals("set incorrect line number", 1001, lnr.getLineNumber());
+ }
+
+ /**
+ * java.io.LineNumberReader#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ lnr = new LineNumberReader(new StringReader(text));
+ char[] c = new char[100];
+ lnr.skip(80);
+ lnr.read(c, 0, 100);
+
+ assertTrue("Failed to skip to correct position", text
+ .substring(80, 180).equals(new String(c, 0, c.length)));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotActiveExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotActiveExceptionTest.java
new file mode 100644
index 0000000..cd62bbc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotActiveExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.NotActiveException;
+
+import junit.framework.TestCase;
+
+public class NotActiveExceptionTest extends TestCase {
+
+ /**
+ * java.io.NotActiveException#NotActiveException()
+ */
+ public void test_Constructor() {
+ NotActiveException e = new NotActiveException();
+ assertNull(e.getMessage());
+ }
+
+ /**
+ * java.io.NotActiveException#NotActiveException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ String message = "Exception message";
+ NotActiveException e = new NotActiveException(message);
+ assertSame(message, e.getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotSerializableExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotSerializableExceptionTest.java
new file mode 100644
index 0000000..9df51a0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/NotSerializableExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.NotSerializableException;
+
+import junit.framework.TestCase;
+
+public class NotSerializableExceptionTest extends TestCase {
+
+ /**
+ * java.io.NotSerializableException#NotSerializableException()
+ */
+ public void test_Constructor() {
+ NotSerializableException nse = new NotSerializableException();
+ assertNull(nse.getMessage());
+ }
+
+ /**
+ * java.io.NotSerializableException#NotSerializableException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ String message = "Test message";
+ NotSerializableException nse = new NotSerializableException(message);
+ assertSame(message, nse.getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectInputStream2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectInputStream2Test.java
new file mode 100644
index 0000000..af5fce5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectInputStream2Test.java
@@ -0,0 +1,213 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InvalidClassException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.ArrayList;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class ObjectInputStream2Test extends TestCase {
+
+ public void test_readUnshared() throws IOException, ClassNotFoundException {
+ // Regression test for HARMONY-819
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try {
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject("abc");
+ oos.writeObject("abc");
+ oos.close();
+
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray()));
+ ois.readUnshared();
+ ois.readObject();
+ ois.close();
+ fail("Expected ObjectStreamException");
+ } catch (ObjectStreamException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Micro-scenario of de/serialization of an object with non-serializable
+ * superclass. The super-constructor only should be invoked on the
+ * deserialized instance.
+ */
+ public void test_readObject_Hierarchy() throws IOException,
+ ClassNotFoundException {
+ 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();
+ 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);
+ }
+
+ /**
+ * {@link java.io.ObjectInputStream#readNewLongString()}
+ */
+ public void test_readNewLongString() throws Exception {
+ LongString longString = new LongString();
+ SerializationTest.verifySelf(longString);
+ }
+
+ @SuppressWarnings("serial")
+ private static class LongString implements Serializable {
+ String lString;
+
+ public LongString() {
+ StringBuilder builder = new StringBuilder();
+ // construct a string whose length > 64K
+ for (int i = 0; i < 65636; i++) {
+ builder.append('1');
+ }
+ lString = builder.toString();
+ }
+
+ @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;
+ }
+
+ @Override
+ public int hashCode() {
+ return lString.hashCode();
+ }
+ }
+
+ 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);
+ }
+ }
+
+ 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);
+ }
+ }
+
+ class OIS extends ObjectInputStream {
+
+ OIS() throws IOException {
+ super();
+ }
+
+ void test() throws ClassNotFoundException, IOException {
+ readClassDescriptor();
+ }
+
+ }
+
+ public void test_readClassDescriptor() throws ClassNotFoundException,
+ IOException {
+ try {
+ new OIS().test();
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ static class TestObjectInputStream extends ObjectInputStream {
+ public TestObjectInputStream(InputStream in) throws IOException {
+ super(in);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Class resolveClass(ObjectStreamClass desc)
+ throws IOException, ClassNotFoundException {
+ if (desc.getName().endsWith("ObjectInputStream2Test$TestClass1")) {
+ return TestClass2.class;
+ }
+ return super.resolveClass(desc);
+ }
+ }
+
+ static class TestClass1 implements Serializable {
+ private static final long serialVersionUID = 11111L;
+ int i = 0;
+ }
+
+ static class TestClass2 implements Serializable {
+ private static final long serialVersionUID = 11111L;
+ int i = 0;
+ }
+
+ public void test_resolveClass_invalidClassName() throws Exception {
+ // Regression test for HARMONY-1920
+ TestClass1 to1 = new TestClass1();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ ByteArrayInputStream bais;
+ ObjectInputStream ois;
+
+ to1.i = 555;
+ oos.writeObject(to1);
+ oos.flush();
+ byte[] bytes = baos.toByteArray();
+ bais = new ByteArrayInputStream(bytes);
+ ois = new TestObjectInputStream(bais);
+
+ try {
+ ois.readObject();
+ fail("Should throw InvalidClassException");
+ } catch (InvalidClassException ice) {
+ // Excpected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStream2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStream2Test.java
new file mode 100644
index 0000000..99546c4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStream2Test.java
@@ -0,0 +1,59 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import junit.framework.TestCase;
+
+public class ObjectOutputStream2Test extends TestCase {
+
+ private static enum MyEnum {
+ ONE {
+ public void anything() {
+ }
+ },
+ TWO {
+ public void anything() {
+ }
+ },
+ THREE {
+ public void anything() {
+ }
+ };
+
+ public abstract void anything();
+ }
+
+ public void test_writeReadEnum() throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream os = new ObjectOutputStream(bos);
+ os.writeObject(MyEnum.TWO);
+ os.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ ObjectInputStream is = new ObjectInputStream(bis);
+ Object readObj = is.readObject();
+ is.close();
+ assertSame(MyEnum.TWO, readObj);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStreamTest.java
new file mode 100644
index 0000000..1c98257
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectOutputStreamTest.java
@@ -0,0 +1,1323 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.NotActiveException;
+import java.io.NotSerializableException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamConstants;
+import java.io.ObjectStreamException;
+import java.io.ObjectStreamField;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.io.SerializablePermission;
+import java.io.WriteAbortedException;
+import java.security.Permission;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+@SuppressWarnings({ "unused", "serial" })
+public class ObjectOutputStreamTest extends TestCase implements Serializable {
+
+ File f;
+
+ 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 IOException {
+ // note aField2 is not read
+ try {
+ ObjectInputStream.GetField fields = ois.readFields();
+ aField1 = (String) fields.get("aField1", "Zap");
+ } catch (Exception e) {
+ }
+ }
+
+ 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;
+ }
+ }
+
+ private static class SerializationTest implements java.io.Serializable {
+ int anInt = INIT_INT_VALUE;
+
+ public SerializationTest() {
+ super();
+ }
+ }
+
+ private static class SerializationTestSubclass1 extends SerializationTest
+ implements Serializable {
+ String aString = INIT_STR_VALUE;
+
+ public SerializationTestSubclass1() {
+ super();
+ // Just to change default superclass init value
+ anInt = INIT_INT_VALUE / 2;
+ }
+ }
+
+ private static class SpecTestSuperClass implements Runnable, Serializable {
+ protected java.lang.String instVar;
+
+ public void run() {
+ }
+ }
+
+ private static class SpecTest extends SpecTestSuperClass implements
+ Cloneable, Serializable {
+ public java.lang.String instVar1;
+
+ public static java.lang.String staticVar1;
+
+ public static java.lang.String staticVar2;
+
+ {
+ instVar1 = "NonStaticInitialValue";
+ }
+
+ static {
+ staticVar1 = "StaticInitialValue";
+ staticVar1 = new String(staticVar1);
+ }
+
+ public Object method(Object objParam, Object objParam2) {
+ return new Object();
+ }
+
+ public boolean method(boolean bParam, Object objParam) {
+ return true;
+ }
+
+ public boolean method(boolean bParam, Object objParam, Object objParam2) {
+ return true;
+ }
+
+ }
+
+ private static class SpecTestSubclass extends SpecTest implements
+ Serializable {
+ public transient java.lang.String transientInstVar = "transientValue";
+ }
+
+ private static class ReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public ReadWriteObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ private static class PublicReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public PublicReadWriteObject() {
+ super();
+ }
+
+ public void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ public void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ private static class FieldOrder implements Serializable {
+ String aaa1NonPrimitive = "aaa1";
+
+ int bbb1PrimitiveInt = 5;
+
+ boolean aaa2PrimitiveBoolean = true;
+
+ String bbb2NonPrimitive = "bbb2";
+ }
+
+ private static class JustReadObject implements java.io.Serializable {
+ public boolean calledReadObject = false;
+
+ public JustReadObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.defaultReadObject();
+ }
+ }
+
+ private static class JustWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public JustWriteObject() {
+ super();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ calledWriteObject = true;
+ out.defaultWriteObject();
+ }
+ }
+
+ private static class ClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ public boolean calledReplacement = false;
+
+ public ClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ calledReplacement = true;
+ return FOO; // Replacement is a String
+ }
+ }
+
+ private static class MultipleClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ private static class C1 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C2();
+ }
+ }
+
+ private static class C2 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C3();
+ }
+ }
+
+ private static class C3 implements java.io.Serializable {
+ private Object writeReplace() {
+ return FOO;
+ }
+ }
+
+ public MultipleClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ return new C1();
+ }
+ }
+
+ private static class ClassBasedReplacementWhenLoading implements
+ java.io.Serializable {
+ public ClassBasedReplacementWhenLoading() {
+ super();
+ }
+
+ private Object readResolve() {
+ return FOO; // Replacement is a String
+ }
+ }
+
+ private static class ClassBasedReplacementWhenLoadingViolatesFieldType
+ implements java.io.Serializable {
+ public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
+
+ public ClassBasedReplacementWhenLoadingViolatesFieldType() {
+ super();
+ }
+ }
+
+ private static class MyExceptionWhenDumping implements java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ }
+
+ ;
+
+ public boolean anInstanceVar = false;
+
+ public MyExceptionWhenDumping() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ private static class NonSerializableExceptionWhenDumping implements
+ java.io.Serializable {
+ public Object anInstanceVar = new Object();
+
+ public NonSerializableExceptionWhenDumping() {
+ super();
+ }
+ }
+
+ private static class MyUnserializableExceptionWhenDumping implements
+ java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ private Object notSerializable = new Object();
+ }
+
+ ;
+
+ public boolean anInstanceVar = false;
+
+ public MyUnserializableExceptionWhenDumping() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ private static class WithUnmatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "value", String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WithUnmatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ private static class WithMatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "anInstanceVar", String.class) };
+
+ public String anInstanceVar = FOO + FOO;
+
+ public WithMatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ private static class SerialPersistentFields implements java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectInputStream.GetField fields = in.readFields();
+ anInstanceVar = Integer.parseInt((String) fields.get(
+ SIMULATED_FIELD_NAME, "-5"));
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectOutputStream.PutField fields = out.putFields();
+ fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
+ out.writeFields();
+ }
+ }
+
+ private static class WriteFieldsWithoutFetchingPutFields implements
+ java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WriteFieldsWithoutFetchingPutFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ out.writeFields();
+ }
+ }
+
+ private static class SerialPersistentFieldsWithoutField implements
+ java.io.Serializable {
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFieldsWithoutField() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ out.putFields();
+ out.writeFields();
+ }
+ }
+
+ private static class NotSerializable {
+ private int foo;
+
+ public NotSerializable() {
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return new Integer(42);
+ }
+ }
+
+ private static class WriteReplaceObject implements Serializable {
+ private Object replaceObject;
+
+ private static enum Color {
+ red, blue, green
+ }
+
+ ;
+
+ public WriteReplaceObject(Object o) {
+ replaceObject = o;
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return replaceObject;
+ }
+ }
+
+ private static class ExternalizableWithReplace implements Externalizable {
+ private int foo;
+
+ public ExternalizableWithReplace() {
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return new Integer(42);
+ }
+
+ public void writeExternal(ObjectOutput out) {
+ }
+
+ public void readExternal(ObjectInput in) {
+ }
+ }
+
+ private static class ObjectOutputStreamWithReplace extends
+ ObjectOutputStream {
+ public ObjectOutputStreamWithReplace(OutputStream out)
+ throws IOException {
+ super(out);
+ enableReplaceObject(true);
+ }
+
+ protected Object replaceObject(Object obj) throws IOException {
+ if (obj instanceof NotSerializable) {
+ return new Long(10);
+ }
+ if (obj instanceof Integer) {
+ return new Long(((Integer) obj).longValue());
+ }
+ return super.replaceObject(obj);
+ }
+ }
+
+ private static class ObjectOutputStreamWithReplace2 extends
+ ObjectOutputStream {
+ public ObjectOutputStreamWithReplace2(OutputStream out)
+ throws IOException {
+ super(out);
+ enableReplaceObject(true);
+ }
+
+ protected Object replaceObject(Object obj) throws IOException {
+ return new Long(10);
+ }
+ }
+
+ private static class ObjectOutputStreamWriteOverride extends
+ ObjectOutputStream {
+ String test = "test";
+
+ protected ObjectOutputStreamWriteOverride() throws IOException,
+ SecurityException {
+ super();
+ }
+
+ @Override
+ protected void writeObjectOverride(Object object) throws IOException {
+ test = null;
+ super.writeObjectOverride(object);
+ }
+ }
+
+ protected static final String MODE_XLOAD = "xload";
+
+ protected static final String MODE_XDUMP = "xdump";
+
+ static final String FOO = "foo";
+
+ static final String MSG_WITE_FAILED = "Failed to write: ";
+
+ private static final boolean DEBUG = false;
+
+ protected static boolean xload = false;
+
+ protected static boolean xdump = false;
+
+ protected static String xFileName = null;
+
+ protected ObjectInputStream ois;
+
+ protected ObjectOutputStream oos;
+
+ protected ByteArrayOutputStream bao;
+
+ static final int INIT_INT_VALUE = 7;
+
+ static final String INIT_STR_VALUE = "a string that is blortz";
+
+ /**
+ * java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws IOException {
+ // Test for method java.io.ObjectOutputStream(java.io.OutputStream)
+ oos.close();
+ oos = new ObjectOutputStream(new ByteArrayOutputStream());
+ oos.close();
+ }
+
+ /**
+ * java.io.ObjectOutputStream#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.ObjectOutputStream.close()
+ }
+
+ /**
+ * java.io.ObjectOutputStream#defaultWriteObject()
+ */
+ public void test_defaultWriteObject() throws IOException {
+ // Test for method void java.io.ObjectOutputStream.defaultWriteObject()
+ try {
+ oos.defaultWriteObject();
+ fail("Failed to throw NotActiveException");
+ } catch (NotActiveException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#flush()
+ */
+ public void test_flush() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.flush()
+ int size = bao.size();
+ oos.writeByte(127);
+ assertTrue("Data flushed already", bao.size() == size);
+ oos.flush();
+ assertTrue("Failed to flush data", bao.size() > size);
+ // we don't know how many bytes are actually written for 1
+ // byte, so we test > <before>
+ oos.close();
+ oos = null;
+ }
+
+ /**
+ * java.io.ObjectOutputStream#putFields()
+ */
+ public void test_putFields() throws Exception {
+ // Test for method java.io.ObjectOutputStream$PutField
+ // java.io.ObjectOutputStream.putFields()
+
+ 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());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#reset()
+ */
+ public void test_reset() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.reset()
+ String o = "HelloWorld";
+ oos.writeObject(o);
+ oos.writeObject(o);
+ oos.reset();
+ oos.writeObject(o);
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.close();
+ }
+
+ private static class ExternalTest implements Externalizable {
+ public String value;
+
+ public ExternalTest() {
+ }
+
+ public void setValue(String val) {
+ value = val;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void writeExternal(ObjectOutput output) {
+ try {
+ output.writeUTF(value);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void readExternal(ObjectInput input) {
+ try {
+ value = input.readUTF();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#useProtocolVersion(int)
+ */
+ public void test_useProtocolVersionI() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.useProtocolVersion(int)
+ oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
+ ExternalTest t1 = new ExternalTest();
+ t1.setValue("hello1");
+ oos.writeObject(t1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ExternalTest t2 = (ExternalTest) ois.readObject();
+ ois.close();
+ assertTrue(
+ "Cannot read/write PROTOCAL_VERSION_1 Externalizable objects: "
+ + t2.getValue(), t1.getValue().equals(t2.getValue()));
+
+ // Cannot set protocol version when stream in-flight
+ ObjectOutputStream out = new ObjectOutputStream(
+ new ByteArrayOutputStream());
+ out.writeObject("hello world");
+ try {
+ out.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_1);
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#write(byte[])
+ */
+ public void test_write$B() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.write(byte [])
+ byte[] buf = new byte[10];
+ oos.write("HelloWorld".getBytes());
+ 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));
+ }
+
+ /**
+ * java.io.ObjectOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.write(byte [], int,
+ // int)
+ byte[] buf = new byte[10];
+ oos.write("HelloWorld".getBytes(), 0, 10);
+ 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));
+ }
+
+ /**
+ * java.io.ObjectOutputStream#write(int)
+ */
+ public void test_writeI() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.write(int)
+ oos.write('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect byte", 'T', ois.read());
+ ois.close();
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeBoolean(boolean)
+ */
+ public void test_writeBooleanZ() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeBoolean(boolean)
+ oos.writeBoolean(true);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Wrote incorrect byte value", ois.readBoolean());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeByte(int)
+ */
+ public void test_writeByteI() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeByte(int)
+ oos.writeByte(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Wrote incorrect byte value", 127, ois.readByte());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeBytes(java.lang.String)
+ */
+ public void test_writeBytesLjava_lang_String() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeBytes(java.lang.String)
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readFully(buf);
+ ois.close();
+ assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(
+ buf, 0, 10, "UTF-8"));
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeChar(int)
+ */
+ public void test_writeCharI() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeChar(int)
+ oos.writeChar('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Wrote incorrect char value", 'T', ois.readChar());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeChars(java.lang.String)
+ */
+ public void test_writeCharsLjava_lang_String() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeChars(java.lang.String)
+ int avail = 0;
+ char[] buf = new char[10];
+ oos.writeChars("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ // Number of prim data bytes in stream / 2 to give char index
+ avail = ois.available() / 2;
+ for (int i = 0; i < avail; ++i)
+ buf[i] = ois.readChar();
+ ois.close();
+ assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0,
+ 10));
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeDouble(double)
+ */
+ public void test_writeDoubleD() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeDouble(double)
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readDouble() == Double.MAX_VALUE);
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeFields()
+ */
+ public void test_writeFields() {
+ // Test for method void java.io.ObjectOutputStream.writeFields()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeFloat(float)
+ */
+ public void test_writeFloatF() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeFloat(float)
+ oos.writeFloat(Float.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readFloat() == Float.MAX_VALUE);
+ ois.close();
+ ois = null;
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeInt(int)
+ */
+ public void test_writeIntI() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeInt(int)
+ oos.writeInt(Integer.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readInt() == Integer.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeLong(long)
+ */
+ public void test_writeLongJ() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeLong(long)
+ oos.writeLong(Long.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readLong() == Long.MAX_VALUE);
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ */
+ public void test_writeObjectLjava_lang_Object() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
+ final int CONST = -500;
+ spf.anInstanceVar = CONST;
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(
+ "serialPersistentFields do not work properly in this implementation",
+ ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
+
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ */
+ public void test_writeObject_NotSerializable() throws Exception {
+ ObjectOutput out = null;
+ try {
+ out = new ObjectOutputStream(new ByteArrayOutputStream());
+ out.writeObject(new NotSerializable());
+ fail("Expected NotSerializableException");
+ } catch (NotSerializableException e) {
+ }
+ out.writeObject(new ExternalizableWithReplace());
+ }
+
+ /**
+ * {@link java.io.ObjectOutputStream#writeObjectOverride(Object)}
+ */
+ public void test_writeObject_WriteOverride() throws Exception {
+ ObjectOutputStreamWriteOverride mockOut = new ObjectOutputStreamWriteOverride();
+ mockOut.writeObject(new Object());
+ assertNull(mockOut.test);
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeShort(int)
+ */
+ public void test_writeShortI() throws Exception {
+ // Test for method void java.io.ObjectOutputStream.writeShort(int)
+ oos.writeShort(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Wrote incorrect short value", 127, ois.readShort());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeUTF(java.lang.String)
+ */
+ public void test_writeUTFLjava_lang_String() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeUTF(java.lang.String)
+ oos.writeUTF("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Wrote incorrect UTF value", "HelloWorld", ois.readUTF());
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ */
+ public void test_writeObject_Exception() throws ClassNotFoundException,
+ IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+
+ try {
+ oos.writeObject(new Object());
+ fail("should throw ObjectStreamException");
+ } catch (ObjectStreamException e) {
+ // expected
+ } finally {
+ oos.close();
+ baos.close();
+ }
+
+ byte[] bytes = baos.toByteArray();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
+ bytes));
+ try {
+ ois.readObject();
+ fail("should throw WriteAbortedException");
+ } catch (WriteAbortedException e) {
+ // expected
+ } finally {
+ ois.close();
+ }
+ }
+
+ /**
+ * {@link java.io.ObjectOutputStream#annotateProxyClass(java.lang.Class<T>)}
+ */
+ public void test_annotateProxyClass() throws SecurityException, IOException {
+ MockObjectOutputStream mockObjectOutputStream = new MockObjectOutputStream();
+ mockObjectOutputStream.annotateProxyClass(this.getClass());
+ assertEquals("The default implementation is doing nothing.",
+ mockObjectOutputStream, mockObjectOutputStream);
+
+ }
+
+ class MockObjectOutputStream extends ObjectOutputStream {
+
+ protected MockObjectOutputStream() throws IOException,
+ SecurityException {
+ super();
+ }
+
+ @Override
+ public void annotateProxyClass(Class<?> aClass) throws IOException {
+ super.annotateProxyClass(aClass);
+ }
+
+ }
+
+ /**
+ * 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();
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (Exception e) {
+ }
+ }
+ if (f != null && f.exists()) {
+ if (!f.delete()) {
+ fail("Error cleaning up files during teardown");
+ }
+ }
+ }
+
+ protected Object reload() throws IOException, ClassNotFoundException {
+
+ // Choose the load stream
+ if (xload || xdump) {
+ // Load from pre-existing file
+ ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
+ + getName() + ".ser"));
+ } else {
+ // Just load from memory, we dumped to memory
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ }
+
+ try {
+ return ois.readObject();
+ } finally {
+ ois.close();
+ }
+ }
+
+ protected void dump(Object o) throws IOException, ClassNotFoundException {
+
+ // Choose the dump stream
+ if (xdump) {
+ oos = new ObjectOutputStream(new FileOutputStream(
+ f = new java.io.File(xFileName + "-" + getName() + ".ser")));
+ } else {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ }
+
+ // Dump the object
+ try {
+ oos.writeObject(o);
+ } finally {
+ oos.close();
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeInt(int)
+ * java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ * java.io.ObjectOutputStream#writeUTF(java.lang.String)
+ */
+
+ public void testMixPrimitivesAndObjects() throws Exception {
+ int i = 7;
+ String s1 = "string 1";
+ String s2 = "string 2";
+ byte[] bytes = { 1, 2, 3 };
+ try {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ oos.writeInt(i);
+ oos.writeObject(s1);
+ oos.writeUTF(s2);
+ oos.writeObject(bytes);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+
+ int j = ois.readInt();
+ assertTrue("Wrong int :" + j, i == j);
+
+ String l1 = (String) ois.readObject();
+ assertTrue("Wrong obj String :" + l1, s1.equals(l1));
+
+ String l2 = ois.readUTF();
+ assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
+
+ byte[] bytes2 = (byte[]) ois.readObject();
+ assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
+ } finally {
+ try {
+ if (oos != null)
+ oos.close();
+ if (ois != null)
+ ois.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
+ */
+ public void test_writeUnshared() throws Exception {
+ // Regression for HARMONY-187
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+
+ Object o = "foobar";
+ oos.writeObject(o);
+ oos.writeUnshared(o);
+ oos.writeObject(o);
+ oos.flush();
+
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
+ baos.toByteArray()));
+
+ Object[] oa = new Object[3];
+ for (int i = 0; i < oa.length; i++) {
+ oa[i] = ois.readObject();
+ }
+
+ oos.close();
+ ois.close();
+
+ // All three conditions must be met
+ assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
+ assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
+ assertSame("oa[0] == oa[2]", oa[0], oa[2]);
+ }
+
+ /**
+ * java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
+ */
+ public void test_writeUnshared2() throws Exception {
+ // Regression for HARMONY-187
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+
+ Object o = new Object[1];
+ oos.writeObject(o);
+ oos.writeUnshared(o);
+ oos.writeObject(o);
+ oos.flush();
+
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
+ baos.toByteArray()));
+
+ Object[] oa = new Object[3];
+ for (int i = 0; i < oa.length; i++) {
+ oa[i] = ois.readObject();
+ }
+
+ oos.close();
+ ois.close();
+
+ // All three conditions must be met
+ assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
+ assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
+ assertSame("oa[0] == oa[2]", oa[0], oa[2]);
+ }
+
+ protected Object dumpAndReload(Object o) throws IOException,
+ ClassNotFoundException {
+ dump(o);
+ return reload();
+ }
+
+ /**
+ * java.io.ObjectOutputStream#useProtocolVersion(int)
+ */
+ public void test_useProtocolVersionI_2() throws Exception {
+ ObjectOutputStream oos = new ObjectOutputStream(
+ new ByteArrayOutputStream());
+
+ oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
+ oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_2);
+ try {
+ oos.useProtocolVersion(3);
+ fail("Protocol 3 should not be accepted");
+ } catch (IllegalArgumentException e) {
+ // expected
+ } finally {
+ oos.close();
+ }
+ }
+
+ /**
+ * java.io.ObjectOutputStream#replaceObject(java.lang.Object)
+ */
+ public void test_replaceObject() throws Exception {
+ // Regression for HARMONY-1429
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStreamWithReplace oos = new ObjectOutputStreamWithReplace(
+ baos);
+
+ oos.writeObject(new NotSerializable());
+ oos.flush();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
+ baos.toByteArray()));
+ Object obj = ois.readObject();
+ oos.close();
+ ois.close();
+ assertTrue("replaceObject has not been called", (obj instanceof Long));
+
+ // Regression for HARMONY-2239
+ Object replaceObject = int.class;
+ baos = new ByteArrayOutputStream();
+ ObjectOutputStreamWithReplace2 oos2 = new ObjectOutputStreamWithReplace2(
+ baos);
+ oos2.writeObject(new WriteReplaceObject(replaceObject));
+ oos2.flush();
+ ois = new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray()));
+ obj = ois.readObject();
+ oos.close();
+ ois.close();
+ assertTrue("replaceObject has not been called", (obj instanceof Long));
+
+ replaceObject = ObjectStreamClass.lookup(Integer.class);
+ baos = new ByteArrayOutputStream();
+ oos2 = new ObjectOutputStreamWithReplace2(baos);
+ oos2.writeObject(new WriteReplaceObject(replaceObject));
+ oos2.flush();
+ ois = new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray()));
+ obj = ois.readObject();
+ oos.close();
+ ois.close();
+ assertTrue("replaceObject has not been called", (obj instanceof Long));
+
+ replaceObject = WriteReplaceObject.Color.red;
+ baos = new ByteArrayOutputStream();
+ oos2 = new ObjectOutputStreamWithReplace2(baos);
+ oos2.writeObject(new WriteReplaceObject(replaceObject));
+ oos2.flush();
+ ois = new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray()));
+ obj = ois.readObject();
+ oos.close();
+ ois.close();
+ assertTrue("replaceObject has not been called", (obj instanceof Long));
+
+ // Regression for HARMONY-3158
+ Object obj1;
+ Object obj2;
+ Object obj3;
+
+ baos = new ByteArrayOutputStream();
+ oos = new ObjectOutputStreamWithReplace(baos);
+
+ oos.writeObject(new Integer(99));
+ oos.writeObject(Integer.class);
+ oos.writeObject(ObjectStreamClass.lookup(Integer.class));
+ oos.flush();
+
+ ois = new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray()));
+ obj1 = ois.readObject();
+ obj2 = ois.readObject();
+ obj3 = ois.readObject();
+ oos.close();
+ ois.close();
+
+ assertTrue("1st replaceObject worked incorrectly", obj1 instanceof Long);
+ assertEquals("1st replaceObject worked incorrectly", 99, ((Long) obj1)
+ .longValue());
+ assertEquals("2nd replaceObject worked incorrectly", Integer.class,
+ obj2);
+ assertEquals("3rd replaceObject worked incorrectly",
+ ObjectStreamClass.class, obj3.getClass());
+ }
+
+ public void test_putFieldWrite() throws Exception {
+ // Regression test for HARMONY-6483
+ ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream());
+ try {
+ oos.writeObject(new OutputObject());
+ fail("Should throw an IllegalArgumentException");
+ } catch (IllegalArgumentException iae) {
+ // Expected
+ }
+ }
+
+ private static class OutputObject implements Serializable {
+ private void writeObject(ObjectOutputStream oos) throws IOException {
+ ObjectOutputStream oos2 = new ObjectOutputStream(new ByteArrayOutputStream());
+ ObjectOutputStream.PutField putField = oos.putFields();
+ putField.write(oos2);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamClassTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamClassTest.java
new file mode 100644
index 0000000..3806492
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamClassTest.java
@@ -0,0 +1,223 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestCase;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
+import java.lang.reflect.Proxy;
+
+public class ObjectStreamClassTest extends TestCase {
+
+ static class DummyClass implements Serializable {
+ private static final long serialVersionUID = 999999999999999L;
+
+ long bam = 999L;
+
+ int ham = 9999;
+
+ public static long getUID() {
+ return serialVersionUID;
+ }
+ }
+
+ /**
+ * java.io.ObjectStreamClass#forClass()
+ */
+ public void test_forClass() {
+ // Need to test during serialization to be sure an instance is
+ // returned
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertEquals("forClass returned an object: " + osc.forClass(),
+ DummyClass.class, osc.forClass());
+ }
+
+ /**
+ * java.io.ObjectStreamClass#getField(java.lang.String)
+ */
+ public void test_getFieldLjava_lang_String() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertEquals("getField did not return correct field", 'J', osc
+ .getField("bam").getTypeCode());
+ assertNull("getField did not null for non-existent field", osc
+ .getField("wham"));
+ }
+
+ /**
+ * java.io.ObjectStreamClass#getFields()
+ */
+ public void test_getFields() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ ObjectStreamField[] osfArray = osc.getFields();
+ assertTrue(
+ "Array of fields should be of length 2 but is instead of length: "
+ + osfArray.length, osfArray.length == 2);
+ }
+
+ /**
+ * java.io.ObjectStreamClass#getName()
+ */
+ public void test_getName() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertEquals(
+ "getName returned incorrect name: " + osc.getName(),
+ "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass",
+ osc.getName());
+ }
+
+ /**
+ * java.io.ObjectStreamClass#getSerialVersionUID()
+ */
+ public void test_getSerialVersionUID() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("getSerialversionUID returned incorrect uid: "
+ + osc.getSerialVersionUID() + " instead of "
+ + DummyClass.getUID(), osc.getSerialVersionUID() == DummyClass
+ .getUID());
+ }
+
+ static class SyntheticTest implements Serializable {
+ private int i;
+
+ private class X implements Serializable {
+ public int get() {
+ return i;
+ }
+ }
+
+ public X foo() {
+ return new X();
+ }
+ }
+
+ /**
+ * java.io.ObjectStreamClass#lookup(java.lang.Class)
+ */
+ public void test_lookupLjava_lang_Class() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertEquals(
+ "lookup returned wrong class: " + osc.getName(),
+ "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass",
+ osc.getName());
+ }
+
+ /**
+ * java.io.ObjectStreamClass#toString()
+ */
+ public void test_toString() {
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ String oscString = osc.toString();
+
+ // The previous test was more specific than the spec so it was replaced
+ // with the test below
+ assertTrue("toString returned incorrect string: " + osc.toString(),
+ oscString.indexOf("serialVersionUID") >= 0
+ && oscString.indexOf("999999999999999L") >= 0);
+ }
+
+ public void testSerialization() {
+ ObjectStreamClass osc = ObjectStreamClass
+ .lookup(ObjectStreamClass.class);
+ assertEquals(0, osc.getFields().length);
+ }
+
+ public void test_specialTypes() {
+ Class<?> proxyClass = Proxy.getProxyClass(this.getClass()
+ .getClassLoader(), new Class[] { Runnable.class });
+
+ ObjectStreamClass proxyStreamClass = ObjectStreamClass
+ .lookup(proxyClass);
+
+ assertEquals("Proxy classes should have zero serialVersionUID", 0,
+ proxyStreamClass.getSerialVersionUID());
+ ObjectStreamField[] proxyFields = proxyStreamClass.getFields();
+ assertEquals("Proxy classes should have no serialized fields", 0,
+ proxyFields.length);
+
+ ObjectStreamClass enumStreamClass = ObjectStreamClass
+ .lookup(Thread.State.class);
+
+ assertEquals("Enum classes should have zero serialVersionUID", 0,
+ enumStreamClass.getSerialVersionUID());
+ ObjectStreamField[] enumFields = enumStreamClass.getFields();
+ assertEquals("Enum classes should have no serialized fields", 0,
+ enumFields.length);
+ }
+
+ /**
+ * @since 1.6
+ */
+ static class NonSerialzableClass {
+ private static final long serialVersionUID = 1l;
+
+ public static long getUID() {
+ return serialVersionUID;
+ }
+ }
+
+ /**
+ * @since 1.6
+ */
+ static class ExternalizableClass implements Externalizable {
+
+ private static final long serialVersionUID = -4285635779249689129L;
+
+ public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException {
+ throw new ClassNotFoundException();
+ }
+
+ public void writeExternal(ObjectOutput output) throws IOException {
+ throw new IOException();
+ }
+
+ }
+
+ /**
+ * java.io.ObjectStreamClass#lookupAny(java.lang.Class)
+ * @since 1.6
+ */
+ public void test_lookupAnyLjava_lang_Class() {
+ // Test for method java.io.ObjectStreamClass
+ // java.io.ObjectStreamClass.lookupAny(java.lang.Class)
+ ObjectStreamClass osc = ObjectStreamClass.lookupAny(DummyClass.class);
+ assertEquals("lookup returned wrong class: " + osc.getName(),
+ "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass", osc
+ .getName());
+
+ osc = ObjectStreamClass.lookupAny(NonSerialzableClass.class);
+ assertEquals("lookup returned wrong class: " + osc.getName(),
+ "org.apache.harmony.tests.java.io.ObjectStreamClassTest$NonSerialzableClass",
+ osc.getName());
+
+ osc = ObjectStreamClass.lookupAny(ExternalizableClass.class);
+ assertEquals("lookup returned wrong class: " + osc.getName(),
+ "org.apache.harmony.tests.java.io.ObjectStreamClassTest$ExternalizableClass",
+ osc.getName());
+
+ osc = ObjectStreamClass.lookup(NonSerialzableClass.class);
+ assertNull(osc);
+
+ }
+
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamConstantsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamConstantsTest.java
new file mode 100644
index 0000000..7fbaa93
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamConstantsTest.java
@@ -0,0 +1,45 @@
+/* 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.tests.java.io;
+
+import java.io.ObjectStreamConstants;
+
+import junit.framework.TestCase;
+
+public class ObjectStreamConstantsTest extends TestCase {
+
+ /**
+ * java.io.ObjectStreamConstants#TC_ENUM
+ */
+ public void test_TC_ENUM() {
+ assertEquals(126, ObjectStreamConstants.TC_ENUM);
+ }
+
+ /**
+ * java.io.ObjectStreamConstants#SC_ENUM
+ */
+ public void test_SC_ENUM() {
+ assertEquals(16, ObjectStreamConstants.SC_ENUM);
+ }
+
+ /**
+ * java.io.ObjectStreamConstants#TC_MAX
+ */
+ public void test_TC_MAX() {
+ assertEquals(126, ObjectStreamConstants.TC_MAX);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamFieldTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamFieldTest.java
new file mode 100644
index 0000000..8dd12a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ObjectStreamFieldTest.java
@@ -0,0 +1,395 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.NotActiveException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamField;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.io.StreamCorruptedException;
+import java.util.Date;
+
+public class ObjectStreamFieldTest extends junit.framework.TestCase {
+
+ static class DummyClass implements Serializable {
+ private static final long serialVersionUID = 999999999999998L;
+
+ long bam = 999L;
+
+ int ham = 9999;
+
+ int sam = 8888;
+
+ Object hola = new Object();
+
+ public static long getUID() {
+ return serialVersionUID;
+ }
+ }
+
+ ObjectStreamClass osc;
+
+ ObjectStreamField hamField;
+
+ ObjectStreamField samField;
+
+ ObjectStreamField bamField;
+
+ ObjectStreamField holaField;
+
+ /**
+ * java.io.ObjectStreamField#ObjectStreamField(java.lang.String,
+ *java.lang.Class)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_Class() {
+ assertTrue("Used to test", true);
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ // Regression test for HARMONY-4273
+ assertTrue(samField.equals(samField));
+ assertFalse(samField.equals(hamField));
+ assertFalse(samField.equals("fish"));
+ assertFalse(samField.equals(null));
+ }
+
+ /**
+ * java.io.ObjectStreamField#compareTo(java.lang.Object)
+ */
+ public void test_compareToLjava_lang_Object() {
+ assertTrue("Object compared to int did not return > 0", holaField
+ .compareTo(hamField) > 0);
+ assertEquals("Int compared to itself did not return 0", 0, hamField
+ .compareTo(hamField));
+ assertTrue("(Int)ham compared to (Int)sam did not return < 0", hamField
+ .compareTo(samField) < 0);
+ }
+
+ /**
+ * java.io.ObjectStreamField#getName()
+ */
+ public void test_getName() {
+ assertEquals("Field did not return correct name", "hola", holaField
+ .getName());
+ }
+
+ /**
+ * java.io.ObjectStreamField#getOffset()
+ */
+ public void test_getOffset() {
+ ObjectStreamField[] osfArray;
+ osfArray = osc.getFields();
+ assertTrue("getOffset did not return reasonable values", osfArray[0]
+ .getOffset() != osfArray[1].getOffset());
+ assertEquals("getOffset for osfArray[0].getOffset() did not return 0",
+ 0, osfArray[0].getOffset());
+ assertEquals("osfArray[1].getOffset() did not return 8", 8, osfArray[1]
+ .getOffset());
+ assertEquals("osfArray[2].getOffset() did not return 12", 12,
+ osfArray[2].getOffset());
+ }
+
+ /**
+ * java.io.ObjectStreamField#getType()
+ */
+ public void test_getType() {
+ assertTrue("getType on an Object field did not answer Object",
+ holaField.getType().equals(Object.class));
+ }
+
+ /**
+ * java.io.ObjectStreamField#getTypeCode()
+ */
+ public void test_getTypeCode() {
+ assertEquals("getTypeCode on an Object field did not answer 'L'", 'L',
+ holaField.getTypeCode());
+ assertEquals("getTypeCode on a long field did not answer 'J'", 'J',
+ bamField.getTypeCode());
+ }
+
+ /**
+ * java.io.ObjectStreamField#getTypeString()
+ */
+ public void test_getTypeString() {
+ assertTrue("getTypeString returned: " + holaField.getTypeString(),
+ holaField.getTypeString().indexOf("Object") >= 0);
+ assertNull("Primitive types' strings should be null", hamField
+ .getTypeString());
+
+ ObjectStreamField osf = new ObjectStreamField("s", String.class, true);
+ assertTrue(osf.getTypeString() == "Ljava/lang/String;");
+ }
+
+ /**
+ * java.io.ObjectStreamField#toString()
+ */
+ public void test_toString() {
+ assertTrue("toString on a long returned: " + bamField.toString(),
+ bamField.toString().indexOf("bam") >= 0);
+ }
+
+ /**
+ * java.io.ObjectStreamField#getType()
+ */
+ public void test_getType_Deserialized() throws IOException,
+ ClassNotFoundException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(new SerializableObject());
+ oos.close();
+ baos.close();
+
+ byte[] bytes = baos.toByteArray();
+ ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ ObjectInputStream ois = new ObjectInputStream(bais);
+ SerializableObject obj = (SerializableObject) ois.readObject();
+
+ ObjectStreamClass oc = obj.getObjectStreamClass();
+ ObjectStreamField field = oc.getField("i");
+ assertEquals(Object.class, field.getType());
+ }
+
+ /**
+ * java.io.ObjectStreamField#getType()
+ */
+ public void test_getType_MockObjectInputStream() throws IOException,
+ ClassNotFoundException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(new SerializableObject());
+ oos.close();
+ baos.close();
+
+ byte[] bytes = baos.toByteArray();
+ ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ MockObjectInputStream ois = new MockObjectInputStream(bais);
+ ois.readObject();
+
+ ObjectStreamClass oc = ois.getObjectStreamClass();
+ ObjectStreamField field = oc.getField("i");
+ assertEquals(Object.class, field.getType());
+ }
+
+ public void test_isUnshared() throws Exception {
+ SerializableObject2 obj = new SerializableObject2();
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(obj);
+ oos.close();
+ baos.close();
+ byte[] bytes = baos.toByteArray();
+ ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ ObjectInputStream ois = new ObjectInputStream(bais);
+ SerializableObject2 newObj = (SerializableObject2) ois.readObject();
+
+ ObjectInputStream.GetField getField = newObj.getGetField();
+ ObjectStreamClass objectStreamClass = getField.getObjectStreamClass();
+
+ assertTrue(objectStreamClass.getField("i").isUnshared());
+ assertFalse(objectStreamClass.getField("d").isUnshared());
+ assertTrue(objectStreamClass.getField("s").isUnshared());
+
+ assertEquals(1000, getField.get("i", null));
+ assertEquals(SerializableObject2.today, getField.get("d", null));
+ assertEquals("Richard", getField.get("s", null));
+
+ assertTrue(objectStreamClass.getField("s").getTypeString() == "Ljava/lang/String;");
+
+ assertEquals(0, objectStreamClass.getField("d").getOffset());
+ assertEquals(1, objectStreamClass.getField("i").getOffset());
+ assertEquals(2, objectStreamClass.getField("s").getOffset());
+ }
+
+
+ /**
+ * Write/serialize and read/de-serialize an object with primitive field
+ */
+ public void test_ObjectWithPrimitiveField()
+ throws IOException, ClassNotFoundException {
+
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final MyObjectOutputStream oos = new MyObjectOutputStream(baos);
+ oos.writeObject(new MockClass());
+ final byte[] bytes = baos.toByteArray();
+ final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ final MyObjectInputStream ois = new MyObjectInputStream(bais);
+ // NullPointerException is thrown by the readObject call below.
+ ois.readObject();
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ osc = ObjectStreamClass.lookup(DummyClass.class);
+ bamField = osc.getField("bam");
+ samField = osc.getField("sam");
+ hamField = osc.getField("ham");
+ holaField = osc.getField("hola");
+ }
+}
+
+class SerializableObject implements Serializable {
+ public ObjectInputStream.GetField getField = null;
+
+ private static final long serialVersionUID = -2953957835918368056L;
+
+ public Date d;
+
+ public Integer i;
+
+ public Exception e;
+
+ public SerializableObject() {
+ d = new Date();
+ i = new Integer(1);
+ e = new Exception("e");
+ }
+
+ private void writeObject(ObjectOutputStream o) throws IOException {
+ o.putFields().put("d", new Date());
+ o.putFields().put("i", new Integer(11));
+ o.writeFields();
+ }
+
+ private void readObject(ObjectInputStream in) throws NotActiveException,
+ IOException, ClassNotFoundException {
+ getField = in.readFields();
+ d = (Date) getField.get("d", null);
+ i = (Integer) getField.get("i", null);
+ }
+
+ public ObjectStreamClass getObjectStreamClass() {
+ return getField.getObjectStreamClass();
+ }
+}
+
+class MockObjectInputStream extends ObjectInputStream {
+ private ObjectStreamClass temp = null;
+
+ public MockObjectInputStream() throws SecurityException, IOException {
+ super();
+ }
+
+ public MockObjectInputStream(InputStream in)
+ throws StreamCorruptedException, IOException {
+ super(in);
+ }
+
+ public ObjectStreamClass readClassDescriptor() throws IOException,
+ ClassNotFoundException {
+ ObjectStreamClass osc = super.readClassDescriptor();
+ // To get the ObjectStreamClass of SerializableObject
+ if (osc.getSerialVersionUID() == -2953957835918368056L) {
+ temp = osc;
+ }
+ return osc;
+ }
+
+ public ObjectStreamClass getObjectStreamClass() {
+ return temp;
+ }
+}
+
+class SerializableObject2 implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("i", Integer.class, true),
+ new ObjectStreamField("d", Date.class, false),
+ new ObjectStreamField("s", String.class, true), };
+
+ private ObjectInputStream.GetField getField;
+
+ public static Date today = new Date(1172632429156l);
+
+ public ObjectInputStream.GetField getGetField() {
+ return getField;
+ }
+
+ private void writeObject(ObjectOutputStream o) throws IOException {
+ ObjectOutputStream.PutField putField = o.putFields();
+ putField.put("i", new Integer(1000));
+ putField.put("d", today);
+ putField.put("s", "Richard");
+ o.writeFields();
+ }
+
+ private void readObject(ObjectInputStream in) throws NotActiveException,
+ IOException, ClassNotFoundException {
+ getField = in.readFields();
+ }
+}
+
+
+// Primitive fields are necessary to cause the NullPointerException.
+class MockClass implements Serializable {
+ String str1 = "string 1";
+ String str2 = "string 2";
+ int int1 = 1;
+ int int2 = 2;
+ String str3 = "string 3";
+}
+
+
+// Overrides writeClassDescriptor to store ObjectStreamClass in map.
+class MyObjectOutputStream extends ObjectOutputStream {
+
+ // record the only ObjectStreamClass
+ static ObjectStreamClass descs;
+
+ MyObjectOutputStream(OutputStream out)
+ throws IOException {
+ super(out);
+ }
+
+ @Override
+ protected void writeClassDescriptor(ObjectStreamClass desc)
+ throws IOException {
+ descs = desc;
+ // Write a int
+ writeInt(1);
+ }
+}
+
+// Overrides readClassDescriptor to get ObjectStreamClass from map.
+class MyObjectInputStream extends ObjectInputStream {
+
+ MyObjectInputStream(InputStream in)
+ throws IOException {
+ super(in);
+ }
+
+ @Override
+ protected ObjectStreamClass readClassDescriptor()
+ throws IOException, ClassNotFoundException {
+ // Read a integer and get the only ObjectStreamClass for the test
+ final int id = readInt();
+ return MyObjectOutputStream.descs;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OpenRandomFileTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OpenRandomFileTest.java
new file mode 100644
index 0000000..2341ee9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OpenRandomFileTest.java
@@ -0,0 +1,58 @@
+/* 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+import junit.framework.TestCase;
+
+public class OpenRandomFileTest extends TestCase {
+
+ public static void main(String[] args) throws IOException {
+ new OpenRandomFileTest().testOpenEmptyFile();
+ }
+
+ public OpenRandomFileTest() {
+ super();
+ }
+
+ public void testOpenNonEmptyFile() throws IOException {
+ File file = File.createTempFile("test", "tmp");
+ assertTrue(file.exists());
+ file.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(file);
+ fos.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
+ fos.close();
+
+ String fileName = file.getCanonicalPath();
+ RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
+ raf.close();
+ }
+
+ public void testOpenEmptyFile() throws IOException {
+ File file = File.createTempFile("test", "tmp");
+ assertTrue(file.exists());
+ file.deleteOnExit();
+
+ String fileName = file.getCanonicalPath();
+ RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
+ raf.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamTesterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamTesterTest.java
new file mode 100644
index 0000000..0b5dde1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamTesterTest.java
@@ -0,0 +1,206 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestSuite;
+import org.apache.harmony.testframework.SinkTester;
+import org.apache.harmony.testframework.WrapperTester;
+import tests.support.Streams;
+
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.PrintStream;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * Tests basic {@link OutputStream} behaviors for the luni implementations of
+ * the type.
+ */
+public class OutputStreamTesterTest {
+
+ // TODO: Rewrite this test so that id doesn't need a suite().
+ private static junit.framework.Test suite() {
+ TestSuite suite = new TestSuite();
+
+ // sink tests
+ suite.addTest(new FileOutputStreamSinkTester(true).createTests());
+ suite.addTest(new FileOutputStreamSinkTester(false).createTests());
+ suite.addTest(new ByteArrayOutputStreamSinkTester(0).setThrowsExceptions(false).createTests());
+ suite.addTest(new ByteArrayOutputStreamSinkTester(4).setThrowsExceptions(false).createTests());
+ suite.addTest(new PipedOutputStreamSinkTester().createTests());
+
+ // wrapper tests
+ suite.addTest(new BufferedOutputStreamTester(1).createTests());
+ suite.addTest(new BufferedOutputStreamTester(5).createTests());
+ suite.addTest(new BufferedOutputStreamTester(1024).createTests());
+ suite.addTest(new FilterOutputStreamTester().createTests());
+ suite.addTest(new DataOutputStreamTester().createTests());
+ // fails wrapperTestFlushThrowsViaClose() and sinkTestWriteAfterClose():
+ // suite.addTest(new ObjectOutputStreamTester().createTests());
+ suite.addTest(new PrintStreamTester().setThrowsExceptions(false).createTests());
+
+ return suite;
+ }
+
+ private static class FileOutputStreamSinkTester extends SinkTester {
+
+ private final boolean append;
+ private File file;
+
+ private FileOutputStreamSinkTester(boolean append) {
+ this.append = append;
+ }
+
+ public OutputStream create() throws IOException {
+ file = File.createTempFile("FileOutputStreamSinkTester", "tmp");
+ file.deleteOnExit();
+ return new FileOutputStream(file, append);
+ }
+
+ public byte[] getBytes() throws IOException {
+ return Streams.streamToBytes(new FileInputStream(file));
+ }
+ }
+
+ private static class ByteArrayOutputStreamSinkTester extends SinkTester {
+
+ private final int size;
+ private ByteArrayOutputStream stream;
+
+ private ByteArrayOutputStreamSinkTester(int size) {
+ this.size = size;
+ }
+
+ public OutputStream create() throws IOException {
+ stream = new ByteArrayOutputStream(size);
+ return stream;
+ }
+
+ public byte[] getBytes() throws IOException {
+ return stream.toByteArray();
+ }
+ }
+
+ private static class PipedOutputStreamSinkTester extends SinkTester {
+
+ private ExecutorService executor;
+ private Future<byte[]> future;
+
+ public OutputStream create() throws IOException {
+ final PipedInputStream in = new PipedInputStream();
+ PipedOutputStream out = new PipedOutputStream(in);
+
+ executor = Executors.newSingleThreadExecutor();
+ future = executor.submit(new Callable<byte[]>() {
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+
+ public byte[] call() throws Exception {
+ byte[] buffer = new byte[256];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ bytes.write(buffer, 0, count);
+ }
+ return bytes.toByteArray();
+ }
+ });
+
+ return out;
+ }
+
+ public byte[] getBytes() throws Exception {
+ executor.shutdown();
+ return future.get();
+ }
+ }
+
+ private static class FilterOutputStreamTester extends WrapperTester {
+
+ public OutputStream create(OutputStream delegate) throws Exception {
+ return new FilterOutputStream(delegate);
+ }
+
+ public byte[] decode(byte[] delegateBytes) throws Exception {
+ return delegateBytes;
+ }
+ }
+
+ private static class BufferedOutputStreamTester extends WrapperTester {
+ private final int bufferSize;
+
+ private BufferedOutputStreamTester(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
+
+ public OutputStream create(OutputStream delegate) throws Exception {
+ return new BufferedOutputStream(delegate, bufferSize);
+ }
+
+ public byte[] decode(byte[] delegateBytes) throws Exception {
+ return delegateBytes;
+ }
+ }
+
+ private static class DataOutputStreamTester extends WrapperTester {
+
+ public OutputStream create(OutputStream delegate) throws Exception {
+ return new DataOutputStream(delegate);
+ }
+
+ public byte[] decode(byte[] delegateBytes) throws Exception {
+ return delegateBytes;
+ }
+ }
+
+ private static class ObjectOutputStreamTester extends WrapperTester {
+
+ public OutputStream create(OutputStream delegate) throws Exception {
+ return new ObjectOutputStream(delegate);
+ }
+
+ public byte[] decode(byte[] delegateBytes) throws Exception {
+ return Streams.streamToBytes(new ObjectInputStream(
+ new ByteArrayInputStream(delegateBytes)));
+ }
+ }
+
+ private static class PrintStreamTester extends WrapperTester {
+
+ public OutputStream create(OutputStream delegate) throws Exception {
+ return new PrintStream(delegate);
+ }
+
+ public byte[] decode(byte[] delegateBytes) throws Exception {
+ return delegateBytes;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamWriterTest.java
new file mode 100644
index 0000000..39b909e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/OutputStreamWriterTest.java
@@ -0,0 +1,701 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestCase;
+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;
+
+public class OutputStreamWriterTest extends TestCase {
+
+ private static final int UPPER = 0xd800;
+
+ private static final int BUFFER_SIZE = 10000;
+
+ private ByteArrayOutputStream out;
+
+ private OutputStreamWriter writer;
+
+ static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
+
+ static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII",
+ "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" };
+
+ OutputStreamWriter osw;
+
+ InputStreamReader isr;
+
+ private ByteArrayOutputStream fos;
+
+ String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, "utf-8");
+
+ fos = new ByteArrayOutputStream();
+ osw = new OutputStreamWriter(fos);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ try {
+ writer.close();
+
+ if (isr != null) {
+ isr.close();
+ }
+ osw.close();
+ } catch (Exception e) {
+ // Ignored
+ }
+
+ super.tearDown();
+ }
+
+ public void testClose() throws Exception {
+ writer.flush();
+ writer.close();
+ try {
+ writer.flush();
+ fail();
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ public void testFlush() throws Exception {
+ writer.write(source);
+ writer.flush();
+ String result = out.toString("utf-8");
+ assertEquals(source, result);
+ }
+
+ /*
+ * Class under test for void write(char[], int, int)
+ */
+ public void testWritecharArrayintint() throws IOException {
+ char[] chars = source.toCharArray();
+
+ // Throws IndexOutOfBoundsException if offset is negative
+ try {
+ writer.write((char[]) null, -1, -1);
+ fail();
+ } catch (NullPointerException exception) {
+ } catch (IndexOutOfBoundsException exception) {
+ }
+
+ // throws NullPointerException though count is negative
+ try {
+ writer.write((char[]) null, 1, -1);
+ fail();
+ } catch (NullPointerException exception) {
+ } catch (IndexOutOfBoundsException exception) {
+ }
+
+ 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
+ }
+
+ try {
+ writer.write((String) null, -1, -1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // Throws NullPointerException before StringIndexOutOfBoundsException
+ try {
+ writer.write((String) null, -1, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException 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();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ writer.write((String) null, -1, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException 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) {
+ }
+ }
+ }
+ }
+
+ /**
+ * java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
+ throws UnsupportedEncodingException {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ try {
+ osw = new OutputStreamWriter(fos, "Bogus");
+ fail("Failed to throw Unsupported Encoding exception");
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.OutputStreamWriter#close()
+ */
+ public void test_close() throws IOException {
+ osw.close();
+
+ try {
+ osw.write(testString, 0, testString.length());
+ fail("Chars written after close");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try {
+ OutputStreamWriter writer = new OutputStreamWriter(bout,
+ "ISO2022JP");
+ writer.write(new char[] { 'a' });
+ writer.close();
+ // the default is ASCII, there should not be any mode changes
+ String converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 1: " + converted, converted
+ .equals("a"));
+
+ bout.reset();
+ writer = new OutputStreamWriter(bout, "ISO2022JP");
+ writer.write(new char[] { '\u3048' });
+ writer.flush();
+ // the byte sequence should not switch to ASCII mode until the
+ // stream is closed
+ converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 2: " + converted, converted
+ .equals("\u001b$B$("));
+ writer.close();
+ converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 3: " + converted, converted
+ .equals("\u001b$B$(\u001b(B"));
+
+ bout.reset();
+ writer = new OutputStreamWriter(bout, "ISO2022JP");
+ writer.write(new char[] { '\u3048' });
+ writer.write(new char[] { '\u3048' });
+ writer.close();
+ // there should not be a mode switch between writes
+ assertEquals("invalid conversion 4", "\u001b$B$($(\u001b(B",
+ new String(bout.toByteArray(), "ISO8859_1"));
+ } catch (UnsupportedEncodingException e) {
+ // Can't test missing converter
+ System.out.println(e);
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * Unlike the RI, we return the canonical encoding name and not something
+ * java specific.
+ */
+ public void test_getEncoding() throws IOException {
+ try {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ } catch (UnsupportedEncodingException e) {
+ assertEquals("Returned incorrect encoding", "8859_1", osw
+ .getEncoding());
+ }
+
+ OutputStreamWriter out = new OutputStreamWriter(
+ new ByteArrayOutputStream(), "UTF-16BE");
+ out.close();
+
+ String result = out.getEncoding();
+ assertNull(result);
+
+ out = null;
+ try {
+ out = new OutputStreamWriter(new ByteArrayOutputStream(),
+ "UTF-16BE");
+ } catch (UnsupportedEncodingException e) {
+ // ok
+ }
+ result = out.getEncoding();
+ assertEquals("UTF-16BE", result);
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedInputStreamTest.java
new file mode 100644
index 0000000..6122dbb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedInputStreamTest.java
@@ -0,0 +1,448 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.concurrent.CountDownLatch;
+
+public class PipedInputStreamTest extends junit.framework.TestCase {
+
+ static class PWriter implements Runnable {
+ PipedOutputStream pos;
+
+ public byte bytes[];
+
+ public void run() {
+ try {
+ pos.write(bytes);
+ synchronized (this) {
+ notify();
+ }
+ } catch (IOException e) {
+ e.printStackTrace(System.out);
+ System.out.println("Could not write bytes");
+ }
+ }
+
+ public PWriter(PipedOutputStream pout, int nbytes) {
+ pos = pout;
+ bytes = new byte[nbytes];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = (byte) (System.currentTimeMillis() % 9);
+ }
+ }
+ }
+
+ Thread t;
+
+ PWriter pw;
+
+ PipedInputStream pis;
+
+ PipedOutputStream pos;
+
+ /**
+ * java.io.PipedInputStream#PipedInputStream()
+ */
+ public void test_Constructor() {
+ // Test for method java.io.PipedInputStream()
+ // Used in tests
+ }
+
+ /**
+ * java.io.PipedInputStream#PipedInputStream(java.io.PipedOutputStream)
+ */
+ public void test_ConstructorLjava_io_PipedOutputStream() throws Exception {
+ // Test for method java.io.PipedInputStream(java.io.PipedOutputStream)
+ pis = new PipedInputStream(new PipedOutputStream());
+ pis.available();
+ }
+
+
+ public void test_readException() throws IOException {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+
+ try {
+ pis.connect(pos);
+ t = new Thread(pw = new PWriter(pos, 1000));
+ t.start();
+ while (true) {
+ pis.read();
+ t.interrupt();
+ }
+ } catch (IOException expected) {
+ } finally {
+ try {
+ pis.close();
+ pos.close();
+ } catch (IOException ee) {
+ }
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#available()
+ */
+ public void test_available() throws Exception {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+
+ pis.connect(pos);
+ t = new Thread(pw = new PWriter(pos, 1000));
+ t.start();
+
+ synchronized (pw) {
+ pw.wait(10000);
+ }
+ assertTrue("Available returned incorrect number of bytes: "
+ + pis.available(), pis.available() == 1000);
+
+ PipedInputStream pin = new PipedInputStream();
+ PipedOutputStream pout = new PipedOutputStream(pin);
+ // We know the PipedInputStream buffer size is 1024.
+ // Writing another byte would cause the write to wait
+ // for a read before returning
+ for (int i = 0; i < 1024; i++) {
+ pout.write(i);
+ }
+ assertEquals("Incorrect available count", 1024, pin.available());
+ }
+
+ /**
+ * java.io.PipedInputStream#close()
+ */
+ public void test_close() throws IOException {
+ // Test for method void java.io.PipedInputStream.close()
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+ pis.connect(pos);
+ pis.close();
+ try {
+ pos.write((byte) 127);
+ fail("Failed to throw expected exception");
+ } catch (IOException e) {
+ // The spec for PipedInput saya an exception should be thrown if
+ // a write is attempted to a closed input. The PipedOuput spec
+ // indicates that an exception should be thrown only when the
+ // piped input thread is terminated without closing
+ return;
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#connect(java.io.PipedOutputStream)
+ */
+ public void test_connectLjava_io_PipedOutputStream() throws Exception {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+ assertEquals("Non-conected pipe returned non-zero available bytes", 0,
+ pis.available());
+
+ pis.connect(pos);
+ t = new Thread(pw = new PWriter(pos, 1000));
+ t.start();
+
+ synchronized (pw) {
+ pw.wait(10000);
+ }
+ assertEquals("Available returned incorrect number of bytes", 1000, pis
+ .available());
+ }
+
+ /**
+ * java.io.PipedInputStream#read()
+ */
+ public void test_read() throws Exception {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+
+ pis.connect(pos);
+ t = new Thread(pw = new PWriter(pos, 1000));
+ t.start();
+
+ synchronized (pw) {
+ pw.wait(10000);
+ }
+ assertEquals("Available returned incorrect number of bytes", 1000, pis
+ .available());
+ assertEquals("read returned incorrect byte", pw.bytes[0], (byte) pis
+ .read());
+ }
+
+ /**
+ * java.io.PipedInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws Exception {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+
+ pis.connect(pos);
+ t = new Thread(pw = new PWriter(pos, 1000));
+ t.start();
+
+ byte[] buf = new byte[400];
+ synchronized (pw) {
+ pw.wait(10000);
+ }
+ assertTrue("Available returned incorrect number of bytes: "
+ + pis.available(), pis.available() == 1000);
+ pis.read(buf, 0, 400);
+ for (int i = 0; i < 400; i++) {
+ assertEquals("read returned incorrect byte[]", pw.bytes[i], buf[i]);
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#read(byte[], int, int)
+ * Regression for HARMONY-387
+ */
+ public void test_read$BII_2() throws IOException {
+ PipedInputStream obj = new PipedInputStream();
+ try {
+ obj.read(new byte[0], 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII_3() throws IOException {
+ PipedInputStream obj = new PipedInputStream();
+ try {
+ obj.read(new byte[0], -1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII_4() throws IOException {
+ PipedInputStream obj = new PipedInputStream();
+ try {
+ obj.read(new byte[0], -1, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#receive(int)
+ */
+ public void test_write_failsAfterReaderDead() throws Exception {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream();
+
+ // test if writer recognizes dead reader
+ pis.connect(pos);
+
+ class WriteRunnable implements Runnable {
+
+ final CountDownLatch readerAlive = new CountDownLatch(1);
+
+ public void run() {
+ try {
+ pos.write(1);
+
+ try {
+ readerAlive.await();
+ } catch (InterruptedException ie) {
+ fail();
+ return;
+ }
+
+ try {
+ // should throw exception since reader thread
+ // is now dead
+ pos.write(1);
+ fail();
+ } catch (IOException expected) {
+ }
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ class ReadRunnable implements Runnable {
+ public void run() {
+ try {
+ pis.read();
+ } catch (IOException e) {
+ fail();
+ }
+ }
+ }
+
+ WriteRunnable writeRunnable = new WriteRunnable();
+ Thread writeThread = new Thread(writeRunnable);
+
+ ReadRunnable readRunnable = new ReadRunnable();
+ Thread readThread = new Thread(readRunnable);
+ writeThread.start();
+ readThread.start();
+ readThread.join();
+
+ writeRunnable.readerAlive.countDown();
+ writeThread.join();
+ }
+
+ static final class PipedInputStreamWithPublicReceive extends PipedInputStream {
+ @Override
+ public void receive(int oneByte) throws IOException {
+ super.receive(oneByte);
+ }
+ }
+
+
+ public void test_receive_failsIfWriterClosed() throws Exception {
+ // attempt to write to stream after writer closed
+ PipedInputStreamWithPublicReceive pis = new PipedInputStreamWithPublicReceive();
+
+ pos = new PipedOutputStream();
+ pos.connect(pis);
+ pos.close();
+ try {
+ pis.receive(1);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ static class Worker extends Thread {
+ PipedOutputStream out;
+
+ Worker(PipedOutputStream pos) {
+ this.out = pos;
+ }
+
+ public void run() {
+ try {
+ out.write(20);
+ out.close();
+ Thread.sleep(5000);
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ public void test_read_after_write_close() throws Exception {
+ PipedInputStream in = new PipedInputStream();
+ PipedOutputStream out = new PipedOutputStream();
+ in.connect(out);
+ Thread worker = new Worker(out);
+ worker.start();
+ Thread.sleep(2000);
+ assertEquals("Should read 20.", 20, in.read());
+ worker.join();
+ assertEquals("Write end is closed, should return -1", -1, in.read());
+ byte[] buf = new byte[1];
+ assertEquals("Write end is closed, should return -1", -1, in.read(buf, 0, 1));
+ assertEquals("Buf len 0 should return first", 0, in.read(buf, 0, 0));
+ in.close();
+ out.close();
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws Exception {
+ try {
+ if (t != null) {
+ t.interrupt();
+ }
+ } catch (Exception ignore) {
+ }
+ super.tearDown();
+ }
+
+
+ /**
+ * java.io.PipedInputStream#PipedInputStream(java.io.PipedOutputStream,
+ *int)
+ * @since 1.6
+ */
+ public void test_Constructor_LPipedOutputStream_I() throws Exception {
+ // Test for method java.io.PipedInputStream(java.io.PipedOutputStream,
+ // int)
+ MockPipedInputStream mpis = new MockPipedInputStream(
+ new PipedOutputStream(), 100);
+ int bufferLength = mpis.bufferLength();
+ assertEquals(100, bufferLength);
+
+ try {
+ pis = new PipedInputStream(null, -1);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ pis = new PipedInputStream(null, 0);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedInputStream#PipedInputStream(int)
+ * @since 1.6
+ */
+ public void test_Constructor_I() throws Exception {
+ // Test for method java.io.PipedInputStream(int)
+ MockPipedInputStream mpis = new MockPipedInputStream(100);
+ int bufferLength = mpis.bufferLength();
+ assertEquals(100, bufferLength);
+
+ try {
+ pis = new PipedInputStream(-1);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ pis = new PipedInputStream(0);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ static class MockPipedInputStream extends PipedInputStream {
+
+ public MockPipedInputStream(java.io.PipedOutputStream src,
+ int bufferSize) throws IOException {
+ super(src, bufferSize);
+ }
+
+ public MockPipedInputStream(int bufferSize) {
+ super(bufferSize);
+ }
+
+ public int bufferLength() {
+ return super.buffer.length;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedOutputStreamTest.java
new file mode 100644
index 0000000..183606e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedOutputStreamTest.java
@@ -0,0 +1,231 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.UnsupportedEncodingException;
+
+import junit.framework.TestCase;
+
+public class PipedOutputStreamTest extends TestCase {
+
+ static class PReader implements Runnable {
+ PipedInputStream reader;
+
+ public PipedInputStream getReader() {
+ return reader;
+ }
+
+ public PReader(PipedOutputStream out) {
+ try {
+ reader = new PipedInputStream(out);
+ } catch (Exception e) {
+ System.out.println("Couldn't start reader");
+ }
+ }
+
+ public int available() {
+ try {
+ return reader.available();
+ } catch (Exception e) {
+ return -1;
+ }
+ }
+
+ public void run() {
+ try {
+ while (true) {
+ Thread.sleep(1000);
+ Thread.yield();
+ }
+ } catch (InterruptedException e) {
+ }
+ }
+
+ public String read(int nbytes) {
+ byte[] buf = new byte[nbytes];
+ try {
+ reader.read(buf, 0, nbytes);
+ return new String(buf, "UTF-8");
+ } catch (IOException e) {
+ System.out.println("Exception reading info");
+ return "ERROR";
+ }
+ }
+ }
+
+ Thread rt;
+
+ PReader reader;
+
+ PipedOutputStream out;
+
+ /**
+ * java.io.PipedOutputStream#PipedOutputStream()
+ */
+ public void test_Constructor() {
+ // Used in tests
+ }
+
+ /**
+ * java.io.PipedOutputStream#PipedOutputStream(java.io.PipedInputStream)
+ */
+ public void test_ConstructorLjava_io_PipedInputStream() throws Exception {
+ out = new PipedOutputStream(new PipedInputStream());
+ out.write('b');
+ }
+
+ /**
+ * java.io.PipedOutputStream#close()
+ */
+ public void test_close() throws Exception {
+ out = new PipedOutputStream();
+ rt = new Thread(reader = new PReader(out));
+ rt.start();
+ out.close();
+ }
+
+ /**
+ * java.io.PipedOutputStream#connect(java.io.PipedInputStream)
+ */
+ public void test_connectLjava_io_PipedInputStream_Exception()
+ throws IOException {
+ out = new PipedOutputStream();
+ out.connect(new PipedInputStream());
+ try {
+ out.connect(null);
+ fail("should throw NullPointerException"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedOutputStream#connect(java.io.PipedInputStream)
+ */
+ public void test_connectLjava_io_PipedInputStream() {
+ try {
+ out = new PipedOutputStream();
+ rt = new Thread(reader = new PReader(out));
+ rt.start();
+ out.connect(new PipedInputStream());
+ fail("Failed to throw exception attempting connect on already connected stream");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.PipedOutputStream#flush()
+ */
+ public void test_flush() throws IOException, UnsupportedEncodingException {
+ out = new PipedOutputStream();
+ rt = new Thread(reader = new PReader(out));
+ rt.start();
+ out.write("HelloWorld".getBytes("UTF-8"), 0, 10);
+ assertTrue("Bytes written before flush", reader.available() != 0);
+ out.flush();
+ assertEquals("Wrote incorrect bytes", "HelloWorld", reader.read(10));
+ }
+
+ /**
+ * java.io.PipedOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException, UnsupportedEncodingException {
+ out = new PipedOutputStream();
+ rt = new Thread(reader = new PReader(out));
+ rt.start();
+ out.write("HelloWorld".getBytes("UTF-8"), 0, 10);
+ out.flush();
+ assertEquals("Wrote incorrect bytes", "HelloWorld", reader.read(10));
+ }
+
+ /**
+ * java.io.PipedOutputStream#write(byte[], int, int) Regression for
+ * HARMONY-387
+ */
+ public void test_write$BII_2() throws IOException {
+ PipedInputStream pis = new PipedInputStream();
+ PipedOutputStream pos = null;
+ try {
+ pos = new PipedOutputStream(pis);
+ pos.write(new byte[0], -1, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // Regression for HARMONY-4311
+ try {
+ pis = new PipedInputStream();
+ PipedOutputStream out = new PipedOutputStream(pis);
+ out.write(null, -10, 10);
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream(pis);
+ pos.close();
+ pos.write(new byte[0], 0, 0);
+
+ try {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream(pis);
+ pos.write(new byte[0], -1, 0);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException t) {
+ //expected
+ }
+
+ try {
+ pis = new PipedInputStream();
+ pos = new PipedOutputStream(pis);
+ pos.write(null, -10, 0);
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.io.PipedOutputStream#write(int)
+ */
+ public void test_writeI() throws IOException {
+ out = new PipedOutputStream();
+ rt = new Thread(reader = new PReader(out));
+ rt.start();
+ out.write('c');
+ out.flush();
+ assertEquals("Wrote incorrect byte", "c", reader.read(1));
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ @Override
+ protected void tearDown() {
+ if (rt != null) {
+ rt.interrupt();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedReaderTest.java
new file mode 100644
index 0000000..6802540
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedReaderTest.java
@@ -0,0 +1,399 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.PipedReader;
+import java.io.PipedWriter;
+
+import junit.framework.TestCase;
+
+public class PipedReaderTest extends TestCase {
+
+ static class PWriter implements Runnable {
+ public PipedWriter pw;
+
+ public PWriter(PipedReader reader) {
+ try {
+ pw = new PipedWriter(reader);
+ } catch (Exception e) {
+ System.out.println("Couldn't create writer");
+ }
+ }
+
+ public PWriter() {
+ pw = new PipedWriter();
+ }
+
+ public void run() {
+ try {
+ char[] c = new char[11];
+ "Hello World".getChars(0, 11, c, 0);
+ pw.write(c);
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ } catch (Exception e) {
+ System.out.println("Exception occurred: " + e.toString());
+ }
+ }
+ }
+
+ PipedReader preader;
+
+ PWriter pwriter;
+
+ Thread t;
+
+ /**
+ * java.io.PipedReader#PipedReader()
+ */
+ public void test_Constructor() {
+ // Used in test
+ }
+
+ /**
+ * java.io.PipedReader#PipedReader(java.io.PipedWriter)
+ */
+ public void test_ConstructorLjava_io_PipedWriter() throws IOException {
+ preader = new PipedReader(new PipedWriter());
+ }
+
+ /**
+ * java.io.PipedReader#PipedReader(java.io.PipedWriter,
+ *int)
+ * @since 1.6
+ */
+ public void test_Constructor_LPipedWriter_I() throws Exception {
+ // Test for method java.io.PipedReader(java.io.PipedWriter,
+ // int)
+ try {
+ preader = new PipedReader(null, -1);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ preader = new PipedReader(null, 0);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedReader#PipedReader(int)
+ * @since 1.6
+ */
+ public void test_Constructor_I() throws Exception {
+ // Test for method java.io.PipedReader(int)
+ try {
+ preader = new PipedReader(-1);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ preader = new PipedReader(0);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedReader#close()
+ */
+ public void test_close() throws Exception {
+ char[] c = null;
+ preader = new PipedReader();
+ t = new Thread(new PWriter(preader), "");
+ t.start();
+ Thread.sleep(500); // Allow writer to start
+ c = new char[11];
+ preader.read(c, 0, 11);
+ preader.close();
+ assertEquals("Read incorrect chars", "Hello World", new String(c));
+ }
+
+ /**
+ * java.io.PipedReader#connect(java.io.PipedWriter)
+ */
+ public void test_connectLjava_io_PipedWriter() throws Exception {
+ char[] c = null;
+
+ preader = new PipedReader();
+ t = new Thread(pwriter = new PWriter(), "");
+ preader.connect(pwriter.pw);
+ t.start();
+ Thread.sleep(500); // Allow writer to start
+ c = new char[11];
+ preader.read(c, 0, 11);
+
+ assertEquals("Read incorrect chars", "Hello World", new String(c));
+ try {
+ preader.connect(pwriter.pw);
+ fail("Failed to throw exception connecting to pre-connected reader");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.PipedReader#read()
+ */
+ public void test_read() throws Exception {
+ char[] c = null;
+ preader = new PipedReader();
+ t = new Thread(new PWriter(preader), "");
+ t.start();
+ Thread.sleep(500); // Allow writer to start
+ c = new char[11];
+ for (int i = 0; i < c.length; i++) {
+ c[i] = (char) preader.read();
+ }
+ assertEquals("Read incorrect chars", "Hello World", new String(c));
+ }
+
+ /**
+ * java.io.PipedReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws Exception {
+ char[] c = null;
+ preader = new PipedReader();
+ t = new Thread(new PWriter(preader), "");
+ t.start();
+ Thread.sleep(500); // Allow writer to start
+ c = new char[11];
+ int n = 0;
+ int x = n;
+ while (x < 11) {
+ n = preader.read(c, x, 11 - x);
+ x = x + n;
+ }
+ assertEquals("Read incorrect chars", "Hello World", new String(c));
+ try {
+ preader.close();
+ preader.read(c, 8, 7);
+ fail("Failed to throw exception reading from closed reader");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ public void test_read$CII_ExceptionPriority() throws IOException {
+ // Regression for HARMONY-387
+ PipedWriter pw = new PipedWriter();
+ PipedReader obj = null;
+ try {
+ obj = new PipedReader(pw);
+ obj.read(new char[0], (int) 0, (int) -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_read$CII_ExceptionPriority2() throws IOException {
+ PipedWriter pw = new PipedWriter();
+ PipedReader obj = null;
+ try {
+ obj = new PipedReader(pw);
+ obj.read(new char[0], (int) -1, (int) 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_read$CII_ExceptionPriority3() throws IOException {
+ PipedWriter pw = new PipedWriter();
+ PipedReader obj = null;
+ try {
+ obj = new PipedReader(pw);
+ obj.read(new char[0], (int) -1, (int) -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_read$CII_ExceptionPriority4() throws IOException {
+ PipedWriter pw = new PipedWriter();
+ PipedReader pr = new PipedReader(pw);
+ try {
+ pr.read(null, -1, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_read_$CII_IOException() throws IOException {
+ PipedWriter pw = new PipedWriter();
+ PipedReader pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(null, 0, 10);
+ fail("Should throws IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pr = new PipedReader();
+ pr.close();
+ try {
+ pr.read(null, 0, 10);
+ fail("Should throws IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(new char[10], -1, 0);
+ fail("Should throws IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(new char[10], 0, -1);
+ fail("Should throws IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(new char[10], 1, 10);
+ fail("Should throws IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(new char[0], -1, -1);
+ fail("should throw IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ pr.close();
+ try {
+ pr.read(null, 0, 1);
+ fail("should throw IOException"); //$NON-NLS-1$
+ } catch (IOException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ try {
+ pr.read(null, 0, -1);
+ fail("should throw NullPointerException"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ try {
+ pr.read(new char[10], 11, 0);
+ fail("should throw IndexOutOfBoundsException"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+
+ pw = new PipedWriter();
+ pr = new PipedReader(pw);
+ try {
+ pr.read(null, 1, 0);
+ fail("should throw NullPointerException"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ } finally {
+ pw = null;
+ pr = null;
+ }
+ }
+
+ /**
+ * java.io.PipedReader#ready()
+ */
+ public void test_ready() throws Exception {
+ char[] c = null;
+ preader = new PipedReader();
+ t = new Thread(new PWriter(preader), "");
+ t.start();
+ Thread.sleep(500); // Allow writer to start
+ assertTrue("Reader should be ready", preader.ready());
+ c = new char[11];
+ for (int i = 0; i < c.length; i++)
+ c[i] = (char) preader.read();
+ assertFalse("Reader should not be ready after reading all chars",
+ preader.ready());
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws Exception {
+ if (t != null) {
+ t.interrupt();
+ }
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedWriterTest.java
new file mode 100644
index 0000000..07c77b9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PipedWriterTest.java
@@ -0,0 +1,477 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.PipedReader;
+import java.io.PipedWriter;
+
+public class PipedWriterTest extends junit.framework.TestCase {
+
+ static class PReader implements Runnable {
+ public PipedReader pr;
+
+ public char[] buf = new char[10];
+
+ public PReader(PipedWriter pw) {
+ try {
+ pr = new PipedReader(pw);
+ } catch (IOException e) {
+ fail();
+ }
+ }
+
+ public PReader(PipedReader pr) {
+ this.pr = pr;
+ }
+
+ public void run() {
+ try {
+ int r = 0;
+ for (int i = 0; i < buf.length; i++) {
+ r = pr.read();
+ if (r == -1)
+ break;
+ buf[i] = (char) r;
+ }
+ } catch (Exception e) {
+ fail();
+ }
+ }
+ }
+
+ Thread rdrThread;
+
+ PReader reader;
+
+ PipedWriter pw;
+
+ /**
+ * java.io.PipedWriter#PipedWriter()
+ */
+ public void test_Constructor() {
+ // Test for method java.io.PipedWriter()
+ // Used in tests
+ }
+
+ /**
+ * java.io.PipedWriter#PipedWriter(java.io.PipedReader)
+ */
+ public void test_ConstructorLjava_io_PipedReader() throws Exception {
+ // Test for method java.io.PipedWriter(java.io.PipedReader)
+ char[] buf = new char[10];
+ "HelloWorld".getChars(0, 10, buf, 0);
+ PipedReader rd = new PipedReader();
+ pw = new PipedWriter(rd);
+ rdrThread = new Thread(reader = new PReader(rd), "Constructor(Reader)");
+ rdrThread.start();
+ pw.write(buf);
+ pw.close();
+ rdrThread.join();
+ assertEquals("Failed to construct writer", "HelloWorld", new String(
+ reader.buf));
+ }
+
+ /**
+ * java.io.PipedWriter#close()
+ */
+ public void test_close() throws Exception {
+ // Test for method void java.io.PipedWriter.close()
+ char[] buf = new char[10];
+ "HelloWorld".getChars(0, 10, buf, 0);
+ PipedReader rd = new PipedReader();
+ pw = new PipedWriter(rd);
+ reader = new PReader(rd);
+ pw.close();
+ try {
+ pw.write(buf);
+ fail("Should have thrown exception when attempting to write to closed writer.");
+ } catch (Exception e) {
+ // correct
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#connect(java.io.PipedReader)
+ */
+ public void test_connectLjava_io_PipedReader() throws Exception {
+ // Test for method void java.io.PipedWriter.connect(java.io.PipedReader)
+ char[] buf = new char[10];
+ "HelloWorld".getChars(0, 10, buf, 0);
+ PipedReader rd = new PipedReader();
+ pw = new PipedWriter();
+ pw.connect(rd);
+ rdrThread = new Thread(reader = new PReader(rd), "connect");
+ rdrThread.start();
+ pw.write(buf);
+ pw.close();
+ rdrThread.join();
+ assertEquals("Failed to write correct chars", "HelloWorld", new String(
+ reader.buf));
+ }
+
+ /**
+ * java.io.PipedWriter#flush()
+ */
+ public void test_flush() throws Exception {
+ // Test for method void java.io.PipedWriter.flush()
+ char[] buf = new char[10];
+ "HelloWorld".getChars(0, 10, buf, 0);
+ pw = new PipedWriter();
+ rdrThread = new Thread(reader = new PReader(pw), "flush");
+ rdrThread.start();
+ pw.write(buf);
+ pw.flush();
+ rdrThread.join();
+ assertEquals("Failed to flush chars", "HelloWorld", new String(
+ reader.buf));
+ }
+
+ /**
+ * java.io.PipedWriter#flush()
+ * Regression HARMONY-6293
+ */
+ public void test_flushAfterClose() throws Exception {
+
+ PipedReader pr = new PipedReader();
+ pw = new PipedWriter(pr);
+ pw.close();
+ try {
+ pw.flush();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ pr = new PipedReader();
+ pw = new PipedWriter(pr);
+ pr.close();
+
+ try {
+ pw.flush();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII() throws Exception {
+ // Test for method void java.io.PipedWriter.write(char [], int, int)
+ char[] buf = new char[10];
+ "HelloWorld".getChars(0, 10, buf, 0);
+ pw = new PipedWriter();
+ rdrThread = new Thread(reader = new PReader(pw), "writeCII");
+ rdrThread.start();
+ pw.write(buf, 0, 10);
+ pw.close();
+ rdrThread.join();
+ assertEquals("Failed to write correct chars", "HelloWorld", new String(
+ reader.buf));
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int) Regression for
+ * HARMONY-387
+ */
+ public void test_write$CII_2() throws IOException {
+ PipedReader pr = new PipedReader();
+ PipedWriter obj = null;
+ try {
+ obj = new java.io.PipedWriter(pr);
+ obj.write(new char[0], (int) 0, (int) -1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII_3() throws IOException {
+ PipedReader pr = new PipedReader();
+ PipedWriter obj = null;
+ try {
+ obj = new java.io.PipedWriter(pr);
+ obj.write(new char[0], (int) -1, (int) 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII_4() throws IOException {
+ PipedReader pr = new PipedReader();
+ PipedWriter obj = null;
+ try {
+ obj = new java.io.PipedWriter(pr);
+ obj.write(new char[0], (int) -1, (int) -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII_5() throws IOException {
+ PipedReader pr = new PipedReader();
+ PipedWriter obj = null;
+ try {
+ obj = new PipedWriter(pr);
+ obj.write((char[]) null, (int) -1, (int) 0);
+ fail("NullPointerException expected");
+ } catch (IndexOutOfBoundsException t) {
+ fail("NullPointerException expected");
+ } catch (NullPointerException t) {
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII_6() throws IOException {
+ PipedReader pr = new PipedReader();
+ PipedWriter obj = null;
+ try {
+ obj = new PipedWriter(pr);
+ obj.write((char[]) null, (int) -1, (int) -1);
+ fail("NullPointerException expected");
+ } catch (IndexOutOfBoundsException t) {
+ fail("NullPointerException expected");
+ } catch (NullPointerException t) {
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write$CII_notConnected() throws IOException {
+ // Regression test for Harmony-2404
+ // create not connected pipe
+ PipedWriter obj = new PipedWriter();
+
+ // char array is null
+ try {
+ obj.write((char[]) null, 0, 1);
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ // expected
+ }
+
+ // negative offset
+ try {
+ obj.write(new char[] { 1 }, -10, 1);
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ // expected
+ }
+
+ // wrong offset
+ try {
+ obj.write(new char[] { 1 }, 10, 1);
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ // expected
+ }
+
+ // negative length
+ try {
+ obj.write(new char[] { 1 }, 0, -10);
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ // expected
+ }
+
+ // all valid params
+ try {
+ obj.write(new char[] { 1, 1 }, 0, 1);
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PipedWriter#write(int)
+ */
+ public void test_write_I_MultiThread() throws IOException {
+ final PipedReader pr = new PipedReader();
+ final PipedWriter pw = new PipedWriter();
+ // test if writer recognizes dead reader
+ pr.connect(pw);
+
+ class WriteRunnable implements Runnable {
+ boolean pass = false;
+ volatile boolean readerAlive = true;
+
+ public void run() {
+ try {
+ pw.write(1);
+ while (readerAlive) {
+ // wait the reader thread dead
+ }
+ try {
+ // should throw exception since reader thread
+ // is now dead
+ pw.write(1);
+ } catch (IOException e) {
+ pass = true;
+ }
+ } catch (IOException e) {
+ //ignore
+ }
+ }
+ }
+ WriteRunnable writeRunnable = new WriteRunnable();
+ Thread writeThread = new Thread(writeRunnable);
+ class ReadRunnable implements Runnable {
+ boolean pass;
+
+ public void run() {
+ try {
+ pr.read();
+ pass = true;
+ } catch (IOException e) {
+ //ignore
+ }
+ }
+ }
+ ReadRunnable readRunnable = new ReadRunnable();
+ Thread readThread = new Thread(readRunnable);
+ writeThread.start();
+ readThread.start();
+ while (readThread.isAlive()) {
+ //wait the reader thread dead
+ }
+ writeRunnable.readerAlive = false;
+ assertTrue("reader thread failed to read", readRunnable.pass);
+ while (writeThread.isAlive()) {
+ //wait the writer thread dead
+ }
+ assertTrue("writer thread failed to recognize dead reader",
+ writeRunnable.pass);
+ }
+
+ /**
+ * java.io.PipedWriter#write(char[], int, int)
+ */
+ public void test_write_$CII_MultiThread() throws Exception {
+ final PipedReader pr = new PipedReader();
+ final PipedWriter pw = new PipedWriter();
+
+ // test if writer recognizes dead reader
+ pr.connect(pw);
+
+ class WriteRunnable implements Runnable {
+ boolean pass = false;
+
+ volatile boolean readerAlive = true;
+
+ public void run() {
+ try {
+ pw.write(1);
+ while (readerAlive) {
+ // wait the reader thread dead
+ }
+ try {
+ // should throw exception since reader thread
+ // is now dead
+ char[] buf = new char[10];
+ pw.write(buf, 0, 10);
+ } catch (IOException e) {
+ pass = true;
+ }
+ } catch (IOException e) {
+ //ignore
+ }
+ }
+ }
+ WriteRunnable writeRunnable = new WriteRunnable();
+ Thread writeThread = new Thread(writeRunnable);
+ class ReadRunnable implements Runnable {
+ boolean pass;
+
+ public void run() {
+ try {
+ pr.read();
+ pass = true;
+ } catch (IOException e) {
+ //ignore
+ }
+ }
+ }
+ ReadRunnable readRunnable = new ReadRunnable();
+ Thread readThread = new Thread(readRunnable);
+ writeThread.start();
+ readThread.start();
+ while (readThread.isAlive()) {
+ //wait the reader thread dead
+ }
+ writeRunnable.readerAlive = false;
+ assertTrue("reader thread failed to read", readRunnable.pass);
+ while (writeThread.isAlive()) {
+ //wait the writer thread dead
+ }
+ assertTrue("writer thread failed to recognize dead reader",
+ writeRunnable.pass);
+ }
+
+ /**
+ * java.io.PipedWriter#write(int)
+ */
+ public void test_writeI() throws Exception {
+ // Test for method void java.io.PipedWriter.write(int)
+
+ pw = new PipedWriter();
+ rdrThread = new Thread(reader = new PReader(pw), "writeI");
+ rdrThread.start();
+ pw.write(1);
+ pw.write(2);
+ pw.write(3);
+ pw.close();
+ rdrThread.join(1000);
+ assertTrue("Failed to write correct chars: " + (int) reader.buf[0]
+ + " " + (int) reader.buf[1] + " " + (int) reader.buf[2],
+ reader.buf[0] == 1 && reader.buf[1] == 2 && reader.buf[2] == 3);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() throws Exception {
+ try {
+ if (rdrThread != null) {
+ rdrThread.interrupt();
+ }
+ } catch (Exception ignore) {
+ }
+ try {
+ if (pw != null) {
+ pw.close();
+ }
+ } catch (Exception ignore) {
+ }
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintStreamTest.java
new file mode 100644
index 0000000..19a63af
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintStreamTest.java
@@ -0,0 +1,673 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStreamReader;
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Locale;
+
+public class PrintStreamTest extends junit.framework.TestCase {
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ byte[] ibuf = new byte[4096];
+
+ private File testFile = null;
+
+ private String testFilePath = null;
+
+ 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_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";
+
+ private static class MockPrintStream extends PrintStream {
+
+ public MockPrintStream(String fileName) throws FileNotFoundException {
+ super(fileName);
+ }
+
+ public MockPrintStream(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException {
+ super(fileName, csn);
+ }
+
+ public MockPrintStream(OutputStream os) {
+ super(os);
+ }
+
+ @Override
+ public void clearError() {
+ super.clearError();
+ }
+
+ @Override
+ public void setError() {
+ super.setError();
+ }
+ }
+
+ /**
+ * {@link java.io.PrintStream#PrintStream(String)}
+ */
+ public void test_Constructor_Ljava_lang_String() throws IOException {
+ MockPrintStream os = new MockPrintStream(testFilePath);
+ assertNotNull(os);
+ os.close();
+ }
+
+ /**
+ * {@link java.io.PrintStream#PrintStream(String, String)}
+ */
+ public void test_Constructor_Ljava_lang_String_Ljava_lang_String() throws Exception {
+ MockPrintStream os = new MockPrintStream(testFilePath, "utf-8");
+ assertNotNull(os);
+ os.close();
+
+ // Test that a bogus charset is mentioned in the exception
+ try {
+ new PrintStream(testFilePath, "Bogus");
+ fail("Exception expected");
+ } catch (UnsupportedEncodingException e) {
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PrintStream#PrintStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws Exception {
+ // Test for method java.io.PrintStream(java.io.OutputStream)
+ PrintStream os = new PrintStream(bos);
+ os.print(2345.76834720202);
+ os.close();
+
+ // regression for HARMONY-1195
+ try {
+ os = new PrintStream(bos, true, null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.io.PrintStream#PrintStream(java.io.OutputStream, boolean)
+ */
+ public void test_ConstructorLjava_io_OutputStreamZ() {
+ // Test for method java.io.PrintStream(java.io.OutputStream, boolean)
+ PrintStream os = new PrintStream(bos);
+ os.println(2345.76834720202);
+ os.flush();
+ assertTrue("Bytes not written", bos.size() > 0);
+ os.close();
+ }
+
+ /**
+ * java.io.PrintStream#PrintStream(java.io.OutputStream, boolean, String)
+ */
+ public void test_ConstructorLjava_io_OutputStreamZLjava_lang_String() {
+ try {
+ new PrintStream(new ByteArrayOutputStream(), false,
+ "%Illegal_name!");
+ fail("Expected UnsupportedEncodingException");
+ } catch (UnsupportedEncodingException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PrintStream#checkError()
+ */
+ public void test_checkError() throws Exception {
+ // Test for method boolean java.io.PrintStream.checkError()
+ PrintStream os = new PrintStream(new OutputStream() {
+
+ public void write(int b) throws IOException {
+ throw new IOException();
+ }
+
+ public void write(byte[] b, int o, int l) throws IOException {
+ throw new IOException();
+ }
+ });
+ os.print(fileString.substring(0, 501));
+
+ assertTrue("Checkerror should return true", os.checkError());
+ }
+
+ /**
+ * {@link java.io.PrintStream#clearError()}
+ */
+ public void test_clearError() throws FileNotFoundException {
+ MockPrintStream os = new MockPrintStream(testFilePath);
+ assertFalse(os.checkError());
+ os.setError();
+ assertTrue(os.checkError());
+ os.clearError();
+ assertFalse(os.checkError());
+ os.close();
+ }
+
+ /**
+ * java.io.PrintStream#close()
+ */
+ public void test_close() throws Exception {
+ // Test for method void java.io.PrintStream.close()
+ PrintStream os = new PrintStream(bos);
+ os.close();
+ bos.close();
+ }
+
+ /**
+ * java.io.PrintStream#flush()
+ */
+ public void test_flush() throws Exception {
+ // Test for method void java.io.PrintStream.flush()
+ PrintStream os = new PrintStream(bos);
+ os.print(fileString.substring(0, 501));
+ os.flush();
+ assertEquals("Bytes not written after flush", 501, bos.size());
+ bos.close();
+ os.close();
+ }
+
+ /**
+ * java.io.PrintStream#print(char[])
+ */
+ public void test_print$C() {
+ // Test for method void java.io.PrintStream.print(char [])
+ PrintStream os = new PrintStream(bos, true);
+ try {
+ os.print((char[]) null);
+ fail("NPE expected");
+ } catch (NullPointerException ok) {
+ }
+
+ os = new PrintStream(bos, true);
+ char[] sc = new char[4000];
+ fileString.getChars(0, fileString.length(), sc, 0);
+ os.print(sc);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ os.close();
+
+ byte[] rbytes = new byte[4000];
+ bis.read(rbytes, 0, fileString.length());
+ assertEquals("Incorrect char[] written", fileString, new String(rbytes,
+ 0, fileString.length()));
+ }
+
+ /**
+ * java.io.PrintStream#print(char)
+ */
+ public void test_printC() throws Exception {
+ // Test for method void java.io.PrintStream.print(char)
+ PrintStream os = new PrintStream(bos, true);
+ os.print('t');
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ assertEquals("Incorrect char written", 't', isr.read());
+ }
+
+ /**
+ * java.io.PrintStream#print(double)
+ */
+ public void test_printD() {
+ // Test for method void java.io.PrintStream.print(double)
+ byte[] rbuf = new byte[100];
+ PrintStream os = new PrintStream(bos, true);
+ os.print(2345.76834720202);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ bis.read(rbuf, 0, 16);
+ assertEquals("Incorrect double written", "2345.76834720202",
+ new String(rbuf, 0, 16));
+ }
+
+ /**
+ * java.io.PrintStream#print(float)
+ */
+ public void test_printF() {
+ // Test for method void java.io.PrintStream.print(float)
+ PrintStream os = new PrintStream(bos, true);
+ byte rbuf[] = new byte[10];
+ os.print(29.08764f);
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ bis.read(rbuf, 0, 8);
+ assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
+ 8));
+
+ }
+
+ /**
+ * java.io.PrintStream#print(int)
+ */
+ public void test_printI() {
+ // Test for method void java.io.PrintStream.print(int)
+ PrintStream os = new PrintStream(bos, true);
+ os.print(768347202);
+ byte[] rbuf = new byte[18];
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ bis.read(rbuf, 0, 9);
+ assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
+ 9));
+ }
+
+ /**
+ * java.io.PrintStream#print(long)
+ */
+ public void test_printJ() {
+ // Test for method void java.io.PrintStream.print(long)
+ byte[] rbuf = new byte[100];
+ PrintStream os = new PrintStream(bos, true);
+ os.print(9875645283333L);
+ os.close();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ bis.read(rbuf, 0, 13);
+ assertEquals("Incorrect long written", "9875645283333", new String(
+ rbuf, 0, 13));
+ }
+
+ /**
+ * java.io.PrintStream#print(java.lang.Object)
+ */
+ public void test_printLjava_lang_Object() throws Exception {
+ // Test for method void java.io.PrintStream.print(java.lang.Object)
+ PrintStream os = new PrintStream(bos, true);
+ os.print((Object) null);
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] nullbytes = new byte[4];
+ bis.read(nullbytes, 0, 4);
+ assertEquals("null should be written", "null", new String(nullbytes, 0,
+ 4));
+
+ bis.close();
+ bos.close();
+ os.close();
+
+ ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
+ os = new PrintStream(bos1, true);
+ os.print(new java.util.Vector());
+ bis = new ByteArrayInputStream(bos1.toByteArray());
+ byte[] rbytes = new byte[2];
+ bis.read(rbytes, 0, 2);
+ assertEquals("Incorrect Object written", "[]", new String(rbytes, 0, 2));
+ }
+
+ /**
+ * java.io.PrintStream#print(java.lang.String)
+ */
+ public void test_printLjava_lang_String() throws Exception {
+ // Test for method void java.io.PrintStream.print(java.lang.String)
+ PrintStream os = new PrintStream(bos, true);
+ os.print((String) null);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] nullbytes = new byte[4];
+ bis.read(nullbytes, 0, 4);
+ assertEquals("null should be written", "null", new String(nullbytes, 0,
+ 4));
+
+ bis.close();
+ bos.close();
+ os.close();
+
+ ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
+ os = new PrintStream(bos1, true);
+ os.print("Hello World");
+ bis = new ByteArrayInputStream(bos1.toByteArray());
+ byte rbytes[] = new byte[100];
+ bis.read(rbytes, 0, 11);
+ assertEquals("Incorrect string written", "Hello World", new String(
+ rbytes, 0, 11));
+ }
+
+ /**
+ * java.io.PrintStream#print(boolean)
+ */
+ public void test_printZ() throws Exception {
+ // Test for method void java.io.PrintStream.print(boolean)
+ PrintStream os = new PrintStream(bos, true);
+ os.print(true);
+ DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bos
+ .toByteArray()));
+
+ assertTrue("Incorrect boolean written", dis.readBoolean());
+ }
+
+ /**
+ * java.io.PrintStream#println()
+ */
+ public void test_println() throws Exception {
+ // Test for method void java.io.PrintStream.println()
+ char c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println("");
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
+ || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(char[])
+ */
+ public void test_println$C() throws Exception {
+ // Test for method void java.io.PrintStream.println(char [])
+ PrintStream os = new PrintStream(bos, true);
+ char[] sc = new char[4000];
+ fileString.getChars(0, fileString.length(), sc, 0);
+ os.println(sc);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte[] rbytes = new byte[4000];
+ bis.read(rbytes, 0, fileString.length());
+ assertEquals("Incorrect char[] written", fileString, new String(rbytes,
+ 0, fileString.length()));
+
+ // In this particular test method, the end of data is not immediately
+ // followed by newLine separator in the reading buffer, instead its
+ // followed by zeros. The newline is written as the last entry
+ // in the inputStream buffer. Therefore, we must keep reading until we
+ // hit a new line.
+ int r;
+ boolean newline = false;
+ while ((r = isr.read()) != -1) {
+ if (r == '\r' || r == '\n')
+ newline = true;
+ }
+ assertTrue("Newline not written", newline);
+ }
+
+ /**
+ * java.io.PrintStream#println(char)
+ */
+ public void test_printlnC() throws Exception {
+ // Test for method void java.io.PrintStream.println(char)
+ int c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println('t');
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ assertEquals("Incorrect char written", 't', isr.read());
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(double)
+ */
+ public void test_printlnD() throws Exception {
+ // Test for method void java.io.PrintStream.println(double)
+ int c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println(2345.76834720202);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte[] rbuf = new byte[100];
+ bis.read(rbuf, 0, 16);
+ assertEquals("Incorrect double written", "2345.76834720202",
+ new String(rbuf, 0, 16));
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(float)
+ */
+ public void test_printlnF() throws Exception {
+ // Test for method void java.io.PrintStream.println(float)
+ int c;
+ byte[] rbuf = new byte[100];
+ PrintStream os = new PrintStream(bos, true);
+ os.println(29.08764f);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ bis.read(rbuf, 0, 8);
+ assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
+ 8));
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(int)
+ */
+ public void test_printlnI() throws Exception {
+ // Test for method void java.io.PrintStream.println(int)
+ int c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println(768347202);
+ byte[] rbuf = new byte[100];
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ bis.read(rbuf, 0, 9);
+ assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
+ 9));
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(long)
+ */
+ public void test_printlnJ() throws Exception {
+ // Test for method void java.io.PrintStream.println(long)
+ int c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println(9875645283333L);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte[] rbuf = new byte[100];
+ bis.read(rbuf, 0, 13);
+ assertEquals("Incorrect long written", "9875645283333", new String(
+ rbuf, 0, 13));
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(java.lang.Object)
+ */
+ public void test_printlnLjava_lang_Object() throws Exception {
+ // Test for method void java.io.PrintStream.println(java.lang.Object)
+ char c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println(new java.util.Vector());
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte[] rbytes = new byte[2];
+ bis.read(rbytes, 0, 2);
+ assertEquals("Incorrect Vector written", "[]", new String(rbytes, 0, 2));
+ assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
+ || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(java.lang.String)
+ */
+ public void test_printlnLjava_lang_String() throws Exception {
+ // Test for method void java.io.PrintStream.println(java.lang.String)
+ char c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println("Hello World");
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte rbytes[] = new byte[100];
+ bis.read(rbytes, 0, 11);
+ assertEquals("Incorrect string written", "Hello World", new String(
+ rbytes, 0, 11));
+ assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
+ || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#println(boolean)
+ */
+ public void test_printlnZ() throws Exception {
+ // Test for method void java.io.PrintStream.println(boolean)
+ int c;
+ PrintStream os = new PrintStream(bos, true);
+ os.println(true);
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ InputStreamReader isr = new InputStreamReader(bis);
+ byte[] rbuf = new byte[100];
+ bis.read(rbuf, 0, 4);
+ assertEquals("Incorrect boolean written", "true",
+ new String(rbuf, 0, 4));
+ assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
+ }
+
+ /**
+ * java.io.PrintStream#write(byte[], int, int)
+ */
+ public void test_write$BII() {
+ // Test for method void java.io.PrintStream.write(byte [], int, int)
+ PrintStream os = new PrintStream(bos, true);
+ os.write(fileString.getBytes(), 0, fileString.length());
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte rbytes[] = new byte[4000];
+ bis.read(rbytes, 0, fileString.length());
+ assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
+ .length()).equals(fileString));
+ }
+
+ /**
+ * java.io.PrintStream#write(int)
+ */
+ public void test_writeI() {
+ // Test for method void java.io.PrintStream.write(int)
+ PrintStream os = new PrintStream(bos, true);
+ os.write('t');
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ assertEquals("Incorrect char written", 't', bis.read());
+ }
+
+ /**
+ * java.io.PrintStream#append(char)
+ */
+ public void test_appendChar() throws IOException {
+ char testChar = ' ';
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(out);
+ printStream.append(testChar);
+ printStream.flush();
+ assertEquals(String.valueOf(testChar), out.toString());
+ printStream.close();
+ }
+
+ /**
+ * java.io.PrintStream#append(CharSequence)
+ */
+ public void test_appendCharSequence() {
+ String testString = "My Test String";
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(out);
+ printStream.append(testString);
+ printStream.flush();
+ assertEquals(testString, out.toString());
+ printStream.close();
+ }
+
+ /**
+ * java.io.PrintStream#append(CharSequence, int, int)
+ */
+ public void test_appendCharSequenceIntInt() {
+ String testString = "My Test String";
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(out);
+ printStream.append(testString, 1, 3);
+ printStream.flush();
+ assertEquals(testString.substring(1, 3), out.toString());
+ printStream.close();
+ }
+
+ /**
+ * java.io.PrintStream#format(java.lang.String, java.lang.Object...)
+ */
+ public void test_formatLjava_lang_String$Ljava_lang_Object() {
+ PrintStream os = new PrintStream(bos, false);
+ os.format("%s %s", "Hello", "World");
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] rbytes = new byte[11];
+ bis.read(rbytes, 0, rbytes.length);
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(rbytes));
+
+ }
+
+ /**
+ * java.io.PrintStream#format(java.util.Locale, java.lang.String,
+ *java.lang.Object...)
+ */
+ public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
+ PrintStream os = new PrintStream(bos, false);
+ os.format(Locale.US, "%s %s", "Hello", "World");
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] rbytes = new byte[11];
+ bis.read(rbytes, 0, rbytes.length);
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(rbytes));
+ }
+
+ /**
+ * java.io.PrintStream#printf(java.lang.String, java.lang.Object...)
+ */
+ public void test_printfLjava_lang_String$Ljava_lang_Object() {
+ PrintStream os = new PrintStream(bos, false);
+ os.printf("%s %s", "Hello", "World");
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] rbytes = new byte[11];
+ bis.read(rbytes, 0, rbytes.length);
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(rbytes));
+ }
+
+ /**
+ * java.io.PrintStream#printf(java.util.Locale, java.lang.String,
+ *java.lang.Object...)
+ */
+ public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
+ PrintStream os = new PrintStream(bos, false);
+ os.printf(Locale.US, "%s %s", "Hello", "World");
+ os.flush();
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ byte[] rbytes = new byte[11];
+ bis.read(rbytes, 0, rbytes.length);
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(rbytes));
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ testFile = File.createTempFile("test", null);
+ testFilePath = testFile.getAbsolutePath();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ testFile.delete();
+ testFile = null;
+ testFilePath = null;
+ super.tearDown();
+ }
+
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintWriterTest.java
new file mode 100644
index 0000000..9c60406
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PrintWriterTest.java
@@ -0,0 +1,779 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.nio.charset.Charset;
+import java.util.Locale;
+
+import tests.support.Support_StringReader;
+import tests.support.Support_StringWriter;
+
+public class PrintWriterTest extends junit.framework.TestCase {
+
+ static class Bogus {
+ public String toString() {
+ return "Bogus";
+ }
+ }
+
+ /**
+ * @since 1.6
+ */
+ static class MockPrintWriter extends PrintWriter {
+
+ public MockPrintWriter(OutputStream out, boolean autoflush) {
+ super(out, autoflush);
+ }
+
+ @Override
+ public void clearError() {
+ super.clearError();
+ }
+
+ }
+
+ PrintWriter pw;
+
+ ByteArrayOutputStream bao;
+
+ ByteArrayInputStream bai;
+
+ BufferedReader br;
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ // Test for method java.io.PrintWriter(java.io.OutputStream)
+ String s;
+ pw.println("Random Chars");
+ pw.write("Hello World");
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ assertTrue("Incorrect string written/read: " + s, s
+ .equals("Random Chars"));
+ s = br.readLine();
+ assertTrue("Incorrect string written/read: " + s, s
+ .equals("Hello World"));
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
+ */
+ public void test_ConstructorLjava_io_OutputStreamZ() {
+ // Test for method java.io.PrintWriter(java.io.OutputStream, boolean)
+ String s;
+ pw = new PrintWriter(bao, true);
+ pw.println("Random Chars");
+ pw.write("Hello World");
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ assertTrue("Incorrect string written/read: " + s, s
+ .equals("Random Chars"));
+ pw.flush();
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ assertTrue("Incorrect string written/read: " + s, s
+ .equals("Random Chars"));
+ s = br.readLine();
+ assertTrue("Incorrect string written/read: " + s, s
+ .equals("Hello World"));
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.Writer)
+ */
+ public void test_ConstructorLjava_io_Writer() {
+ // Test for method java.io.PrintWriter(java.io.Writer)
+ Support_StringWriter sw;
+ pw = new PrintWriter(sw = new Support_StringWriter());
+ pw.print("Hello");
+ pw.flush();
+ assertEquals("Failed to construct proper writer",
+ "Hello", sw.toString());
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.Writer, boolean)
+ */
+ public void test_ConstructorLjava_io_WriterZ() {
+ // Test for method java.io.PrintWriter(java.io.Writer, boolean)
+ Support_StringWriter sw;
+ pw = new PrintWriter(sw = new Support_StringWriter(), true);
+ pw.print("Hello");
+ // Auto-flush should have happened
+ assertEquals("Failed to construct proper writer",
+ "Hello", sw.toString());
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() throws Exception {
+ File file = File.createTempFile(getClass().getName(), null);
+ try {
+ PrintWriter writer = new PrintWriter(file);
+ writer.close();
+ } finally {
+ file.delete();
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.io.File, java.lang.String)
+ */
+ public void test_ConstructorLjava_io_File_Ljava_lang_String() throws Exception {
+ File file = File.createTempFile(getClass().getName(), null);
+ try {
+ PrintWriter writer = new PrintWriter(file,
+ Charset.defaultCharset().name());
+ writer.close();
+ } finally {
+ file.delete();
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws Exception {
+ File file = File.createTempFile(getClass().getName(), null);
+ try {
+ PrintWriter writer = new PrintWriter(file.getPath());
+ writer.close();
+ } finally {
+ file.delete();
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#PrintWriter(java.lang.String, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String_Ljava_lang_String() throws Exception {
+ File file = File.createTempFile(getClass().getName(), null);
+ try {
+ PrintWriter writer = new PrintWriter(file.getPath(),
+ Charset.defaultCharset().name());
+ writer.close();
+ } finally {
+ file.delete();
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#checkError()
+ */
+ public void test_checkError() {
+ // Test for method boolean java.io.PrintWriter.checkError()
+ pw.close();
+ pw.print(490000000000.08765);
+ assertTrue("Failed to return error", pw.checkError());
+ }
+
+ /**
+ * java.io.PrintWriter#clearError()
+ * @since 1.6
+ */
+ public void test_clearError() {
+ // Test for method boolean java.io.PrintWriter.clearError()
+ MockPrintWriter mpw = new MockPrintWriter(new ByteArrayOutputStream(), false);
+ mpw.close();
+ mpw.print(490000000000.08765);
+ assertTrue("Failed to return error", mpw.checkError());
+ mpw.clearError();
+ assertFalse("Internal error state has not be cleared", mpw.checkError());
+ }
+
+ /**
+ * java.io.PrintWriter#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.PrintWriter.close()
+ pw.close();
+ pw.println("l");
+ assertTrue("Write on closed stream failed to generate error", pw
+ .checkError());
+ }
+
+ /**
+ * java.io.PrintWriter#flush()
+ */
+ public void test_flush() {
+ // Test for method void java.io.PrintWriter.flush()
+ final double dub = 490000000000.08765;
+ pw.print(dub);
+ pw.flush();
+ assertTrue("Failed to flush", new String(bao.toByteArray())
+ .equals(String.valueOf(dub)));
+ }
+
+ /**
+ * java.io.PrintWriter#print(char[])
+ */
+ public void test_print$C() {
+ // Test for method void java.io.PrintWriter.print(char [])
+ String s = null;
+ char[] schars = new char[11];
+ "Hello World".getChars(0, 11, schars, 0);
+ pw.print(schars);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s
+ .equals("Hello World"));
+ int r = 0;
+ try {
+ pw.print((char[]) null);
+ } catch (NullPointerException e) {
+ r = 1;
+ }
+ assertEquals("null pointer exception for printing null char[] is not caught",
+ 1, r);
+ }
+
+ /**
+ * java.io.PrintWriter#print(char)
+ */
+ public void test_printC() {
+ // Test for method void java.io.PrintWriter.print(char)
+ pw.print('c');
+ pw.flush();
+ assertEquals("Wrote incorrect char string", "c", new String(bao.toByteArray())
+ );
+ }
+
+ /**
+ * java.io.PrintWriter#print(double)
+ */
+ public void test_printD() {
+ // Test for method void java.io.PrintWriter.print(double)
+ final double dub = 490000000000.08765;
+ pw.print(dub);
+ pw.flush();
+ assertTrue("Wrote incorrect double string", new String(bao
+ .toByteArray()).equals(String.valueOf(dub)));
+ }
+
+ /**
+ * java.io.PrintWriter#print(float)
+ */
+ public void test_printF() {
+ // Test for method void java.io.PrintWriter.print(float)
+ final float flo = 49.08765f;
+ pw.print(flo);
+ pw.flush();
+ assertTrue("Wrote incorrect float string",
+ new String(bao.toByteArray()).equals(String.valueOf(flo)));
+ }
+
+ /**
+ * java.io.PrintWriter#print(int)
+ */
+ public void test_printI() {
+ // Test for method void java.io.PrintWriter.print(int)
+ pw.print(4908765);
+ pw.flush();
+ assertEquals("Wrote incorrect int string", "4908765", new String(bao.toByteArray())
+ );
+ }
+
+ /**
+ * java.io.PrintWriter#print(long)
+ */
+ public void test_printJ() {
+ // Test for method void java.io.PrintWriter.print(long)
+ pw.print(49087650000L);
+ pw.flush();
+ assertEquals("Wrote incorrect long string", "49087650000", new String(bao.toByteArray())
+ );
+ }
+
+ /**
+ * java.io.PrintWriter#print(java.lang.Object)
+ */
+ public void test_printLjava_lang_Object() {
+ // Test for method void java.io.PrintWriter.print(java.lang.Object)
+ pw.print((Object) null);
+ pw.flush();
+ assertEquals("Did not write null", "null", new String(bao.toByteArray())
+ );
+ bao.reset();
+
+ pw.print(new Bogus());
+ pw.flush();
+ assertEquals("Wrote in incorrect Object string", "Bogus", new String(bao
+ .toByteArray()));
+ }
+
+ /**
+ * java.io.PrintWriter#print(java.lang.String)
+ */
+ public void test_printLjava_lang_String() {
+ // Test for method void java.io.PrintWriter.print(java.lang.String)
+ pw.print((String) null);
+ pw.flush();
+ assertEquals("did not write null", "null", new String(bao.toByteArray())
+ );
+ bao.reset();
+
+ pw.print("Hello World");
+ pw.flush();
+ assertEquals("Wrote incorrect string", "Hello World", new String(bao.toByteArray())
+ );
+ }
+
+ /**
+ * java.io.PrintWriter#print(boolean)
+ */
+ public void test_printZ() {
+ // Test for method void java.io.PrintWriter.print(boolean)
+ pw.print(true);
+ pw.flush();
+ assertEquals("Wrote in incorrect boolean string", "true", new String(bao
+ .toByteArray()));
+ }
+
+ /**
+ * java.io.PrintWriter#println()
+ */
+ public void test_println() {
+ // Test for method void java.io.PrintWriter.println()
+ String s;
+ pw.println("Blarg");
+ pw.println();
+ pw.println("Bleep");
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ assertTrue("Wrote incorrect line: " + s, s.equals("Blarg"));
+ s = br.readLine();
+ assertTrue("Wrote incorrect line: " + s, s.equals(""));
+ s = br.readLine();
+ assertTrue("Wrote incorrect line: " + s, s.equals("Bleep"));
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PrintWriter#println(char[])
+ */
+ public void test_println$C() {
+ // Test for method void java.io.PrintWriter.println(char [])
+ String s = null;
+ char[] schars = new char[11];
+ "Hello World".getChars(0, 11, schars, 0);
+ pw.println("Random Chars");
+ pw.println(schars);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s
+ .equals("Hello World"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(char)
+ */
+ public void test_printlnC() {
+ // Test for method void java.io.PrintWriter.println(char)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println('c');
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ s = br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char string: " + s, s.equals("c"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(double)
+ */
+ public void test_printlnD() {
+ // Test for method void java.io.PrintWriter.println(double)
+ String s = null;
+ final double dub = 4000000000000000.657483;
+ pw.println("Random Chars");
+ pw.println(dub);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect double string: " + s, s.equals(String
+ .valueOf(dub)));
+ }
+
+ /**
+ * java.io.PrintWriter#println(float)
+ */
+ public void test_printlnF() {
+ // Test for method void java.io.PrintWriter.println(float)
+ String s;
+ final float flo = 40.4646464f;
+ pw.println("Random Chars");
+ pw.println(flo);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ assertTrue("Wrote incorrect float string: " + s + " wanted: "
+ + String.valueOf(flo), s.equals(String.valueOf(flo)));
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+
+ }
+
+ /**
+ * java.io.PrintWriter#println(int)
+ */
+ public void test_printlnI() {
+ // Test for method void java.io.PrintWriter.println(int)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println(400000);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect int string: " + s, s.equals("400000"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(long)
+ */
+ public void test_printlnJ() {
+ // Test for method void java.io.PrintWriter.println(long)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println(4000000000000L);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect long string: " + s, s
+ .equals("4000000000000"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(java.lang.Object)
+ */
+ public void test_printlnLjava_lang_Object() {
+ // Test for method void java.io.PrintWriter.println(java.lang.Object)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println(new Bogus());
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect Object string: " + s, s.equals("Bogus"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(java.lang.String)
+ */
+ public void test_printlnLjava_lang_String() {
+ // Test for method void java.io.PrintWriter.println(java.lang.String)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println("Hello World");
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect string: " + s, s.equals("Hello World"));
+ }
+
+ /**
+ * java.io.PrintWriter#println(boolean)
+ */
+ public void test_printlnZ() {
+ // Test for method void java.io.PrintWriter.println(boolean)
+ String s = null;
+ pw.println("Random Chars");
+ pw.println(false);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect boolean string: " + s, s.equals("false"));
+ }
+
+ /**
+ * java.io.PrintWriter#write(char[])
+ */
+ public void test_write$C() {
+ // Test for method void java.io.PrintWriter.write(char [])
+ String s = null;
+ char[] schars = new char[11];
+ "Hello World".getChars(0, 11, schars, 0);
+ pw.println("Random Chars");
+ pw.write(schars);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test: " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s
+ .equals("Hello World"));
+ }
+
+ /**
+ * java.io.PrintWriter#write(char[], int, int)
+ */
+ public void test_write$CII() {
+ // Test for method void java.io.PrintWriter.write(char [], int, int)
+ String s = null;
+ char[] schars = new char[11];
+ "Hello World".getChars(0, 11, schars, 0);
+ pw.println("Random Chars");
+ pw.write(schars, 6, 5);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s.equals("World"));
+ }
+
+ /**
+ * java.io.PrintWriter#write(int)
+ */
+ public void test_writeI() throws IOException {
+ // Test for method void java.io.PrintWriter.write(int)
+ char[] cab = new char[3];
+ pw.write('a');
+ pw.write('b');
+ pw.write('c');
+ pw.flush();
+ InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(bao.toByteArray()));
+ cab[0] = (char) isr.read();
+ cab[1] = (char) isr.read();
+ cab[2] = (char) isr.read();
+ assertTrue("Wrote incorrect ints", cab[0] == 'a' && cab[1] == 'b'
+ && cab[2] == 'c');
+
+ }
+
+ /**
+ * java.io.PrintWriter#write(java.lang.String)
+ */
+ public void test_writeLjava_lang_String() {
+ // Test for method void java.io.PrintWriter.write(java.lang.String)
+ String s = null;
+ pw.println("Random Chars");
+ pw.write("Hello World");
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s
+ .equals("Hello World"));
+ }
+
+ /**
+ * java.io.PrintWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() {
+ // Test for method void java.io.PrintWriter.write(java.lang.String, int,
+ // int)
+ String s = null;
+ pw.println("Random Chars");
+ pw.write("Hello World", 6, 5);
+ pw.flush();
+ try {
+ br = new BufferedReader(new Support_StringReader(bao.toString()));
+ br.readLine();
+ s = br.readLine();
+ } catch (IOException e) {
+ fail("IOException during test : " + e.getMessage());
+ }
+ assertTrue("Wrote incorrect char[] string: " + s, s.equals("World"));
+ }
+
+ /**
+ * java.io.PrintWriter#append(char)
+ */
+ public void test_appendChar() {
+ char testChar = ' ';
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintWriter printWriter = new PrintWriter(out);
+ printWriter.append(testChar);
+ printWriter.flush();
+ assertEquals(String.valueOf(testChar), out.toString());
+ printWriter.close();
+ }
+
+ /**
+ * java.io.PrintWriter#append(CharSequence)
+ */
+ public void test_appendCharSequence() {
+
+ String testString = "My Test String";
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintWriter printWriter = new PrintWriter(out);
+ printWriter.append(testString);
+ printWriter.flush();
+ assertEquals(testString, out.toString());
+ printWriter.close();
+
+ }
+
+ /**
+ * java.io.PrintWriter#append(CharSequence, int, int)
+ */
+ public void test_appendCharSequenceIntInt() {
+ String testString = "My Test String";
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintWriter printWriter = new PrintWriter(out);
+ printWriter.append(testString, 1, 3);
+ printWriter.flush();
+ assertEquals(testString.substring(1, 3), out.toString());
+ printWriter.close();
+
+ }
+
+ /**
+ * java.io.PrintWriter#format(java.lang.String, java.lang.Object...)
+ */
+ public void test_formatLjava_lang_String$Ljava_lang_Object() {
+ pw.format("%s %s", "Hello", "World");
+ pw.flush();
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(bao.toByteArray()));
+ }
+
+ /**
+ * java.io.PrintWriter#format(java.util.Locale, java.lang.String, java.lang.Object...)
+ */
+ public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
+ pw.format(Locale.US, "%s %s", "Hello", "World");
+ pw.flush();
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(bao.toByteArray()));
+ }
+
+ /**
+ * java.io.PrintWriter#printf(java.lang.String, java.lang.Object...)
+ */
+ public void test_printfLjava_lang_String$Ljava_lang_Object() {
+ pw.printf("%s %s", "Hello", "World");
+ pw.flush();
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(bao.toByteArray()));
+ }
+
+ /**
+ * java.io.PrintWriter#printf(java.util.Locale, java.lang.String, java.lang.Object...)
+ */
+ public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
+ pw.printf(Locale.US, "%s %s", "Hello", "World");
+ pw.flush();
+ assertEquals("Wrote incorrect string", "Hello World",
+ new String(bao.toByteArray()));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ bao = new ByteArrayOutputStream();
+ pw = new PrintWriter(bao, false);
+
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ pw.close();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackInputStreamTest.java
new file mode 100644
index 0000000..8c56934
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackInputStreamTest.java
@@ -0,0 +1,256 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.PushbackInputStream;
+import java.io.UnsupportedEncodingException;
+
+public class PushbackInputStreamTest extends junit.framework.TestCase {
+
+ PushbackInputStream pis;
+
+ 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_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";
+
+ public void test_reset() {
+ PushbackInputStream pb = new PushbackInputStream(
+ new ByteArrayInputStream(new byte[] { 0 }), 2);
+ try {
+ pb.reset();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ public void test_mark() {
+ PushbackInputStream pb = new PushbackInputStream(
+ new ByteArrayInputStream(new byte[] { 0 }), 2);
+ pb.mark(Integer.MAX_VALUE);
+ pb.mark(0);
+ pb.mark(-1);
+ pb.mark(Integer.MIN_VALUE);
+ }
+
+
+ /**
+ * java.io.PushbackInputStream#PushbackInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ try {
+ PushbackInputStream str = new PushbackInputStream(null);
+ str.read();
+ fail("Expected IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ try {
+ pis = new PushbackInputStream(new ByteArrayInputStream("Hello"
+ .getBytes()));
+ pis.unread("He".getBytes());
+ fail("Failed to throw exception on unread when buffer full");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#PushbackInputStream(java.io.InputStream,
+ *int)
+ */
+ public void test_ConstructorLjava_io_InputStreamI() {
+ // Test for method java.io.PushbackInputStream(java.io.InputStream, int)
+ try {
+ pis = new PushbackInputStream(new ByteArrayInputStream("Hello"
+ .getBytes()), 5);
+ pis.unread("Hellos".getBytes());
+ } catch (IOException e) {
+ // Correct
+ // Pushback buffer should be full
+ return;
+
+ }
+ fail("Failed to throw exception on unread when buffer full");
+ }
+
+ /*
+ * java.io.PushBackInputStream(InputStream, int)
+ */
+ public void test_ConstructorLjava_io_InputStreamL() {
+ try {
+ PushbackInputStream str = new PushbackInputStream(null, 1);
+ str.read();
+ fail("Expected IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#available()
+ */
+ public void test_available() {
+ // Test for method int java.io.PushbackInputStream.available()
+ try {
+ assertTrue("Available returned incorrect number of bytes", pis
+ .available() == fileString.getBytes().length);
+ } catch (IOException e) {
+ fail("Exception during available test: " + e.toString());
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#markSupported()
+ */
+ public void test_markSupported() {
+ // Test for method boolean java.io.PushbackInputStream.markSupported()
+ assertTrue("markSupported returned true", !pis.markSupported());
+ }
+
+ /**
+ * java.io.PushbackInputStream#read()
+ */
+ public void test_read() {
+ // Test for method int java.io.PushbackInputStream.read()
+ try {
+ assertTrue("Incorrect byte read", pis.read() == fileString
+ .getBytes("UTF-8")[0]);
+ } catch (IOException e) {
+ fail("Exception during read test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() {
+ // Test for method int java.io.PushbackInputStream.read(byte [], int,
+ // int)
+ try {
+ byte[] buf = new byte[100];
+ pis.read(buf, 0, buf.length);
+ assertTrue("Incorrect bytes read", new String(buf, "UTF-8")
+ .equals(fileString.substring(0, 100)));
+ } catch (IOException e) {
+ fail("Exception during read test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#skip(long)
+ */
+ public void test_skipJ() throws Exception {
+ // Test for method long java.io.PushbackInputStream.skip(long)
+ byte[] buf = new byte[50];
+ pis.skip(50);
+ pis.read(buf, 0, buf.length);
+ assertTrue("a) Incorrect bytes read", new String(buf, "UTF-8")
+ .equals(fileString.substring(50, 100)));
+ pis.unread(buf);
+ pis.skip(25);
+ byte[] buf2 = new byte[25];
+ pis.read(buf2, 0, buf2.length);
+ assertTrue("b) Incorrect bytes read", new String(buf2, "UTF-8")
+ .equals(fileString.substring(75, 100)));
+ }
+
+ /**
+ * java.io.PushbackInputStream#unread(byte[])
+ */
+ public void test_unread$B() {
+ // Test for method void java.io.PushbackInputStream.unread(byte [])
+ try {
+ byte[] buf = new byte[100];
+ pis.read(buf, 0, buf.length);
+ assertTrue("Incorrect bytes read", new String(buf, "UTF-8")
+ .equals(fileString.substring(0, 100)));
+ pis.unread(buf);
+ pis.read(buf, 0, 50);
+ assertTrue("Failed to unread bytes", new String(buf, 0, 50, "UTF-8")
+ .equals(fileString.substring(0, 50)));
+ } catch (IOException e) {
+ fail("IOException during unread test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#unread(byte[], int, int)
+ */
+ public void test_unread$BII() throws IOException {
+ // Test for method void java.io.PushbackInputStream.unread(byte [], int,
+ // int)
+ byte[] buf = new byte[100];
+ pis.read(buf, 0, buf.length);
+ assertTrue("Incorrect bytes read", new String(buf, "UTF-8")
+ .equals(fileString.substring(0, 100)));
+ pis.unread(buf, 50, 50);
+ pis.read(buf, 0, 50);
+ assertTrue("Failed to unread bytes", new String(buf, 0, 50, "UTF-8")
+ .equals(fileString.substring(50, 100)));
+
+ // Regression for HARMONY-49
+ try {
+ PushbackInputStream pb = new PushbackInputStream(
+ new ByteArrayInputStream(new byte[] { 0 }), 2);
+ pb.unread(new byte[1], 0, 5);
+ fail("Assert 0: should throw IOE");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PushbackInputStream#unread(int)
+ */
+ public void test_unreadI() {
+ // Test for method void java.io.PushbackInputStream.unread(int)
+ try {
+ int x;
+ assertTrue("Incorrect byte read", (x = pis.read()) == fileString
+ .getBytes("UTF-8")[0]);
+ pis.unread(x);
+ assertTrue("Failed to unread", pis.read() == x);
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() throws UnsupportedEncodingException {
+
+ pis = new PushbackInputStream(new ByteArrayInputStream(fileString
+ .getBytes("UTF-8")), 65535);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ pis.close();
+ } catch (IOException e) {
+ fail("IOException during tearDown : " + e.getMessage());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackReaderTest.java
new file mode 100644
index 0000000..d49ee53
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/PushbackReaderTest.java
@@ -0,0 +1,381 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.CharArrayReader;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.io.PushbackReader;
+import java.io.Reader;
+import java.io.StringReader;
+
+public class PushbackReaderTest extends junit.framework.TestCase {
+
+ PushbackReader pbr;
+
+ String pbString = "Hello World";
+
+ /**
+ * java.io.PushbackReader#PushbackReader(java.io.Reader)
+ */
+ public void test_ConstructorLjava_io_Reader() {
+ // Test for method java.io.PushbackReader(java.io.Reader)
+ try {
+ pbr.close();
+ pbr = new PushbackReader(new StringReader(pbString));
+ char buf[] = new char[5];
+ pbr.read(buf, 0, 5);
+ pbr.unread(buf);
+ } catch (IOException e) {
+ // Correct
+ return;
+ }
+ fail("Created reader with buffer larger than 1");
+ }
+
+ /**
+ * java.io.PushbackReader#PushbackReader(java.io.Reader, int)
+ */
+ public void test_ConstructorLjava_io_ReaderI() {
+ // Test for method java.io.PushbackReader(java.io.Reader, int)
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.io.PushbackReader#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.PushbackReader.close()
+ try {
+ pbr.close();
+ pbr.read();
+ } catch (Exception e) {
+ return;
+ }
+ fail("Failed to throw exception reading from closed reader");
+ }
+
+ /**
+ * java.io.PushbackReader#mark(int)
+ */
+ public void test_markI() {
+ try {
+ pbr.mark(3);
+ } catch (IOException e) {
+ // correct
+ return;
+ }
+ fail("mark failed to throw expected IOException");
+ }
+
+ /**
+ * java.io.PushbackReader#markSupported()
+ */
+ public void test_markSupported() {
+ // Test for method boolean java.io.PushbackReader.markSupported()
+ assertTrue("markSupported returned true", !pbr.markSupported());
+ }
+
+ /**
+ * java.io.PushbackReader#read()
+ */
+ public void test_read() {
+ // Test for method int java.io.PushbackReader.read()
+ try {
+ char c;
+ pbr.read();
+ c = (char) pbr.read();
+ assertTrue("Failed to read char: " + c, c == pbString.charAt(1));
+ Reader reader = new PushbackReader(new CharArrayReader(
+ new char[] { '\u8765' }));
+ assertTrue("Wrong double byte character", reader.read() == '\u8765');
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#read(char[], int, int)
+ */
+ public void test_read$CII() {
+ // Test for method int java.io.PushbackReader.read(char [], int, int)
+ try {
+ char[] c = new char[5];
+ pbr.read(c, 0, 5);
+ assertTrue("Failed to read chars", new String(c).equals(pbString
+ .substring(0, 5)));
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+ }
+
+ public void test_read_$CII_Exception() throws IOException {
+ pbr = new PushbackReader(new StringReader(pbString), 10);
+
+ char[] charArray = new char[10];
+
+ try {
+ pbr.read(null, 1, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ pbr.read(charArray, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ pbr.read(charArray, -1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ pbr.read(charArray, 0, 0);
+ pbr.read(charArray, 0, charArray.length);
+ pbr.read(charArray, charArray.length, 0);
+
+ try {
+ pbr.read(charArray, charArray.length + 1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ pbr.read(charArray, 0, charArray.length + 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // Can't read from a closed PushbackReader.
+ pbr.close();
+ try {
+ pbr.read(charArray, 0, 1);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#ready()
+ */
+ public void test_ready() {
+ // Test for method boolean java.io.PushbackReader.ready()
+ try {
+ char[] c = new char[11];
+ if (c.length > 0)
+ ;// use c to avoid warning msg
+ assertTrue("Ready stream returned false to ready()", pbr.ready());
+ } catch (IOException e) {
+ fail("IOException during ready() test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#reset()
+ */
+ public void test_reset() {
+ try {
+ pbr.reset();
+ } catch (IOException e) {
+ // correct
+ return;
+ }
+ fail("mark failed to throw expected IOException");
+ }
+
+ /**
+ * java.io.PushbackReader#unread(char[])
+ */
+ public void test_unread$C() {
+ // Test for method void java.io.PushbackReader.unread(char [])
+ try {
+ char[] c = new char[5];
+ pbr.read(c, 0, 5);
+ pbr.unread(c);
+ pbr.read(c, 0, 5);
+ assertTrue("Failed to unread chars", new String(c).equals(pbString
+ .substring(0, 5)));
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#skip(long)
+ */
+ public void test_skip$J() {
+ char chars[] = new char[] { 'h', 'e', 'l', 'l', 'o' };
+ for (int i = 0; i < 3; i++) {
+ Reader reader, reader2;
+ switch (i) {
+ case 0:
+ reader = new StringReader(new String(chars));
+ reader2 = new StringReader(new String(chars));
+ break;
+ case 1:
+ reader = new FilterReader(new StringReader(new String(chars))) {
+ };
+ reader2 = new FilterReader(new StringReader(new String(chars))) {
+ };
+ break;
+ default:
+ reader = new CharArrayReader(chars);
+ reader2 = new CharArrayReader(chars);
+ }
+ PushbackReader pReader = new PushbackReader(reader, 2);
+ PushbackReader pReader2 = new PushbackReader(reader2, 2);
+ boolean skipped = false;
+ long numSkipped = 0;
+ try {
+ numSkipped = pReader2.skip(3);
+ pReader2.unread('a');
+ pReader2.unread('b');
+ numSkipped += pReader2.skip(10);
+ numSkipped += pReader2.skip(10);
+ numSkipped += pReader2.skip(10);
+ numSkipped += pReader2.skip(10);
+ numSkipped += pReader2.skip(10);
+ numSkipped += pReader2.skip(10);
+ assertEquals("Did not skip correct number of characters",
+ 7, numSkipped);
+ numSkipped = 0;
+ numSkipped += pReader.skip(2);
+ pReader.unread('i');
+ numSkipped += pReader.skip(2);
+ numSkipped += pReader.skip(0);
+ skipped = true;
+ numSkipped += pReader.skip(-1);
+ fail("Failed to throw "
+ + new IllegalArgumentException().getClass().getName());
+ } catch (IllegalArgumentException e) {
+ assertTrue("Failed to skip characters" + e, skipped);
+ } catch (IOException e) {
+ fail("Failed to skip characters" + e);
+ }
+ try {
+ numSkipped += pReader.skip(1);
+ numSkipped += pReader.skip(1);
+ numSkipped += pReader.skip(1);
+ assertEquals("Failed to skip all characters", 6, numSkipped);
+ long nextSkipped = pReader.skip(1);
+ assertEquals("skipped empty reader", 0, nextSkipped);
+ } catch (IOException e) {
+ fail("Failed to skip more characters" + e);
+ }
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#unread(char[], int, int)
+ */
+ public void test_unread$CII() {
+ // Test for method void java.io.PushbackReader.unread(char [], int, int)
+ try {
+ char[] c = new char[5];
+ pbr.read(c, 0, 5);
+ pbr.unread(c, 0, 2);
+ pbr.read(c, 0, 5);
+ assertTrue("Failed to unread chars", new String(c).equals(pbString
+ .substring(0, 2)
+ + pbString.substring(5, 8)));
+ } catch (IOException e) {
+ fail("IOException during unread test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#unread(char[], int, int)
+ */
+ public void test_unread_$CII_NullPointerException() throws IOException {
+ //a pushback reader with one character buffer
+ pbr = new PushbackReader(new StringReader(pbString));
+
+ try {
+ pbr.unread(null, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#unread(char[], int, int)
+ */
+ public void test_unread_$CII_Exception_InsufficientBuffer() throws IOException {
+ //a pushback reader with one character buffer
+ pbr = new PushbackReader(new StringReader(pbString));
+
+ //if count > buffer's size , should throw IOException
+ try {
+ pbr.unread(new char[pbString.length()], 0, 2);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#unread(char[], int, int)
+ */
+ public void test_unread_$CII_ArrayIndexOutOfBoundsException() throws IOException {
+ //a pushback reader with one character buffer
+ pbr = new PushbackReader(new StringReader(pbString));
+
+ try {
+ pbr.unread(new char[pbString.length()], -1, -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.io.PushbackReader#unread(int)
+ */
+ public void test_unreadI() {
+ // Test for method void java.io.PushbackReader.unread(int)
+
+ try {
+ int c;
+ pbr.read();
+ c = pbr.read();
+ pbr.unread(c);
+ assertTrue("Failed to unread char", pbr.read() == c);
+ } catch (IOException e) {
+ fail("IOException during unread test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ pbr = new PushbackReader(new StringReader(pbString), 10);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ try {
+ pbr.close();
+ } catch (IOException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/RandomAccessFileTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/RandomAccessFileTest.java
new file mode 100644
index 0000000..f6784fb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/RandomAccessFileTest.java
@@ -0,0 +1,1059 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import java.nio.channels.NonWritableChannelException;
+
+public class RandomAccessFileTest extends junit.framework.TestCase {
+
+ public String fileName;
+
+ public boolean ufile = true;
+
+ java.io.RandomAccessFile raf;
+
+ java.io.File f;
+
+ String unihw = "\u0048\u0065\u006C\u0801\u006C\u006F\u0020\u0057\u0081\u006F\u0072\u006C\u0064";
+
+ //java.io.FileOutputStream fos;
+
+ public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
+
+ /**
+ * java.io.RandomAccessFile#RandomAccessFile(java.io.File,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_io_FileLjava_lang_String()
+ throws Exception {
+ // Test for method java.io.RandomAccessFile(java.io.File,
+ // java.lang.String)
+ RandomAccessFile raf = new java.io.RandomAccessFile(f, "rw");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(f, "rwd");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(f, "rws");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
+ // Regression for HARMONY-50
+ File f = File.createTempFile("xxx", "yyy");
+ f.deleteOnExit();
+ raf = new RandomAccessFile(f, "rws");
+ raf.close();
+
+ f = File.createTempFile("xxx", "yyy");
+ f.deleteOnExit();
+ raf = new RandomAccessFile(f, "rwd");
+ raf.close();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.io.RandomAccessFile#RandomAccessFile(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String_I()
+ throws IOException {
+ RandomAccessFile raf = null;
+ try {
+ raf = new RandomAccessFile("", "r");
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (raf != null) {
+ raf.close();
+ raf = null;
+ }
+ }
+ try {
+ raf = new RandomAccessFile(new File(""), "r");
+ fail("should throw FileNotFoundException.");
+ } catch (FileNotFoundException e) {
+ // Expected
+ } finally {
+ if (raf != null) {
+ raf.close();
+ raf = null;
+ }
+ }
+ File dir = new File("/");
+ assertTrue(dir.isDirectory());
+ try {
+ raf = new RandomAccessFile(dir.getPath(), "r");
+ fail();
+ } catch (FileNotFoundException expected) {
+ } finally {
+ if (raf != null) {
+ raf.close();
+ raf = null;
+ }
+ }
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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);
+ }
+
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.io.RandomAccessFile#seek(long)
+ * <p/>
+ * 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();
+ }
+
+ /**
+ * java.io.RandomAccessFile#read(byte[], int, int)
+ * <p/>
+ * 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();
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.io.RandomAccessFile#write(byte[], int, int)
+ * <p/>
+ * 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();
+ }
+
+ // Regression test for HARMONY-6542
+ public void testRandomAccessFile_seekMoreThan2gb() throws IOException {
+ if (File.separator != "/") {
+ // skip windows until a test can be implemented that doesn't
+ // require 2GB of free disk space
+ return;
+ }
+ // (all?) unix platforms support sparse files so this should not
+ // need to have 2GB free disk space to pass
+ RandomAccessFile raf = new RandomAccessFile(f, "rw");
+ // write a few bytes so we get more helpful error messages
+ // if we land in the wrong places
+ raf.write(1);
+ raf.write(2);
+ raf.seek(2147483647);
+ raf.write(3);
+ raf.write(4);
+ raf.write(5);
+ raf.write(6);
+ raf.seek(0);
+ assertEquals("seek 0", 1, raf.read());
+ raf.seek(2147483649L);
+ assertEquals("seek >2gb", 5, raf.read());
+ raf.seek(0);
+ assertEquals("seek back to 0", 1, raf.read());
+ 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ReaderTest.java
new file mode 100644
index 0000000..f2b1439
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/ReaderTest.java
@@ -0,0 +1,205 @@
+/* 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.CharBuffer;
+
+import junit.framework.TestCase;
+
+public class ReaderTest extends TestCase {
+
+ public void test_Reader_CharBuffer_null() throws IOException {
+ String s = "MY TEST STRING";
+ MockReader mockReader = new MockReader(s.toCharArray());
+ CharBuffer charBuffer = null;
+ try {
+ mockReader.read(charBuffer);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ //expected;
+ }
+ }
+
+ public void test_Reader_CharBuffer_ZeroChar() throws IOException {
+ //the charBuffer has the capacity of 0, then there the number of char read
+ // to the CharBuffer is 0. Furthermore, the MockReader is intact in its content.
+ String s = "MY TEST STRING";
+ char[] srcBuffer = s.toCharArray();
+ MockReader mockReader = new MockReader(srcBuffer);
+ CharBuffer charBuffer = CharBuffer.allocate(0);
+ int result = mockReader.read(charBuffer);
+ assertEquals(0, result);
+ char[] destBuffer = new char[srcBuffer.length];
+ mockReader.read(destBuffer);
+ assertEquals(s, String.valueOf(destBuffer));
+ }
+
+ public void test_Reader_CharBufferChar() throws IOException {
+ String s = "MY TEST STRING";
+ char[] srcBuffer = s.toCharArray();
+ final int CHARBUFFER_SIZE = 10;
+ MockReader mockReader = new MockReader(srcBuffer);
+ CharBuffer charBuffer = CharBuffer.allocate(CHARBUFFER_SIZE);
+ charBuffer.append('A');
+ final int CHARBUFFER_REMAINING = charBuffer.remaining();
+ int result = mockReader.read(charBuffer);
+ assertEquals(CHARBUFFER_REMAINING, result);
+ charBuffer.rewind();
+ assertEquals(s.substring(0, CHARBUFFER_REMAINING), charBuffer
+ .subSequence(CHARBUFFER_SIZE - CHARBUFFER_REMAINING,
+ CHARBUFFER_SIZE).toString());
+ char[] destBuffer = new char[srcBuffer.length - CHARBUFFER_REMAINING];
+ mockReader.read(destBuffer);
+ assertEquals(s.substring(CHARBUFFER_REMAINING), String
+ .valueOf(destBuffer));
+ }
+
+ /**
+ * {@link java.io.Reader#mark(int)}
+ */
+ public void test_mark() {
+ MockReader mockReader = new MockReader();
+ try {
+ mockReader.mark(0);
+ fail("Should throw IOException for Reader do not support mark");
+ } catch (IOException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * {@link java.io.Reader#read()}
+ */
+ public void test_read() throws IOException {
+ MockReader reader = new MockReader();
+
+ // return -1 when the stream is null;
+ assertEquals("Should be equal to -1", -1, reader.read());
+
+ String string = "MY TEST STRING";
+ char[] srcBuffer = string.toCharArray();
+ MockReader mockReader = new MockReader(srcBuffer);
+
+ // normal read
+ for (char c : srcBuffer) {
+ assertEquals("Should be equal to \'" + c + "\'", c, mockReader
+ .read());
+ }
+
+ // return -1 when read Out of Index
+ mockReader.read();
+ assertEquals("Should be equal to -1", -1, reader.read());
+
+ }
+
+ /**
+ * {@link java.io.Reader#ready()}
+ */
+ public void test_ready() throws IOException {
+ MockReader mockReader = new MockReader();
+ assertFalse("Should always return false", mockReader.ready());
+
+ }
+
+ /**
+ * {@link java.io.Reader#reset()}
+ */
+ public void test_reset() {
+ MockReader mockReader = new MockReader();
+ try {
+ mockReader.reset();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * {@link java.io.Reader#skip(long)}
+ */
+ public void test_skip() throws IOException {
+ String string = "MY TEST STRING";
+ char[] srcBuffer = string.toCharArray();
+ int length = srcBuffer.length;
+ MockReader mockReader = new MockReader(srcBuffer);
+ assertEquals("Should be equal to \'M\'", 'M', mockReader.read());
+
+ // normal skip
+ mockReader.skip(length / 2);
+ assertEquals("Should be equal to \'S\'", 'S', mockReader.read());
+
+ // try to skip a bigger number of characters than the total
+ // Should do nothing
+ mockReader.skip(length);
+
+ // try to skip a negative number of characters throw IllegalArgumentException
+ try {
+ mockReader.skip(-1);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Excepted
+ }
+ }
+
+ class MockReader extends Reader {
+
+ private char[] contents;
+
+ private int current_offset = 0;
+
+ private int length = 0;
+
+ public MockReader() {
+ super();
+ }
+
+ public MockReader(char[] data) {
+ contents = data;
+ length = contents.length;
+ }
+
+ @Override
+ public void close() throws IOException {
+
+ contents = null;
+ }
+
+ @Override
+ public int read(char[] buf, int offset, int count) throws IOException {
+
+ if (null == contents) {
+ return -1;
+ }
+ if (length <= current_offset) {
+ return -1;
+ }
+ if (buf.length < offset + count) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ count = Math.min(count, length - current_offset);
+ for (int i = 0; i < count; i++) {
+ buf[offset + i] = contents[current_offset + i];
+ }
+ current_offset += count;
+ return count;
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SequenceInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SequenceInputStreamTest.java
new file mode 100644
index 0000000..e4608db
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SequenceInputStreamTest.java
@@ -0,0 +1,193 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Enumeration;
+
+public class SequenceInputStreamTest extends junit.framework.TestCase {
+
+ SequenceInputStream si;
+
+ String s1 = "Hello";
+
+ String s2 = "World";
+
+ /**
+ * java.io.SequenceInputStream#SequenceInputStream(java.io.InputStream,
+ *java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_io_InputStream() {
+ // Test for method java.io.SequenceInputStream(java.io.InputStream,
+ // java.io.InputStream)
+ // Used in tests
+ }
+
+ /**
+ * SequenceInputStream#SequenceInputStream(java.io.InputStream,
+ *java.io.InputStream)
+ */
+ public void test_Constructor_LInputStreamLInputStream_Null() throws UnsupportedEncodingException {
+ try {
+ si = new SequenceInputStream(null, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ //will not throw NullPointerException if the first InputStream is not null
+ InputStream is = new ByteArrayInputStream(s1.getBytes("UTF-8"));
+ si = new SequenceInputStream(is, null);
+ }
+
+ /**
+ * java.io.SequenceInputStream#SequenceInputStream(java.util.Enumeration)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_ConstructorLjava_util_Enumeration() {
+ // Test for method java.io.SequenceInputStream(java.util.Enumeration)
+ class StreamEnumerator implements Enumeration {
+ InputStream streams[] = new InputStream[2];
+
+ int count = 0;
+
+ public StreamEnumerator() throws UnsupportedEncodingException {
+ streams[0] = new ByteArrayInputStream(s1.getBytes("UTF-8"));
+ streams[1] = new ByteArrayInputStream(s2.getBytes("UTF-8"));
+ }
+
+ public boolean hasMoreElements() {
+ return count < streams.length;
+ }
+
+ public Object nextElement() {
+ return streams[count++];
+ }
+ }
+
+ try {
+ si = new SequenceInputStream(new StreamEnumerator());
+ byte buf[] = new byte[s1.length() + s2.length()];
+ si.read(buf, 0, s1.length());
+ si.read(buf, s1.length(), s2.length());
+ assertTrue("Read incorrect bytes: " + new String(buf), new String(
+ buf, "UTF-8").equals(s1 + s2));
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+
+ }
+
+ /**
+ * java.io.SequenceInputStream#available()
+ */
+ public void test_available() {
+ // Test for method int java.io.SequenceInputStream.available()
+ try {
+
+ assertTrue("Returned incorrect number of bytes: " + si.available(),
+ si.available() == s1.length());
+ } catch (IOException e) {
+ fail("IOException during available test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.SequenceInputStream#close()
+ */
+ public void test_close() throws IOException {
+ si.close();
+ //will not throw IOException to close a stream which is closed already
+ si.close();
+ }
+
+ /**
+ * java.io.SequenceInputStream#read()
+ */
+ public void test_read() throws IOException {
+ // Test for method int java.io.SequenceInputStream.read()
+ try {
+ si.read();
+ assertTrue("Read incorrect char", (char) si.read() == s1.charAt(1));
+ } catch (IOException e) {
+ fail("IOException during read test: " + e.getMessage());
+ }
+
+ //returns -1 if the stream is closed , do not throw IOException
+ si.close();
+ int result = si.read();
+ assertEquals(-1, result);
+ }
+
+ /**
+ * java.io.SequenceInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ // Test for method int java.io.SequenceInputStream.read(byte [], int,
+ // int)
+ try {
+ byte buf[] = new byte[s1.length() + s2.length()];
+ si.read(buf, 0, s1.length());
+ si.read(buf, s1.length(), s2.length());
+ assertTrue("Read incorrect bytes: " + new String(buf), new String(
+ buf, "UTF-8").equals(s1 + s2));
+ } catch (IOException e) {
+ fail("IOException during read test : " + e.getMessage());
+ }
+
+ ByteArrayInputStream bis1 = new ByteArrayInputStream(
+ new byte[] { 1, 2, 3, 4 });
+ ByteArrayInputStream bis2 = new ByteArrayInputStream(
+ new byte[] { 5, 6, 7, 8 });
+ SequenceInputStream sis = new SequenceInputStream(bis1, bis2);
+
+ try {
+ sis.read(null, 0, -1);
+ fail("Expected NullPointerException exception");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ //returns -1 if the stream is closed , do not throw IOException
+ byte[] array = new byte[] { 1, 2, 3, 4 };
+ sis.close();
+ int result = sis.read(array, 0, 5);
+ assertEquals(-1, result);
+
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() throws UnsupportedEncodingException {
+ si = new SequenceInputStream(new ByteArrayInputStream(s1.getBytes("UTF-8")),
+ new ByteArrayInputStream(s2.getBytes("UTF-8")));
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest.java
new file mode 100644
index 0000000..5d9b18c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest.java
@@ -0,0 +1,1022 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InvalidObjectException;
+import java.io.NotActiveException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.io.StreamCorruptedException;
+import java.io.WriteAbortedException;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.PropertyPermission;
+import java.util.Set;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TimeZone;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.Vector;
+import libcore.io.Streams;
+
+/**
+ * Automated Test Suite for class java.io.ObjectOutputStream
+ */
+@SuppressWarnings("serial")
+public class SerializationStressTest extends junit.framework.TestCase implements
+ Serializable {
+
+ // protected static final String MODE_XLOAD = "xload";
+
+ // protected static final String MODE_XDUMP = "xdump";
+
+ static final String FOO = "foo";
+
+ static final String MSG_TEST_FAILED = "Failed to write/read/assertion checking: ";
+
+ protected static final boolean DEBUG = false;
+
+ protected static boolean xload = false;
+
+ protected static boolean xdump = false;
+
+ protected static String xFileName = null;
+
+ protected transient int dumpCount = 0;
+
+ protected transient ObjectInputStream ois;
+
+ protected transient ObjectOutputStream oos;
+
+ protected transient ByteArrayOutputStream bao;
+
+ // -----------------------------------------------------------------------------------
+
+ private static class ObjectInputStreamSubclass extends ObjectInputStream {
+ private Vector<Class> resolvedClasses = new Vector<Class>();
+
+ public ObjectInputStreamSubclass(InputStream in) throws IOException,
+ StreamCorruptedException {
+ super(in);
+ }
+
+ public Class<?> resolveClass(ObjectStreamClass osClass)
+ throws IOException, ClassNotFoundException {
+ Class result = super.resolveClass(osClass);
+ resolvedClasses.addElement(result);
+ return result;
+ }
+
+ public Class[] resolvedClasses() {
+ return (Class[]) resolvedClasses.toArray(new Class[resolvedClasses
+ .size()]);
+ }
+ }
+
+ static final Map<String, String> TABLE = new Hashtable<String, String>();
+
+ static final Map<String, String> MAP = new HashMap<String, String>();
+
+ static final SortedMap<String, String> TREE = new TreeMap<String, String>();
+
+ static final LinkedHashMap<String, String> LINKEDMAP = new LinkedHashMap<String, String>();
+
+ static final LinkedHashSet<String> LINKEDSET = new LinkedHashSet<String>();
+
+ static final IdentityHashMap<String, String> IDENTITYMAP = new IdentityHashMap<String, String>();
+
+ static final List<String> ALIST = Arrays.asList(new String[] { "a", "list", "of",
+ "strings" });
+
+ static final List<String> LIST = new ArrayList<String>(ALIST);
+
+ static final Set<String> SET = new HashSet<String>(Arrays.asList(new String[] { "one",
+ "two", "three" }));
+
+ static final SortedSet<String> SORTSET = new TreeSet<String>(Arrays.asList(new String[] {
+ "one", "two", "three" }));
+
+ static final java.text.DateFormat DATEFORM = java.text.DateFormat
+ .getInstance();
+
+ static final java.text.ChoiceFormat CHOICE = new java.text.ChoiceFormat(
+ "1#one|2#two|3#three");
+
+ static final java.text.NumberFormat NUMBERFORM = java.text.NumberFormat
+ .getInstance();
+
+ static final java.text.MessageFormat MESSAGE = new java.text.MessageFormat(
+ "the time: {0,time} and date {0,date}");
+
+ static final LinkedList<String> LINKEDLIST = new LinkedList<String>(Arrays
+ .asList(new String[] { "a", "linked", "list", "of", "strings" }));
+
+ static final SimpleTimeZone TIME_ZONE = new SimpleTimeZone(3600000,
+ "S-TEST");
+
+ static final Calendar CALENDAR = new GregorianCalendar(TIME_ZONE);
+
+ static {
+ TABLE.put("one", "1");
+ TABLE.put("two", "2");
+ TABLE.put("three", "3");
+ MAP.put("one", "1");
+ MAP.put("two", "2");
+ MAP.put("three", "3");
+ LINKEDMAP.put("one", "1");
+ LINKEDMAP.put("two", "2");
+ LINKEDMAP.put("three", "3");
+ IDENTITYMAP.put("one", "1");
+ IDENTITYMAP.put("two", "2");
+ IDENTITYMAP.put("three", "3");
+ LINKEDSET.add("one");
+ LINKEDSET.add("two");
+ LINKEDSET.add("three");
+ TREE.put("one", "1");
+ TREE.put("two", "2");
+ TREE.put("three", "3");
+ // To make sure they all use the same Calendar
+ CALENDAR.setTimeZone(new SimpleTimeZone(0, "GMT"));
+ CALENDAR.set(1999, Calendar.JUNE, 23, 15, 47, 13);
+ CALENDAR.set(Calendar.MILLISECOND, 553);
+ DATEFORM.setCalendar(CALENDAR);
+ java.text.DateFormatSymbols symbols = new java.text.DateFormatSymbols();
+ symbols.setZoneStrings(new String[][] { { "a", "b", "c", "d", "e" },
+ { "f", "g", "h", "i", "j" } });
+ ((java.text.SimpleDateFormat) DATEFORM).setDateFormatSymbols(symbols);
+ DATEFORM.setNumberFormat(new java.text.DecimalFormat("#0.#"));
+ DATEFORM.setTimeZone(TimeZone.getTimeZone("EST"));
+ ((java.text.DecimalFormat) NUMBERFORM).applyPattern("#0.#");
+ MESSAGE.setFormat(0, DATEFORM);
+ MESSAGE.setFormat(1, DATEFORM);
+ }
+
+ public SerializationStressTest() {
+ }
+
+ public SerializationStressTest(String name) {
+ super(name);
+ }
+
+ public String getDumpName() {
+ return getName() + dumpCount;
+ }
+
+ protected void dump(Object o) throws IOException, ClassNotFoundException {
+ if (dumpCount > 0)
+ setUp();
+ // Dump the object
+ try {
+ oos.writeObject(o);
+ } finally {
+ oos.close();
+ }
+ }
+
+ protected Object dumpAndReload(Object o) throws IOException,
+ ClassNotFoundException {
+ dump(o);
+ return reload();
+ }
+
+ protected InputStream loadStream() throws IOException {
+ // Choose the load stream
+ if (xload || xdump) {
+ // Load from pre-existing file
+ return new FileInputStream(xFileName + "-" + getDumpName() + ".ser");
+ } else {
+ // Just load from memory, we dumped to memory
+ return new ByteArrayInputStream(bao.toByteArray());
+ }
+ }
+
+ protected Object reload() throws IOException, ClassNotFoundException {
+ ois = new ObjectInputStream(loadStream());
+ dumpCount++;
+ try {
+ return ois.readObject();
+ } finally {
+ ois.close();
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ try {
+ if (xdump) {
+ oos = new ObjectOutputStream(new FileOutputStream(xFileName
+ + "-" + getDumpName() + ".ser"));
+ } else {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ }
+ } catch (Exception e) {
+ fail("Exception thrown during setup : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ public void test_1_Constructor() throws Exception {
+ // Test for method java.io.ObjectOutputStream(java.io.OutputStream)
+ oos.close();
+ oos = new ObjectOutputStream(new ByteArrayOutputStream());
+ oos.close();
+ }
+
+ public void test_2_close() {
+ // Test for method void java.io.ObjectOutputStream.close()
+ try {
+ oos.close();
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ oos.close();
+ oos.writeChar('T');
+ oos.writeObject(FOO);
+ // Writing to a closed stream does not cause problems. This is
+ // the expected behavior
+ } catch (IOException e) {
+ fail("Operation on closed stream threw IOException : "
+ + e.getMessage());
+ }
+ }
+
+ public void test_3_defaultWriteObject() {
+ // Test for method void java.io.ObjectOutputStream.defaultWriteObject()
+
+ try {
+ oos.defaultWriteObject();
+ } catch (NotActiveException e) {
+ // Correct
+ return;
+ } catch (IOException e) {
+ }
+ fail(
+ "Failed to throw NotActiveException when invoked outside readObject");
+ }
+
+ public void test_4_flush() {
+ // Test for method void java.io.ObjectOutputStream.flush()
+ try {
+ oos.close();
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ int size = bao.size();
+ oos.writeByte(127);
+ assertTrue("Data flushed already", bao.size() == size);
+ oos.flush();
+ assertTrue("Failed to flush data", bao.size() > size);
+ // we don't know how many bytes are actually written for 1 byte,
+ // so we test > <before>
+ oos.close();
+ oos = null;
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_5_reset() {
+ // Test for method void java.io.ObjectOutputStream.reset()
+ try {
+ String o = "HelloWorld";
+ oos.writeObject(o);
+ oos.writeObject(o);
+ oos.reset();
+ oos.writeObject(o);
+ ois = new ObjectInputStream(loadStream());
+ ois.close();
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_6_write() {
+ // Test for method void java.io.ObjectOutputStream.write(byte [], int,
+ // int)
+ try {
+ byte[] buf = new byte[255];
+ byte[] output = new byte[255];
+ for (int i = 0; i < output.length; i++)
+ output[i] = (byte) i;
+ oos.write(output, 0, output.length);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ ois.readFully(buf);
+ ois.close();
+ for (int i = 0; i < output.length; i++)
+ if (buf[i] != output[i])
+ fail("Read incorrect byte: " + i);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_6a_write() {
+ // Test for method void java.io.ObjectOutputStream.write(byte [], int,
+ // int)
+ try {
+ byte[] buf = new byte[256];
+ byte[] output = new byte[256];
+ for (int i = 0; i < output.length; i++)
+ output[i] = (byte) (i & 0xff);
+ oos.write(output, 0, output.length);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ ois.readFully(buf);
+ ois.close();
+ for (int i = 0; i < output.length; i++)
+ if (buf[i] != output[i])
+ fail("Read incorrect byte: " + i);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_7_write() {
+ // Test for method void java.io.ObjectOutputStream.write(int)
+ try {
+ oos.write('T');
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertEquals("Read incorrect byte", 'T', ois.read());
+ ois.close();
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_8_write() {
+ // Test for method void java.io.ObjectOutputStream.write(byte [])
+ try {
+ byte[] buf = new byte[10];
+ oos.write("HelloWorld".getBytes());
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ ois.read(buf, 0, 10);
+ ois.close();
+ assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, 10)
+ );
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_9_writeBoolean() {
+ // Test for method void java.io.ObjectOutputStream.writeBoolean(boolean)
+ try {
+ oos.writeBoolean(true);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertTrue("Wrote incorrect byte value", ois.readBoolean());
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_10_writeByte() {
+ // Test for method void java.io.ObjectOutputStream.writeByte(int)
+ try {
+ oos.writeByte(127);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertEquals("Wrote incorrect byte value", 127, ois.readByte());
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_11_writeBytes() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeBytes(java.lang.String)
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ ois.readFully(buf);
+ ois.close();
+ assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(buf, 0, 10, "UTF-8")
+ );
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_12_writeChar() {
+ // Test for method void java.io.ObjectOutputStream.writeChar(int)
+ try {
+ oos.writeChar('T');
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertEquals("Wrote incorrect char value", 'T', ois.readChar());
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_13_writeChars() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeChars(java.lang.String)
+ try {
+ int avail = 0;
+ char[] buf = new char[10];
+ oos.writeChars("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ // Number of prim data bytes in stream / 2 to give char index
+ avail = ois.available() / 2;
+ for (int i = 0; i < avail; ++i)
+ buf[i] = ois.readChar();
+ ois.close();
+ assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0, 10)
+ );
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_14_writeDouble() {
+ // Test for method void java.io.ObjectOutputStream.writeDouble(double)
+ try {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertTrue("Wrote incorrect double value",
+ ois.readDouble() == Double.MAX_VALUE);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_15_writeFloat() {
+ // Test for method void java.io.ObjectOutputStream.writeFloat(float)
+ try {
+ oos.writeFloat(Float.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertTrue("Wrote incorrect double value",
+ ois.readFloat() == Float.MAX_VALUE);
+ ois.close();
+ ois = null;
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_16_writeInt() {
+ // Test for method void java.io.ObjectOutputStream.writeInt(int)
+ try {
+ oos.writeInt(Integer.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertTrue("Wrote incorrect double value",
+ ois.readInt() == Integer.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_17_writeLong() {
+ // Test for method void java.io.ObjectOutputStream.writeLong(long)
+ try {
+ oos.writeLong(Long.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertTrue("Wrote incorrect double value",
+ ois.readLong() == Long.MAX_VALUE);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_19_writeShort() {
+ // Test for method void java.io.ObjectOutputStream.writeShort(int)
+ try {
+ oos.writeShort(127);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertEquals("Wrote incorrect short value", 127, ois.readShort());
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_20_writeUTF() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeUTF(java.lang.String)
+ try {
+ oos.writeUTF("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ assertEquals("Wrote incorrect UTF value",
+ "HelloWorld", ois.readUTF());
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_25_available() {
+ try {
+ oos.writeObject(FOO);
+ oos.writeObject(FOO);
+ oos.flush();
+ int available1 = 0;
+ int available2 = 0;
+ Object obj1 = null;
+ Object obj2 = null;
+ ObjectInputStream ois = new ObjectInputStream(loadStream());
+ available1 = ois.available();
+ obj1 = ois.readObject();
+ available2 = ois.available();
+ obj2 = ois.readObject();
+
+ assertEquals("available returned incorrect value", 0, available1);
+ assertEquals("available returned incorrect value", 0, available2);
+
+ assertTrue("available caused incorrect reading", FOO.equals(obj1));
+ assertTrue("available returned incorrect value", FOO.equals(obj2));
+
+ } catch (IOException e) {
+ fail("IOException serializing object : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("Unable to read Object type : " + e.toString());
+ } catch (Error err) {
+ System.out.println("Error " + err);
+ throw err;
+ }
+
+ }
+
+ protected void t_MixPrimitivesAndObjects() throws IOException,
+ ClassNotFoundException {
+ int i = 7;
+ String s1 = "string 1";
+ String s2 = "string 2";
+ byte[] bytes = { 1, 2, 3 };
+
+ oos.writeInt(i);
+ oos.writeObject(s1);
+ oos.writeUTF(s2);
+ oos.writeObject(bytes);
+ oos.close();
+ try {
+ ois = new ObjectInputStream(loadStream());
+
+ int j = ois.readInt();
+ assertTrue("Wrong int :" + j, i == j);
+
+ String l1 = (String) ois.readObject();
+ assertTrue("Wrong obj String :" + l1, s1.equals(l1));
+
+ String l2 = (String) ois.readUTF();
+ assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
+
+ byte[] bytes2 = (byte[]) ois.readObject();
+ assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
+
+ } finally {
+ ois.close();
+ }
+ }
+
+ public void test_resolveClass() {
+ try {
+ oos.writeObject(new Object[] { Integer.class, new Integer(1) });
+ oos.close();
+
+ ois = new ObjectInputStreamSubclass(loadStream());
+ ois.readObject();
+ ois.close();
+ } catch (IOException e1) {
+ fail("IOException : " + e1.getMessage());
+ } catch (ClassNotFoundException e2) {
+ fail("ClassNotFoundException : " + e2.getMessage());
+ }
+
+ Class[] resolvedClasses = ((ObjectInputStreamSubclass) ois)
+ .resolvedClasses();
+ assertEquals("missing resolved", 3, resolvedClasses.length);
+ assertTrue("resolved class 1", resolvedClasses[0] == Object[].class);
+ assertTrue("resolved class 2", resolvedClasses[1] == Integer.class);
+ assertTrue("resolved class 3", resolvedClasses[2] == Number.class);
+ }
+
+ public void test_reset() throws IOException, ClassNotFoundException {
+ oos.reset();
+ oos.writeObject("R");
+ oos.reset();
+ oos.writeByte(24);
+ oos.close();
+
+ DataInputStream dis = new DataInputStream(loadStream());
+ byte[] input = Streams.readFully(dis);
+ byte[] result = new byte[] { (byte) 0xac, (byte) 0xed, (byte) 0,
+ (byte) 5, (byte) 0x79, (byte) 0x74, (byte) 0, (byte) 1,
+ (byte) 'R', (byte) 0x79, (byte) 0x77, (byte) 1, (byte) 24 };
+ assertTrue("incorrect output", Arrays.equals(input, result));
+
+ ois = new ObjectInputStreamSubclass(loadStream());
+ assertEquals("Wrong result from readObject()", "R", ois.readObject());
+ assertEquals("Wrong result from readByte()", 24, ois.readByte());
+ ois.close();
+ }
+
+ private static class ResolveObjectTest implements Serializable {
+ Object field1, field2;
+ }
+
+ private static class ResolveObjectInputStream extends ObjectInputStream {
+ ResolveObjectInputStream(InputStream in)
+ throws StreamCorruptedException, IOException {
+ super(in);
+ }
+
+ public void enableResolve() {
+ enableResolveObject(true);
+ }
+
+ public Object resolveObject(Object obj) {
+ if (obj instanceof Vector) // test_1_resolveObject()
+ return new Hashtable();
+ else if ("abc".equals(obj)) // test_2_resolveObject()
+ return "ABC";
+ else if (obj instanceof String) // test_3_resolveObject()
+ return String.valueOf(((String) obj).length());
+ else if (obj instanceof int[]) // test_4_resolveObject()
+ return new Object[1];
+ else if (obj instanceof Object[] && ((Object[]) obj).length == 2) // test_5_resolveObject()
+ return new char[1];
+ return obj;
+ }
+ }
+
+ public void test_1_resolveObject() {
+ try {
+ ResolveObjectTest obj = new ResolveObjectTest();
+ obj.field1 = new Vector();
+ obj.field2 = obj.field1;
+ oos.writeObject(obj);
+ oos.close();
+ ois = new ResolveObjectInputStream(loadStream());
+ ((ResolveObjectInputStream) ois).enableResolve();
+ ResolveObjectTest result = null;
+ try {
+ result = (ResolveObjectTest) ois.readObject();
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ }
+ assertTrue("Object not resolved",
+ result.field1 instanceof Hashtable);
+ assertTrue("Second reference not resolved",
+ result.field1 == result.field2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_2_resolveObject() {
+ try {
+ ResolveObjectTest obj = new ResolveObjectTest();
+ obj.field1 = "abc";
+ obj.field2 = obj.field1;
+ oos.writeObject(obj);
+ oos.close();
+ ois = new ResolveObjectInputStream(loadStream());
+ ((ResolveObjectInputStream) ois).enableResolve();
+ ResolveObjectTest result = null;
+ try {
+ result = (ResolveObjectTest) ois.readObject();
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ }
+ assertEquals("String not resolved", "ABC", result.field1);
+ assertTrue("Second reference not resolved",
+ result.field1 == result.field2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_3_resolveObject() {
+ try {
+ ResolveObjectTest obj = new ResolveObjectTest();
+ char[] lchars = new char[70000];
+ obj.field1 = new String(lchars);
+ obj.field2 = obj.field1;
+ oos.writeObject(obj);
+ oos.close();
+ ois = new ResolveObjectInputStream(loadStream());
+ ((ResolveObjectInputStream) ois).enableResolve();
+ ResolveObjectTest result = null;
+ try {
+ result = (ResolveObjectTest) ois.readObject();
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ }
+ assertTrue("Long String not resolved", "70000"
+ .equals(result.field1));
+ assertTrue("Second reference not resolved",
+ result.field1 == result.field2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_4_resolveObject() {
+ try {
+ ResolveObjectTest obj = new ResolveObjectTest();
+ obj.field1 = new int[5];
+ obj.field2 = obj.field1;
+ oos.writeObject(obj);
+ oos.close();
+ ois = new ResolveObjectInputStream(loadStream());
+ ((ResolveObjectInputStream) ois).enableResolve();
+ ResolveObjectTest result = null;
+ try {
+ result = (ResolveObjectTest) ois.readObject();
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ }
+ Class cl = new Object[0].getClass();
+ assertTrue("int[] not resolved", result.field1.getClass() == cl);
+ assertTrue("Second reference not resolved",
+ result.field1 == result.field2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_5_resolveObject() {
+ try {
+ ResolveObjectTest obj = new ResolveObjectTest();
+ obj.field1 = new Object[2];
+ obj.field2 = obj.field1;
+ oos.writeObject(obj);
+ oos.close();
+ ois = new ResolveObjectInputStream(loadStream());
+ ((ResolveObjectInputStream) ois).enableResolve();
+ ResolveObjectTest result = null;
+ try {
+ result = (ResolveObjectTest) ois.readObject();
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ }
+ Class cl = new char[0].getClass();
+ assertTrue("int[] not resolved", result.field1.getClass() == cl);
+ assertTrue("Second reference not resolved",
+ result.field1 == result.field2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ }
+ }
+
+ static class WriteReplaceTestA implements Serializable {
+ public Object writeReplace() throws ObjectStreamException {
+ return new ReadResolveTestB();
+ }
+ }
+
+ static class WriteReplaceTestB extends WriteReplaceTestA {
+ }
+
+ static class WriteReplaceTestC extends WriteReplaceTestA {
+ public Object writeReplace() throws ObjectStreamException {
+ return new ReadResolveTestC();
+ }
+ }
+
+ static class WriteReplaceTestD implements Serializable {
+ private Object writeReplace() throws ObjectStreamException {
+ return new ReadResolveTestD();
+ }
+ }
+
+ static class WriteReplaceTestE extends WriteReplaceTestD {
+ }
+
+ static class WriteReplaceTestF implements Serializable {
+ int type, readType;
+
+ public WriteReplaceTestF(int type, int readType) {
+ this.type = type;
+ this.readType = readType;
+ }
+
+ public Object writeReplace() throws ObjectStreamException {
+ switch (type) {
+ case 0:
+ throw new InvalidObjectException("invalid");
+ case 1:
+ throw new RuntimeException("runtime");
+ case 2:
+ throw new Error("error");
+ default:
+ return new ReadResolveTestE(readType);
+ }
+ }
+ }
+
+ static class ReadResolveTestA implements Serializable {
+ public Object readResolve() throws ObjectStreamException {
+ return new ReadResolveTestA();
+ }
+ }
+
+ static class ReadResolveTestB extends ReadResolveTestA {
+ }
+
+ static class ReadResolveTestC implements Serializable {
+ private Object readResolve() throws ObjectStreamException {
+ return new ReadResolveTestB();
+ }
+ }
+
+ static class ReadResolveTestD extends ReadResolveTestC {
+ }
+
+ static class ReadResolveTestE implements Serializable {
+ int type;
+
+ public ReadResolveTestE(int type) {
+ this.type = type;
+ }
+
+ public Object readResolve() throws ObjectStreamException {
+ switch (type) {
+ case 0:
+ throw new InvalidObjectException("invalid");
+ case 1:
+ throw new RuntimeException("runtime");
+ case 2:
+ throw new Error("error");
+ case 3:
+ return this;
+ default:
+ return new ReadResolveTestF();
+ }
+ }
+ }
+
+ static class ReadResolveTestF implements Serializable {
+ }
+
+ public void test_1_writeReplace() {
+ try {
+ Vector<Object> v = new Vector<Object>();
+ v.addElement(new WriteReplaceTestA());
+ v.addElement(new WriteReplaceTestB());
+ v.addElement(new WriteReplaceTestB());
+ v.addElement(new WriteReplaceTestC());
+ v.addElement(new WriteReplaceTestD());
+ v.addElement(new WriteReplaceTestE());
+ oos.writeObject(v);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ Vector result = (Vector) ois.readObject();
+ assertTrue("invalid 0 : " + result.elementAt(0), result
+ .elementAt(0).getClass() == ReadResolveTestA.class);
+ assertTrue("invalid 1 : " + result.elementAt(1), result
+ .elementAt(1).getClass() == ReadResolveTestA.class);
+ assertTrue("invalid 2 : " + result.elementAt(2), result
+ .elementAt(2).getClass() == ReadResolveTestA.class);
+ assertTrue("invalid 3 : " + result.elementAt(3), result
+ .elementAt(3).getClass() == ReadResolveTestB.class);
+ assertTrue("invalid 4 : " + result.elementAt(4), result
+ .elementAt(4).getClass() == ReadResolveTestD.class);
+ assertTrue("invalid 5 : " + result.elementAt(5), result
+ .elementAt(5).getClass() == WriteReplaceTestE.class);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException serializing data : " + e.getMessage());
+ }
+ }
+
+ public void test_2_writeReplace() {
+ try {
+ boolean exception = false;
+ try {
+ oos.writeObject(new WriteReplaceTestF(0, -1));
+ } catch (ObjectStreamException e) {
+ exception = true;
+ }
+ assertTrue("Should throw ObjectStreamException", exception);
+ exception = false;
+ try {
+ oos.writeObject(new WriteReplaceTestF(1, -1));
+ } catch (RuntimeException e) {
+ exception = true;
+ }
+ assertTrue("Should throw RuntimeException", exception);
+ exception = false;
+ try {
+ oos.writeObject(new WriteReplaceTestF(2, -1));
+ } catch (Error e) {
+ exception = true;
+ }
+ assertTrue("Should throw Error", exception);
+
+ oos.writeObject(new WriteReplaceTestF(3, 0));
+ oos.writeObject(new WriteReplaceTestF(3, 1));
+ oos.writeObject(new WriteReplaceTestF(3, 2));
+ WriteReplaceTestF test = new WriteReplaceTestF(3, 3);
+ oos.writeObject(test);
+ oos.writeObject(test);
+ WriteReplaceTestF test2 = new WriteReplaceTestF(3, 4);
+ oos.writeObject(test2);
+ oos.writeObject(test2);
+ oos.close();
+ ois = new ObjectInputStream(loadStream());
+ try {
+ ois.readObject();
+ } catch (WriteAbortedException e) {
+ }
+
+ exception = false;
+ try {
+ ois.readObject();
+ } catch (ObjectStreamException e) {
+ exception = true;
+ }
+ assertTrue("Expected ObjectStreamException", exception);
+ exception = false;
+ try {
+ ois.readObject();
+ } catch (RuntimeException e) {
+ exception = true;
+ }
+ assertTrue("Expected RuntimeException", exception);
+ exception = false;
+ try {
+ ois.readObject();
+ } catch (Error e) {
+ exception = true;
+ }
+ assertTrue("Expected Error", exception);
+
+ Object readE1 = ois.readObject();
+ Object readE2 = ois.readObject();
+ assertTrue("Replaced objects should be identical", readE1 == readE2);
+ Object readF1 = ois.readObject();
+ Object readF2 = ois.readObject();
+ assertTrue("Replaced resolved objects should be identical: "
+ + readF1 + " " + readF2, readF1 == readF2);
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException serializing data : " + e.getMessage());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest1.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest1.java
new file mode 100644
index 0000000..27d8b33
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest1.java
@@ -0,0 +1,1657 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+@SuppressWarnings({ "serial", "unused" })
+public class SerializationStressTest1 extends SerializationStressTest {
+
+ // The purpose of these two classes is to test if serialization, when
+ // loading, runs the object's constructor (wrong) or the constructor defined
+ // at the topmost Serializable superclass(correct).
+ static final int INIT_INT_VALUE = 7;
+
+ // HAS to be static class so that our constructor signature will remain
+ // untouched (no synthetic param)
+ private static class SerializationTest implements java.io.Serializable {
+ int anInt = INIT_INT_VALUE;
+
+ public SerializationTest() {
+ super();
+ }
+ }
+
+ static final String INIT_STR_VALUE = "a string that is blortz";
+
+ // HAS to be static class so that our constructor signature will remain
+ // untouched (no synthetic param)
+ private static class SerializationTestSubclass1 extends SerializationTest {
+ String aString = INIT_STR_VALUE;
+
+ public SerializationTestSubclass1() {
+ super();
+ // Just to change default superclass init value
+ anInt = INIT_INT_VALUE / 2;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ private static class SpecTestSuperClass implements Runnable {
+ protected java.lang.String instVar;
+
+ public SpecTestSuperClass() {
+ }
+
+ public void run() {
+ }
+ }
+
+ private static class SpecTest extends SpecTestSuperClass implements
+ Cloneable, Serializable {
+ public java.lang.String instVar1;
+
+ public static java.lang.String staticVar1;
+
+ public static java.lang.String staticVar2;
+
+ {
+ instVar1 = "NonStaticInitialValue";
+ }
+
+ static {
+ staticVar1 = "StaticInitialValue";
+ staticVar1 = new String(staticVar1);
+ }
+
+ public Object method(Object objParam, Object objParam2) {
+ return new Object();
+ }
+
+ public boolean method(boolean bParam, Object objParam) {
+ return true;
+ }
+
+ public boolean method(boolean bParam, Object objParam, Object objParam2) {
+ return true;
+ }
+
+ }
+
+ private static class SpecTestSubclass extends SpecTest {
+ public transient java.lang.String transientInstVar = "transientValue";
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ // This one tests what happens if the read/writeObject methods are defined
+ // Serialization should work fine.
+ private static class ReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public ReadWriteObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ // This one tests what happens if the read/writeObject methods are not
+ // private.
+ // Serialization should fail.
+ private static class PublicReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public PublicReadWriteObject() {
+ super();
+ }
+
+ public void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ public void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ // This one tests if field names are serialized in the same way (sorting)
+ // across different VMs
+ private static class FieldOrder implements Serializable {
+ String aaa1NonPrimitive = "aaa1";
+
+ int bbb1PrimitiveInt = 5;
+
+ boolean aaa2PrimitiveBoolean = true;
+
+ String bbb2NonPrimitive = "bbb2";
+ }
+
+ // This one tests what happens if you define just readObject, but not
+ // writeObject.
+ // Does it run or not ?
+ private static class JustReadObject implements java.io.Serializable {
+ public boolean calledReadObject = false;
+
+ public JustReadObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.defaultReadObject();
+ }
+ }
+
+ // This one tests what happens if you define just writeObject, but not
+ // readObject.
+ // Does it run or not ?
+ private static class JustWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public JustWriteObject() {
+ super();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ calledWriteObject = true;
+ out.defaultWriteObject();
+ }
+ }
+
+ // This one tests class-based replacement when dumping
+ private static class ClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ public boolean calledReplacement = false;
+
+ public ClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ calledReplacement = true;
+ return FOO; // Replacement is a String
+ }
+ }
+
+ // This one tests whether class-based replacement supports multiple levels.
+ // MultipleClassBasedReplacementWhenDumping -> C1 -> C2 -> C3 -> FOO
+ private static class MultipleClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ private static class C1 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C2();
+ }
+ }
+
+ private static class C2 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C3();
+ }
+ }
+
+ private static class C3 implements java.io.Serializable {
+ private Object writeReplace() {
+ return FOO;
+ }
+ }
+
+ public MultipleClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ return new C1();
+ }
+ }
+
+ // This one tests class-based replacement when loading
+ private static class ClassBasedReplacementWhenLoading implements
+ java.io.Serializable {
+ public ClassBasedReplacementWhenLoading() {
+ super();
+ }
+
+ private Object readResolve() {
+ return FOO; // Replacement is a String
+ }
+ }
+
+ // This one tests what happens if a loading-replacement is not
+ // type-compatible with the original object
+ private static class ClassBasedReplacementWhenLoadingViolatesFieldType
+ implements java.io.Serializable {
+ public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
+
+ public ClassBasedReplacementWhenLoadingViolatesFieldType() {
+ super();
+ }
+ }
+
+ // What happens if dumping causes an error and you try to reload ?
+ // Should the load throw the same exception ?
+ private static class MyExceptionWhenDumping1 implements
+ java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ }
+
+ // A primitive instance variable exposes a bug in the serialization
+ // spec.
+ // Primitive instance variables are written without primitive data tags
+ // and so are read without checking for tags. If an exception is
+ // written, reading primitive data will just read bytes from the stream
+ // which may be tags
+ public boolean anInstanceVar = false;
+
+ public MyExceptionWhenDumping1() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ // What happens if dumping causes an error and you try to reload ?
+ // Should the load throw the same exception ?
+ private static class MyExceptionWhenDumping2 implements
+ java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ }
+
+ ;
+
+ public Integer anInstanceVar = new Integer(0xA1);
+
+ public MyExceptionWhenDumping2() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ // What happens if dumping causes an error (NonSerializable inst var) and
+ // you try to reload ?
+ // Should the load throw the same exception ?
+ private static class NonSerializableExceptionWhenDumping implements
+ java.io.Serializable {
+ public Object anInstanceVar = new Object();
+
+ public NonSerializableExceptionWhenDumping() {
+ super();
+ }
+ }
+
+ // What happens if dumping causes an error (which is not serializable) and
+ // you try to reload ?
+ // Should the load throw the same exception ?
+ private static class MyUnserializableExceptionWhenDumping implements
+ java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ private Object notSerializable = new Object();
+ }
+
+ public boolean anInstanceVar = false;
+
+ public MyUnserializableExceptionWhenDumping() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ public SerializationStressTest1(String name) {
+ super(name);
+ }
+
+ public void test_18_1_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = "HelloWorld";
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, (((String) objLoaded)
+ .equals((String) objToSave)));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_2_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = null;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_3_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ byte[] bytes = { 0, 1, 2, 3 };
+ objToSave = bytes;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (byte[]) objLoaded, (byte[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_4_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ int[] ints = { 0, 1, 2, 3 };
+ objToSave = ints;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (int[]) objLoaded, (int[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_5_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ short[] shorts = { 0, 1, 2, 3 };
+ objToSave = shorts;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (short[]) objLoaded, (short[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_6_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ long[] longs = { 0, 1, 2, 3 };
+ objToSave = longs;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (long[]) objLoaded, (long[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_7_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ float[] floats = { 0.0f, 1.1f, 2.2f, 3.3f };
+ objToSave = floats;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (float[]) objLoaded, (float[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data: " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_8_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ double[] doubles = { 0.0, 1.1, 2.2, 3.3 };
+ objToSave = doubles;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (double[]) objLoaded, (double[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_9_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ boolean[] booleans = { true, false, false, true };
+ objToSave = booleans;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (boolean[]) objLoaded, (boolean[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : " + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_10_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ String[] strings = { "foo", "bar", "java" };
+ objToSave = strings;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (Object[]) objLoaded, (Object[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("Unable to read Object type: " + e.toString());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_11_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ objToSave = new Object(); // Not serializable
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean passed = false;
+ Throwable t = null;
+ try {
+ objLoaded = dumpAndReload(objToSave);
+ } catch (NotSerializableException ns) {
+ passed = true;
+ t = ns;
+ } catch (Exception wrongExc) {
+ passed = false;
+ t = wrongExc;
+ }
+ assertTrue(
+ "Failed to throw NotSerializableException when serializing "
+ + objToSave + " Threw(if non-null) this: " + t,
+ passed);
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_12_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ try {
+ if (DEBUG)
+ System.out.println("Obj = <mixed>");
+ t_MixPrimitivesAndObjects();
+ } catch (IOException e) {
+ fail("IOException serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when dumping mixed types");
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_13_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SerializationTestSubclass1 st = new SerializationTestSubclass1();
+ // Just change the default ivar values
+ st.anInt = Integer.MAX_VALUE;
+ st.aString = FOO;
+ objToSave = st;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // non-serializable inst var has to be initialized from top
+ // constructor
+ assertTrue(
+ MSG_TEST_FAILED + objToSave,
+ ((SerializationTestSubclass1) objLoaded).anInt == Integer.MAX_VALUE);
+ // but serialized var has to be restored as it was in the object
+ // when dumped
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((SerializationTestSubclass1) objLoaded).aString
+ .equals(FOO));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_14_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SpecTest specTest = new SpecTest();
+ // Just change the default ivar values
+ specTest.instVar = FOO;
+ specTest.instVar1 = specTest.instVar;
+ objToSave = specTest;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // non-serializable inst var has to be initialized from top
+ // constructor
+ assertNull(MSG_TEST_FAILED + objToSave,
+ ((SpecTest) objLoaded).instVar);
+ // instVar from non-serialized class, cant be saved/restored
+ // by serialization but serialized ivar has to be restored as it
+ // was in the object when dumped
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((SpecTest) objLoaded).instVar1.equals(FOO));
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_15_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SpecTestSubclass specTestSubclass = new SpecTestSubclass();
+ // Just change the default ivar values
+ specTestSubclass.transientInstVar = FOO;
+ objToSave = specTestSubclass;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // non-serializable inst var cant be saved, and it is not init'ed
+ // from top constructor in this case
+ assertNull(MSG_TEST_FAILED + objToSave,
+ ((SpecTestSubclass) objLoaded).transientInstVar);
+ // transient slot, cant be saved/restored by serialization
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_16_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ String[] strings = new String[2];
+ strings[0] = FOO;
+ strings[1] = (" " + FOO + " ").trim(); // Safe way to get a copy
+ // that is not ==
+ objToSave = strings;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ String[] stringsLoaded = (String[]) objLoaded;
+ // Serialization has to use identity-based table for assigning IDs
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ !(stringsLoaded[0] == stringsLoaded[1]));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_17_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ ReadWriteObject readWrite = new ReadWriteObject();
+ objToSave = readWrite;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // has to have called the writeObject on the instance to dump
+ assertTrue(MSG_TEST_FAILED + objToSave, readWrite.calledWriteObject);
+ // has to have called the readObject on the instance loaded
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((ReadWriteObject) objLoaded).calledReadObject);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_18_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ PublicReadWriteObject publicReadWrite = new PublicReadWriteObject();
+ objToSave = publicReadWrite;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Can't have called the writeObject on the instance to dump
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ !publicReadWrite.calledWriteObject);
+ // Can't have called the readObject on the instance loaded
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ !((PublicReadWriteObject) objLoaded).calledReadObject);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_19_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ FieldOrder fieldOrder = new FieldOrder();
+ objToSave = fieldOrder;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // This test is only useful for X-loading, so if it managed to
+ // dump&load, we passed the test
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_20_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = Class.forName("java.lang.Integer");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Classes with the same name are unique, so test for ==
+ assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_21_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ // Even though instances of java.lang.Object are not Serializable,
+ // instances of java.lang.Class are. So, the object
+ // java.lang.Object.class
+ // should be serializable
+ objToSave = Class.forName("java.lang.Object");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Classes with the same name are unique, so test for ==
+ assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_22_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.net.URL url = new java.net.URL("http://localhost/a.txt");
+ objToSave = url;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue("URLs are not the same: " + url + "\t,\t" + objLoaded,
+ url.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_23_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ JustReadObject justReadObject = new JustReadObject();
+ objToSave = justReadObject;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Only calls readObject on the instance loaded if writeObject was
+ // also defined
+ assertTrue("Called readObject on an object without a writeObject",
+ !((JustReadObject) objLoaded).calledReadObject);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_24_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ JustWriteObject justWriteObject = new JustWriteObject();
+ objToSave = justWriteObject;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Call writeObject on the instance even if it does not define
+ // readObject
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ justWriteObject.calledWriteObject);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_25_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Vector<String> vector = new Vector<String>(1);
+ vector.add(FOO);
+ objToSave = vector;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have the string there
+ assertTrue(MSG_TEST_FAILED + objToSave, FOO
+ .equals(((java.util.Vector) objLoaded).elementAt(0)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_26_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Hashtable<String, String> hashTable = new Hashtable<String, String>(
+ 5);
+ hashTable.put(FOO, FOO);
+ objToSave = hashTable;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ java.util.Hashtable loadedHashTable = (java.util.Hashtable) objLoaded;
+ // Has to have the key/value there (FOO -> FOO)
+ assertTrue(MSG_TEST_FAILED + objToSave, FOO.equals(loadedHashTable
+ .get(FOO)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_27_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ClassBasedReplacementWhenDumping classBasedReplacementWhenDumping = new ClassBasedReplacementWhenDumping();
+ objToSave = classBasedReplacementWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have run the replacement method
+ assertTrue("Did not run writeReplace",
+ classBasedReplacementWhenDumping.calledReplacement);
+
+ // Has to have loaded a String (replacement object)
+ assertTrue("Did not replace properly", FOO.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_28_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ MultipleClassBasedReplacementWhenDumping multipleClassBasedReplacementWhenDumping = new MultipleClassBasedReplacementWhenDumping();
+ objToSave = multipleClassBasedReplacementWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have loaded a String (replacement object)
+ assertTrue(
+ "Executed multiple levels of replacement (see PR 1F9RNT1), loaded= "
+ + objLoaded,
+ objLoaded instanceof MultipleClassBasedReplacementWhenDumping.C1);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.toString());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_29_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
+ objToSave = classBasedReplacementWhenLoading;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have loaded a String (replacement object)
+ assertTrue("Did not run readResolve", FOO.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_30_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ClassBasedReplacementWhenLoadingViolatesFieldType classBasedReplacementWhenLoadingViolatesFieldType = new ClassBasedReplacementWhenLoadingViolatesFieldType();
+ objToSave = classBasedReplacementWhenLoadingViolatesFieldType;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // We cannot gere here, the load replacement must have caused a
+ // field type violation
+ fail(
+ "Loading replacements can cause field type violation in this implementation");
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (ClassCastException e) {
+ assertTrue(
+ "Loading replacements can NOT cause field type violation in this implementation",
+ true);
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_31_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ MyExceptionWhenDumping1 exceptionWhenDumping = new MyExceptionWhenDumping1();
+ objToSave = exceptionWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ dump(objToSave);
+ } catch (MyExceptionWhenDumping1.MyException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue("Should have caused an exception when dumping",
+ causedException);
+ causedException = false;
+ try {
+ objLoaded = reload();
+ // Although the spec says we should get a WriteAbortedException,
+ // the serialization format handle an Exception when reading
+ // primitive data so we get ClassCastException instead
+ } catch (ClassCastException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue("Should have caused a ClassCastException when loading",
+ causedException);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_32_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ MyExceptionWhenDumping2 exceptionWhenDumping = new MyExceptionWhenDumping2();
+ objToSave = exceptionWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ dump(objToSave);
+ } catch (MyExceptionWhenDumping2.MyException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue("Should have caused an exception when dumping",
+ causedException);
+ causedException = false;
+ try {
+ objLoaded = reload();
+ } catch (java.io.WriteAbortedException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue(
+ "Should have caused a java.io.WriteAbortedException when loading",
+ causedException);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (ClassCastException e) {
+ fail("ClassCastException : " + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_NonSerializableExceptionWhenDumping() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ NonSerializableExceptionWhenDumping nonSerializableExceptionWhenDumping = new NonSerializableExceptionWhenDumping();
+ objToSave = nonSerializableExceptionWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ dump(objToSave);
+ } catch (java.io.NotSerializableException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue("Should have caused an exception when dumping",
+ causedException);
+ causedException = false;
+ try {
+ objLoaded = reload();
+ } catch (java.io.WriteAbortedException e) {
+ causedException = true;
+ }
+ ;
+ assertTrue(
+ "Should have caused a java.io.WriteAbortedException when loading",
+ causedException);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_33_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ MyUnserializableExceptionWhenDumping exceptionWhenDumping = new MyUnserializableExceptionWhenDumping();
+ objToSave = exceptionWhenDumping;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ dump(objToSave);
+ } catch (MyUnserializableExceptionWhenDumping.MyException e) {
+ causedException = true;
+ }
+
+ assertTrue("Should have caused an exception when dumping",
+ causedException);
+ // As the stream is corrupted, reading the stream will have
+ // undefined results
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_34_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ioe = new java.io.IOException();
+ objToSave = ioe;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_35_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = Class.forName("java.util.Hashtable");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Classes with the same name are unique, so test for ==
+ assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_36_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.InvalidClassException(FOO);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_37_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.InvalidObjectException(FOO);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_38_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.NotActiveException(FOO);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_39_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.NotSerializableException(FOO);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_40_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.StreamCorruptedException(FOO);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest2.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest2.java
new file mode 100644
index 0000000..359050e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest2.java
@@ -0,0 +1,2101 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InvalidClassException;
+import java.io.NotActiveException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamConstants;
+import java.io.ObjectStreamField;
+import java.io.OptionalDataException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Locale;
+
+
+@SuppressWarnings({ "serial", "unused" })
+public class SerializationStressTest2 extends SerializationStressTest {
+
+ private static class ReadWriteObjectAndPrimitiveData implements
+ java.io.Serializable {
+ transient long milliseconds;
+
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public ReadWriteObjectAndPrimitiveData() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ // This *has* to come after the call to defaultReadObject or the
+ // value from the stream will override
+ calledReadObject = true;
+ milliseconds = in.readLong();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.defaultWriteObject();
+ out.writeLong(milliseconds);
+ }
+ }
+
+ // What happens if a class defines serialPersistentFields that do not match
+ // real fields but does not override read/writeObject
+ private static class WithUnmatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "value", String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WithUnmatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ // What happens if a class defines serialPersistentFields which match actual
+ // fields
+ private static class WithMatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "anInstanceVar", String.class) };
+
+ public String anInstanceVar = FOO + FOO;
+
+ public WithMatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ // Tests the oficial behavior for serialPersistentFields
+ private static class SerialPersistentFields implements java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectInputStream.GetField fields = in.readFields();
+ anInstanceVar = Integer.parseInt((String) fields.get(
+ SIMULATED_FIELD_NAME, "-5"));
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectOutputStream.PutField fields = out.putFields();
+ fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
+ out.writeFields();
+ }
+ }
+
+ // Tests the behavior for serialPersistentFields when no fields are actually
+ // set
+ private static class WriteFieldsWithoutFetchingPutFields implements
+ java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WriteFieldsWithoutFetchingPutFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectInputStream.GetField fields = in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ out.writeFields();
+ }
+ }
+
+ // Tests what happens if one asks for PutField/getField when the class does
+ // not declare one
+ private static class SerialPersistentFieldsWithoutField implements
+ java.io.Serializable {
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFieldsWithoutField() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectInputStream.GetField fields = in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectOutputStream.PutField fields = out.putFields();
+ out.writeFields();
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ // writeObject writes extra primitive types and objects which readObject
+ // does not consume. Have to make sure we can load object properly AND
+ // object after it (to show the extra byte[] is consumed)
+ private static class OptionalDataNotRead implements java.io.Serializable {
+ private int field1, field2;
+
+ public OptionalDataNotRead() {
+ }
+
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("field1", Integer.TYPE),
+ new ObjectStreamField("field2", Integer.TYPE),
+ new ObjectStreamField("monthLength", byte[].class), };
+
+ private void writeObject(ObjectOutputStream stream) throws IOException {
+ ObjectOutputStream.PutField fields = stream.putFields();
+ fields.put("field1", 1);
+ fields.put("field2", 2);
+ fields.put("monthLength", new byte[] { 7, 8, 9 });
+ stream.writeFields();
+ stream.writeInt(4);
+ byte[] values = new byte[4];
+ values[0] = (byte) 16;
+ values[1] = (byte) 17;
+ values[2] = (byte) 18;
+ values[3] = (byte) 19;
+ stream.writeObject(values);
+ }
+
+ private void readObject(ObjectInputStream stream) throws IOException,
+ ClassNotFoundException {
+ ObjectInputStream.GetField fields = stream.readFields();
+ field1 = fields.get("field1", 0);
+ field2 = fields.get("field1", 0);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class NestedPutField implements java.io.Serializable {
+ public OptionalDataNotRead field1;
+
+ public NestedPutField() {
+ }
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "field1", OptionalDataNotRead.class), };
+
+ private void writeObject(ObjectOutputStream stream) throws IOException {
+ ObjectOutputStream.PutField fields = stream.putFields();
+ fields.put("field1", new OptionalDataNotRead());
+ stream.writeFields();
+ }
+
+ private void readObject(ObjectInputStream stream) throws IOException,
+ ClassNotFoundException {
+ ObjectInputStream.GetField fields = stream.readFields();
+ field1 = (OptionalDataNotRead) fields.get("field1", null);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ // This one tests stream-based replacement when dumping
+ private static class StreamBasedReplacementWhenDumping extends
+ java.io.ObjectOutputStream {
+ public boolean calledArrayReplacement = false;
+
+ public boolean calledStringReplacement = false;
+
+ public boolean calledClassReplacement = false;
+
+ public boolean calledObjectStreamClassReplacement = false;
+
+ public StreamBasedReplacementWhenDumping(java.io.OutputStream output)
+ throws java.io.IOException {
+ super(output);
+ enableReplaceObject(true);
+ }
+
+ protected Object replaceObject(Object obj) throws IOException {
+ Class objClass = obj.getClass();
+ if (objClass == String.class)
+ calledStringReplacement = true;
+
+ if (objClass == Class.class)
+ calledClassReplacement = true;
+
+ if (objClass == ObjectStreamClass.class)
+ calledObjectStreamClassReplacement = true;
+
+ if (objClass.isArray())
+ calledArrayReplacement = true;
+
+ return obj;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ private static class ArrayOfSerializable implements Serializable {
+ private Serializable[] testField = null;
+
+ public ArrayOfSerializable() {
+ testField = new Serializable[2];
+ testField[0] = "Hi";
+ testField[1] = "there!";
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+
+ private static class ClassSubClassTest0 extends java.lang.Object implements
+ java.io.Serializable {
+ String stringVar;
+
+ public ClassSubClassTest0(String init) {
+ stringVar = init;
+ }
+ }
+
+ private static class ClassSubClassTest1 extends ClassSubClassTest0 {
+ String subStringVar;
+
+ public ClassSubClassTest1(String superString, String subString) {
+ super(superString);
+ subStringVar = subString;
+ }
+
+ public boolean equals(Object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ClassSubClassTest1))
+ return false;
+
+ ClassSubClassTest1 inst = (ClassSubClassTest1) obj;
+ return inst.subStringVar.equals(this.subStringVar)
+ && inst.stringVar.equals(this.stringVar);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class ConstructorTestA {
+ public String instVar_classA;
+
+ public final static String ConstrA = "Init in Constructor Class A";
+
+ public final static String ConstrB = "Init in Constructor Class B";
+
+ public final static String ConstrC = "Init in Constructor Class C";
+
+ public final static String ChangedC = "Changed before Serialize - Class C";
+
+ public ConstructorTestA() {
+ instVar_classA = ConstrA;
+ }
+ }
+
+ private static class ConstructorTestB extends ConstructorTestA implements
+ java.io.Serializable {
+ public String instVar_classB;
+
+ public ConstructorTestB() {
+ instVar_classA = ConstrB;
+ instVar_classB = ConstrB;
+ }
+ }
+
+ private static class ConstructorTestC extends ConstructorTestB {
+ public String instVar_classC;
+
+ public ConstructorTestC() {
+ instVar_classA = ConstrC;
+ instVar_classB = ConstrC;
+ instVar_classC = ConstrC;
+ }
+
+ public boolean verify(Object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ConstructorTestC))
+ return false;
+
+ ConstructorTestC inst = (ConstructorTestC) obj;
+ return inst.instVar_classC.equals(this.instVar_classC)
+ && inst.instVar_classB.equals(this.instVar_classB)
+ && inst.instVar_classA.equals(ConstrA);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class HashCodeTest implements java.io.Serializable {
+ private boolean serializationUsesHashCode = false;
+
+ public int hashCode() {
+ serializationUsesHashCode = true;
+ return super.hashCode();
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class InitializerFieldsTest implements java.io.Serializable {
+ public java.lang.String toBeSerialized;
+
+ public static java.lang.String toBeNotSerialized;
+
+ public static java.lang.String toBeNotSerialized2;
+
+ {
+ toBeSerialized = "NonStaticInitialValue";
+ }
+
+ static {
+ toBeNotSerialized = "StaticInitialValue";
+ toBeNotSerialized2 = new String(toBeNotSerialized);
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof InitializerFieldsTest))
+ return false;
+
+ InitializerFieldsTest inst = (InitializerFieldsTest) obj;
+ return inst.toBeSerialized.equals(this.toBeSerialized)
+ && InitializerFieldsTest.toBeNotSerialized.equals(toBeNotSerialized2);
+ }
+ }
+
+ private static class InitializerFieldsTest2 implements java.io.Serializable {
+ public java.lang.String toBeSerialized;
+
+ public static java.lang.String toBeNotSerialized;
+
+ public static java.lang.String toBeNotSerialized2;
+
+ {
+ toBeSerialized = "NonStaticInitialValue";
+ }
+
+ public java.lang.String toBeSerialized3;
+
+ public java.lang.String toBeSerialized4;
+
+ static {
+ toBeNotSerialized = "StaticInitialValue";
+ toBeNotSerialized2 = new String(toBeNotSerialized);
+ }
+
+ public java.lang.String toBeSerialized5;
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof InitializerFieldsTest2))
+ return false;
+
+ InitializerFieldsTest2 inst = (InitializerFieldsTest2) obj;
+ return inst.toBeSerialized.equals(this.toBeSerialized)
+ && inst.toBeSerialized3.equals(this.toBeSerialized3)
+ && inst.toBeSerialized4.equals(this.toBeSerialized4)
+ && inst.toBeSerialized5.equals(this.toBeSerialized5)
+ && InitializerFieldsTest2.toBeNotSerialized.equals(toBeNotSerialized2);
+ }
+ }
+
+ private static class InitializerFieldsTest3 extends InitializerFieldsTest2
+ implements java.io.Serializable {
+ public java.lang.String sub_toBeSerialized;
+
+ public static java.lang.String sub_toBeNotSerialized;
+
+ public static java.lang.String sub_toBeNotSerialized2;
+
+ {
+ sub_toBeSerialized = "NonStaticInitialValue";
+ }
+
+ public java.lang.String sub_toBeSerialized3;
+
+ public java.lang.String sub_toBeSerialized4;
+
+ static {
+ sub_toBeNotSerialized = "StaticInitialValue";
+ sub_toBeNotSerialized2 = new String(sub_toBeNotSerialized);
+ }
+
+ public java.lang.String sub_toBeSerialized5;
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (!super.equals(obj))
+ return false;
+ if (!(obj instanceof InitializerFieldsTest3))
+ return false;
+
+ InitializerFieldsTest3 inst = (InitializerFieldsTest3) obj;
+ return inst.sub_toBeSerialized.equals(this.sub_toBeSerialized)
+ && inst.sub_toBeSerialized3
+ .equals(this.sub_toBeSerialized3)
+ && inst.sub_toBeSerialized4
+ .equals(this.sub_toBeSerialized4)
+ && inst.sub_toBeSerialized5
+ .equals(this.sub_toBeSerialized5)
+ && InitializerFieldsTest3.sub_toBeNotSerialized
+ .equals(sub_toBeNotSerialized2);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class DeepNesting implements java.io.Serializable {
+ public float id;
+
+ public DeepNesting next;
+
+ public boolean dump;
+
+ public boolean load;
+
+ public DeepNesting(float id) {
+ this.id = id;
+ next = null;
+ dump = false;
+ load = false;
+ }
+
+ public DeepNesting(int howMany) {
+ DeepNesting prev = new DeepNesting(0.0F);
+ next(prev);
+ for (int i = 1; i < howMany; i++) {
+ prev = prev.next(new DeepNesting(i * 1.0F));
+ }
+ }
+
+ public boolean equals(Object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj instanceof DeepNesting))
+ return false;
+
+ DeepNesting inst = (DeepNesting) obj;
+ if (inst.dump != this.dump || inst.load != this.load)
+ return false;
+
+ if (inst.next == null || this.next == null)
+ return inst.next == this.next; // both null
+ return this.next.equals(inst.next);
+ }
+
+ public DeepNesting next(DeepNesting ivt) {
+ next = ivt;
+ return ivt;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class DeepNestingWithWriteObject implements
+ java.io.Serializable {
+ public float id;
+
+ public DeepNestingWithWriteObject next;
+
+ public boolean dump;
+
+ public boolean load;
+
+ public DeepNestingWithWriteObject(float id) {
+ this.id = id;
+ next = null;
+ dump = false;
+ load = false;
+ }
+
+ public DeepNestingWithWriteObject(int howMany) {
+ DeepNestingWithWriteObject prev = new DeepNestingWithWriteObject(
+ 0.0F);
+ next(prev);
+ for (int i = 1; i < howMany; i++) {
+ prev = prev.next(new DeepNestingWithWriteObject(i * 1.0F));
+ }
+ }
+
+ public boolean equals(Object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj instanceof DeepNestingWithWriteObject))
+ return false;
+
+ DeepNestingWithWriteObject inst = (DeepNestingWithWriteObject) obj;
+ if (inst.dump != this.dump || inst.load != this.load)
+ return false;
+
+ if (inst.next == null || this.next == null)
+ return inst.next == this.next; // both null;
+ return this.next.equals(inst.next);
+ }
+
+ public DeepNestingWithWriteObject next(DeepNestingWithWriteObject ivt) {
+ next = ivt;
+ return ivt;
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws IOException {
+ s.defaultWriteObject();
+ }
+
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ s.defaultReadObject();
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ static class NonPublicClassTest extends java.lang.Object implements
+ java.io.Serializable {
+ int field = 1;
+
+ public NonPublicClassTest() {
+ field = 10;
+ }
+
+ public boolean equals(Object o) {
+ if (o instanceof NonPublicClassTest)
+ return field == ((NonPublicClassTest) o).field;
+ return false;
+ }
+
+ public void x10() {
+ field *= 10;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SameInstVarNameSuperClass {
+ private int foo;
+
+ public SameInstVarNameSuperClass() {
+ super();
+ }
+
+ public SameInstVarNameSuperClass(int fooValue) {
+ foo = fooValue;
+ }
+
+ public String toString() {
+ return "foo = " + foo;
+ }
+ }
+
+ private static class SameInstVarNameSubClass extends
+ SameInstVarNameSuperClass implements java.io.Serializable {
+ protected int foo;
+
+ public SameInstVarNameSubClass() {
+ super();
+ }
+
+ public SameInstVarNameSubClass(int fooValue) {
+ super(-fooValue);
+ foo = fooValue;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SInterfaceTest implements java.io.Serializable {
+ public static int staticVar = 5;
+
+ public transient int[] transVar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
+
+ public int instanceVar = 7;
+
+ public boolean equals(Object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj instanceof SInterfaceTest))
+ return false;
+
+ SInterfaceTest inst = (SInterfaceTest) obj;
+ if (this.instanceVar != inst.instanceVar)
+ return false;
+ if (inst.transVar == null || this.transVar == null)
+ return inst.transVar == this.transVar; // both null
+ for (int i = 0; i < transVar.length; i++)
+ if (inst.transVar[i] != this.transVar[i])
+ return false;
+ return true;
+ }
+
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ Object arr;
+ s.defaultReadObject();
+ arr = s.readObject();
+ transVar = (int[]) arr;
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws IOException {
+ s.defaultWriteObject();
+ s.writeObject(transVar);
+ }
+
+ public void x10() {
+ for (int i = 0; i < transVar.length; i++)
+ transVar[i] = transVar[i] * 10;
+ instanceVar = instanceVar * 10;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SInterfaceTest2 extends SInterfaceTest {
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ Object arr;
+ instanceVar = s.readInt();
+ arr = s.readObject();
+ transVar = (int[]) arr;
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws IOException {
+ s.writeInt(instanceVar);
+ s.writeObject(transVar);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SuperclassTest extends java.lang.Object implements
+ java.io.Serializable {
+ int superfield = 1;
+
+ public SuperclassTest() {
+ superfield = 10;
+ }
+
+ public boolean equals(Object o) {
+ if (o.getClass() == this.getClass())
+ return superfield == ((SuperclassTest) o).superfield;
+ return false;
+ }
+
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ superfield = s.readInt();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws IOException {
+ s.writeInt(superfield);
+ }
+
+ public void x10() {
+ superfield *= 10;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SuperclassTest2 extends SuperclassTest {
+ int subfield = 5;
+
+ public SuperclassTest2() {
+ subfield = 50;
+ }
+
+ public boolean equals(Object o) {
+ if (o instanceof SuperclassTest2)
+ if (subfield == ((SuperclassTest2) o).subfield)
+ return super.equals(o);
+ return false;
+ }
+
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ subfield = s.readInt();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws IOException {
+ s.writeInt(subfield);
+ }
+
+ public void x10() {
+ subfield *= 10;
+ super.x10();
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class SyntheticFieldTest implements java.io.Serializable {
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+ if (obj == null)
+ return false;
+ return obj instanceof SyntheticFieldTest;
+ }
+
+ public int hashCode() {
+ // Insert code to generate a hash code for the receiver here.
+ // This implementation forwards the message to super. You may
+ // replace or supplement this.
+ // NOTE: if two objects are equal (equals Object) returns true) they
+ // must have the same hash code
+ Class[] c = { String.class }; // *** synthetic field
+ return super.hashCode();
+ }
+ }
+
+ public SerializationStressTest2(String name) {
+ super(name);
+ }
+
+ public void test_18_41_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ java.io.IOException ex = new java.io.WriteAbortedException(FOO,
+ null);
+ objToSave = ex;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_42_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ WithUnmatchingSerialPersistentFields spf = new WithUnmatchingSerialPersistentFields();
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ objLoaded = dumpAndReload(objToSave);
+ } catch (InvalidClassException ce) {
+ causedException = true;
+ }
+ assertTrue("serialPersistentFields do not match real fields",
+ causedException);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_43_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ WithMatchingSerialPersistentFields spf = new WithMatchingSerialPersistentFields();
+ spf.anInstanceVar = FOO;
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(
+ "serialPersistentFields do not work properly in this implementation",
+ FOO
+ .equals(((WithMatchingSerialPersistentFields) objLoaded).anInstanceVar));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_44_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SerialPersistentFields spf = new SerialPersistentFields();
+ final int CONST = -500;
+ spf.anInstanceVar = CONST;
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(
+ "serialPersistentFields do not work properly in this implementation",
+ ((SerialPersistentFields) objLoaded).anInstanceVar == CONST);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_45_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ WriteFieldsWithoutFetchingPutFields spf = new WriteFieldsWithoutFetchingPutFields();
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ boolean causedException = false;
+ try {
+ objLoaded = dumpAndReload(objToSave);
+ } catch (NotActiveException ce) {
+ causedException = true;
+ }
+ assertTrue("WriteFieldsWithoutFetchingPutFields", causedException);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_46_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = SerialPersistentFields.class; // Test for 1FA7TA6
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_47_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = ObjectStreamClass.lookup(SerialPersistentFields.class); // Test
+ // for
+ // 1FA7TA6
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to be able to save/load an exception
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_48_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
+ final int CONST = -500;
+ spf.anInstanceVar = CONST;
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(
+ "serialPersistentFields do not work properly in this implementation",
+ ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_51_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ ReadWriteObjectAndPrimitiveData readWrite = new ReadWriteObjectAndPrimitiveData();
+ objToSave = readWrite;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // has to have called the writeObject on the instance to dump
+ assertTrue(MSG_TEST_FAILED + objToSave, readWrite.calledWriteObject);
+ // has to have called the readObject on the instance loaded
+ assertTrue(
+ MSG_TEST_FAILED + objToSave,
+ ((ReadWriteObjectAndPrimitiveData) objLoaded).calledReadObject);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_52_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ ArrayList list = new ArrayList<String>(Arrays.asList(new String[] { "a",
+ "list", "of", "strings" }));
+ objToSave = list;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_53_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+
+ objToSave = Locale.CHINESE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_OptionalDataNotRead() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ OptionalDataNotRead test = new OptionalDataNotRead();
+ // Have to save an object after the one above, and when we read it,
+ // it cannot be a byte[]
+ Date now = new Date();
+ Object[] twoObjects = new Object[2];
+ twoObjects[0] = test;
+ twoObjects[1] = now;
+ objToSave = twoObjects;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ Object[] twoLoadedObjects = (Object[]) objLoaded;
+ assertTrue(MSG_TEST_FAILED + objToSave, twoLoadedObjects[0]
+ .getClass() == OptionalDataNotRead.class);
+ assertTrue(MSG_TEST_FAILED + objToSave, twoLoadedObjects[1]
+ .getClass() == Date.class);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_55_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object[] threeObjects = new Object[3];
+ threeObjects[0] = new Integer(2);
+ threeObjects[1] = Date.class;
+ threeObjects[2] = threeObjects[0]; // has to be the same
+ objToSave = threeObjects;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ Object[] threeLoadedObjects = (Object[]) objLoaded;
+ assertTrue(MSG_TEST_FAILED + objToSave, threeLoadedObjects[0]
+ .getClass() == Integer.class);
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ threeLoadedObjects[1] == Date.class);
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ threeLoadedObjects[0] == threeLoadedObjects[2]);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_56_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ // Test for 1FD24BY
+ NestedPutField test = new NestedPutField();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertNotNull(MSG_TEST_FAILED + objToSave,
+ ((NestedPutField) objLoaded).field1);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_57_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ByteArrayOutputStream out;
+ StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
+
+ out = new ByteArrayOutputStream();
+ streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(out);
+ objToSave = FOO.getClass();
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ streamBasedReplacementWhenDumping.writeObject(objToSave);
+ // Has to have run the replacement method
+ assertTrue(streamBasedReplacementWhenDumping.calledClassReplacement);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_58_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ByteArrayOutputStream out;
+ StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
+
+ out = new ByteArrayOutputStream();
+ streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
+ out);
+
+ objToSave = ObjectStreamClass.lookup(FOO.getClass());
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ streamBasedReplacementWhenDumping.writeObject(objToSave);
+ // Has to have run the replacement method
+ assertTrue(streamBasedReplacementWhenDumping.calledObjectStreamClassReplacement);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_59_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ByteArrayOutputStream out;
+ StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
+
+ out = new ByteArrayOutputStream();
+ streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
+ out);
+ ;
+ objToSave = new int[3];
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ streamBasedReplacementWhenDumping.writeObject(objToSave);
+ // Has to have run the replacement method
+ assertTrue("DId not execute replacement when it should: "
+ + objToSave,
+ streamBasedReplacementWhenDumping.calledArrayReplacement);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_60_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ByteArrayOutputStream out;
+ StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
+
+ out = new ByteArrayOutputStream();
+ streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
+ out);
+ ;
+ objToSave = FOO;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ streamBasedReplacementWhenDumping.writeObject(objToSave);
+ // Has to have run the replacement method
+ assertTrue("Did not execute replacement when it should: "
+ + objToSave,
+ streamBasedReplacementWhenDumping.calledStringReplacement);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.toString());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_61_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ArrayOfSerializable test = new ArrayOfSerializable();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, true);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_62_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ClassSubClassTest1 test = new ClassSubClassTest1(
+ "SuperInitialString", "SubInitialString");
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_63_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ConstructorTestC test = new ConstructorTestC();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.verify(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_64_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ HashCodeTest test = new HashCodeTest();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ !((HashCodeTest) objLoaded).serializationUsesHashCode);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_65_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ InitializerFieldsTest test = new InitializerFieldsTest();
+ test.toBeSerialized = "serializing";
+ InitializerFieldsTest.toBeNotSerialized = "It should not have this value after loaded from a File";
+ InitializerFieldsTest.toBeNotSerialized2 = "Good-This is the rigth value.";
+
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ dump(objToSave);
+ InitializerFieldsTest.toBeNotSerialized = new String(
+ InitializerFieldsTest.toBeNotSerialized2);
+ objLoaded = reload();
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_66_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ InitializerFieldsTest2 test = new InitializerFieldsTest2();
+ test.toBeSerialized = "serializing";
+ test.toBeSerialized3 = "serializing3";
+ test.toBeSerialized4 = "serializing4";
+ test.toBeSerialized5 = "serializing5";
+ InitializerFieldsTest2.toBeNotSerialized = "It should not have this value after loaded from a File";
+ InitializerFieldsTest2.toBeNotSerialized2 = "Good-This is the rigth value.";
+
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ dump(objToSave);
+ InitializerFieldsTest2.toBeNotSerialized = new String(
+ InitializerFieldsTest2.toBeNotSerialized2);
+ objLoaded = reload();
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_67_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ InitializerFieldsTest3 test = new InitializerFieldsTest3();
+ test.toBeSerialized = "serializing";
+ test.toBeSerialized3 = "serializing3";
+ test.toBeSerialized4 = "serializing4";
+ test.toBeSerialized5 = "serializing5";
+ InitializerFieldsTest2.toBeNotSerialized = "It should not have this value after loaded from a File";
+ InitializerFieldsTest2.toBeNotSerialized2 = "Good-This is the rigth value.";
+ test.sub_toBeSerialized = "serializingSub";
+ test.sub_toBeSerialized3 = "serializing3sub";
+ test.sub_toBeSerialized4 = "serializing4sub";
+ test.sub_toBeSerialized5 = "serializing5sub";
+ InitializerFieldsTest3.sub_toBeNotSerialized = "(Subclass) It should not have this value after loaded from a File";
+ InitializerFieldsTest3.sub_toBeNotSerialized2 = "(Subclass) Good-This is the rigth value.";
+ // Before dumping the two static vars are differents.
+ // After dumping the value of toBeNotSerialized2 is put in
+ // toBeNotSerialized
+ // After loading it must be the same.
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ dump(objToSave);
+ InitializerFieldsTest2.toBeNotSerialized = new String(
+ InitializerFieldsTest2.toBeNotSerialized2);
+ InitializerFieldsTest3.sub_toBeNotSerialized = new String(
+ InitializerFieldsTest3.sub_toBeNotSerialized2);
+ objLoaded = reload();
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_DeepNesting() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ DeepNesting test = new DeepNesting(25);
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ // err.printStackTrace();
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_DeepNestingWithWriteObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ DeepNestingWithWriteObject test = new DeepNestingWithWriteObject(10);
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ // err.printStackTrace();
+ System.out.println("Error " + err + " when obj = " + objToSave);
+ throw err;
+ }
+ }
+
+ public void test_18_69_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ NonPublicClassTest test = new NonPublicClassTest();
+ test.x10();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_70_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ int[] test = new int[1];
+ int intValue = 0;
+ test[0] = intValue;
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(test,
+ (int[]) objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_71_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ int i, j, maxJ = 3, maxI = 200;
+ byte[][] obj = new byte[maxJ][maxI];
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ obj[j][i] = (byte) (i - 100);
+ }
+ objToSave = obj;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ byte[][] toCompare = (byte[][]) objLoaded;
+
+ boolean ok = true;
+ // Has to have worked
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ if (obj[j][i] != toCompare[j][i]) {
+ ok = false;
+ break;
+ }
+ }
+
+ assertTrue(MSG_TEST_FAILED + objToSave, ok);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_72_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ int i, j, maxJ = 3, maxI = 200;
+ int[][] obj = new int[maxJ][maxI];
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ obj[j][i] = (i - 100);
+ }
+ objToSave = obj;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ int[][] toCompare = (int[][]) objLoaded;
+
+ boolean ok = true;
+ // Has to have worked
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ if (obj[j][i] != toCompare[j][i]) {
+ ok = false;
+ break;
+ }
+ }
+
+ assertTrue(MSG_TEST_FAILED + objToSave, ok);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_73_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ String org = "abcdefghijklmnopqrstuvxyz1234567890abcdefghijklmnopqrstuvxyz1234567890";
+ int i, j, maxJ = 3, maxI = 70;
+ String[][] obj = new String[maxJ][maxI];
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ obj[j][i] = org.substring(0, i);
+ }
+ objToSave = obj;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ String[][] toCompare = (String[][]) objLoaded;
+
+ boolean ok = true;
+ // Has to have worked
+ for (j = 0; j < maxJ; j++) {
+ for (i = 0; i < maxI; i++)
+ if (!obj[j][i].equals(toCompare[j][i])) {
+ ok = false;
+ break;
+ }
+ }
+
+ assertTrue(MSG_TEST_FAILED + objToSave, ok);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_74_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SameInstVarNameSubClass test = new SameInstVarNameSubClass(100);
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((SameInstVarNameSubClass) objLoaded).foo == 100);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_75_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SInterfaceTest test = new SInterfaceTest();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_76_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SInterfaceTest2 test = new SInterfaceTest2();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_77_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SuperclassTest test = new SuperclassTest();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_78_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SuperclassTest2 test = new SuperclassTest2();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_79_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SyntheticFieldTest test = new SyntheticFieldTest();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_80_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(out);
+ new ObjectOutputStream(dos); // just to make sure we get a header
+ dos.writeByte(ObjectStreamConstants.TC_BLOCKDATA);
+ int length = 99;
+ dos.writeByte(length);
+ for (int i = 0; i < length; i++) {
+ dos.writeByte(0); // actual value does not matter
+ }
+ dos.flush();
+ int lengthRead = 0;
+ try {
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(out.toByteArray()));
+ Object obj = ois.readObject();
+ } catch (OptionalDataException e) {
+ lengthRead = e.length;
+ }
+ assertTrue("Did not throw exception with optional data size ",
+ length == lengthRead);
+ } catch (ClassNotFoundException e) {
+ fail("Unable to read BLOCKDATA: " + e.getMessage());
+ } catch (IOException e) {
+ fail("IOException testing BLOCKDATA : " + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when testing BLOCKDATA");
+ throw err;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest3.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest3.java
new file mode 100644
index 0000000..8087761
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest3.java
@@ -0,0 +1,1670 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamConstants;
+import java.io.ObjectStreamField;
+import java.io.OptionalDataException;
+import java.math.BigInteger;
+import java.security.PermissionCollection;
+import java.util.Arrays;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.Locale;
+import java.util.PropertyPermission;
+import java.util.TimeZone;
+import java.util.Vector;
+
+
+@SuppressWarnings({ "serial", "unused" })
+public class SerializationStressTest3 extends SerializationStressTest {
+
+ // -----------------------------------------------------------------------------------
+ private static class DefaultConstructor implements java.io.Serializable {
+ int f1;
+
+ static int valueAfterConstructor = 5;
+
+ DefaultConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof DefaultConstructor))
+ return false;
+
+ DefaultConstructor inst = (DefaultConstructor) obj;
+ return inst.f1 == valueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class NonSerDefaultConstructor {
+ public int f1;
+
+ public static int valueAfterConstructor = 5;
+
+ NonSerDefaultConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public NonSerDefaultConstructor(String notUsed) {
+ }
+ }
+
+ private static class NonSerPrivateConstructor {
+ public int f1;
+
+ public static int valueAfterConstructor = 5;
+
+ private NonSerPrivateConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public NonSerPrivateConstructor(String notUsed) {
+ }
+ }
+
+ private static class NonSerProtectedConstructor {
+ public int f1;
+
+ public static int valueAfterConstructor = 5;
+
+ protected NonSerProtectedConstructor() {
+ f1 = valueAfterConstructor;
+ }
+ }
+
+ private static class NonSerPublicConstructor {
+ public int f1;
+
+ public static int valueAfterConstructor = 5;
+
+ public NonSerPublicConstructor() {
+ f1 = valueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class DefaultConstructorSub extends NonSerDefaultConstructor
+ implements java.io.Serializable {
+ int fsub;
+
+ static int subValueAfterConstructor = 11;
+
+ public DefaultConstructorSub() {
+ f1 = 7;
+ fsub = subValueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof DefaultConstructorSub))
+ return false;
+
+ DefaultConstructorSub inst = (DefaultConstructorSub) obj;
+ if (inst.f1 != valueAfterConstructor)
+ return false;
+ return inst.fsub == subValueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class PrivateConstructor implements java.io.Serializable {
+ int f1;
+
+ static int valueAfterConstructor = 5;
+
+ private PrivateConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. Is is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof PrivateConstructor))
+ return false;
+
+ PrivateConstructor inst = (PrivateConstructor) obj;
+ return inst.f1 == valueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class PrivateConstructorSub extends NonSerPrivateConstructor
+ implements java.io.Serializable {
+ int fsub;
+
+ static int subValueAfterConstructor = 11;
+
+ public PrivateConstructorSub() {
+ super("notUsed");
+ f1 = 7;
+ fsub = subValueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. Is is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof PrivateConstructorSub))
+ return false;
+
+ PrivateConstructorSub inst = (PrivateConstructorSub) obj;
+ return inst.f1 == valueAfterConstructor
+ && inst.fsub == subValueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class ProtectedConstructor implements java.io.Serializable {
+ int f1;
+
+ static int valueAfterConstructor = 5;
+
+ protected ProtectedConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. Is is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ProtectedConstructor))
+ return false;
+
+ ProtectedConstructor inst = (ProtectedConstructor) obj;
+ return inst.f1 == valueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class ProtectedConstructorSub extends
+ NonSerProtectedConstructor implements java.io.Serializable {
+ int fsub;
+
+ static int subValueAfterConstructor = 11;
+
+ public ProtectedConstructorSub() {
+ f1 = 7;
+ fsub = subValueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. Is is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ProtectedConstructorSub))
+ return false;
+
+ ProtectedConstructorSub inst = (ProtectedConstructorSub) obj;
+ return inst.f1 == valueAfterConstructor
+ && inst.fsub == subValueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class PublicConstructor implements java.io.Serializable {
+ int f1;
+
+ static int valueAfterConstructor = 5;
+
+ public PublicConstructor() {
+ f1 = valueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. Is is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof PublicConstructor))
+ return false;
+
+ PublicConstructor inst = (PublicConstructor) obj;
+ return inst.f1 == valueAfterConstructor;
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ private static class PublicConstructorSub extends NonSerPublicConstructor
+ implements java.io.Serializable {
+ int fsub;
+
+ static final int subValueAfterConstructor = 11;
+
+ public PublicConstructorSub() {
+ f1 = 7;
+ fsub = subValueAfterConstructor;
+ }
+
+ public boolean equals(Object obj) {
+ /*
+ * This method is not answering it the objs is equal. It is
+ * answering if the vars have the value that it have to have after
+ * dumping and loading
+ */
+
+ if (obj == null)
+ return false;
+ if (!(obj instanceof PublicConstructorSub))
+ return false;
+
+ PublicConstructorSub inst = (PublicConstructorSub) obj;
+ return inst.f1 == valueAfterConstructor
+ && inst.fsub == subValueAfterConstructor;
+ }
+ }
+
+ // Tests the behavior of ObjectOutputStream.PutField.write()
+ private static class WriteFieldsUsingPutFieldWrite implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("object1", Vector.class),
+ new ObjectStreamField("int1", Integer.TYPE) };
+
+ private static Vector v1 = new Vector<String>(Arrays.asList(new String[] {
+ "1st", "2nd" }));
+
+ private boolean passed = false;
+
+ public WriteFieldsUsingPutFieldWrite() {
+ super();
+ }
+
+ public boolean passed() {
+ return passed;
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ int int1 = in.readInt();
+ Vector object1 = (Vector) in.readObject();
+ passed = int1 == 0xA9 && object1.equals(v1);
+ }
+
+ @SuppressWarnings("deprecation")
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectOutputStream.PutField fields = out.putFields();
+ fields.put("object1", v1);
+ fields.put("int1", 0xA9);
+ // Use fields.write() instead of out.writeFields();
+ fields.write(out);
+ }
+ }
+
+ public SerializationStressTest3(String name) {
+ super(name);
+ }
+
+ public void test_18_81_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(out);
+ new ObjectOutputStream(dos); // just to make sure we get a header
+ dos.writeByte(ObjectStreamConstants.TC_BLOCKDATALONG);
+ int length = 333; // Bigger than 1 byte
+ dos.writeInt(length);
+ for (int i = 0; i < length; i++) {
+ dos.writeByte(0); // actual value does not matter
+ }
+ dos.flush();
+ int lengthRead = 0;
+ try {
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(out.toByteArray()));
+ Object obj = ois.readObject();
+ } catch (OptionalDataException e) {
+ lengthRead = e.length;
+ }
+ assertTrue("Did not throw exception with optional data size ",
+ length == lengthRead);
+ } catch (ClassNotFoundException e) {
+ fail("Unable to read BLOCKDATA : " + e.getMessage());
+ } catch (IOException e) {
+ fail("IOException testing BLOCKDATALONG : " + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error " + err + " when testing BLOCKDATALONG");
+ throw err;
+ }
+ }
+
+ public void test_18_82_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ DefaultConstructor test = new DefaultConstructor();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_83_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ DefaultConstructorSub test = new DefaultConstructorSub();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_84_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ PrivateConstructor test = new PrivateConstructor();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_85_writeObject() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ PrivateConstructorSub test = new PrivateConstructorSub();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ try {
+ objLoaded = dumpAndReload(objToSave);
+ fail();
+ } catch (Exception expected) {
+ // It is an error to mark a class serializable if it derives
+ // from a non serializable class with an inaccessible constructor.
+ }
+ }
+
+ public void test_18_86_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ProtectedConstructor test = new ProtectedConstructor();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_87_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ ProtectedConstructorSub test = new ProtectedConstructorSub();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_88_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ PublicConstructor test = new PublicConstructor();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_89_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ PublicConstructorSub test = new PublicConstructorSub();
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_90_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = TABLE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, TABLE.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_91_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedMap(TABLE);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_92_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableMap(TABLE);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_93_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = MAP;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, MAP.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_94_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedMap(MAP);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_95_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableMap(MAP);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_96_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = ALIST;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, ALIST.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_97_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = LIST;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, LIST.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_98_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedList(LIST);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_99_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableList(LIST);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_100_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = SET;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, SET.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_101_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedSet(SET);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_102_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableSet(SET);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_103_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = TREE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, TREE.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_104_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedSortedMap(TREE);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_105_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableSortedMap(TREE);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_106_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = SORTSET;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, SET.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_107_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.synchronizedSortedSet(SORTSET);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_108_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ Object col = Collections.unmodifiableSortedSet(SORTSET);
+ objToSave = col;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_109_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = CALENDAR;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, CALENDAR.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_110_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ TimeZone test = TimeZone.getTimeZone("EST");
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_111_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ TimeZone test = TimeZone.getTimeZone("EST");
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_112_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ TimeZone test = TimeZone.getTimeZone("GMT");
+ objToSave = test;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_113_writeObject() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ objToSave = DATEFORM;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertEquals(MSG_TEST_FAILED + objToSave, DATEFORM, objLoaded);
+ }
+
+ public void test_18_114_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = CHOICE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, CHOICE.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_115_writeObject() throws Exception {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ objToSave = NUMBERFORM;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertEquals(MSG_TEST_FAILED + objToSave, NUMBERFORM, objLoaded);
+ }
+
+ public void test_18_116_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = MESSAGE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, MESSAGE.toPattern().equals(
+ ((java.text.MessageFormat) objLoaded).toPattern()));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_119_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = Locale.CHINESE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, Locale.CHINESE
+ .equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_120_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = LINKEDLIST;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, LINKEDLIST
+ .equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_121_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = java.text.AttributedCharacterIterator.Attribute.INPUT_METHOD_SEGMENT;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(
+ MSG_TEST_FAILED + objToSave,
+ java.text.AttributedCharacterIterator.Attribute.INPUT_METHOD_SEGMENT == objLoaded);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_122_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = java.text.AttributedCharacterIterator.Attribute.LANGUAGE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(
+ MSG_TEST_FAILED + objToSave,
+ java.text.AttributedCharacterIterator.Attribute.LANGUAGE == objLoaded);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_123_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = java.text.AttributedCharacterIterator.Attribute.READING;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(
+ MSG_TEST_FAILED + objToSave,
+ java.text.AttributedCharacterIterator.Attribute.READING == objLoaded);
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_124_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = new Object[] { Integer.class, new Integer(1) };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Classes with the same name are unique, so test for ==
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((Object[]) objLoaded)[0] == ((Object[]) objToSave)[0]
+ && ((Object[]) objLoaded)[1]
+ .equals(((Object[]) objToSave)[1]));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_125_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = new BigInteger[] { BigInteger.ZERO, BigInteger.ONE,
+ BigInteger.valueOf(-1), BigInteger.valueOf(255),
+ BigInteger.valueOf(-255),
+ new BigInteger("75881644843307850793466070"),
+ new BigInteger("-636104487142732527326202462") };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (BigInteger[]) objLoaded, (BigInteger[]) objToSave));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_126_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = new WriteFieldsUsingPutFieldWrite();
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((WriteFieldsUsingPutFieldWrite) objLoaded).passed());
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_127_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ BitSet bs = new BitSet(64);
+ bs.set(1);
+ bs.set(10);
+ bs.set(100);
+ bs.set(1000);
+ objToSave = bs;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave, bs.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_18_128_writeObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ PropertyPermission test = new PropertyPermission("java.*",
+ "read,write");
+ PermissionCollection p = test.newPermissionCollection();
+ p.add(new PropertyPermission("java.*", "read"));
+ p.add(new PropertyPermission("java.*", "write"));
+ // System.out.println("Does implies work? " + p.implies(test));
+
+ objToSave = p;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(MSG_TEST_FAILED + objToSave,
+ ((PermissionCollection) objLoaded).implies(test));
+
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest4.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest4.java
new file mode 100644
index 0000000..c5dd4f0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationStressTest4.java
@@ -0,0 +1,1969 @@
+/*
+ * 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.tests.java.io;
+
+import tests.support.Support_Proxy_I1;
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.text.NumberFormat;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.Stack;
+import java.util.TimeZone;
+
+@SuppressWarnings({ "serial", "unused" })
+public class SerializationStressTest4 extends SerializationStressTest {
+ // -----------------------------------------------------------------------------------
+ private static class GuardImplementation implements java.security.Guard,
+ java.io.Serializable {
+ public GuardImplementation() {
+ }
+
+ public void checkGuard(Object o) {
+ }
+ }
+
+ public SerializationStressTest4(String name) {
+ super(name);
+ }
+
+ public void test_writeObject_EventObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.EventObject)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.EventObject("Source");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = true;
+ // The the only data in EventObject that
+ // differentiates between instantiations is transient
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_Collections_EmptySet() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptySet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.EMPTY_SET;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = objToSave.equals(objLoaded);
+ if (equals)
+ equals = ((Set) objLoaded).size() == 0;
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_EmptyMap() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptySet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.EMPTY_MAP;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = objToSave.equals(objLoaded);
+ if (equals)
+ equals = ((Map) objLoaded).size() == 0;
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Character() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Character)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Character('c');
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_UnmodifiableCollection() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.UnmodifiableCollection)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = Collections.unmodifiableCollection(SET);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((java.util.Collection) objToSave).size() == ((java.util.Collection) objLoaded)
+ .size();
+ if (equals) {
+ java.util.Iterator iter1 = ((java.util.Collection) objToSave)
+ .iterator(), iter2 = ((java.util.Collection) objLoaded)
+ .iterator();
+ while (iter1.hasNext())
+ equals = equals && iter1.next().equals(iter2.next());
+ }
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Format() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.Format)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new java.text.Format() {
+ String save = "default";
+
+ public StringBuffer format(Object p1, StringBuffer p2,
+ java.text.FieldPosition p3) {
+ return new StringBuffer();
+ }
+
+ public Object parseObject(String p1, java.text.ParsePosition p2) {
+ if (p1 != null)
+ save = p1;
+ return save;
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof java.text.Format))
+ return false;
+ return save.equals(((java.text.Format) obj).parseObject(
+ null, null));
+ }
+ };
+
+ ((java.text.Format) objToSave).parseObject("Test", null);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_BigDecimal() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.math.BigDecimal)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.math.BigDecimal("1.2345");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_SecureRandomSpi() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.security.SecureRandomSpi)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new java.security.SecureRandomSpi() {
+ protected byte[] engineGenerateSeed(int p1) {
+ return new byte[0];
+ }
+
+ protected void engineNextBytes(byte[] p1) {
+ }
+
+ protected void engineSetSeed(byte[] p1) {
+ }
+
+ public boolean equals(Object obj) {
+ return true;
+ }
+ };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_Short() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Short)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Short((short) 107);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Byte() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Byte)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Byte((byte) 107);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void test_writeObject_String_CaseInsensitiveComparator() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.String.CaseInsensitiveComparator)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.lang.String.CASE_INSENSITIVE_ORDER;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((Comparator) objToSave).compare("apple", "Banana") == ((Comparator) objLoaded)
+ .compare("apple", "Banana");
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Calendar() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Calendar)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.Calendar(TimeZone.getTimeZone("EST"),
+ Locale.CANADA) {
+ public void add(int p1, int p2) {
+ }
+
+ protected void computeFields() {
+ }
+
+ protected void computeTime() {
+ }
+
+ public int getGreatestMinimum(int p1) {
+ return 0;
+ }
+
+ public int getLeastMaximum(int p1) {
+ return 0;
+ }
+
+ public int getMaximum(int p1) {
+ return 0;
+ }
+
+ public int getMinimum(int p1) {
+ return 0;
+ }
+
+ public void roll(int p1, boolean p2) {
+ }
+ };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + "Calendar", objToSave
+ .equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_StringBuffer() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.StringBuffer)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.StringBuffer("This is a test.");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((java.lang.StringBuffer) objToSave).toString().equals(
+ ((java.lang.StringBuffer) objLoaded).toString());
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_File() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.io.File)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new File("afile.txt");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_BitSet() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.BitSet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.BitSet();
+ ((java.util.BitSet) objToSave).set(3);
+ ((java.util.BitSet) objToSave).set(5);
+ ((java.util.BitSet) objToSave).set(61, 89);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_DateFormat() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.DateFormat)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new java.text.DateFormat() {
+ // Thu Feb 01 01:01:01 EST 2001
+ java.util.Date save = new java.util.Date(981007261000L);
+
+ public StringBuffer format(Date p1, StringBuffer p2,
+ java.text.FieldPosition p3) {
+ if (p1 != null)
+ save = p1;
+ return new StringBuffer(Long.toString(save.getTime()));
+ }
+
+ public Date parse(String p1, java.text.ParsePosition p2) {
+ return save;
+ }
+
+ public String toString() {
+ return save.toString();
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof java.text.DateFormat))
+ return false;
+ return save.equals(((java.text.DateFormat) obj).parse(null,
+ null));
+ }
+ };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_CopiesList() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.CopiesList)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.nCopies(2, new Integer(2));
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((List) objToSave).get(0)
+ .equals(((List) objLoaded).get(0));
+ if (equals)
+ equals = ((List) objToSave).get(1).equals(
+ ((List) objLoaded).get(1));
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Properties() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Properties)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.Properties();
+ ((java.util.Properties) objToSave).put("key1", "value1");
+ ((java.util.Properties) objToSave).put("key2", "value2");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ Enumeration enum1 = ((java.util.Properties) objToSave).elements(), enum2 = ((java.util.Properties) objLoaded)
+ .elements();
+
+ equals = true;
+ while (enum1.hasMoreElements() && equals) {
+ if (enum2.hasMoreElements())
+ equals = enum1.nextElement().equals(enum2.nextElement());
+ else
+ equals = false;
+ }
+
+ if (equals)
+ equals = !enum2.hasMoreElements();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_NumberFormat() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.NumberFormat)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new java.text.NumberFormat() {
+ long save = 107;
+
+ public StringBuffer format(double p1, StringBuffer p2,
+ java.text.FieldPosition p3) {
+ return new StringBuffer();
+ }
+
+ public StringBuffer format(long p1, StringBuffer p2,
+ java.text.FieldPosition p3) {
+ if (p1 != 0)
+ save = p1;
+ return new StringBuffer(Long.toString(save));
+ }
+
+ public Number parse(String p1, java.text.ParsePosition p2) {
+ return new Long(save);
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof java.text.NumberFormat))
+ return false;
+ return save == ((Long) ((java.text.NumberFormat) obj)
+ .parse(null, null)).longValue();
+ }
+ };
+
+ ((java.text.NumberFormat) objToSave).format(63L, null, null);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_TimeZone() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.TimeZone)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new java.util.TimeZone() {
+ int save = 0;
+
+ public int getOffset(int p1, int p2, int p3, int p4, int p5,
+ int p6) {
+ return 0;
+ }
+
+ public int getRawOffset() {
+ return save;
+ }
+
+ public boolean inDaylightTime(java.util.Date p1) {
+ return false;
+ }
+
+ public void setRawOffset(int p1) {
+ save = p1;
+ }
+
+ public boolean useDaylightTime() {
+ return false;
+ }
+
+ public boolean equals(Object obj) {
+ if (obj instanceof TimeZone)
+ return save == ((TimeZone) obj).getRawOffset();
+ return false;
+ }
+ };
+
+ ((java.util.TimeZone) objToSave).setRawOffset(48);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Double() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Double)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Double(1.23);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Number() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Number)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = null;
+ objToSave = new Number() {
+ int numCalls = 0;
+
+ public double doubleValue() {
+ return ++numCalls;
+ }
+
+ public float floatValue() {
+ return ++numCalls;
+ }
+
+ public int intValue() {
+ return numCalls;
+ }
+
+ public long longValue() {
+ return ++numCalls;
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof java.lang.Number))
+ return false;
+ return intValue() == ((Number) obj).intValue();
+ }
+ };
+ ((java.lang.Number) objToSave).doubleValue();
+ ((java.lang.Number) objToSave).floatValue();
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_ReverseComparator() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.ReverseComparator)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.reverseOrder();
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((Comparator) objToSave).compare("Hello", "Jello") == ((Comparator) objLoaded)
+ .compare("Hello", "Jello");
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("IOException serializing " + objToSave + " : "
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type : "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_DateFormatSymbols() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.DateFormatSymbols)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.text.DateFormatSymbols(Locale.CHINESE);
+ ((java.text.DateFormatSymbols) objToSave)
+ .setZoneStrings(new String[][] { { "a", "b", "c", "d", "e" },
+ { "e", "f", "g", "h", "i" } });
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_EmptyList() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptyList)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.EMPTY_LIST;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = objToSave.equals(objLoaded);
+ if (equals)
+ equals = ((List) objLoaded).size() == 0;
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Boolean() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Boolean)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Boolean(true);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_SingletonSet() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.singleton(new Byte((byte) 107));
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ java.util.Iterator iter = ((Set) objLoaded).iterator();
+ equals = iter.hasNext();
+ if (equals)
+ equals = iter.next().equals(new Byte((byte) 107));
+ if (equals)
+ equals = !iter.hasNext();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_SingletonList() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections
+ .singletonList(new Byte((byte) 107));
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ java.util.Iterator iter = ((List) objLoaded).iterator();
+ equals = objLoaded.equals(objToSave) && iter.hasNext()
+ && iter.next().equals(new Byte((byte) 107))
+ && !iter.hasNext();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_SingletonMap() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.singletonMap("key", new Byte(
+ (byte) 107));
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ java.util.Iterator iter = ((Map) objLoaded).entrySet().iterator();
+ equals = objLoaded.equals(objToSave) && iter.hasNext();
+ Map.Entry entry = (Map.Entry) iter.next();
+ equals = equals && entry.getKey().equals("key")
+ && entry.getValue().equals(new Byte((byte) 107))
+ && !iter.hasNext();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_SecureRandom() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.security.SecureRandom)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.security.SecureRandom();
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = true; // assume fine because of the nature of the class,
+ // it is difficult to determine if they are the same
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_InetAddress() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.net.InetAddress)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.net.InetAddress.getByName("127.0.0.1");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Inet6Address() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.net.Inet6Address)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.net.Inet6Address.getByName("fe80::20d:60ff:fe24:7410");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Date() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Date)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ // Thu Feb 01 01:01:01 EST 2001
+ objToSave = new java.util.Date(981007261000L);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Float() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Float)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Float(1.23f);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Stack() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Stack)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.Stack();
+ ((Stack) objToSave).push("String 1");
+ ((Stack) objToSave).push("String 2");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = true;
+ while (!((java.util.Stack) objToSave).empty() && equals) {
+ if (!((java.util.Stack) objLoaded).empty())
+ equals = ((java.util.Stack) objToSave).pop().equals(
+ ((java.util.Stack) objLoaded).pop());
+ else
+ equals = false;
+ }
+
+ if (equals)
+ equals = ((java.util.Stack) objLoaded).empty();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_DecimalFormatSymbols() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.DecimalFormatSymbols)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.text.DecimalFormatSymbols(Locale.CHINESE);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_AttributedCharacterIterator_Attribute() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.AttributedCharacterIterator.Attribute)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.text.AttributedCharacterIterator.Attribute.LANGUAGE;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_Long() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Long)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.lang.Long(107L);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Collections_SynchronizedCollection() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Collections.SynchronizedCollection)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Collections.synchronizedCollection(SET);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((java.util.Collection) objToSave).size() == ((java.util.Collection) objLoaded)
+ .size();
+ if (equals) {
+ java.util.Iterator iter1 = ((java.util.Collection) objToSave)
+ .iterator(), iter2 = ((java.util.Collection) objLoaded)
+ .iterator();
+ while (iter1.hasNext())
+ equals = equals && iter1.next().equals(iter2.next());
+ }
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Random() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Random)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.util.Random(107L);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((java.util.Random) objToSave).nextInt() == ((java.util.Random) objLoaded)
+ .nextInt();
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_GuardedObject() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = new java.security.GuardedObject("Test Object",
+ new GuardImplementation());
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ boolean equals;
+ equals = ((java.security.GuardedObject) objToSave).getObject()
+ .equals(
+ ((java.security.GuardedObject) objLoaded)
+ .getObject());
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ // TODO : Reintroduce when we have a working security implementation
+ // public void test_writeObject_KeyPair() {
+ // // Test for method void
+ // // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
+ //
+ // Object objToSave = null;
+ // Object objLoaded = null;
+ //
+ // try {
+ // objToSave = new java.security.KeyPair(null, null);
+ // if (DEBUG)
+ // System.out.println("Obj = " + objToSave);
+ // objLoaded = dumpAndReload(objToSave);
+ //
+ // // Has to have worked
+ // boolean equals;
+ // equals = true;
+ // assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ // } catch (IOException e) {
+ // fail("IOException serializing " + objToSave + " : "
+ // + e.getMessage());
+ // } catch (ClassNotFoundException e) {
+ // fail("ClassNotFoundException reading Object type : " + e.getMessage());
+ // } catch (Error err) {
+ // System.out.println("Error when obj = " + objToSave);
+ // // err.printStackTrace();
+ // throw err;
+ // }
+ // }
+
+ static class MyInvocationHandler implements InvocationHandler, Serializable {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ if (method.getName().equals("equals"))
+ return new Boolean(proxy == args[0]);
+ if (method.getName().equals("array"))
+ return new int[] { (int) ((long[]) args[0])[1], -1 };
+ if (method.getName().equals("string")) {
+ if ("error".equals(args[0]))
+ throw new ArrayStoreException();
+ if ("any".equals(args[0]))
+ throw new IllegalAccessException();
+ }
+ return null;
+ }
+ }
+
+ public void test_writeObject_Proxy() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = Proxy.getProxyClass(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class });
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ assertTrue(MSG_TEST_FAILED + "not a proxy class", Proxy
+ .isProxyClass((Class) objLoaded));
+ Class[] interfaces = ((Class) objLoaded).getInterfaces();
+ assertTrue(MSG_TEST_FAILED + "wrong interfaces length",
+ interfaces.length == 1);
+ assertTrue(MSG_TEST_FAILED + "wrong interface",
+ interfaces[0] == Support_Proxy_I1.class);
+
+ InvocationHandler handler = new MyInvocationHandler();
+ objToSave = Proxy.newProxyInstance(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class },
+ handler);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ boolean equals = Proxy.getInvocationHandler(objLoaded).getClass() == MyInvocationHandler.class;
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_URI() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.net.URI)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ try {
+ objToSave = 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"),
+ // multiple arg constructors
+ new URI("http", "user%60%20info", "host", 80,
+ "/a%20path", "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"),
+ 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
+ };
+ } catch (URISyntaxException e) {
+ fail("Unexpected Exception:" + e);
+ }
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
+ (URI[]) objToSave, (URI[]) objLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_URISyntaxException() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.net.URISyntaxException)
+
+ URISyntaxException objToSave = null;
+ URISyntaxException objLoaded = null;
+
+ try {
+ objToSave = new URISyntaxException("str", "problem", 4);
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = (URISyntaxException) dumpAndReload(objToSave);
+
+ boolean equals = objToSave.getMessage().equals(
+ objLoaded.getMessage())
+ && objToSave.getInput().equals(objLoaded.getInput())
+ && objToSave.getIndex() == objLoaded.getIndex()
+ && objToSave.getReason().equals(objLoaded.getReason());
+
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, equals);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+
+ }
+
+ public void test_writeObject_Currency() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.util.Currency)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = java.util.Currency.getInstance("AMD");
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ // we need same instance for the same currency code
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave == objToSave);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_DateFormat_Field() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.DateFormat.Field)
+
+ DateFormat.Field[] objToSave = null;
+ DateFormat.Field[] objLoaded = null;
+
+ try {
+ objToSave = new DateFormat.Field[] { DateFormat.Field.AM_PM,
+ DateFormat.Field.DAY_OF_MONTH, DateFormat.Field.ERA,
+ DateFormat.Field.HOUR0, DateFormat.Field.HOUR1,
+ DateFormat.Field.HOUR_OF_DAY0,
+ DateFormat.Field.HOUR_OF_DAY1, DateFormat.Field.TIME_ZONE,
+ DateFormat.Field.YEAR,
+ DateFormat.Field.DAY_OF_WEEK_IN_MONTH };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+
+ objLoaded = (DateFormat.Field[]) dumpAndReload(objToSave);
+
+ // Has to have worked
+ // we need same instances for the same field names
+ for (int i = 0; i < objToSave.length; i++) {
+ assertTrue(MSG_TEST_FAILED + objToSave[i],
+ objToSave[i] == objLoaded[i]);
+ }
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_NumberFormat_Field() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.NumberFormat.Field)
+
+ NumberFormat.Field[] objToSave = null;
+ NumberFormat.Field[] objLoaded = null;
+
+ try {
+ objToSave = new NumberFormat.Field[] { NumberFormat.Field.CURRENCY,
+ NumberFormat.Field.DECIMAL_SEPARATOR,
+ NumberFormat.Field.EXPONENT,
+ NumberFormat.Field.EXPONENT_SIGN,
+ NumberFormat.Field.EXPONENT_SYMBOL,
+ NumberFormat.Field.FRACTION,
+ NumberFormat.Field.GROUPING_SEPARATOR,
+ NumberFormat.Field.INTEGER, NumberFormat.Field.PERCENT,
+ NumberFormat.Field.PERMILLE, NumberFormat.Field.SIGN };
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+
+ objLoaded = (NumberFormat.Field[]) dumpAndReload(objToSave);
+
+ // Has to have worked
+ // we need same instances for the same field names
+ for (int i = 0; i < objToSave.length; i++) {
+ assertTrue(MSG_TEST_FAILED + objToSave[i],
+ objToSave[i] == objLoaded[i]);
+ }
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_MessageFormat_Field() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.text.MessageFormat.Field)
+
+ Object objToSave = null;
+ Object objLoaded = null;
+
+ try {
+ objToSave = MessageFormat.Field.ARGUMENT;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+
+ objLoaded = dumpAndReload(objToSave);
+
+ // Has to have worked
+ // we need same instance for the same field name
+ assertTrue(MSG_TEST_FAILED + objToSave, objToSave == objLoaded);
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_LinkedHashMap() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = LINKEDMAP;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, LINKEDMAP.equals(objLoaded));
+
+ Map mapLoaded = (Map) objLoaded;
+ Iterator loadedIterator = mapLoaded.keySet().iterator();
+ Iterator iterator = LINKEDMAP.keySet().iterator();
+ while (loadedIterator.hasNext()) {
+ assertTrue("invalid iterator order", loadedIterator.next()
+ .equals(iterator.next()));
+ }
+ assertTrue("invalid iterator size", !iterator.hasNext());
+
+ loadedIterator = mapLoaded.entrySet().iterator();
+ iterator = LINKEDMAP.entrySet().iterator();
+ while (loadedIterator.hasNext()) {
+ assertTrue("invalid entry set iterator order", loadedIterator
+ .next().equals(iterator.next()));
+ }
+ assertTrue("invalid entry set iterator size", !iterator.hasNext());
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_LinkedHashSet() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ objToSave = LINKEDSET;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ // Has to have worked
+ assertTrue(MSG_TEST_FAILED + objToSave, LINKEDSET.equals(objLoaded));
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+
+ public void test_writeObject_IdentityHashMap() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ IdentityHashMap objToSave = null;
+ IdentityHashMap objLoaded;
+
+ try {
+ objToSave = IDENTITYMAP;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = (IdentityHashMap) dumpAndReload(objToSave);
+ // Has to have worked
+
+ // a serialized identity hash map will not be equal to its original
+ // because it is an "identity" mapping,
+ // so we simply check for the usual meaning of equality
+
+ assertEquals(
+ "Loaded IdentityHashMap is not of the same size as the saved one.",
+ objToSave.size(), objLoaded.size());
+ HashMap duplicateSaved = new HashMap();
+ duplicateSaved.putAll(objToSave);
+ HashMap duplicateLoaded = new HashMap();
+ duplicateLoaded.putAll(objLoaded);
+ assertTrue(MSG_TEST_FAILED + duplicateSaved, duplicateSaved
+ .equals(duplicateLoaded));
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + " : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("ClassNotFoundException reading Object type: "
+ + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ // err.printStackTrace();
+ throw err;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationTestClass.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationTestClass.java
new file mode 100644
index 0000000..e15a978
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SerializationTestClass.java
@@ -0,0 +1,337 @@
+package org.apache.harmony.tests.java.io;
+
+/**
+ * Test classes for {@link ComputeSerialVersionUIDTest}. Used to ensure
+ * that serial version UIDs are generated correctly for various combinations
+ * of interfaces, fields, constructors and methods.
+ */
+public class SerializationTestClass implements java.io.Serializable {
+
+ // Test class names
+ public static class TestClassName1 implements java.io.Serializable {
+ }
+
+ public static class TestClassName2T_T$T implements java.io.Serializable {
+ }
+
+ // Test Modifiers
+ public static class TestClassModifierPublic implements java.io.Serializable {
+ }
+
+ interface TestClassModifierInterfaceHelper extends java.io.Serializable {
+ }
+
+ public static class TestClassModifierInterface implements
+ TestClassModifierInterfaceHelper {
+ }
+
+ final static class TestClassModifierFinal implements java.io.Serializable {
+ }
+
+ abstract static class TestClassModifierAbstractHelper implements
+ java.io.Serializable {
+ }
+
+ public static class TestClassModifierAbstract extends
+ TestClassModifierAbstractHelper {
+ }
+
+
+ // TODO Arrays always are abstract
+
+ // TODO Non public interface has no abstract modifier
+
+
+ // Test interfaces
+ interface A extends java.io.Serializable {
+ }
+
+ interface B extends java.io.Serializable {
+ }
+
+ interface C extends A {
+ }
+
+ public static class TestInterfaces implements java.io.Serializable {
+ }
+
+ public static class TestInterfacesA implements A {
+ }
+
+ public static class TestInterfacesAB implements A, B {
+ }
+
+ public static class TestInterfacesBA implements B, A {
+ }
+
+ public static class TestInterfacesC implements C {
+ }
+
+ public static class TestInterfacesCA implements C, A {
+ }
+
+ public static class TestInterfacesABC implements A, B, C {
+ }
+
+ public static class TestInterfacesACB implements A, C, B {
+ }
+
+ public static class TestInterfacesBAC implements B, A, C {
+ }
+
+ public static class TestInterfacesBCA implements B, C, A {
+ }
+
+ public static class TestInterfacesCAB implements C, A, B {
+ }
+
+ public static class TestInterfacesCBA implements C, B, A {
+ }
+
+ /**
+ * Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC |
+ * Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT
+ */
+ // Test Fields
+ public static class TestFieldsNone implements java.io.Serializable {
+ }
+
+ public static class TestFieldsOnePublic implements java.io.Serializable {
+ public int one;
+ }
+
+ public static class TestFieldsTwoPublic implements java.io.Serializable {
+ public int one;
+ public int two;
+ }
+
+ @SuppressWarnings("unused")
+ public static class TestFieldsOnePrivate implements java.io.Serializable {
+ private int one;
+ }
+
+ @SuppressWarnings("unused")
+ public static class TestFieldsTwoPrivate implements java.io.Serializable {
+ private int one;
+ private int two;
+ }
+
+ public static class TestFieldsOneProtected implements java.io.Serializable {
+ protected int one;
+ }
+
+ public static class TestFieldsTwoProtected implements java.io.Serializable {
+ protected int one;
+ protected int two;
+ }
+
+ public static class TestFieldsOneStatic implements java.io.Serializable {
+ static int one;
+ }
+
+ public static class TestFieldsTwoStatic implements java.io.Serializable {
+ static int one;
+ static int two;
+ }
+
+ public static class TestFieldsOneFinal implements java.io.Serializable {
+ final int one = 0;
+ }
+
+ public static class TestFieldsTwoFinal implements java.io.Serializable {
+ final int one = 0;
+ final int two = 0;
+ }
+
+ public static class TestFieldsOneVolatile implements java.io.Serializable {
+ volatile int one;
+ }
+
+ public static class TestFieldsTwoVolatile implements java.io.Serializable {
+ volatile int one;
+ volatile int two;
+ }
+
+ public static class TestFieldsOneTransient implements java.io.Serializable {
+ transient int one;
+ }
+
+ public static class TestFieldsTwoTransient implements java.io.Serializable {
+ transient int one;
+ transient int two;
+ }
+
+ public static class TestFieldSignatures implements java.io.Serializable {
+ Object l;
+ int i;
+ short s;
+ long j;
+ boolean z;
+ char c;
+ double d;
+ float f;
+ byte b;
+ }
+
+
+ // Test Constructors
+ public static class TestConstructorNone implements java.io.Serializable {
+ }
+
+ public static class TestConstructorOne implements java.io.Serializable {
+ public TestConstructorOne() {
+ }
+ }
+
+ public static class TestConstructorTwo implements java.io.Serializable {
+ public TestConstructorTwo(byte b) {
+ }
+
+ public TestConstructorTwo(char c) {
+ }
+ }
+
+ public static class TestConstructorTwoReverse implements java.io.Serializable {
+ public TestConstructorTwoReverse(char c) {
+ }
+
+ public TestConstructorTwoReverse(byte b) {
+ }
+ }
+
+
+ // Test Constructor Modifiers
+ public static class TestConstructorPublic implements java.io.Serializable {
+ public TestConstructorPublic() {
+ }
+ }
+
+ public static class TestConstructorPrivate implements java.io.Serializable {
+ private TestConstructorPrivate() {
+ }
+
+ public TestConstructorPrivate(int i) {
+ this();
+ }
+ }
+
+ public static class TestConstructorProtected implements java.io.Serializable {
+ protected TestConstructorProtected() {
+ }
+ }
+ // TODO constructor modifier strict?
+ // TODO constructor modifier static?
+ // TODO constructor modifier final?
+ // TODO constructor modifier synchronized?
+ // TODO constructor modifier native?
+ // TODO constructor modifier abstract?
+
+
+ // Test constructor signature
+ public static class TestConstructorSignature implements java.io.Serializable {
+ public TestConstructorSignature(boolean z, byte b, char c, short s,
+ int i, float f, double j, Object l) {
+ }
+ }
+
+
+ // Test Method Modifiers
+ public static class TestMethodPublic implements java.io.Serializable {
+ public void method() {
+ }
+ }
+
+ @SuppressWarnings("unused")
+ public static class TestMethodPrivate implements java.io.Serializable {
+ private void method() {
+ }
+ }
+
+ public static class TestMethodProtected implements java.io.Serializable {
+ protected void method() {
+ }
+ }
+
+ public static class TestMethodStrict implements java.io.Serializable {
+ strictfp void method() {
+ }
+ }
+
+ public static class TestMethodStatic implements java.io.Serializable {
+ static void method() {
+ }
+ }
+
+ public static class TestMethodFinal implements java.io.Serializable {
+ final void method() {
+ }
+ }
+
+ public static class TestMethodSynchronized implements java.io.Serializable {
+ synchronized void method() {
+ }
+ }
+
+ public static class TestMethodNative implements java.io.Serializable {
+ native void method();
+ }
+
+ public static abstract class TestMethodAbstractHelper implements
+ java.io.Serializable {
+ abstract void method();
+ }
+
+ public static class TestMethodAbstract extends TestMethodAbstractHelper implements
+ java.io.Serializable {
+ @Override
+ void method() {
+ }
+ }
+
+
+ // Test method signature
+ public static class TestMethodSignature implements java.io.Serializable {
+ public void method(boolean z, byte b, char c, short s, int i, float f,
+ double j, Object l) {
+ }
+ }
+
+
+ // Test method return signature
+ public static class TestMethodReturnSignature implements java.io.Serializable {
+ public void methodV() {
+ }
+
+ public boolean methodZ() {
+ return false;
+ }
+
+ public byte methodB() {
+ return 0;
+ }
+
+ public char methodC() {
+ return '0';
+ }
+
+ public short methodS() {
+ return 0;
+ }
+
+ public int methodI() {
+ return 0;
+ }
+
+ public float methodF() {
+ return 0F;
+ }
+
+ public double methodD() {
+ return 0D;
+ }
+
+ public Object methodL() {
+ return null;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamCorruptedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamCorruptedExceptionTest.java
new file mode 100644
index 0000000..e9e6a70
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamCorruptedExceptionTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ObjectInputStream;
+import java.io.StreamCorruptedException;
+
+public class StreamCorruptedExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.StreamCorruptedException#StreamCorruptedException()
+ */
+ public void test_Constructor() throws Exception {
+ // Test for method java.io.StreamCorruptedException()
+
+ try {
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(
+ "kLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLl"
+ .getBytes()));
+ ois.readObject();
+ } catch (StreamCorruptedException e) {
+ // Correct
+ return;
+ }
+
+ fail("Failed to throw StreamCorruptedException for non serialized stream");
+ }
+
+ /**
+ * java.io.StreamCorruptedException#StreamCorruptedException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws Exception {
+ // Test for method java.io.StreamCorruptedException(java.lang.String)
+ try {
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(
+ "kLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLl"
+ .getBytes()));
+ ois.readObject();
+ } catch (StreamCorruptedException e) {
+ // Correct
+ return;
+ }
+
+ fail("Failed to throw StreamCorruptedException for non serialized stream");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamTokenizerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamTokenizerTest.java
new file mode 100644
index 0000000..f4d4401
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StreamTokenizerTest.java
@@ -0,0 +1,448 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.CharArrayReader;
+import java.io.IOException;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.Reader;
+import java.io.StreamTokenizer;
+import java.io.StringBufferInputStream;
+
+import tests.support.Support_StringReader;
+
+public class StreamTokenizerTest extends junit.framework.TestCase {
+ Support_StringReader r;
+
+ StreamTokenizer st;
+
+ String testString;
+
+ /**
+ * java.io.StreamTokenizer#StreamTokenizer(java.io.InputStream)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ st = new StreamTokenizer(new StringBufferInputStream(
+ "/comments\n d 8 'h'"));
+
+ assertEquals("the next token returned should be the letter d",
+ StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals("the next token returned should be the letter d",
+ "d", st.sval);
+
+ assertEquals("the next token returned should be the digit 8",
+ StreamTokenizer.TT_NUMBER, st.nextToken());
+ assertEquals("the next token returned should be the digit 8",
+ 8.0, st.nval);
+
+ assertEquals("the next token returned should be the quote character",
+ 39, st.nextToken());
+ assertEquals("the next token returned should be the quote character",
+ "h", st.sval);
+ }
+
+ /**
+ * java.io.StreamTokenizer#StreamTokenizer(java.io.Reader)
+ */
+ public void test_ConstructorLjava_io_Reader() throws IOException {
+ setTest("/testing\n d 8 'h' ");
+ assertEquals("the next token returned should be the letter d skipping the comments",
+ StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals("the next token returned should be the letter d",
+ "d", st.sval);
+
+ assertEquals("the next token returned should be the digit 8",
+ StreamTokenizer.TT_NUMBER, st.nextToken());
+ assertEquals("the next token returned should be the digit 8",
+ 8.0, st.nval);
+
+ assertEquals("the next token returned should be the quote character",
+ 39, st.nextToken());
+ assertEquals("the next token returned should be the quote character",
+ "h", st.sval);
+ }
+
+ /**
+ * java.io.StreamTokenizer#commentChar(int)
+ */
+ public void test_commentCharI() throws IOException {
+ setTest("*comment \n / 8 'h' ");
+ st.ordinaryChar('/');
+ st.commentChar('*');
+ assertEquals("nextToken() did not return the character / skiping the comments starting with *",
+ 47, st.nextToken());
+ assertTrue("the next token returned should be the digit 8", st
+ .nextToken() == StreamTokenizer.TT_NUMBER
+ && st.nval == 8.0);
+ assertTrue("the next token returned should be the quote character",
+ st.nextToken() == 39 && st.sval.equals("h"));
+ }
+
+ /**
+ * java.io.StreamTokenizer#eolIsSignificant(boolean)
+ */
+ public void test_eolIsSignificantZ() throws IOException {
+ setTest("d 8\n");
+ // by default end of line characters are not significant
+ assertTrue("nextToken did not return d",
+ st.nextToken() == StreamTokenizer.TT_WORD
+ && st.sval.equals("d"));
+ assertTrue("nextToken did not return 8",
+ st.nextToken() == StreamTokenizer.TT_NUMBER
+ && st.nval == 8.0);
+ assertTrue("nextToken should be the end of file",
+ st.nextToken() == StreamTokenizer.TT_EOF);
+ setTest("d\n");
+ st.eolIsSignificant(true);
+ // end of line characters are significant
+ assertTrue("nextToken did not return d",
+ st.nextToken() == StreamTokenizer.TT_WORD
+ && st.sval.equals("d"));
+ assertTrue("nextToken is the end of line",
+ st.nextToken() == StreamTokenizer.TT_EOL);
+ }
+
+ /**
+ * java.io.StreamTokenizer#lineno()
+ */
+ public void test_lineno() throws IOException {
+ setTest("d\n 8\n");
+ assertEquals("the lineno should be 1", 1, st.lineno());
+ st.nextToken();
+ st.nextToken();
+ assertEquals("the lineno should be 2", 2, st.lineno());
+ st.nextToken();
+ assertEquals("the next line no should be 3", 3, st.lineno());
+ }
+
+ /**
+ * java.io.StreamTokenizer#lowerCaseMode(boolean)
+ */
+ public void test_lowerCaseModeZ() throws Exception {
+ // SM.
+ setTest("HELLOWORLD");
+ st.lowerCaseMode(true);
+
+ st.nextToken();
+ assertEquals("sval not converted to lowercase.", "helloworld", st.sval
+ );
+ }
+
+ /**
+ * java.io.StreamTokenizer#nextToken()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_nextToken() throws IOException {
+ // SM.
+ setTest("\r\n/* fje fje 43.4 f \r\n f g */ 456.459 \r\n"
+ + "Hello / \r\n \r\n \n \r \257 Hi \'Hello World\'");
+ st.ordinaryChar('/');
+ st.slashStarComments(true);
+ st.nextToken();
+ assertTrue("Wrong Token type1: " + (char) st.ttype,
+ st.ttype == StreamTokenizer.TT_NUMBER);
+ st.nextToken();
+ assertTrue("Wrong Token type2: " + st.ttype,
+ st.ttype == StreamTokenizer.TT_WORD);
+ st.nextToken();
+ assertTrue("Wrong Token type3: " + st.ttype, st.ttype == '/');
+ st.nextToken();
+ assertTrue("Wrong Token type4: " + st.ttype,
+ st.ttype == StreamTokenizer.TT_WORD);
+ st.nextToken();
+ assertTrue("Wrong Token type5: " + st.ttype,
+ st.ttype == StreamTokenizer.TT_WORD);
+ st.nextToken();
+ assertTrue("Wrong Token type6: " + st.ttype, st.ttype == '\'');
+ assertTrue("Wrong Token type7: " + st.ttype, st.sval
+ .equals("Hello World"));
+ st.nextToken();
+ assertTrue("Wrong Token type8: " + st.ttype, st.ttype == -1);
+
+ final PipedInputStream pin = new PipedInputStream();
+ PipedOutputStream pout = new PipedOutputStream(pin);
+ pout.write("hello\n\r\r".getBytes("UTF-8"));
+ StreamTokenizer s = new StreamTokenizer(pin);
+ s.eolIsSignificant(true);
+ assertTrue("Wrong token 1,1",
+ s.nextToken() == StreamTokenizer.TT_WORD
+ && s.sval.equals("hello"));
+ assertTrue("Wrong token 1,2", s.nextToken() == '\n');
+ assertTrue("Wrong token 1,3", s.nextToken() == '\n');
+ assertTrue("Wrong token 1,4", s.nextToken() == '\n');
+ pout.close();
+ assertTrue("Wrong token 1,5",
+ s.nextToken() == StreamTokenizer.TT_EOF);
+ StreamTokenizer tokenizer = new StreamTokenizer(
+ new Support_StringReader("\n \r\n#"));
+ tokenizer.ordinaryChar('\n'); // make \n ordinary
+ tokenizer.eolIsSignificant(true);
+ assertTrue("Wrong token 2,1", tokenizer.nextToken() == '\n');
+ assertTrue("Wrong token 2,2", tokenizer.nextToken() == '\n');
+ assertEquals("Wrong token 2,3", '#', tokenizer.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#ordinaryChar(int)
+ */
+ public void test_ordinaryCharI() throws IOException {
+ // SM.
+ setTest("Ffjein 893");
+ st.ordinaryChar('F');
+ st.nextToken();
+ assertTrue("OrdinaryChar failed." + (char) st.ttype,
+ st.ttype == 'F');
+ }
+
+ /**
+ * java.io.StreamTokenizer#ordinaryChars(int, int)
+ */
+ public void test_ordinaryCharsII() throws IOException {
+ // SM.
+ setTest("azbc iof z 893");
+ st.ordinaryChars('a', 'z');
+ assertEquals("OrdinaryChars failed.", 'a', st.nextToken());
+ assertEquals("OrdinaryChars failed.", 'z', st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#parseNumbers()
+ */
+ public void test_parseNumbers() throws IOException {
+ // SM
+ setTest("9.9 678");
+ assertTrue("Base behavior failed.",
+ st.nextToken() == StreamTokenizer.TT_NUMBER);
+ st.ordinaryChars('0', '9');
+ assertEquals("setOrdinary failed.", '6', st.nextToken());
+ st.parseNumbers();
+ assertTrue("parseNumbers failed.",
+ st.nextToken() == StreamTokenizer.TT_NUMBER);
+ }
+
+ /**
+ * java.io.StreamTokenizer#pushBack()
+ */
+ public void test_pushBack() throws IOException {
+ // SM.
+ setTest("Hello 897");
+ st.nextToken();
+ st.pushBack();
+ assertTrue("PushBack failed.",
+ st.nextToken() == StreamTokenizer.TT_WORD);
+ }
+
+ /**
+ * java.io.StreamTokenizer#quoteChar(int)
+ */
+ public void test_quoteCharI() throws IOException {
+ // SM
+ setTest("<Hello World< HelloWorldH");
+ st.quoteChar('<');
+ assertEquals("QuoteChar failed.", '<', st.nextToken());
+ assertEquals("QuoteChar failed.", "Hello World", st.sval);
+ st.quoteChar('H');
+ st.nextToken();
+ assertEquals("QuoteChar failed for word.", "elloWorld", st.sval
+ );
+ }
+
+ /**
+ * java.io.StreamTokenizer#resetSyntax()
+ */
+ public void test_resetSyntax() throws IOException {
+ // SM
+ setTest("H 9\' ello World");
+ st.resetSyntax();
+ assertTrue("resetSyntax failed1." + (char) st.ttype,
+ st.nextToken() == 'H');
+ assertTrue("resetSyntax failed1." + (char) st.ttype,
+ st.nextToken() == ' ');
+ assertTrue("resetSyntax failed2." + (char) st.ttype,
+ st.nextToken() == '9');
+ assertTrue("resetSyntax failed3." + (char) st.ttype,
+ st.nextToken() == '\'');
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashSlashComments(boolean)
+ */
+ public void test_slashSlashCommentsZ() throws IOException {
+ // SM.
+ setTest("// foo \r\n /fiji \r\n -456");
+ st.ordinaryChar('/');
+ st.slashSlashComments(true);
+ assertEquals("Test failed.", '/', st.nextToken());
+ assertTrue("Test failed.",
+ st.nextToken() == StreamTokenizer.TT_WORD);
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashSlashComments(boolean)
+ */
+ public void test_slashSlashComments_withSSOpen() throws IOException {
+ Reader reader = new CharArrayReader("t // t t t".toCharArray());
+
+ StreamTokenizer st = new StreamTokenizer(reader);
+ st.slashSlashComments(true);
+
+ assertEquals(StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals(StreamTokenizer.TT_EOF, st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashSlashComments(boolean)
+ */
+ public void test_slashSlashComments_withSSOpen_NoComment() throws IOException {
+ Reader reader = new CharArrayReader("// t".toCharArray());
+
+ StreamTokenizer st = new StreamTokenizer(reader);
+ st.slashSlashComments(true);
+ st.ordinaryChar('/');
+
+ assertEquals(StreamTokenizer.TT_EOF, st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashSlashComments(boolean)
+ */
+ public void test_slashSlashComments_withSSClosed() throws IOException {
+ Reader reader = new CharArrayReader("// t".toCharArray());
+
+ StreamTokenizer st = new StreamTokenizer(reader);
+ st.slashSlashComments(false);
+ st.ordinaryChar('/');
+
+ assertEquals('/', st.nextToken());
+ assertEquals('/', st.nextToken());
+ assertEquals(StreamTokenizer.TT_WORD, st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashStarComments(boolean)
+ */
+ public void test_slashStarCommentsZ() throws IOException {
+ setTest("/* foo \r\n /fiji \r\n*/ -456");
+ st.ordinaryChar('/');
+ st.slashStarComments(true);
+ assertTrue("Test failed.",
+ st.nextToken() == StreamTokenizer.TT_NUMBER);
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashStarComments(boolean)
+ */
+ public void test_slashStarComments_withSTOpen() throws IOException {
+ Reader reader = new CharArrayReader("t /* t */ t".toCharArray());
+
+ StreamTokenizer st = new StreamTokenizer(reader);
+ st.slashStarComments(true);
+
+ assertEquals(StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals(StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals(StreamTokenizer.TT_EOF, st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#slashStarComments(boolean)
+ */
+ public void test_slashStarComments_withSTClosed() throws IOException {
+ Reader reader = new CharArrayReader("t /* t */ t".toCharArray());
+
+ StreamTokenizer st = new StreamTokenizer(reader);
+ st.slashStarComments(false);
+
+ assertEquals(StreamTokenizer.TT_WORD, st.nextToken());
+ assertEquals(StreamTokenizer.TT_EOF, st.nextToken());
+ }
+
+ /**
+ * java.io.StreamTokenizer#toString()
+ */
+ public void test_toString() throws IOException {
+ setTest("ABC Hello World");
+ st.nextToken();
+ assertTrue("toString failed." + st.toString(),
+ st.toString().equals(
+ "Token[ABC], line 1"));
+
+ // Regression test for HARMONY-4070
+ byte[] data = new byte[] { (byte) '-' };
+ StreamTokenizer tokenizer = new StreamTokenizer(
+ new ByteArrayInputStream(data));
+ tokenizer.nextToken();
+ String result = tokenizer.toString();
+ assertEquals("Token['-'], line 1", result);
+ }
+
+ /**
+ * java.io.StreamTokenizer#whitespaceChars(int, int)
+ */
+ public void test_whitespaceCharsII() throws IOException {
+ setTest("azbc iof z 893");
+ st.whitespaceChars('a', 'z');
+ assertTrue("OrdinaryChar failed.",
+ st.nextToken() == StreamTokenizer.TT_NUMBER);
+ }
+
+ /**
+ * java.io.StreamTokenizer#wordChars(int, int)
+ */
+ public void test_wordCharsII() throws IOException {
+ setTest("A893 -9B87");
+ st.wordChars('0', '9');
+ assertTrue("WordChar failed1.",
+ st.nextToken() == StreamTokenizer.TT_WORD);
+ assertEquals("WordChar failed2.", "A893", st.sval);
+ assertTrue("WordChar failed3.",
+ st.nextToken() == StreamTokenizer.TT_NUMBER);
+ st.nextToken();
+ assertEquals("WordChar failed4.", "B87", st.sval);
+
+ setTest(" Hello World");
+ st.wordChars(' ', ' ');
+ st.nextToken();
+ assertEquals("WordChars failed for whitespace.", "Hello World", st.sval
+ );
+
+ setTest(" Hello World\r\n \'Hello World\' Hello\' World");
+ st.wordChars(' ', ' ');
+ st.wordChars('\'', '\'');
+ st.nextToken();
+ assertTrue("WordChars failed for whitespace: " + st.sval, st.sval
+ .equals("Hello World"));
+ st.nextToken();
+ assertTrue("WordChars failed for quote1: " + st.sval, st.sval
+ .equals("\'Hello World\' Hello\' World"));
+ }
+
+ private void setTest(String s) {
+ testString = s;
+ r = new Support_StringReader(testString);
+ st = new StreamTokenizer(r);
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringBufferInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringBufferInputStreamTest.java
new file mode 100644
index 0000000..8ca4ca5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringBufferInputStreamTest.java
@@ -0,0 +1,99 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.StringBufferInputStream;
+import java.io.UnsupportedEncodingException;
+
+@SuppressWarnings("deprecation")
+public class StringBufferInputStreamTest extends junit.framework.TestCase {
+
+ StringBufferInputStream sbis;
+
+ /**
+ * java.io.StringBufferInputStream#StringBufferInputStream(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.io.StringBufferInputStream(java.lang.String)
+ }
+
+ /**
+ * java.io.StringBufferInputStream#available()
+ */
+ public void test_available() {
+ // Test for method int java.io.StringBufferInputStream.available()
+ assertEquals("Returned incorrect number of available bytes", 11, sbis
+ .available());
+ }
+
+ /**
+ * java.io.StringBufferInputStream#read()
+ */
+ public void test_read() throws UnsupportedEncodingException {
+ // Test for method int java.io.StringBufferInputStream.read()
+ byte[] buf = new byte[5];
+ sbis.skip(6);
+ sbis.read(buf, 0, 5);
+ assertEquals("Returned incorrect chars", "World", new String(buf, "UTF-8"));
+ }
+
+ /**
+ * java.io.StringBufferInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() {
+ // Test for method int java.io.StringBufferInputStream.read(byte [],
+ // int, int)
+ assertEquals("Read returned incorrect char", 'H', sbis.read());
+ }
+
+ /**
+ * java.io.StringBufferInputStream#reset()
+ */
+ public void test_reset() {
+ // Test for method void java.io.StringBufferInputStream.reset()
+ long s = sbis.skip(6);
+ assertEquals("Unable to skip correct umber of chars", 6, s);
+ sbis.reset();
+ assertEquals("Failed to reset", 'H', sbis.read());
+ }
+
+ /**
+ * java.io.StringBufferInputStream#skip(long)
+ */
+ public void test_skipJ() {
+ // Test for method long java.io.StringBufferInputStream.skip(long)
+ long s = sbis.skip(6);
+ assertEquals("Unable to skip correct umber of chars", 6, s);
+ assertEquals("Skip positioned at incorrect char", 'W', sbis.read());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ sbis = new StringBufferInputStream("Hello World");
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringReaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringReaderTest.java
new file mode 100644
index 0000000..4d44d98
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringReaderTest.java
@@ -0,0 +1,172 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.StringReader;
+
+public class StringReaderTest extends junit.framework.TestCase {
+
+ String testString = "This is a test string";
+
+ StringReader sr;
+
+ /**
+ * java.io.StringReader#StringReader(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.io.StringReader(java.lang.String)
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * java.io.StringReader#close()
+ */
+ public void test_close() throws Exception {
+ // Test for method void java.io.StringReader.close()
+ try {
+ sr = new StringReader(testString);
+ sr.close();
+ char[] buf = new char[10];
+ sr.read(buf, 0, 2);
+ fail("Close failed");
+ } catch (java.io.IOException e) {
+ return;
+ }
+ }
+
+ /**
+ * java.io.StringReader#mark(int)
+ */
+ public void test_markI() throws Exception {
+ // Test for method void java.io.StringReader.mark(int)
+ sr = new StringReader(testString);
+ sr.skip(5);
+ sr.mark(0);
+ sr.skip(5);
+ sr.reset();
+ char[] buf = new char[10];
+ sr.read(buf, 0, 2);
+ assertTrue("Failed to return to mark", new String(buf, 0, 2)
+ .equals(testString.substring(5, 7)));
+ }
+
+ /**
+ * java.io.StringReader#markSupported()
+ */
+ public void test_markSupported() {
+ // Test for method boolean java.io.StringReader.markSupported()
+
+ sr = new StringReader(testString);
+ assertTrue("markSupported returned false", sr.markSupported());
+ }
+
+ /**
+ * java.io.StringReader#read()
+ */
+ public void test_read() throws Exception {
+ // Test for method int java.io.StringReader.read()
+ sr = new StringReader(testString);
+ int r = sr.read();
+ assertEquals("Failed to read char", 'T', r);
+ sr = new StringReader(new String(new char[] { '\u8765' }));
+ assertTrue("Wrong double byte char", sr.read() == '\u8765');
+ }
+
+ /**
+ * java.io.StringReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws Exception {
+ // Test for method int java.io.StringReader.read(char [], int, int)
+ sr = new StringReader(testString);
+ char[] buf = new char[testString.length()];
+ int r = sr.read(buf, 0, testString.length());
+ assertTrue("Failed to read chars", r == testString.length());
+ assertTrue("Read chars incorrectly", new String(buf, 0, r)
+ .equals(testString));
+ }
+
+ /**
+ * java.io.StringReader#ready()
+ */
+ public void test_ready() throws Exception {
+ // Test for method boolean java.io.StringReader.ready()
+ sr = new StringReader(testString);
+ assertTrue("Steam not ready", sr.ready());
+ sr.close();
+ int r = 0;
+ try {
+ sr.ready();
+ } catch (IOException e) {
+ r = 1;
+ }
+ assertEquals("Expected IOException not thrown in read()", 1, r);
+ }
+
+ /**
+ * java.io.StringReader#reset()
+ */
+ public void test_reset() throws Exception {
+ // Test for method void java.io.StringReader.reset()
+ sr = new StringReader(testString);
+ sr.skip(5);
+ sr.mark(0);
+ sr.skip(5);
+ sr.reset();
+ char[] buf = new char[10];
+ sr.read(buf, 0, 2);
+ assertTrue("Failed to reset properly", new String(buf, 0, 2)
+ .equals(testString.substring(5, 7)));
+ }
+
+ /**
+ * java.io.StringReader#skip(long)
+ */
+ public void test_skipJ() throws Exception {
+ // Test for method long java.io.StringReader.skip(long)
+ sr = new StringReader(testString);
+ sr.skip(5);
+ char[] buf = new char[10];
+ sr.read(buf, 0, 2);
+ assertTrue("Failed to skip properly", new String(buf, 0, 2)
+ .equals(testString.substring(5, 7)));
+ }
+
+ // Regression test for HARMONY-5077
+ static boolean finish = false;
+
+ public void test_synchronization() {
+ String anything = "Hello world";
+ final StringReader sr = new StringReader(anything);
+ Thread other = new Thread(new Runnable() {
+ public void run() {
+ sr.close();
+ finish = true;
+ }
+
+ ;
+ });
+
+ synchronized (anything) {
+ other.start();
+ while (!finish) {
+ Thread.yield();
+ }
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringWriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringWriterTest.java
new file mode 100644
index 0000000..c3db539
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/StringWriterTest.java
@@ -0,0 +1,211 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.io;
+
+import java.io.IOException;
+import java.io.StringWriter;
+
+public class StringWriterTest extends junit.framework.TestCase {
+
+ StringWriter sw;
+
+ /**
+ * java.io.StringWriter#StringWriter()
+ */
+ public void test_Constructor() {
+ // Test for method java.io.StringWriter()
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * java.io.StringWriter#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.StringWriter.close()
+ try {
+ sw.close();
+ } catch (IOException e) {
+ fail("IOException closing StringWriter : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.StringWriter#flush()
+ */
+ public void test_flush() {
+ // Test for method void java.io.StringWriter.flush()
+ sw.flush();
+ sw.write('c');
+ assertEquals("Failed to flush char", "c", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#getBuffer()
+ */
+ public void test_getBuffer() {
+ // Test for method java.lang.StringBuffer
+ // java.io.StringWriter.getBuffer()
+
+ sw.write("This is a test string");
+ StringBuffer sb = sw.getBuffer();
+ assertEquals("Incorrect buffer returned",
+ "This is a test string", sb.toString());
+ }
+
+ /**
+ * java.io.StringWriter#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.io.StringWriter.toString()
+ sw.write("This is a test string");
+ assertEquals("Incorrect string returned",
+ "This is a test string", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#write(char[], int, int)
+ */
+ public void test_write$CII() {
+ // Test for method void java.io.StringWriter.write(char [], int, int)
+ char[] c = new char[1000];
+ "This is a test string".getChars(0, 21, c, 0);
+ sw.write(c, 0, 21);
+ assertEquals("Chars not written properly",
+ "This is a test string", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#write(char[], int, int)
+ * Regression for HARMONY-387
+ */
+ public void test_write$CII_2() {
+ StringWriter obj = null;
+ try {
+ obj = new StringWriter();
+ obj.write(new char[0], (int) 0, (int) -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.StringWriter#write(char[], int, int)
+ */
+ public void test_write$CII_3() {
+ StringWriter obj = null;
+ try {
+ obj = new StringWriter();
+ obj.write(new char[0], (int) -1, (int) 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.StringWriter#write(char[], int, int)
+ */
+ public void test_write$CII_4() {
+ StringWriter obj = null;
+ try {
+ obj = new StringWriter();
+ obj.write(new char[0], (int) -1, (int) -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * java.io.StringWriter#write(int)
+ */
+ public void test_writeI() {
+ // Test for method void java.io.StringWriter.write(int)
+ sw.write('c');
+ assertEquals("Char not written properly", "c", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#write(java.lang.String)
+ */
+ public void test_writeLjava_lang_String() {
+ // Test for method void java.io.StringWriter.write(java.lang.String)
+ sw.write("This is a test string");
+ assertEquals("String not written properly",
+ "This is a test string", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() {
+ // Test for method void java.io.StringWriter.write(java.lang.String,
+ // int, int)
+ sw.write("This is a test string", 2, 2);
+ assertEquals("String not written properly", "is", sw.toString());
+ }
+
+ /**
+ * java.io.StringWriter#append(char)
+ */
+ public void test_appendChar() throws IOException {
+ char testChar = ' ';
+ StringWriter stringWriter = new StringWriter(20);
+ stringWriter.append(testChar);
+ assertEquals(String.valueOf(testChar), stringWriter.toString());
+ stringWriter.close();
+ }
+
+ /**
+ * java.io.PrintWriter#append(CharSequence)
+ */
+ public void test_appendCharSequence() throws IOException {
+
+ String testString = "My Test String";
+ StringWriter stringWriter = new StringWriter(20);
+ stringWriter.append(testString);
+ assertEquals(String.valueOf(testString), stringWriter.toString());
+ stringWriter.close();
+ }
+
+ /**
+ * java.io.PrintWriter#append(CharSequence, int, int)
+ */
+ public void test_appendCharSequenceIntInt() throws IOException {
+ String testString = "My Test String";
+ StringWriter stringWriter = new StringWriter(20);
+ stringWriter.append(testString, 1, 3);
+ assertEquals(testString.substring(1, 3), stringWriter.toString());
+ stringWriter.close();
+
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+
+ sw = new StringWriter();
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SyncFailedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SyncFailedExceptionTest.java
new file mode 100644
index 0000000..d1772a3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/SyncFailedExceptionTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.SyncFailedException;
+
+public class SyncFailedExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.SyncFailedException#SyncFailedException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws Exception {
+ // Test for method java.io.SyncFailedException(java.lang.String)
+ File f = null;
+ try {
+ f = File.createTempFile("SyncFailedExceptionTest", "tst");
+ FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
+ FileDescriptor fd = fos.getFD();
+ fos.close();
+ fd.sync();
+ } catch (SyncFailedException e) {
+ f.delete();
+ return;
+ }
+
+ fail("Failed to generate expected Exception");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UTFDataFormatExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UTFDataFormatExceptionTest.java
new file mode 100644
index 0000000..cf5aa82
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UTFDataFormatExceptionTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.UTFDataFormatException;
+
+public class UTFDataFormatExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.UTFDataFormatException#UTFDataFormatException()
+ */
+ public void test_Constructor() {
+ // Test for method java.io.UTFDataFormatException()
+ try {
+ int stringBufferSize = 70000;
+ int loopCount = 66;
+ StringBuffer sb = new StringBuffer(stringBufferSize);
+ for (int i = 0; i < (loopCount); i++)
+ sb
+ .append("qwertyuiopasdfghjklzxcvbnmlkjhgfdsaqwertyuioplkjhgqwertyuiopasdfghjklzxcvbnmlkjhgfdsaqwertyuioplkjhg");
+ DataOutputStream dos = new DataOutputStream(
+ new ByteArrayOutputStream());
+ dos.writeUTF(sb.toString());
+ } catch (UTFDataFormatException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during Constructor test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.io.UTFDataFormatException#UTFDataFormatException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.io.UTFDataFormatException(java.lang.String)
+ try {
+ int stringBufferSize = 70000;
+ int loopCount = 66;
+ StringBuffer sb = new StringBuffer(stringBufferSize);
+ for (int i = 0; i < (loopCount); i++)
+ sb
+ .append("qwertyuiopasdfghjklzxcvbnmlkjhgfdsaqwertyuioplkjhgqwertyuiopasdfghjklzxcvbnmlkjhgfdsaqwertyuioplkjhg");
+ DataOutputStream dos = new DataOutputStream(
+ new ByteArrayOutputStream());
+ dos.writeUTF(sb.toString());
+ } catch (UTFDataFormatException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during Constructor test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UnsupportedEncodingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UnsupportedEncodingExceptionTest.java
new file mode 100644
index 0000000..82b2dfb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/UnsupportedEncodingExceptionTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+
+public class UnsupportedEncodingExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.UnsupportedEncodingException#UnsupportedEncodingException()
+ */
+ public void test_Constructor() {
+ // Test for method java.io.UnsupportedEncodingException()
+ try {
+ new OutputStreamWriter(new ByteArrayOutputStream(), "BogusEncoding");
+ } catch (UnsupportedEncodingException e) {
+ return;
+ }
+
+ fail("Failed to generate expected exception");
+ }
+
+ /**
+ * java.io.UnsupportedEncodingException#UnsupportedEncodingException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method
+ // java.io.UnsupportedEncodingException(java.lang.String)
+ try {
+ new OutputStreamWriter(new ByteArrayOutputStream(), "BogusEncoding");
+ } catch (UnsupportedEncodingException e) {
+ return;
+ }
+
+ fail("Failed to generate expected exception");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriteAbortedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriteAbortedExceptionTest.java
new file mode 100644
index 0000000..1c3f1e3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriteAbortedExceptionTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.tests.java.io;
+
+import java.io.WriteAbortedException;
+
+public class WriteAbortedExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.io.WriteAbortedException#WriteAbortedException(java.lang.String,
+ *java.lang.Exception)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_Exception() {
+ // Test for method java.io.WriteAbortedException(java.lang.String,
+ // java.lang.Exception)
+ try {
+ if (true)
+ throw new WriteAbortedException("HelloWorld",
+ new WriteAbortedException("ByeWorld", null));
+ } catch (WriteAbortedException e) {
+ return;
+ }
+ fail("Failed to generate expected Exception");
+ }
+
+ /**
+ * java.io.WriteAbortedException#getMessage()
+ */
+ public void test_getMessage() {
+ // Test for method java.lang.String
+ // java.io.WriteAbortedException.getMessage()
+ try {
+ if (true)
+ throw new WriteAbortedException("HelloWorld",
+ new WriteAbortedException("ByeWorld", null));
+ } catch (WriteAbortedException e) {
+ assertTrue("WriteAbortedException::getMessage() failed"
+ + e.getMessage(), e.getMessage().equals(
+ "HelloWorld; java.io.WriteAbortedException: ByeWorld"));
+ return;
+ }
+ fail("Failed to generate expected Exception");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTest.java
new file mode 100644
index 0000000..d4c33ea
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTest.java
@@ -0,0 +1,147 @@
+/* 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.tests.java.io;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import junit.framework.TestCase;
+
+public class WriterTest extends TestCase {
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+
+ }
+
+ /**
+ * 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();
+
+ }
+
+
+ /**
+ * java.io.Writer#write(String)
+ */
+ public void test_writeLjava_lang_String() throws IOException {
+ // Regression for HARMONY-51
+ Object lock = new Object();
+ Writer wr = new MockLockWriter(lock);
+ wr.write("Some string");
+ wr.close();
+ }
+
+ class MockLockWriter extends Writer {
+ final Object myLock;
+
+ MockLockWriter(Object lock) {
+ super(lock);
+ myLock = lock;
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ // do nothing
+ }
+
+ @Override
+ public synchronized void flush() throws IOException {
+ // do nothing
+ }
+
+ @Override
+ public void write(char[] arg0, int arg1, int arg2) throws IOException {
+ assertTrue(Thread.holdsLock(myLock));
+ }
+ }
+
+
+ class MockWriter extends Writer {
+ private char[] contents;
+
+ private int length;
+
+ private int offset;
+
+ MockWriter(int capacity) {
+ contents = new char[capacity];
+ length = capacity;
+ offset = 0;
+ }
+
+ public synchronized void close() throws IOException {
+ flush();
+ contents = null;
+ }
+
+ public synchronized void flush() throws IOException {
+ // do nothing
+ }
+
+ public void write(char[] buffer, int offset, int count)
+ throws IOException {
+ if (null == contents) {
+ throw new IOException();
+ }
+ if (offset < 0 || count < 0 || offset >= buffer.length) {
+ throw new IndexOutOfBoundsException();
+ }
+ count = Math.min(count, buffer.length - offset);
+ count = Math.min(count, this.length - this.offset);
+ for (int i = 0; i < count; i++) {
+ contents[this.offset + i] = buffer[offset + i];
+ }
+ this.offset += count;
+
+ }
+
+ public char[] getContents() {
+ char[] result = new char[offset];
+ for (int i = 0; i < offset; i++) {
+ result[i] = contents[i];
+ }
+ return result;
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTesterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTesterTest.java
new file mode 100644
index 0000000..0995638
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/io/WriterTesterTest.java
@@ -0,0 +1,213 @@
+/*
+ * 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.tests.java.io;
+
+import junit.framework.TestSuite;
+import org.apache.harmony.testframework.CharSinkTester;
+import org.apache.harmony.testframework.CharWrapperTester;
+import tests.support.Streams;
+
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.FilterWriter;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PipedReader;
+import java.io.PipedWriter;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * Tests basic {@link Writer} behaviors for the luni implementations of the type.
+ */
+public class WriterTesterTest {
+
+ // TODO: Rewrite this test so that id doesn't need a suite().
+ private static junit.framework.Test suite() {
+ TestSuite suite = new TestSuite();
+
+ // sink tests
+ suite.addTest(new FileWriterCharSinkTester(true).createTests());
+ suite.addTest(new FileWriterCharSinkTester(false).createTests());
+ suite.addTest(new CharArrayWriterCharSinkTester().setThrowsExceptions(false).createTests());
+ suite.addTest(new StringWriterCharSinkTester().setThrowsExceptions(false).createTests());
+ suite.addTest(new PipedWriterCharSinkTester().createTests());
+
+ // wrapper tests
+ suite.addTest(new BufferedWriterCharSinkTester(1).createTests());
+ suite.addTest(new BufferedWriterCharSinkTester(5).createTests());
+ suite.addTest(new BufferedWriterCharSinkTester(1024).createTests());
+ suite.addTest(new FilterWriterCharSinkTester().createTests());
+ suite.addTest(new PrintWriterCharSinkTester().setThrowsExceptions(false).createTests());
+ suite.addTest(new OutputStreamWriterCharSinkTester().createTests());
+
+ return suite;
+ }
+
+ private static class FileWriterCharSinkTester extends CharSinkTester {
+ private final boolean append;
+ private File file;
+
+ public FileWriterCharSinkTester(boolean append) {
+ this.append = append;
+ }
+
+ @Override
+ public Writer create() throws Exception {
+ file = File.createTempFile("FileOutputStreamSinkTester", "tmp");
+ file.deleteOnExit();
+ return new FileWriter(file, append);
+ }
+
+ @Override
+ public char[] getChars() throws Exception {
+ return Streams.streamToString(new FileReader(file)).toCharArray();
+ }
+ }
+
+ private static class CharArrayWriterCharSinkTester extends CharSinkTester {
+ private CharArrayWriter writer;
+
+ @Override
+ public Writer create() throws Exception {
+ writer = new CharArrayWriter();
+ return writer;
+ }
+
+ @Override
+ public char[] getChars() throws Exception {
+ return writer.toCharArray();
+ }
+ }
+
+ private static class PipedWriterCharSinkTester extends CharSinkTester {
+
+ private ExecutorService executor;
+ private Future<char[]> future;
+
+ public Writer create() throws IOException {
+ final PipedReader in = new PipedReader();
+ PipedWriter out = new PipedWriter(in);
+
+ executor = Executors.newSingleThreadExecutor();
+ future = executor.submit(new Callable<char[]>() {
+ final CharArrayWriter chars = new CharArrayWriter();
+
+ public char[] call() throws Exception {
+ char[] buffer = new char[256];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ chars.write(buffer, 0, count);
+ }
+ return chars.toCharArray();
+ }
+ });
+
+ return out;
+ }
+
+ @Override
+ public char[] getChars() throws Exception {
+ executor.shutdown();
+ return future.get();
+ }
+ }
+
+ private static class StringWriterCharSinkTester extends CharSinkTester {
+ private StringWriter writer;
+
+ @Override
+ public Writer create() throws Exception {
+ writer = new StringWriter();
+ return writer;
+ }
+
+ @Override
+ public char[] getChars() throws Exception {
+ return writer.toString().toCharArray();
+ }
+ }
+
+ private static class BufferedWriterCharSinkTester extends CharWrapperTester {
+ private final int bufferSize;
+
+ private BufferedWriterCharSinkTester(int bufferSize) {
+ this.bufferSize = bufferSize;
+ }
+
+ @Override
+ public Writer create(Writer delegate) throws Exception {
+ return new BufferedWriter(delegate, bufferSize);
+ }
+
+ @Override
+ public char[] decode(char[] delegateChars) throws Exception {
+ return delegateChars;
+ }
+ }
+
+ private static class FilterWriterCharSinkTester extends CharWrapperTester {
+ @Override
+ public Writer create(Writer delegate) throws Exception {
+ return new FilterWriter(delegate) {
+ };
+ }
+
+ @Override
+ public char[] decode(char[] delegateChars) throws Exception {
+ return delegateChars;
+ }
+ }
+
+ private static class PrintWriterCharSinkTester extends CharWrapperTester {
+ @Override
+ public Writer create(Writer delegate) throws Exception {
+ return new PrintWriter(delegate) {
+ };
+ }
+
+ @Override
+ public char[] decode(char[] delegateChars) throws Exception {
+ return delegateChars;
+ }
+ }
+
+ private static class OutputStreamWriterCharSinkTester extends CharSinkTester {
+ private ByteArrayOutputStream out;
+
+ @Override
+ public Writer create() throws Exception {
+ out = new ByteArrayOutputStream();
+ return new OutputStreamWriter(out, "UTF-8");
+ }
+
+ @Override
+ public char[] getChars() throws Exception {
+ return new String(out.toByteArray(), "UTF-8").toCharArray();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AbstractMethodErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AbstractMethodErrorTest.java
new file mode 100644
index 0000000..596792e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AbstractMethodErrorTest.java
@@ -0,0 +1,62 @@
+/*
+ * 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.tests.java.lang;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class AbstractMethodErrorTest extends junit.framework.TestCase {
+
+ /**
+ * {@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());
+ }
+
+ /**
+ * {@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());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new AbstractMethodError());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SerializationTest.verifyGolden(this, new AbstractMethodError());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArithmeticExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArithmeticExceptionTest.java
new file mode 100644
index 0000000..77e0671
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArithmeticExceptionTest.java
@@ -0,0 +1,41 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ArithmeticExceptionTest extends TestCase {
+
+ /**
+ * java.lang.ArithmeticException#ArithmeticException()
+ */
+ public void test_Constructor() {
+ ArithmeticException e = new ArithmeticException();
+ assertNull(e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.ArithmeticException#ArithmeticException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ ArithmeticException e = new ArithmeticException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
new file mode 100644
index 0000000..3561dd9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
+
+ /**
+ * java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(int)
+ */
+ public void test_ConstructorI() {
+ ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException(-1);
+ assertNotNull(e.getMessage());
+ assertTrue("Unable to find index value in 'message' property.", e.getMessage().indexOf(
+ "-1", 0) >= 0);
+
+ }
+
+ /**
+ * java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException()
+ */
+ public void test_Constructor() {
+ ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException();
+ assertNull(e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayStoreExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayStoreExceptionTest.java
new file mode 100644
index 0000000..0379769
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ArrayStoreExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ArrayStoreExceptionTest extends TestCase {
+
+ /**
+ * java.lang.ArrayStoreException#ArrayStoreException()
+ */
+ public void test_Constructor() {
+ ArrayStoreException e = new ArrayStoreException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.ArrayStoreException#ArrayStoreException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ ArrayStoreException e = new ArrayStoreException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AssertionErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AssertionErrorTest.java
new file mode 100644
index 0000000..8b6c80d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/AssertionErrorTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class AssertionErrorTest extends TestCase {
+
+ public void test_Constructor() {
+ AssertionError e = new AssertionError();
+ assertNull(e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorObject() {
+ Object obj = "toString";
+ AssertionError e = new AssertionError(obj);
+ assertEquals("toString", e.getMessage());
+ assertNull(e.getCause());
+
+ NullPointerException npe = new NullPointerException("null value");
+ e = new AssertionError(npe);
+ assertEquals(npe.toString(), e.getMessage());
+ assertSame(npe, e.getCause());
+ }
+
+ public void test_ConstructorBoolean() {
+ AssertionError e = new AssertionError(true);
+ assertEquals("true", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorChar() {
+ AssertionError e = new AssertionError('a');
+ assertEquals("a", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorInt() {
+ AssertionError e = new AssertionError(1);
+ assertEquals("1", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorLong() {
+ AssertionError e = new AssertionError(1L);
+ assertEquals("1", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorFloat() {
+ AssertionError e = new AssertionError(1.0F);
+ assertEquals("1.0", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ public void test_ConstructorDouble() {
+ AssertionError e = new AssertionError(1.0D);
+ assertEquals("1.0", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/BooleanTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/BooleanTest.java
new file mode 100644
index 0000000..a6dda7a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/BooleanTest.java
@@ -0,0 +1,157 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class BooleanTest extends TestCase {
+
+ /**
+ * java.lang.Boolean#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals(1231, Boolean.TRUE.hashCode());
+ assertEquals(1237, Boolean.FALSE.hashCode());
+ }
+
+ /**
+ * java.lang.Boolean#Boolean(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertEquals(Boolean.TRUE, new Boolean("TRUE"));
+ assertEquals(Boolean.TRUE, new Boolean("true"));
+ assertEquals(Boolean.TRUE, new Boolean("True"));
+
+ assertEquals(Boolean.FALSE, new Boolean("yes"));
+ assertEquals(Boolean.FALSE, new Boolean("false"));
+ }
+
+ /**
+ * java.lang.Boolean#Boolean(boolean)
+ */
+ public void test_ConstructorZ() {
+ assertEquals(Boolean.TRUE, new Boolean(true));
+ assertEquals(Boolean.FALSE, new Boolean(false));
+ }
+
+ /**
+ * java.lang.Boolean#booleanValue()
+ */
+ public void test_booleanValue() {
+ assertTrue(Boolean.TRUE.booleanValue());
+ assertFalse(Boolean.FALSE.booleanValue());
+ }
+
+ /**
+ * java.lang.Boolean#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertTrue(Boolean.TRUE.equals(Boolean.TRUE));
+ assertTrue(Boolean.TRUE.equals(new Boolean(true)));
+ assertFalse(Boolean.TRUE.equals("true"));
+ assertFalse(Boolean.TRUE.equals(null));
+ assertFalse(Boolean.FALSE.equals(Boolean.TRUE));
+ assertTrue(Boolean.FALSE.equals(Boolean.FALSE));
+ assertTrue(Boolean.FALSE.equals(new Boolean(false)));
+ }
+
+ /**
+ * java.lang.Boolean#getBoolean(String)
+ */
+ public void test_getBooleanLjava_lang_String() {
+ System.setProperty(getClass().getName(), "true");
+ assertTrue(Boolean.getBoolean(getClass().getName()));
+
+ System.setProperty(getClass().getName(), "TRUE");
+ assertTrue(Boolean.getBoolean(getClass().getName()));
+
+ System.setProperty(getClass().getName(), "false");
+ assertFalse(Boolean.getBoolean(getClass().getName()));
+ }
+
+ /**
+ * java.lang.Boolean#toString()
+ */
+ public void test_toString() {
+ assertEquals("true", Boolean.TRUE.toString());
+ assertEquals("false", Boolean.FALSE.toString());
+ }
+
+ /**
+ * java.lang.Boolean#toString(boolean)
+ */
+ public void test_toStringZ() {
+ assertEquals("true", Boolean.toString(true));
+ assertEquals("false", Boolean.toString(false));
+ }
+
+ /**
+ * java.lang.Boolean#valueOf(String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertEquals(Boolean.TRUE, Boolean.valueOf("true"));
+ assertEquals(Boolean.FALSE, Boolean.valueOf("false"));
+
+ assertEquals(Boolean.TRUE, Boolean.valueOf("TRUE"));
+ assertEquals(Boolean.FALSE, Boolean.valueOf("false"));
+
+ assertEquals(Boolean.FALSE, Boolean.valueOf(null));
+ assertEquals(Boolean.FALSE, Boolean.valueOf(""));
+ assertEquals(Boolean.FALSE, Boolean.valueOf("invalid"));
+
+ assertTrue("Failed to parse true to true", Boolean.valueOf("true").booleanValue());
+ assertTrue("Failed to parse mixed case true to true", Boolean.valueOf("TrUe")
+ .booleanValue());
+ assertTrue("parsed non-true to true", !Boolean.valueOf("ddddd").booleanValue());
+ }
+
+ /**
+ * java.lang.Boolean#valueOf(boolean)
+ */
+ public void test_valueOfZ() {
+ assertEquals(Boolean.TRUE, Boolean.valueOf(true));
+ assertEquals(Boolean.FALSE, Boolean.valueOf(false));
+ }
+
+ /**
+ * java.lang.Boolean#parseBoolean(String)
+ */
+ public void test_parseBooleanLjava_lang_String() {
+ assertTrue(Boolean.parseBoolean("true"));
+ assertTrue(Boolean.parseBoolean("TRUE"));
+ assertFalse(Boolean.parseBoolean("false"));
+ assertFalse(Boolean.parseBoolean(null));
+ assertFalse(Boolean.parseBoolean(""));
+ assertFalse(Boolean.parseBoolean("invalid"));
+ }
+
+ /**
+ * java.lang.Boolean#compareTo(Boolean)
+ */
+ public void test_compareToLjava_lang_Boolean() {
+ assertTrue(Boolean.TRUE.compareTo(Boolean.TRUE) == 0);
+ assertTrue(Boolean.FALSE.compareTo(Boolean.FALSE) == 0);
+ assertTrue(Boolean.TRUE.compareTo(Boolean.FALSE) > 0);
+ assertTrue(Boolean.FALSE.compareTo(Boolean.TRUE) < 0);
+
+ try {
+ Boolean.TRUE.compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ByteTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ByteTest.java
new file mode 100644
index 0000000..bbff653
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ByteTest.java
@@ -0,0 +1,672 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ByteTest extends TestCase {
+
+ /**
+ * java.lang.Byte#valueOf(byte)
+ */
+ 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));
+ assertEquals(new Byte((byte) 0), Byte.valueOf((byte) 0));
+
+ byte b = Byte.MIN_VALUE + 1;
+ while (b < Byte.MAX_VALUE) {
+ assertEquals(new Byte(b), Byte.valueOf(b));
+ assertSame(Byte.valueOf(b), Byte.valueOf(b));
+ b++;
+ }
+ }
+
+ /**
+ * java.lang.Byte#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals(1, new Byte((byte) 1).hashCode());
+ assertEquals(2, new Byte((byte) 2).hashCode());
+ assertEquals(0, new Byte((byte) 0).hashCode());
+ assertEquals(-1, new Byte((byte) -1).hashCode());
+ }
+
+ /**
+ * java.lang.Byte#Byte(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertEquals(new Byte((byte) 0), new Byte("0"));
+ assertEquals(new Byte((byte) 1), new Byte("1"));
+ assertEquals(new Byte((byte) -1), new Byte("-1"));
+
+ try {
+ new Byte("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Byte("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Byte("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Byte(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#Byte(byte)
+ */
+ public void test_ConstructorB() {
+ assertEquals(1, new Byte((byte) 1).byteValue());
+ assertEquals(2, new Byte((byte) 2).byteValue());
+ assertEquals(0, new Byte((byte) 0).byteValue());
+ assertEquals(-1, new Byte((byte) -1).byteValue());
+ }
+
+ /**
+ * java.lang.Byte#byteValue()
+ */
+ 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());
+ assertEquals(-1, new Byte((byte) -1).byteValue());
+ }
+
+ /**
+ * java.lang.Byte#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertEquals(new Byte((byte) 0), Byte.valueOf((byte) 0));
+ assertEquals(new Byte((byte) 1), Byte.valueOf((byte) 1));
+ assertEquals(new Byte((byte) -1), Byte.valueOf((byte) -1));
+
+ Byte fixture = new Byte((byte) 25);
+ assertEquals(fixture, fixture);
+ assertFalse(fixture.equals(null));
+ assertFalse(fixture.equals("Not a Byte"));
+ }
+
+ /**
+ * java.lang.Byte#toString()
+ */
+ public void test_toString() {
+ assertEquals("-1", new Byte((byte) -1).toString());
+ assertEquals("0", new Byte((byte) 0).toString());
+ assertEquals("1", new Byte((byte) 1).toString());
+ assertEquals("-1", new Byte((byte) 0xFF).toString());
+ }
+
+ /**
+ * java.lang.Byte#toString(byte)
+ */
+ public void test_toStringB() {
+ assertEquals("-1", Byte.toString((byte) -1));
+ assertEquals("0", Byte.toString((byte) 0));
+ assertEquals("1", Byte.toString((byte) 1));
+ assertEquals("-1", Byte.toString((byte) 0xFF));
+ }
+
+ /**
+ * java.lang.Byte#valueOf(String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertEquals(new Byte((byte) 0), Byte.valueOf("0"));
+ assertEquals(new Byte((byte) 1), Byte.valueOf("1"));
+ assertEquals(new Byte((byte) -1), Byte.valueOf("-1"));
+
+ try {
+ Byte.valueOf("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#valueOf(String, int)
+ */
+ public void test_valueOfLjava_lang_StringI() {
+ assertEquals(new Byte((byte) 0), Byte.valueOf("0", 10));
+ assertEquals(new Byte((byte) 1), Byte.valueOf("1", 10));
+ assertEquals(new Byte((byte) -1), Byte.valueOf("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Byte.valueOf("1", 2).byteValue());
+ assertEquals(Character.digit('F', 16), Byte.valueOf("F", 16).byteValue());
+
+ try {
+ Byte.valueOf("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.valueOf(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#parseByte(String)
+ */
+ public void test_parseByteLjava_lang_String() {
+ assertEquals(0, Byte.parseByte("0"));
+ assertEquals(1, Byte.parseByte("1"));
+ assertEquals(-1, Byte.parseByte("-1"));
+
+ try {
+ Byte.parseByte("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#parseByte(String, int)
+ */
+ public void test_parseByteLjava_lang_StringI() {
+ assertEquals(0, Byte.parseByte("0", 10));
+ assertEquals(1, Byte.parseByte("1", 10));
+ assertEquals(-1, Byte.parseByte("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Byte.parseByte("1", 2));
+ assertEquals(Character.digit('F', 16), Byte.parseByte("F", 16));
+
+ try {
+ Byte.parseByte("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#decode(String)
+ */
+ public void test_decodeLjava_lang_String() {
+ assertEquals(new Byte((byte) 0), Byte.decode("0"));
+ assertEquals(new Byte((byte) 1), Byte.decode("1"));
+ assertEquals(new Byte((byte) -1), Byte.decode("-1"));
+ assertEquals(new Byte((byte) 0xF), Byte.decode("0xF"));
+ assertEquals(new Byte((byte) 0xF), Byte.decode("#F"));
+ assertEquals(new Byte((byte) 0xF), Byte.decode("0XF"));
+ assertEquals(new Byte((byte) 07), Byte.decode("07"));
+
+ try {
+ Byte.decode("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.decode("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.decode(null);
+ //undocumented NPE, but seems consistent across JREs
+ fail("Expected NullPointerException with null string.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#doubleValue()
+ */
+ public void test_doubleValue() {
+ assertEquals(-1D, new Byte((byte) -1).doubleValue(), 0D);
+ assertEquals(0D, new Byte((byte) 0).doubleValue(), 0D);
+ assertEquals(1D, new Byte((byte) 1).doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Byte#floatValue()
+ */
+ public void test_floatValue() {
+ assertEquals(-1F, new Byte((byte) -1).floatValue(), 0F);
+ assertEquals(0F, new Byte((byte) 0).floatValue(), 0F);
+ assertEquals(1F, new Byte((byte) 1).floatValue(), 0F);
+ }
+
+ /**
+ * java.lang.Byte#intValue()
+ */
+ public void test_intValue() {
+ assertEquals(-1, new Byte((byte) -1).intValue());
+ assertEquals(0, new Byte((byte) 0).intValue());
+ assertEquals(1, new Byte((byte) 1).intValue());
+ }
+
+ /**
+ * java.lang.Byte#longValue()
+ */
+ public void test_longValue() {
+ assertEquals(-1L, new Byte((byte) -1).longValue());
+ assertEquals(0L, new Byte((byte) 0).longValue());
+ assertEquals(1L, new Byte((byte) 1).longValue());
+ }
+
+ /**
+ * java.lang.Byte#shortValue()
+ */
+ public void test_shortValue() {
+ assertEquals(-1, new Byte((byte) -1).shortValue());
+ assertEquals(0, new Byte((byte) 0).shortValue());
+ assertEquals(1, new Byte((byte) 1).shortValue());
+ }
+
+ /**
+ * java.lang.Byte#compareTo(Byte)
+ */
+ public void test_compareToLjava_lang_Byte() {
+ final Byte min = new Byte(Byte.MIN_VALUE);
+ final Byte zero = new Byte((byte) 0);
+ final Byte max = new Byte(Byte.MAX_VALUE);
+
+ assertTrue(max.compareTo(max) == 0);
+ assertTrue(min.compareTo(min) == 0);
+ assertTrue(zero.compareTo(zero) == 0);
+
+ assertTrue(max.compareTo(zero) > 0);
+ assertTrue(max.compareTo(min) > 0);
+
+ assertTrue(zero.compareTo(max) < 0);
+ assertTrue(zero.compareTo(min) > 0);
+
+ assertTrue(min.compareTo(zero) < 0);
+ assertTrue(min.compareTo(max) < 0);
+
+ try {
+ min.compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#Byte(byte)
+ */
+ public void test_ConstructorB2() {
+ // Test for method java.lang.Byte(byte)
+
+ Byte b = new Byte((byte) 127);
+ assertTrue("Byte creation failed", b.byteValue() == (byte) 127);
+ }
+
+ /**
+ * java.lang.Byte#Byte(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String2() {
+ // Test for method java.lang.Byte(java.lang.String)
+
+ Byte b = new Byte("127");
+ Byte nb = new Byte("-128");
+ assertTrue("Incorrect Byte Object created", b.byteValue() == (byte) 127
+ && (nb.byteValue() == (byte) -128));
+
+ }
+
+ /**
+ * java.lang.Byte#byteValue()
+ */
+ public void test_byteValue() {
+ // Test for method byte java.lang.Byte.byteValue()
+ assertTrue("Returned incorrect byte value",
+ new Byte((byte) 127).byteValue() == (byte) (127));
+ }
+
+ /**
+ * java.lang.Byte#compareTo(java.lang.Byte)
+ */
+ 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);
+ assertTrue("Comparison failed", new Byte((byte) 1).compareTo(new Byte((byte) -2)) > 0);
+ assertEquals("Comparison failed", 0, new Byte((byte) 1).compareTo(new Byte((byte) 1)));
+ }
+
+ /**
+ * java.lang.Byte#decode(java.lang.String)
+ */
+ public void test_decodeLjava_lang_String2() {
+ // Test for method java.lang.Byte
+ // java.lang.Byte.decode(java.lang.String)
+ assertTrue("String decoded incorrectly, wanted: 1 got: " + Byte.decode("1").toString(),
+ Byte.decode("1").equals(new Byte((byte) 1)));
+ assertTrue("String decoded incorrectly, wanted: -1 got: "
+ + Byte.decode("-1").toString(), Byte.decode("-1").equals(new Byte((byte) -1)));
+ assertTrue("String decoded incorrectly, wanted: 127 got: "
+ + Byte.decode("127").toString(), Byte.decode("127")
+ .equals(new Byte((byte) 127)));
+ assertTrue("String decoded incorrectly, wanted: -128 got: "
+ + Byte.decode("-128").toString(), Byte.decode("-128").equals(
+ new Byte((byte) -128)));
+ assertTrue("String decoded incorrectly, wanted: 127 got: "
+ + Byte.decode("0x7f").toString(), Byte.decode("0x7f").equals(
+ new Byte((byte) 127)));
+ assertTrue("String decoded incorrectly, wanted: -128 got: "
+ + Byte.decode("-0x80").toString(), Byte.decode("-0x80").equals(
+ new Byte((byte) -128)));
+
+ boolean exception = false;
+ try {
+ Byte.decode("128");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Byte.decode("-129");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Byte.decode("0x80");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Byte.decode("-0x81");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Byte#doubleValue()
+ */
+ public void test_doubleValue2() {
+ assertEquals(127D, new Byte((byte) 127).doubleValue(), 0.0);
+ }
+
+ /**
+ * java.lang.Byte#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object2() {
+ // Test for method boolean java.lang.Byte.equals(java.lang.Object)
+ Byte b1 = new Byte((byte) 90);
+ Byte b2 = new Byte((byte) 90);
+ Byte b3 = new Byte((byte) -90);
+ assertTrue("Equality test failed", b1.equals(b2));
+ assertTrue("Equality test failed", !b1.equals(b3));
+ }
+
+ /**
+ * java.lang.Byte#floatValue()
+ */
+ public void test_floatValue2() {
+ assertEquals(127F, new Byte((byte) 127).floatValue(), 0.0);
+ }
+
+ /**
+ * java.lang.Byte#hashCode()
+ */
+ public void test_hashCode2() {
+ // Test for method int java.lang.Byte.hashCode()
+ assertEquals("Incorrect hash returned", 127, new Byte((byte) 127).hashCode());
+ }
+
+ /**
+ * java.lang.Byte#intValue()
+ */
+ public void test_intValue2() {
+ // Test for method int java.lang.Byte.intValue()
+ assertEquals("Returned incorrect int value", 127, new Byte((byte) 127).intValue());
+ }
+
+ /**
+ * java.lang.Byte#longValue()
+ */
+ public void test_longValue2() {
+ // Test for method long java.lang.Byte.longValue()
+ assertEquals("Returned incorrect long value", 127L, new Byte((byte) 127).longValue());
+ }
+
+ /**
+ * java.lang.Byte#parseByte(java.lang.String)
+ */
+ public void test_parseByteLjava_lang_String2() {
+ assertEquals((byte) 127, Byte.parseByte("127"));
+ assertEquals((byte) -128, Byte.parseByte("-128"));
+ assertEquals((byte) 0, Byte.parseByte("0"));
+ assertEquals((byte) 0x80, Byte.parseByte("-128"));
+ assertEquals((byte) 0x7F, Byte.parseByte("127"));
+
+ try {
+ Byte.parseByte("-1000");
+ fail("No NumberFormatException");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("128");
+ fail("No NumberFormatException");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("-129");
+ fail("No NumberFormatException");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#parseByte(java.lang.String, int)
+ */
+ public void test_parseByteLjava_lang_StringI2() {
+ // Test for method byte java.lang.Byte.parseByte(java.lang.String, int)
+ byte b = Byte.parseByte("127", 10);
+ byte bn = Byte.parseByte("-128", 10);
+ assertTrue("Invalid parse of dec byte", b == (byte) 127 && (bn == (byte) -128));
+ assertEquals("Failed to parse hex value", 10, Byte.parseByte("A", 16));
+ assertEquals("Returned incorrect value for 0 hex", 0, Byte.parseByte("0", 16));
+ assertTrue("Returned incorrect value for most negative value hex", Byte.parseByte(
+ "-80", 16) == (byte) 0x80);
+ assertTrue("Returned incorrect value for most positive value hex", Byte.parseByte("7f",
+ 16) == 0x7f);
+ assertEquals("Returned incorrect value for 0 decimal", 0, Byte.parseByte("0", 10));
+ assertTrue("Returned incorrect value for most negative value decimal", Byte.parseByte(
+ "-128", 10) == (byte) 0x80);
+ assertTrue("Returned incorrect value for most positive value decimal", Byte.parseByte(
+ "127", 10) == 0x7f);
+
+ try {
+ Byte.parseByte("-1000", 10);
+ fail("Failed to throw exception");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("128", 10);
+ fail("Failed to throw exception for MAX_VALUE + 1");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("-129", 10);
+ fail("Failed to throw exception for MIN_VALUE - 1");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("80", 16);
+ fail("Failed to throw exception for hex MAX_VALUE + 1");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Byte.parseByte("-81", 16);
+ fail("Failed to throw exception for hex MIN_VALUE + 1");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#shortValue()
+ */
+ public void test_shortValue2() {
+ assertEquals((short) 127, new Byte((byte) 127).shortValue());
+ }
+
+ /**
+ * java.lang.Byte#toString()
+ */
+ public void test_toString2() {
+ assertEquals("Returned incorrect String", "127", new Byte((byte) 127).toString());
+ assertEquals("Returned incorrect String", "-127", new Byte((byte) -127).toString());
+ assertEquals("Returned incorrect String", "-128", new Byte((byte) -128).toString());
+ }
+
+ /**
+ * java.lang.Byte#toString(byte)
+ */
+ public void test_toStringB2() {
+ assertEquals("Returned incorrect String", "127", Byte.toString((byte) 127));
+ assertEquals("Returned incorrect String", "-127", Byte.toString((byte) -127));
+ assertEquals("Returned incorrect String", "-128", Byte.toString((byte) -128));
+ }
+
+ /**
+ * java.lang.Byte#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String2() {
+ assertEquals("Returned incorrect byte", 0, Byte.valueOf("0").byteValue());
+ assertEquals("Returned incorrect byte", 127, Byte.valueOf("127").byteValue());
+ assertEquals("Returned incorrect byte", -127, Byte.valueOf("-127").byteValue());
+ assertEquals("Returned incorrect byte", -128, Byte.valueOf("-128").byteValue());
+
+ try {
+ Byte.valueOf("128");
+ fail("Failed to throw exception when passes value > byte");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Byte#valueOf(java.lang.String, int)
+ */
+ 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());
+ assertEquals("Returned incorrect byte", -127, Byte.valueOf("-127", 10).byteValue());
+ assertEquals("Returned incorrect byte", -128, Byte.valueOf("-128", 10).byteValue());
+ assertEquals("Returned incorrect byte", 127, Byte.valueOf("7f", 16).byteValue());
+ assertEquals("Returned incorrect byte", -127, Byte.valueOf("-7f", 16).byteValue());
+ assertEquals("Returned incorrect byte", -128, Byte.valueOf("-80", 16).byteValue());
+
+ try {
+ Byte.valueOf("128", 10);
+ fail("Failed to throw exception when passes value > byte");
+ } catch (NumberFormatException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterImplTest.java
new file mode 100644
index 0000000..4db5b82
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterImplTest.java
@@ -0,0 +1,38 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class CharacterImplTest extends TestCase {
+
+ public void test_valueOfC() {
+ // test the cache range
+ for (char c = '\u0000'; c < 128; c++) {
+ Character e = new Character(c);
+ Character a = Character.valueOf(c);
+ assertEquals(e, a);
+
+ // WARN: this assertion may not be valid on other JREs
+ assertSame(Character.valueOf(c), Character.valueOf(c));
+ }
+ // test the rest of the chars
+ for (int c = 128; c <= Character.MAX_VALUE; c++) {
+ assertEquals(new Character((char) c), Character.valueOf((char) c));
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterTest.java
new file mode 100644
index 0000000..eaaae86
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CharacterTest.java
@@ -0,0 +1,1637 @@
+/* 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.tests.java.lang;
+
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+public class CharacterTest extends TestCase {
+
+ public void test_isValidCodePointI() {
+ assertFalse(Character.isValidCodePoint(-1));
+ assertTrue(Character.isValidCodePoint(0));
+ assertTrue(Character.isValidCodePoint(1));
+ assertFalse(Character.isValidCodePoint(Integer.MAX_VALUE));
+
+ for (int c = '\u0000'; c <= 0x10FFFF; c++) {
+ assertTrue(Character.isValidCodePoint(c));
+ }
+
+ assertFalse(Character.isValidCodePoint(0x10FFFF + 1));
+ }
+
+ public void test_isSupplementaryCodePointI() {
+ assertFalse(Character.isSupplementaryCodePoint(-1));
+
+ for (int c = '\u0000'; c <= '\uFFFF'; c++) {
+ assertFalse(Character.isSupplementaryCodePoint(c));
+ }
+
+ for (int c = 0xFFFF + 1; c <= 0x10FFFF; c++) {
+ assertTrue(Character.isSupplementaryCodePoint(c));
+ }
+
+ assertFalse(Character.isSupplementaryCodePoint(0x10FFFF + 1));
+ }
+
+ public void test_isHighSurrogateC() {
+ // (\uD800-\uDBFF)
+ assertFalse(Character.isHighSurrogate((char) ('\uD800' - 1)));
+ for (int c = '\uD800'; c <= '\uDBFF'; c++) {
+ assertTrue(Character.isHighSurrogate((char) c));
+ }
+ assertFalse(Character.isHighSurrogate((char) ('\uDBFF' + 1)));
+ assertFalse(Character.isHighSurrogate('\uFFFF'));
+ }
+
+ public void test_isLowSurrogateC() {
+ // (\uDC00-\uDFFF)
+ assertFalse(Character.isLowSurrogate((char) ('\uDC00' - 1)));
+ for (int c = '\uDC00'; c <= '\uDFFF'; c++) {
+ assertTrue(Character.isLowSurrogate((char) c));
+ }
+ assertFalse(Character.isLowSurrogate((char) ('\uDFFF' + 1)));
+ }
+
+ public void test_isSurrogatePairCC() {
+ assertFalse(Character.isSurrogatePair('\u0000', '\u0000'));
+ assertFalse(Character.isSurrogatePair('\u0000', '\uDC00'));
+
+ assertTrue(Character.isSurrogatePair('\uD800', '\uDC00'));
+ assertTrue(Character.isSurrogatePair('\uD800', '\uDFFF'));
+ assertTrue(Character.isSurrogatePair('\uDBFF', '\uDFFF'));
+
+ assertFalse(Character.isSurrogatePair('\uDBFF', '\uF000'));
+ }
+
+ public void test_charCountI() {
+ for (int c = '\u0000'; c <= '\uFFFF'; c++) {
+ assertEquals(1, Character.charCount(c));
+ }
+
+ for (int c = 0xFFFF + 1; c <= 0x10FFFF; c++) {
+ assertEquals(2, Character.charCount(c));
+ }
+
+ // invalid code points work in this method
+ assertEquals(2, Character.charCount(Integer.MAX_VALUE));
+ }
+
+ public void test_toCodePointCC() {
+ int result = Character.toCodePoint('\uD800', '\uDC00');
+ assertEquals(0x00010000, result);
+
+ result = Character.toCodePoint('\uD800', '\uDC01');
+ assertEquals(0x00010001, result);
+
+ result = Character.toCodePoint('\uD801', '\uDC01');
+ assertEquals(0x00010401, result);
+
+ result = Character.toCodePoint('\uDBFF', '\uDFFF');
+ assertEquals(0x00010FFFF, result);
+ }
+
+ @SuppressWarnings("cast")
+ public void test_codePointAtLjava_lang_CharSequenceI() {
+ assertEquals('a', Character.codePointAt("abc", 0));
+ assertEquals('b', Character.codePointAt("abc", 1));
+ assertEquals('c', Character.codePointAt("abc", 2));
+ assertEquals(0x10000, Character.codePointAt("\uD800\uDC00", 0));
+ assertEquals('\uDC00', Character.codePointAt("\uD800\uDC00", 1));
+
+ try {
+ Character.codePointAt((CharSequence) null, 0);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointAt("abc", -1);
+ fail("No IOOBE, negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointAt("abc", 4);
+ fail("No IOOBE, index too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointAt$CI() {
+ assertEquals('a', Character.codePointAt("abc".toCharArray(), 0));
+ assertEquals('b', Character.codePointAt("abc".toCharArray(), 1));
+ assertEquals('c', Character.codePointAt("abc".toCharArray(), 2));
+ assertEquals(0x10000, Character.codePointAt("\uD800\uDC00".toCharArray(), 0));
+ assertEquals('\uDC00', Character.codePointAt("\uD800\uDC00".toCharArray(), 1));
+
+ try {
+ Character.codePointAt((char[]) null, 0);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), -1);
+ fail("No IOOBE, negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), 4);
+ fail("No IOOBE, index too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointAt$CII() {
+ assertEquals('a', Character.codePointAt("abc".toCharArray(), 0, 3));
+ assertEquals('b', Character.codePointAt("abc".toCharArray(), 1, 3));
+ assertEquals('c', Character.codePointAt("abc".toCharArray(), 2, 3));
+ assertEquals(0x10000, Character.codePointAt("\uD800\uDC00".toCharArray(), 0, 2));
+ assertEquals('\uDC00', Character.codePointAt("\uD800\uDC00".toCharArray(), 1, 2));
+ assertEquals('\uD800', Character.codePointAt("\uD800\uDC00".toCharArray(), 0, 1));
+
+ try {
+ Character.codePointAt(null, 0, 1);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), -1, 3);
+ fail("No IOOBE, negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), 4, 3);
+ fail("No IOOBE, index too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), 2, 1);
+ fail("No IOOBE, index larger than limit.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointAt("abc".toCharArray(), 2, -1);
+ fail("No IOOBE, limit is negative.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ @SuppressWarnings("cast")
+ public void test_codePointBeforeLjava_lang_CharSequenceI() {
+ assertEquals('a', Character.codePointBefore("abc", 1));
+ assertEquals('b', Character.codePointBefore("abc", 2));
+ assertEquals('c', Character.codePointBefore("abc", 3));
+ assertEquals(0x10000, Character.codePointBefore("\uD800\uDC00", 2));
+ assertEquals('\uD800', Character.codePointBefore("\uD800\uDC00", 1));
+
+ try {
+ Character.codePointBefore((CharSequence) null, 0);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc", 0);
+ fail("No IOOBE, index below one.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc", 4);
+ fail("No IOOBE, index too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointBefore$CI() {
+ assertEquals('a', Character.codePointBefore("abc".toCharArray(), 1));
+ assertEquals('b', Character.codePointBefore("abc".toCharArray(), 2));
+ assertEquals('c', Character.codePointBefore("abc".toCharArray(), 3));
+ assertEquals(0x10000, Character.codePointBefore("\uD800\uDC00".toCharArray(), 2));
+ assertEquals('\uD800', Character.codePointBefore("\uD800\uDC00".toCharArray(), 1));
+
+ try {
+ Character.codePointBefore((char[]) null, 0);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), -1);
+ fail("No IOOBE, negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), 4);
+ fail("No IOOBE, index too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointBefore$CII() {
+ assertEquals('a', Character.codePointBefore("abc".toCharArray(), 1, 0));
+ assertEquals('b', Character.codePointBefore("abc".toCharArray(), 2, 0));
+ assertEquals('c', Character.codePointBefore("abc".toCharArray(), 3, 0));
+ assertEquals(0x10000, Character.codePointBefore("\uD800\uDC00".toCharArray(), 2, 0));
+ assertEquals('\uDC00', Character.codePointBefore("\uD800\uDC00".toCharArray(), 2, 1));
+ assertEquals('\uD800', Character.codePointBefore("\uD800\uDC00".toCharArray(), 1, 0));
+
+ try {
+ Character.codePointBefore(null, 1, 0);
+ fail("No NPE.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), 0, 1);
+ fail("No IOOBE, index less than start.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), 4, 0);
+ fail("No IOOBE, index larger than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), 2, -1);
+ fail("No IOOBE, start is negative.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointBefore("abc".toCharArray(), 2, 4);
+ fail("No IOOBE, start larger than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_toCharsI$CI() {
+ char[] dst = new char[2];
+ int result = Character.toChars(0x10000, dst, 0);
+ assertEquals(2, result);
+ assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC00' }, dst));
+
+ result = Character.toChars(0x10001, dst, 0);
+ assertEquals(2, result);
+ assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC01' }, dst));
+
+ result = Character.toChars(0x10401, dst, 0);
+ assertEquals(2, result);
+ assertTrue(Arrays.equals(new char[] { '\uD801', '\uDC01' }, dst));
+
+ result = Character.toChars(0x10FFFF, dst, 0);
+ assertEquals(2, result);
+ assertTrue(Arrays.equals(new char[] { '\uDBFF', '\uDFFF' }, dst));
+
+ try {
+ Character.toChars(Integer.MAX_VALUE, new char[2], 0);
+ fail("No IAE, invalid code point.");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ Character.toChars('a', null, 0);
+ fail("No NPE, null char[].");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.toChars('a', new char[1], -1);
+ fail("No IOOBE, negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.toChars('a', new char[1], 1);
+ fail("No IOOBE, index equal to length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_toCharsI() {
+ assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC00' }, Character.toChars(0x10000)));
+ assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC01' }, Character.toChars(0x10001)));
+ assertTrue(Arrays.equals(new char[] { '\uD801', '\uDC01' }, Character.toChars(0x10401)));
+ assertTrue(Arrays.equals(new char[] { '\uDBFF', '\uDFFF' }, Character.toChars(0x10FFFF)));
+
+ try {
+ Character.toChars(Integer.MAX_VALUE);
+ fail("No IAE, invalid code point.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ public void test_codePointCountLjava_lang_CharSequenceII() {
+ assertEquals(1, Character.codePointCount("\uD800\uDC00", 0, 2));
+ assertEquals(1, Character.codePointCount("\uD800\uDC01", 0, 2));
+ assertEquals(1, Character.codePointCount("\uD801\uDC01", 0, 2));
+ assertEquals(1, Character.codePointCount("\uDBFF\uDFFF", 0, 2));
+
+ assertEquals(3, Character.codePointCount("a\uD800\uDC00b", 0, 4));
+ assertEquals(4, Character.codePointCount("a\uD800\uDC00b\uD800", 0, 5));
+
+ try {
+ Character.codePointCount((CharSequence) null, 0, 1);
+ fail("No NPE, null char sequence.");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.codePointCount("abc", -1, 1);
+ fail("No IOOBE, negative start.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointCount("abc", 0, 4);
+ fail("No IOOBE, end greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.codePointCount("abc", 2, 1);
+ fail("No IOOBE, end greater than start.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_offsetByCodePointsLjava_lang_CharSequenceII() {
+ int result = Character.offsetByCodePoints("a\uD800\uDC00b", 0, 2);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("abcd", 3, -1);
+ assertEquals(2, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b", 0, 3);
+ assertEquals(4, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b", 3, -1);
+ assertEquals(1, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b", 3, 0);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("\uD800\uDC00bc", 3, 0);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("a\uDC00bc", 3, -1);
+ assertEquals(2, result);
+
+ result = Character.offsetByCodePoints("a\uD800bc", 3, -1);
+ assertEquals(2, result);
+
+ try {
+ Character.offsetByCodePoints(null, 0, 1);
+ fail();
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc", -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc", 4, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc", 1, 3);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc", 1, -2);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_offsetByCodePoints$CIIII() {
+ int result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(), 0, 4, 0, 2);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(), 0, 4, 0, 3);
+ assertEquals(4, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b\uD800c".toCharArray(), 0, 5, 0, 3);
+ assertEquals(4, result);
+
+ result = Character.offsetByCodePoints("abcd".toCharArray(), 0, 4, 3, -1);
+ assertEquals(2, result);
+
+ result = Character.offsetByCodePoints("abcd".toCharArray(), 1, 2, 3, -2);
+ assertEquals(1, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(), 0, 4, 3, -1);
+ assertEquals(1, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(), 0, 2, 2, -1);
+ assertEquals(1, result);
+
+ result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(), 0, 4, 3, 0);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("\uD800\uDC00bc".toCharArray(), 0, 4, 3, 0);
+ assertEquals(3, result);
+
+ result = Character.offsetByCodePoints("a\uDC00bc".toCharArray(), 0, 4, 3, -1);
+ assertEquals(2, result);
+
+ result = Character.offsetByCodePoints("a\uD800bc".toCharArray(), 0, 4, 3, -1);
+ assertEquals(2, result);
+
+ try {
+ Character.offsetByCodePoints(null, 0, 4, 1, 1);
+ fail();
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abcd".toCharArray(), -1, 4, 1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abcd".toCharArray(), 0, -1, 1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abcd".toCharArray(), 2, 4, 1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abcd".toCharArray(), 1, 3, 0, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abcd".toCharArray(), 1, 1, 3, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc".toCharArray(), 0, 3, 1, 3);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc".toCharArray(), 0, 2, 1, 2);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Character.offsetByCodePoints("abc".toCharArray(), 1, 3, 1, -2);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ /**
+ * java.lang.Character#compareTo(Character)
+ */
+ public void test_compareToLjava_lang_Byte() {
+ final Character min = new Character(Character.MIN_VALUE);
+ final Character mid = new Character((char) (Character.MAX_VALUE / 2));
+ final Character max = new Character(Character.MAX_VALUE);
+
+ assertTrue(max.compareTo(max) == 0);
+ assertTrue(min.compareTo(min) == 0);
+ assertTrue(mid.compareTo(mid) == 0);
+
+ assertTrue(max.compareTo(mid) > 0);
+ assertTrue(max.compareTo(min) > 0);
+
+ assertTrue(mid.compareTo(max) < 0);
+ assertTrue(mid.compareTo(min) > 0);
+
+ assertTrue(min.compareTo(mid) < 0);
+ assertTrue(min.compareTo(max) < 0);
+
+ try {
+ min.compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_codePointAt_Invalid() {
+ try {
+ Character.codePointAt(null, 6, 4);
+ fail("Expected IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ Character.codePointAt(null, 4, 6);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ Character.codePointAt(null, 0, 0);
+ fail("Expected IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.Character#Character(char)
+ */
+ public void test_ConstructorC() {
+ assertEquals("Constructor failed", 'T', new Character('T').charValue());
+ }
+
+ /**
+ * java.lang.Character#charValue()
+ */
+ public void test_charValue() {
+ assertEquals("Incorrect char value returned", 'T', new Character('T').charValue());
+ }
+
+ /**
+ * java.lang.Character#compareTo(java.lang.Character)
+ */
+ public void test_compareToLjava_lang_Character() {
+ Character c = new Character('c');
+ Character x = new Character('c');
+ Character y = new Character('b');
+ Character z = new Character('d');
+
+ assertEquals("Returned false for same Character", 0, c.compareTo(c));
+ assertEquals("Returned false for identical Character", 0, c.compareTo(x));
+ assertTrue("Returned other than less than for lesser char", c.compareTo(y) > 0);
+ assertTrue("Returned other than greater than for greater char", c.compareTo(z) < 0);
+ }
+
+ /**
+ * java.lang.Character#digit(char, int)
+ */
+ public void test_digitCI() {
+ assertEquals("Returned incorrect digit", 1, Character.digit('1', 10));
+ assertEquals("Returned incorrect digit", 15, Character.digit('F', 16));
+ }
+
+ /**
+ * java.lang.Character#digit(int, int)
+ */
+ public void test_digit_II() {
+ assertEquals(1, Character.digit((int) '1', 10));
+ assertEquals(15, Character.digit((int) 'F', 16));
+
+ assertEquals(-1, Character.digit(0x0000, 37));
+ assertEquals(-1, Character.digit(0x0045, 10));
+
+ assertEquals(10, Character.digit(0x0041, 20));
+ assertEquals(10, Character.digit(0x0061, 20));
+
+ assertEquals(-1, Character.digit(0x110000, 20));
+ }
+
+ /**
+ * java.lang.Character#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean java.lang.Character.equals(java.lang.Object)
+ assertTrue("Equality test failed", new Character('A').equals(new Character('A')));
+ assertFalse("Equality test failed", (new Character('A').equals(new Character('a'))));
+ }
+
+ /**
+ * java.lang.Character#forDigit(int, int)
+ */
+ public void test_forDigitII() {
+ char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+ 'a', 'b', 'c', 'd', 'e', 'f' };
+ for (int i = 0; i < hexChars.length; i++) {
+ assertTrue("Returned incorrect char for " + Integer.toString(i),
+ Character.forDigit(i, hexChars.length) == hexChars[i]);
+ }
+
+ char decimalChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
+ for (int i = 0; i < decimalChars.length; i++) {
+ assertTrue(
+ "Returned incorrect char for " + Integer.toString(i),
+ Character.forDigit(i, decimalChars.length) == decimalChars[i]);
+ }
+
+ }
+
+ /**
+ * java.lang.Character#getNumericValue(char)
+ */
+ public void test_getNumericValueC() {
+ assertEquals("Returned incorrect numeric value 1", 1, Character.getNumericValue('1'));
+ assertEquals("Returned incorrect numeric value 2", 15, Character.getNumericValue('F'));
+ assertEquals("Returned incorrect numeric value 3", -1, Character.getNumericValue('\u221e'));
+ assertEquals("Returned incorrect numeric value 4", -2, Character.getNumericValue('\u00be'));
+ assertEquals("Returned incorrect numeric value 5", 10000,
+ Character.getNumericValue('\u2182'));
+ assertEquals("Returned incorrect numeric value 6", 2, Character.getNumericValue('\uff12'));
+ }
+
+ /**
+ * java.lang.Character#getNumericValue(int)
+ */
+ public void test_getNumericValue_I() {
+ assertEquals(1, Character.getNumericValue((int) '1'));
+ assertEquals(15, Character.getNumericValue((int) 'F'));
+ assertEquals(-1, Character.getNumericValue((int) '\u221e'));
+ assertEquals(-2, Character.getNumericValue((int) '\u00be'));
+ assertEquals(10000, Character.getNumericValue((int) '\u2182'));
+ assertEquals(2, Character.getNumericValue((int) '\uff12'));
+ assertEquals(-1, Character.getNumericValue(0xFFFF));
+
+ assertEquals(-1, Character.getNumericValue(0xFFFF));
+ assertEquals(0, Character.getNumericValue(0x1D7CE));
+ assertEquals(0, Character.getNumericValue(0x1D7D8));
+ assertEquals(-1, Character.getNumericValue(0x2F800));
+ assertEquals(-1, Character.getNumericValue(0x10FFFD));
+ assertEquals(-1, Character.getNumericValue(0x110000));
+
+ assertEquals(50, Character.getNumericValue(0x216C));
+
+ assertEquals(10, Character.getNumericValue(0x0041));
+ assertEquals(35, Character.getNumericValue(0x005A));
+ assertEquals(10, Character.getNumericValue(0x0061));
+ assertEquals(35, Character.getNumericValue(0x007A));
+ assertEquals(10, Character.getNumericValue(0xFF21));
+ assertEquals(35, Character.getNumericValue(0xFF3A));
+
+ assertEquals(10, Character.getNumericValue(0xFF41));
+ assertEquals(35, Character.getNumericValue(0xFF5A));
+ }
+
+ /**
+ * java.lang.Character#getType(char)
+ */
+ public void test_getTypeC() {
+ assertTrue("Returned incorrect type for: \n",
+ Character.getType('\n') == Character.CONTROL);
+ assertTrue("Returned incorrect type for: 1",
+ Character.getType('1') == Character.DECIMAL_DIGIT_NUMBER);
+ assertTrue("Returned incorrect type for: ' '",
+ Character.getType(' ') == Character.SPACE_SEPARATOR);
+ assertTrue("Returned incorrect type for: a",
+ Character.getType('a') == Character.LOWERCASE_LETTER);
+ assertTrue("Returned incorrect type for: A",
+ Character.getType('A') == Character.UPPERCASE_LETTER);
+ assertTrue("Returned incorrect type for: <",
+ Character.getType('<') == Character.MATH_SYMBOL);
+ assertTrue("Returned incorrect type for: ;",
+ Character.getType(';') == Character.OTHER_PUNCTUATION);
+ assertTrue("Returned incorrect type for: _",
+ Character.getType('_') == Character.CONNECTOR_PUNCTUATION);
+ assertTrue("Returned incorrect type for: $",
+ Character.getType('$') == Character.CURRENCY_SYMBOL);
+ assertTrue("Returned incorrect type for: \u2029",
+ Character.getType('\u2029') == Character.PARAGRAPH_SEPARATOR);
+
+ assertEquals("Wrong constant for FORMAT", 16, Character.FORMAT);
+ assertEquals("Wrong constant for PRIVATE_USE", 18, Character.PRIVATE_USE);
+ }
+
+ /**
+ * java.lang.Character#getType(int)
+ */
+ public void test_getType_I() {
+ assertTrue(Character.getType((int) '\n') == Character.CONTROL);
+ assertTrue(Character.getType((int) '1') == Character.DECIMAL_DIGIT_NUMBER);
+ assertTrue(Character.getType((int) ' ') == Character.SPACE_SEPARATOR);
+ assertTrue(Character.getType((int) 'a') == Character.LOWERCASE_LETTER);
+ assertTrue(Character.getType((int) 'A') == Character.UPPERCASE_LETTER);
+ assertTrue(Character.getType((int) '<') == Character.MATH_SYMBOL);
+ assertTrue(Character.getType((int) ';') == Character.OTHER_PUNCTUATION);
+ assertTrue(Character.getType((int) '_') == Character.CONNECTOR_PUNCTUATION);
+ assertTrue(Character.getType((int) '$') == Character.CURRENCY_SYMBOL);
+ assertTrue(Character.getType((int) '\u2029') == Character.PARAGRAPH_SEPARATOR);
+
+ assertTrue(Character.getType(0x9FFF) == Character.UNASSIGNED);
+ assertTrue(Character.getType(0x30000) == Character.UNASSIGNED);
+ assertTrue(Character.getType(0x110000) == Character.UNASSIGNED);
+
+ assertTrue(Character.getType(0x0041) == Character.UPPERCASE_LETTER);
+ assertTrue(Character.getType(0x10400) == Character.UPPERCASE_LETTER);
+
+ assertTrue(Character.getType(0x0061) == Character.LOWERCASE_LETTER);
+ assertTrue(Character.getType(0x10428) == Character.LOWERCASE_LETTER);
+
+ assertTrue(Character.getType(0x01C5) == Character.TITLECASE_LETTER);
+ assertTrue(Character.getType(0x1FFC) == Character.TITLECASE_LETTER);
+
+ assertTrue(Character.getType(0x02B0) == Character.MODIFIER_LETTER);
+ assertTrue(Character.getType(0xFF9F) == Character.MODIFIER_LETTER);
+
+ assertTrue(Character.getType(0x01BB) == Character.OTHER_LETTER);
+ assertTrue(Character.getType(0x2F888) == Character.OTHER_LETTER);
+
+ assertTrue(Character.getType(0x0F82) == Character.NON_SPACING_MARK);
+ assertTrue(Character.getType(0x1D180) == Character.NON_SPACING_MARK);
+
+ assertTrue(Character.getType(0x0488) == Character.ENCLOSING_MARK);
+ assertTrue(Character.getType(0x20DE) == Character.ENCLOSING_MARK);
+
+ assertTrue(Character.getType(0x1938) == Character.COMBINING_SPACING_MARK);
+ assertTrue(Character.getType(0x1D165) == Character.COMBINING_SPACING_MARK);
+
+ assertTrue(Character.getType(0x194D) == Character.DECIMAL_DIGIT_NUMBER);
+ assertTrue(Character.getType(0x1D7CE) == Character.DECIMAL_DIGIT_NUMBER);
+
+ assertTrue(Character.getType(0x2160) == Character.LETTER_NUMBER);
+ assertTrue(Character.getType(0x1034A) == Character.LETTER_NUMBER);
+
+ assertTrue(Character.getType(0x00B2) == Character.OTHER_NUMBER);
+ assertTrue(Character.getType(0x10120) == Character.OTHER_NUMBER);
+
+ assertTrue(Character.getType(0x0020) == Character.SPACE_SEPARATOR);
+ assertTrue(Character.getType(0x3000) == Character.SPACE_SEPARATOR);
+
+ assertTrue(Character.getType(0x2028) == Character.LINE_SEPARATOR);
+
+ assertTrue(Character.getType(0x2029) == Character.PARAGRAPH_SEPARATOR);
+
+ assertTrue(Character.getType(0x0000) == Character.CONTROL);
+ assertTrue(Character.getType(0x009F) == Character.CONTROL);
+
+ assertTrue(Character.getType(0x00AD) == Character.FORMAT);
+ assertTrue(Character.getType(0xE007F) == Character.FORMAT);
+
+ assertTrue(Character.getType(0xE000) == Character.PRIVATE_USE);
+ assertTrue(Character.getType(0x10FFFD) == Character.PRIVATE_USE);
+
+ assertTrue(Character.getType(0xD800) == Character.SURROGATE);
+ assertTrue(Character.getType(0xDFFF) == Character.SURROGATE);
+
+ assertTrue(Character.getType(0xFE31) == Character.DASH_PUNCTUATION);
+ assertTrue(Character.getType(0xFF0D) == Character.DASH_PUNCTUATION);
+
+ assertTrue(Character.getType(0x0028) == Character.START_PUNCTUATION);
+ assertTrue(Character.getType(0xFF62) == Character.START_PUNCTUATION);
+
+ assertTrue(Character.getType(0x0029) == Character.END_PUNCTUATION);
+ assertTrue(Character.getType(0xFF63) == Character.END_PUNCTUATION);
+
+ assertTrue(Character.getType(0x005F) == Character.CONNECTOR_PUNCTUATION);
+ assertTrue(Character.getType(0xFF3F) == Character.CONNECTOR_PUNCTUATION);
+
+ assertTrue(Character.getType(0x2034) == Character.OTHER_PUNCTUATION);
+ assertTrue(Character.getType(0x1039F) == Character.OTHER_PUNCTUATION);
+
+ assertTrue(Character.getType(0x002B) == Character.MATH_SYMBOL);
+ assertTrue(Character.getType(0x1D6C1) == Character.MATH_SYMBOL);
+
+ assertTrue(Character.getType(0x0024) == Character.CURRENCY_SYMBOL);
+ assertTrue(Character.getType(0xFFE6) == Character.CURRENCY_SYMBOL);
+
+ assertTrue(Character.getType(0x005E) == Character.MODIFIER_SYMBOL);
+ assertTrue(Character.getType(0xFFE3) == Character.MODIFIER_SYMBOL);
+
+ assertTrue(Character.getType(0x00A6) == Character.OTHER_SYMBOL);
+ assertTrue(Character.getType(0x1D356) == Character.OTHER_SYMBOL);
+
+ assertTrue(Character.getType(0x00AB) == Character.INITIAL_QUOTE_PUNCTUATION);
+ assertTrue(Character.getType(0x2039) == Character.INITIAL_QUOTE_PUNCTUATION);
+
+ assertTrue(Character.getType(0x00BB) == Character.FINAL_QUOTE_PUNCTUATION);
+ assertTrue(Character.getType(0x203A) == Character.FINAL_QUOTE_PUNCTUATION);
+ }
+
+ /**
+ * java.lang.Character#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals("Incorrect hash returned", 89, new Character('Y').hashCode());
+ }
+
+ /**
+ * java.lang.Character#isDefined(char)
+ */
+ public void test_isDefinedC() {
+ assertTrue("Defined character returned false", Character.isDefined('v'));
+ assertTrue("Defined character returned false", Character.isDefined('\u6039'));
+ }
+
+ /**
+ * java.lang.Character#isDefined(int)
+ */
+ public void test_isDefined_I() {
+ assertTrue(Character.isDefined((int) 'v'));
+ assertTrue(Character.isDefined((int) '\u6039'));
+ assertTrue(Character.isDefined(0x10300));
+
+ assertFalse(Character.isDefined(0x30000));
+ assertFalse(Character.isDefined(0x3FFFF));
+ assertFalse(Character.isDefined(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isDigit(char)
+ */
+ public void test_isDigitC() {
+ assertTrue("Digit returned false", Character.isDigit('1'));
+ assertFalse("Non-Digit returned false", Character.isDigit('A'));
+ }
+
+ /**
+ * java.lang.Character#isDigit(int)
+ */
+ public void test_isDigit_I() {
+ assertTrue(Character.isDigit((int) '1'));
+ assertFalse(Character.isDigit((int) 'A'));
+
+ assertTrue(Character.isDigit(0x0030));
+ assertTrue(Character.isDigit(0x0035));
+ assertTrue(Character.isDigit(0x0039));
+
+ assertTrue(Character.isDigit(0x0660));
+ assertTrue(Character.isDigit(0x0665));
+ assertTrue(Character.isDigit(0x0669));
+
+ assertTrue(Character.isDigit(0x06F0));
+ assertTrue(Character.isDigit(0x06F5));
+ assertTrue(Character.isDigit(0x06F9));
+
+ assertTrue(Character.isDigit(0x0966));
+ assertTrue(Character.isDigit(0x096A));
+ assertTrue(Character.isDigit(0x096F));
+
+ assertTrue(Character.isDigit(0xFF10));
+ assertTrue(Character.isDigit(0xFF15));
+ assertTrue(Character.isDigit(0xFF19));
+
+ assertTrue(Character.isDigit(0x1D7CE));
+ assertTrue(Character.isDigit(0x1D7D8));
+
+ assertFalse(Character.isDigit(0x2F800));
+ assertFalse(Character.isDigit(0x10FFFD));
+ assertFalse(Character.isDigit(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isIdentifierIgnorable(char)
+ */
+ public void test_isIdentifierIgnorableC() {
+ assertTrue("Ignorable whitespace returned false",
+ Character.isIdentifierIgnorable('\u0007'));
+ assertTrue("Ignorable non - whitespace control returned false",
+ Character.isIdentifierIgnorable('\u000f'));
+ assertTrue("Ignorable join control returned false",
+ Character.isIdentifierIgnorable('\u200e'));
+
+ // the spec is wrong, and our implementation is correct
+ assertTrue("Ignorable bidi control returned false",
+ Character.isIdentifierIgnorable('\u202b'));
+
+ assertTrue("Ignorable format control returned false",
+ Character.isIdentifierIgnorable('\u206c'));
+ assertTrue("Ignorable zero-width no-break returned false",
+ Character.isIdentifierIgnorable('\ufeff'));
+
+ assertFalse("Non-Ignorable returned true", Character.isIdentifierIgnorable('\u0065'));
+ }
+
+ /**
+ * java.lang.Character#isIdentifierIgnorable(int)
+ */
+ public void test_isIdentifierIgnorable_I() {
+ assertTrue(Character.isIdentifierIgnorable(0x0000));
+ assertTrue(Character.isIdentifierIgnorable(0x0004));
+ assertTrue(Character.isIdentifierIgnorable(0x0008));
+
+ assertTrue(Character.isIdentifierIgnorable(0x000E));
+ assertTrue(Character.isIdentifierIgnorable(0x0013));
+ assertTrue(Character.isIdentifierIgnorable(0x001B));
+
+ assertTrue(Character.isIdentifierIgnorable(0x007F));
+ assertTrue(Character.isIdentifierIgnorable(0x008F));
+ assertTrue(Character.isIdentifierIgnorable(0x009F));
+
+ assertTrue(Character.isIdentifierIgnorable(0x202b));
+ assertTrue(Character.isIdentifierIgnorable(0x206c));
+ assertTrue(Character.isIdentifierIgnorable(0xfeff));
+ assertFalse(Character.isIdentifierIgnorable(0x0065));
+
+ assertTrue(Character.isIdentifierIgnorable(0x1D173));
+
+ assertFalse(Character.isIdentifierIgnorable(0x10FFFD));
+ assertFalse(Character.isIdentifierIgnorable(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isMirrored(char)
+ */
+ public void test_isMirrored_C() {
+ assertTrue(Character.isMirrored('\u0028'));
+ assertFalse(Character.isMirrored('\uFFFF'));
+ }
+
+ /**
+ * java.lang.Character#isMirrored(int)
+ */
+ public void test_isMirrored_I() {
+ assertTrue(Character.isMirrored(0x0028));
+ assertFalse(Character.isMirrored(0xFFFF));
+ assertFalse(Character.isMirrored(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isISOControl(char)
+ */
+ public void test_isISOControlC() {
+ // Test for method boolean java.lang.Character.isISOControl(char)
+ for (int i = 0; i < 32; i++) {
+ assertTrue("ISOConstrol char returned false", Character.isISOControl((char) i));
+ }
+
+ for (int i = 127; i < 160; i++) {
+ assertTrue("ISOConstrol char returned false", Character.isISOControl((char) i));
+ }
+ }
+
+ /**
+ * java.lang.Character#isISOControl(int)
+ */
+ public void test_isISOControlI() {
+ // Test for method boolean java.lang.Character.isISOControl(char)
+ for (int i = 0; i < 32; i++) {
+ assertTrue("ISOConstrol char returned false", Character.isISOControl(i));
+ }
+
+ for (int i = 127; i < 160; i++) {
+ assertTrue("ISOConstrol char returned false", Character.isISOControl(i));
+ }
+
+ for (int i = 160; i < 260; i++) {
+ assertFalse("Not ISOConstrol char returned true", Character.isISOControl(i));
+ }
+ }
+
+
+ /**
+ * java.lang.Character#isJavaIdentifierPart(char)
+ */
+ public void test_isJavaIdentifierPartC() {
+ assertTrue("letter returned false", Character.isJavaIdentifierPart('l'));
+ assertTrue("currency returned false", Character.isJavaIdentifierPart('$'));
+ assertTrue("digit returned false", Character.isJavaIdentifierPart('9'));
+ assertTrue("connecting char returned false", Character.isJavaIdentifierPart('_'));
+ assertTrue("ignorable control returned false", Character.isJavaIdentifierPart('\u200b'));
+ assertFalse("semi returned true", Character.isJavaIdentifierPart(';'));
+ }
+
+ /**
+ * java.lang.Character#isJavaIdentifierPart(int)
+ */
+ public void test_isJavaIdentifierPart_I() {
+ assertTrue(Character.isJavaIdentifierPart((int) 'l'));
+ assertTrue(Character.isJavaIdentifierPart((int) '$'));
+ assertTrue(Character.isJavaIdentifierPart((int) '9'));
+ assertTrue(Character.isJavaIdentifierPart((int) '_'));
+ assertFalse(Character.isJavaIdentifierPart((int) ';'));
+
+ assertTrue(Character.isJavaIdentifierPart(0x0041));
+ assertTrue(Character.isJavaIdentifierPart(0x10400));
+ assertTrue(Character.isJavaIdentifierPart(0x0061));
+ assertTrue(Character.isJavaIdentifierPart(0x10428));
+ assertTrue(Character.isJavaIdentifierPart(0x01C5));
+ assertTrue(Character.isJavaIdentifierPart(0x1FFC));
+ assertTrue(Character.isJavaIdentifierPart(0x02B0));
+ assertTrue(Character.isJavaIdentifierPart(0xFF9F));
+ assertTrue(Character.isJavaIdentifierPart(0x01BB));
+ assertTrue(Character.isJavaIdentifierPart(0x2F888));
+
+ assertTrue(Character.isJavaIdentifierPart(0x0024));
+ assertTrue(Character.isJavaIdentifierPart(0xFFE6));
+
+ assertTrue(Character.isJavaIdentifierPart(0x005F));
+ assertTrue(Character.isJavaIdentifierPart(0xFF3F));
+
+ assertTrue(Character.isJavaIdentifierPart(0x194D));
+ assertTrue(Character.isJavaIdentifierPart(0x1D7CE));
+ assertTrue(Character.isJavaIdentifierPart(0x2160));
+ assertTrue(Character.isJavaIdentifierPart(0x1034A));
+
+ assertTrue(Character.isJavaIdentifierPart(0x0F82));
+ assertTrue(Character.isJavaIdentifierPart(0x1D180));
+
+ assertTrue(Character.isJavaIdentifierPart(0x0000));
+ assertTrue(Character.isJavaIdentifierPart(0x0008));
+ assertTrue(Character.isJavaIdentifierPart(0x000E));
+ assertTrue(Character.isJavaIdentifierPart(0x001B));
+ assertTrue(Character.isJavaIdentifierPart(0x007F));
+ assertTrue(Character.isJavaIdentifierPart(0x009F));
+ assertTrue(Character.isJavaIdentifierPart(0x00AD));
+ assertTrue(Character.isJavaIdentifierPart(0xE007F));
+
+ assertTrue(Character.isJavaIdentifierPart(0x200B));
+ }
+
+ /**
+ * java.lang.Character#isJavaIdentifierStart(char)
+ */
+ public void test_isJavaIdentifierStartC() {
+ assertTrue("letter returned false", Character.isJavaIdentifierStart('l'));
+ assertTrue("currency returned false", Character.isJavaIdentifierStart('$'));
+ assertTrue("connecting char returned false", Character.isJavaIdentifierStart('_'));
+ assertFalse("digit returned true", Character.isJavaIdentifierStart('9'));
+ assertFalse("ignorable control returned true", Character.isJavaIdentifierStart('\u200b'));
+ assertFalse("semi returned true", Character.isJavaIdentifierStart(';'));
+ }
+
+ /**
+ * java.lang.Character#isJavaIdentifierStart(int)
+ */
+ public void test_isJavaIdentifierStart_I() {
+ assertTrue(Character.isJavaIdentifierStart((int) 'l'));
+ assertTrue(Character.isJavaIdentifierStart((int) '$'));
+ assertTrue(Character.isJavaIdentifierStart((int) '_'));
+ assertFalse(Character.isJavaIdentifierStart((int) '9'));
+ assertFalse(Character.isJavaIdentifierStart((int) '\u200b'));
+ assertFalse(Character.isJavaIdentifierStart((int) ';'));
+
+ assertTrue(Character.isJavaIdentifierStart(0x0041));
+ assertTrue(Character.isJavaIdentifierStart(0x10400));
+ assertTrue(Character.isJavaIdentifierStart(0x0061));
+ assertTrue(Character.isJavaIdentifierStart(0x10428));
+ assertTrue(Character.isJavaIdentifierStart(0x01C5));
+ assertTrue(Character.isJavaIdentifierStart(0x1FFC));
+ assertTrue(Character.isJavaIdentifierStart(0x02B0));
+ assertTrue(Character.isJavaIdentifierStart(0xFF9F));
+ assertTrue(Character.isJavaIdentifierStart(0x01BB));
+ assertTrue(Character.isJavaIdentifierStart(0x2F888));
+
+ assertTrue(Character.isJavaIdentifierPart(0x0024));
+ assertTrue(Character.isJavaIdentifierPart(0xFFE6));
+
+ assertTrue(Character.isJavaIdentifierPart(0x005F));
+ assertTrue(Character.isJavaIdentifierPart(0xFF3F));
+
+ assertTrue(Character.isJavaIdentifierPart(0x2160));
+ assertTrue(Character.isJavaIdentifierPart(0x1034A));
+
+ assertFalse(Character.isJavaIdentifierPart(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isJavaLetter(char)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_isJavaLetterC() {
+ assertTrue("letter returned false", Character.isJavaLetter('l'));
+ assertTrue("currency returned false", Character.isJavaLetter('$'));
+ assertTrue("connecting char returned false", Character.isJavaLetter('_'));
+
+ assertFalse("digit returned true", Character.isJavaLetter('9'));
+ assertFalse("ignored control returned true", Character.isJavaLetter('\u200b'));
+ assertFalse("semi returned true", Character.isJavaLetter(';'));
+ }
+
+ /**
+ * java.lang.Character#isJavaLetterOrDigit(char)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_isJavaLetterOrDigitC() {
+ assertTrue("letter returned false", Character.isJavaLetterOrDigit('l'));
+ assertTrue("currency returned false", Character.isJavaLetterOrDigit('$'));
+ assertTrue("digit returned false", Character.isJavaLetterOrDigit('9'));
+ assertTrue("connecting char returned false", Character.isJavaLetterOrDigit('_'));
+ assertFalse("semi returned true", Character.isJavaLetterOrDigit(';'));
+ }
+
+ /**
+ * java.lang.Character#isLetter(char)
+ */
+ public void test_isLetterC() {
+ assertTrue("Letter returned false", Character.isLetter('L'));
+ assertFalse("Non-Letter returned true", Character.isLetter('9'));
+ }
+
+ /**
+ * java.lang.Character#isLetter(int)
+ */
+ public void test_isLetter_I() {
+ assertTrue(Character.isLetter((int) 'L'));
+ assertFalse(Character.isLetter((int) '9'));
+
+ assertTrue(Character.isLetter(0x1FA9));
+ assertTrue(Character.isLetter(0x1D400));
+ assertTrue(Character.isLetter(0x1D622));
+ assertTrue(Character.isLetter(0x10000));
+
+ assertFalse(Character.isLetter(0x1012C));
+ assertFalse(Character.isLetter(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isLetterOrDigit(char)
+ */
+ public void test_isLetterOrDigitC() {
+ assertTrue("Digit returned false", Character.isLetterOrDigit('9'));
+ assertTrue("Letter returned false", Character.isLetterOrDigit('K'));
+ assertFalse("Control returned true", Character.isLetterOrDigit('\n'));
+ assertFalse("Punctuation returned true", Character.isLetterOrDigit('?'));
+ }
+
+ /**
+ * java.lang.Character#isLetterOrDigit(int)
+ */
+ public void test_isLetterOrDigit_I() {
+ assertTrue(Character.isLetterOrDigit((int) '9'));
+ assertTrue(Character.isLetterOrDigit((int) 'K'));
+ assertFalse(Character.isLetterOrDigit((int) '\n'));
+ assertFalse(Character.isLetterOrDigit((int) '?'));
+
+ assertTrue(Character.isLetterOrDigit(0x1FA9));
+ assertTrue(Character.isLetterOrDigit(0x1D400));
+ assertTrue(Character.isLetterOrDigit(0x1D622));
+ assertTrue(Character.isLetterOrDigit(0x10000));
+
+ assertTrue(Character.isLetterOrDigit(0x1D7CE));
+ assertTrue(Character.isLetterOrDigit(0x1D7D8));
+
+ assertFalse(Character.isLetterOrDigit(0x10FFFD));
+ assertFalse(Character.isLetterOrDigit(0x1012C));
+ assertFalse(Character.isLetterOrDigit(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isLowerCase(char)
+ */
+ public void test_isLowerCaseC() {
+ assertTrue("lower returned false", Character.isLowerCase('a'));
+ assertFalse("upper returned true", Character.isLowerCase('T'));
+ }
+
+ /**
+ * java.lang.Character#isLowerCase(int)
+ */
+ public void test_isLowerCase_I() {
+ assertTrue(Character.isLowerCase((int) 'a'));
+ assertFalse(Character.isLowerCase((int) 'T'));
+
+ assertTrue(Character.isLowerCase(0x10428));
+ assertTrue(Character.isLowerCase(0x1D4EA));
+
+ assertFalse(Character.isLowerCase(0x1D504));
+ assertFalse(Character.isLowerCase(0x30000));
+ assertFalse(Character.isLowerCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isSpace(char)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_isSpaceC() {
+ // Test for method boolean java.lang.Character.isSpace(char)
+ assertTrue("space returned false", Character.isSpace('\n'));
+ assertFalse("non-space returned true", Character.isSpace('T'));
+ }
+
+ /**
+ * java.lang.Character#isSpaceChar(char)
+ */
+ public void test_isSpaceCharC() {
+ assertTrue("space returned false", Character.isSpaceChar('\u0020'));
+ assertFalse("non-space returned true", Character.isSpaceChar('\n'));
+ }
+
+ /**
+ * java.lang.Character#isSpaceChar(int)
+ */
+ public void test_isSpaceChar_I() {
+ assertTrue(Character.isSpaceChar((int) '\u0020'));
+ assertFalse(Character.isSpaceChar((int) '\n'));
+
+ assertTrue(Character.isSpaceChar(0x2000));
+ assertTrue(Character.isSpaceChar(0x200A));
+
+ assertTrue(Character.isSpaceChar(0x2028));
+ assertTrue(Character.isSpaceChar(0x2029));
+
+ assertFalse(Character.isSpaceChar(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isTitleCase(char)
+ */
+ public void test_isTitleCaseC() {
+ char[] tChars = { (char) 0x01c5, (char) 0x01c8, (char) 0x01cb,
+ (char) 0x01f2, (char) 0x1f88, (char) 0x1f89, (char) 0x1f8a,
+ (char) 0x1f8b, (char) 0x1f8c, (char) 0x1f8d, (char) 0x1f8e,
+ (char) 0x1f8f, (char) 0x1f98, (char) 0x1f99, (char) 0x1f9a,
+ (char) 0x1f9b, (char) 0x1f9c, (char) 0x1f9d, (char) 0x1f9e,
+ (char) 0x1f9f, (char) 0x1fa8, (char) 0x1fa9, (char) 0x1faa,
+ (char) 0x1fab, (char) 0x1fac, (char) 0x1fad, (char) 0x1fae,
+ (char) 0x1faf, (char) 0x1fbc, (char) 0x1fcc, (char) 0x1ffc };
+ byte tnum = 0;
+ for (char c = 0; c < 65535; c++) {
+ if (Character.isTitleCase(c)) {
+ tnum++;
+ int i;
+ for (i = 0; i < tChars.length; i++) {
+ if (tChars[i] == c) {
+ i = tChars.length + 1;
+ }
+ }
+ if (i < tChars.length) {
+ fail("Non Title Case char returned true");
+ }
+ }
+ }
+ assertTrue("Failed to find all Title Case chars", tnum == tChars.length);
+ }
+
+ /**
+ * java.lang.Character#isTitleCase(int)
+ */
+ public void test_isTitleCase_I() {
+ //all the titlecase characters
+ int[] titleCaseCharacters = { 0x01c5, 0x01c8, 0x01cb, 0x01f2, 0x1f88,
+ 0x1f89, 0x1f8a, 0x1f8b, 0x1f8c, 0x1f8d, 0x1f8e, 0x1f8f, 0x1f98,
+ 0x1f99, 0x1f9a, 0x1f9b, 0x1f9c, 0x1f9d, 0x1f9e, 0x1f9f, 0x1fa8,
+ 0x1fa9, 0x1faa, 0x1fab, 0x1fac, 0x1fad, 0x1fae, 0x1faf, 0x1fbc,
+ 0x1fcc, 0x1ffc };
+
+ for (int titleCaseCharacter : titleCaseCharacters) {
+ assertTrue(Character.isTitleCase(titleCaseCharacter));
+ }
+
+ assertFalse(Character.isTitleCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isUnicodeIdentifierPart(char)
+ */
+ public void test_isUnicodeIdentifierPartC() {
+ assertTrue("'a' returned false", Character.isUnicodeIdentifierPart('a'));
+ assertTrue("'2' returned false", Character.isUnicodeIdentifierPart('2'));
+ assertFalse("'+' returned true", Character.isUnicodeIdentifierPart('+'));
+ }
+
+ /**
+ * java.lang.Character#isUnicodeIdentifierPart(int)
+ */
+ public void test_isUnicodeIdentifierPart_I() {
+ assertTrue(Character.isUnicodeIdentifierPart((int) 'a'));
+ assertTrue(Character.isUnicodeIdentifierPart((int) '2'));
+ assertFalse(Character.isUnicodeIdentifierPart((int) '+'));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x1FA9));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D400));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D622));
+ assertTrue(Character.isUnicodeIdentifierPart(0x10000));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x0030));
+ assertTrue(Character.isUnicodeIdentifierPart(0x0035));
+ assertTrue(Character.isUnicodeIdentifierPart(0x0039));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x0660));
+ assertTrue(Character.isUnicodeIdentifierPart(0x0665));
+ assertTrue(Character.isUnicodeIdentifierPart(0x0669));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x06F0));
+ assertTrue(Character.isUnicodeIdentifierPart(0x06F5));
+ assertTrue(Character.isUnicodeIdentifierPart(0x06F9));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x0966));
+ assertTrue(Character.isUnicodeIdentifierPart(0x096A));
+ assertTrue(Character.isUnicodeIdentifierPart(0x096F));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0xFF10));
+ assertTrue(Character.isUnicodeIdentifierPart(0xFF15));
+ assertTrue(Character.isUnicodeIdentifierPart(0xFF19));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D7CE));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D7D8));
+
+ assertTrue(Character.isUnicodeIdentifierPart(0x16EE));
+ assertTrue(Character.isUnicodeIdentifierPart(0xFE33));
+ assertTrue(Character.isUnicodeIdentifierPart(0xFF10));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D165));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D167));
+ assertTrue(Character.isUnicodeIdentifierPart(0x1D173));
+
+ assertFalse(Character.isUnicodeIdentifierPart(0x10FFFF));
+ assertFalse(Character.isUnicodeIdentifierPart(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isUnicodeIdentifierStart(char)
+ */
+ public void test_isUnicodeIdentifierStartC() {
+ assertTrue("'a' returned false", Character.isUnicodeIdentifierStart('a'));
+ assertFalse("'2' returned true", Character.isUnicodeIdentifierStart('2'));
+ assertFalse("'+' returned true", Character.isUnicodeIdentifierStart('+'));
+ }
+
+ /**
+ * java.lang.Character#isUnicodeIdentifierStart(int)
+ */
+ public void test_isUnicodeIdentifierStart_I() {
+ assertTrue(Character.isUnicodeIdentifierStart((int) 'a'));
+ assertFalse(Character.isUnicodeIdentifierStart((int) '2'));
+ assertFalse(Character.isUnicodeIdentifierStart((int) '+'));
+
+ assertTrue(Character.isUnicodeIdentifierStart(0x1FA9));
+ assertTrue(Character.isUnicodeIdentifierStart(0x1D400));
+ assertTrue(Character.isUnicodeIdentifierStart(0x1D622));
+ assertTrue(Character.isUnicodeIdentifierStart(0x10000));
+
+ assertTrue(Character.isUnicodeIdentifierStart(0x16EE));
+
+ // number is not a valid start of a Unicode identifier
+ assertFalse(Character.isUnicodeIdentifierStart(0x0030));
+ assertFalse(Character.isUnicodeIdentifierStart(0x0039));
+ assertFalse(Character.isUnicodeIdentifierStart(0x0660));
+ assertFalse(Character.isUnicodeIdentifierStart(0x0669));
+ assertFalse(Character.isUnicodeIdentifierStart(0x06F0));
+ assertFalse(Character.isUnicodeIdentifierStart(0x06F9));
+
+ assertFalse(Character.isUnicodeIdentifierPart(0x10FFFF));
+ assertFalse(Character.isUnicodeIdentifierPart(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isUpperCase(char)
+ */
+ public void test_isUpperCaseC() {
+ assertFalse("Incorrect case value", Character.isUpperCase('t'));
+ assertTrue("Incorrect case value", Character.isUpperCase('T'));
+ }
+
+ /**
+ * java.lang.Character#isUpperCase(int)
+ */
+ public void test_isUpperCase_I() {
+ assertFalse(Character.isUpperCase((int) 't'));
+ assertTrue(Character.isUpperCase((int) 'T'));
+
+ assertTrue(Character.isUpperCase(0x1D504));
+ assertTrue(Character.isUpperCase(0x1D608));
+
+ assertFalse(Character.isUpperCase(0x1D656));
+ assertFalse(Character.isUpperCase(0x10FFFD));
+ assertFalse(Character.isUpperCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#isWhitespace(char)
+ */
+ public void test_isWhitespaceC() {
+ assertTrue("space returned false", Character.isWhitespace('\n'));
+ assertFalse("non-space returned true", Character.isWhitespace('T'));
+ }
+
+ /**
+ * java.lang.Character#isWhitespace(int)
+ */
+ public void test_isWhitespace_I() {
+ assertTrue(Character.isWhitespace((int) '\n'));
+ assertFalse(Character.isWhitespace((int) 'T'));
+
+ assertTrue(Character.isWhitespace(0x0009));
+ assertTrue(Character.isWhitespace(0x000A));
+ assertTrue(Character.isWhitespace(0x000B));
+ assertTrue(Character.isWhitespace(0x000C));
+ assertTrue(Character.isWhitespace(0x000D));
+ assertTrue(Character.isWhitespace(0x001C));
+ assertTrue(Character.isWhitespace(0x001D));
+ assertTrue(Character.isWhitespace(0x001F));
+ assertTrue(Character.isWhitespace(0x001E));
+
+ assertTrue(Character.isWhitespace(0x2000));
+ assertTrue(Character.isWhitespace(0x200A));
+
+ assertTrue(Character.isWhitespace(0x2028));
+ assertTrue(Character.isWhitespace(0x2029));
+
+ assertFalse(Character.isWhitespace(0x00A0));
+ assertFalse(Character.isWhitespace(0x202F));
+ assertFalse(Character.isWhitespace(0x110000));
+
+ assertFalse(Character.isWhitespace(0xFEFF));
+
+ assertFalse(Character.isWhitespace(0x2007));
+
+ }
+
+ /**
+ * java.lang.Character#reverseBytes(char)
+ */
+ public void test_reverseBytesC() {
+ char original[] = new char[] { 0x0000, 0x0010, 0x00AA, 0xB000, 0xCC00, 0xABCD, 0xFFAA };
+ char reversed[] = new char[] { 0x0000, 0x1000, 0xAA00, 0x00B0, 0x00CC, 0xCDAB, 0xAAFF };
+ assertTrue("Test self check", original.length == reversed.length);
+
+ for (int i = 0; i < original.length; i++) {
+ char origChar = original[i];
+ char reversedChar = reversed[i];
+ char origReversed = Character.reverseBytes(origChar);
+
+ assertTrue("java.lang.Character.reverseBytes failed: orig char="
+ + Integer.toHexString(origChar) + ", reversed char="
+ + Integer.toHexString(origReversed), reversedChar == origReversed);
+ }
+ }
+
+ /**
+ * java.lang.Character#toLowerCase(char)
+ */
+ public void test_toLowerCaseC() {
+ assertEquals("Failed to change case", 't', Character.toLowerCase('T'));
+ }
+
+ /**
+ * java.lang.Character#toLowerCase(int)
+ */
+ public void test_toLowerCase_I() {
+ assertEquals('t', Character.toLowerCase((int) 'T'));
+
+ assertEquals(0x10428, Character.toLowerCase(0x10400));
+ assertEquals(0x10428, Character.toLowerCase(0x10428));
+
+ assertEquals(0x1D504, Character.toLowerCase(0x1D504));
+ assertEquals(0x10FFFD, Character.toLowerCase(0x10FFFD));
+ assertEquals(0x110000, Character.toLowerCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#toString()
+ */
+ public void test_toString() {
+ assertEquals("Incorrect String returned", "T", new Character('T').toString());
+ }
+
+ /**
+ * java.lang.Character#toTitleCase(char)
+ */
+ public void test_toTitleCaseC() {
+ assertEquals("Incorrect title case for a", 'A', Character.toTitleCase('a'));
+ assertEquals("Incorrect title case for A", 'A', Character.toTitleCase('A'));
+ assertEquals("Incorrect title case for 1", '1', Character.toTitleCase('1'));
+ }
+
+ /**
+ * java.lang.Character#toTitleCase(int)
+ */
+ public void test_toTitleCase_I() {
+ assertEquals('A', Character.toTitleCase((int) 'a'));
+ assertEquals('A', Character.toTitleCase((int) 'A'));
+ assertEquals('1', Character.toTitleCase((int) '1'));
+
+ assertEquals(0x10400, Character.toTitleCase(0x10428));
+ assertEquals(0x10400, Character.toTitleCase(0x10400));
+
+ assertEquals(0x10FFFF, Character.toTitleCase(0x10FFFF));
+ assertEquals(0x110000, Character.toTitleCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#toUpperCase(char)
+ */
+ public void test_toUpperCaseC() {
+ // Test for method char java.lang.Character.toUpperCase(char)
+ assertEquals("Incorrect upper case for a", 'A', Character.toUpperCase('a'));
+ assertEquals("Incorrect upper case for A", 'A', Character.toUpperCase('A'));
+ assertEquals("Incorrect upper case for 1", '1', Character.toUpperCase('1'));
+ }
+
+ /**
+ * java.lang.Character#toUpperCase(int)
+ */
+ public void test_toUpperCase_I() {
+ assertEquals('A', Character.toUpperCase((int) 'a'));
+ assertEquals('A', Character.toUpperCase((int) 'A'));
+ assertEquals('1', Character.toUpperCase((int) '1'));
+
+ assertEquals(0x10400, Character.toUpperCase(0x10428));
+ assertEquals(0x10400, Character.toUpperCase(0x10400));
+
+ assertEquals(0x10FFFF, Character.toUpperCase(0x10FFFF));
+ assertEquals(0x110000, Character.toUpperCase(0x110000));
+ }
+
+ /**
+ * java.lang.Character#getDirectionality(int)
+ */
+ public void test_isDirectionaliy_I() {
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0xFFFE));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x30000));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x110000));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(-1));
+
+ assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character.getDirectionality(0x0041));
+ assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character.getDirectionality(0x10000));
+ assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character.getDirectionality(0x104A9));
+
+ assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character.getDirectionality(0xFB4F));
+ assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character.getDirectionality(0x10838));
+ // Unicode standard 5.1 changed category of unicode point 0x0600 from AL to AN
+ assertEquals(Character.DIRECTIONALITY_ARABIC_NUMBER, Character.getDirectionality(0x0600));
+ assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC,
+ Character.getDirectionality(0xFEFC));
+
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER, Character.getDirectionality(0x2070));
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER,
+ Character.getDirectionality(0x1D7FF));
+
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR,
+ Character.getDirectionality(0x002B));
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR,
+ Character.getDirectionality(0xFF0B));
+
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR,
+ Character.getDirectionality(0x0023));
+ assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR,
+ Character.getDirectionality(0x17DB));
+
+ assertEquals(Character.DIRECTIONALITY_ARABIC_NUMBER, Character.getDirectionality(0x0660));
+ assertEquals(Character.DIRECTIONALITY_ARABIC_NUMBER, Character.getDirectionality(0x066C));
+
+ assertEquals(Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR,
+ Character.getDirectionality(0x002C));
+ assertEquals(Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR,
+ Character.getDirectionality(0xFF1A));
+
+ assertEquals(Character.DIRECTIONALITY_NONSPACING_MARK, Character.getDirectionality(0x17CE));
+ assertEquals(Character.DIRECTIONALITY_NONSPACING_MARK,
+ Character.getDirectionality(0xE01DB));
+
+ assertEquals(Character.DIRECTIONALITY_BOUNDARY_NEUTRAL,
+ Character.getDirectionality(0x0000));
+ assertEquals(Character.DIRECTIONALITY_BOUNDARY_NEUTRAL,
+ Character.getDirectionality(0xE007F));
+
+ assertEquals(Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR,
+ Character.getDirectionality(0x000A));
+ assertEquals(Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR,
+ Character.getDirectionality(0x2029));
+
+ assertEquals(Character.DIRECTIONALITY_SEGMENT_SEPARATOR,
+ Character.getDirectionality(0x0009));
+ assertEquals(Character.DIRECTIONALITY_SEGMENT_SEPARATOR,
+ Character.getDirectionality(0x001F));
+
+ assertEquals(Character.DIRECTIONALITY_WHITESPACE, Character.getDirectionality(0x0020));
+ assertEquals(Character.DIRECTIONALITY_WHITESPACE, Character.getDirectionality(0x3000));
+
+ assertEquals(Character.DIRECTIONALITY_OTHER_NEUTRALS, Character.getDirectionality(0x2FF0));
+ assertEquals(Character.DIRECTIONALITY_OTHER_NEUTRALS, Character.getDirectionality(0x1D356));
+
+ assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING,
+ Character.getDirectionality(0x202A));
+
+ assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE,
+ Character.getDirectionality(0x202D));
+
+ assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING,
+ Character.getDirectionality(0x202B));
+
+ assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE,
+ Character.getDirectionality(0x202E));
+
+ assertEquals(Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT,
+ Character.getDirectionality(0x202C));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_SubsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_SubsetTest.java
new file mode 100644
index 0000000..41408ec
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_SubsetTest.java
@@ -0,0 +1,49 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class Character_SubsetTest extends TestCase {
+
+ /**
+ * java.lang.Character.Subset#Character.Subset(java.lang.String)
+ */
+ public void test_Ctor() {
+
+ try {
+ // Regression for HARMONY-888
+ new Character.Subset(null) {
+ };
+ fail("No expected NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Character.Subset#toString()
+ */
+ public void test_toString() {
+
+ String name = "name";
+ Character.Subset subset = new Character.Subset(name) {
+ };
+ assertSame(name, subset.toString());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_UnicodeBlockTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_UnicodeBlockTest.java
new file mode 100644
index 0000000..792ee3d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Character_UnicodeBlockTest.java
@@ -0,0 +1,822 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class Character_UnicodeBlockTest extends TestCase {
+
+ public void test_ofC() {
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char) 0x0));
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char) 0x7f));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x80));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char) 0xff));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char) 0x100));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char) 0x17f));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char) 0x180));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char) 0x24f));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char) 0x250));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char) 0x2af));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char) 0x2b0));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char) 0x2ff));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char) 0x300));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char) 0x36f));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char) 0x370));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char) 0x3ff));
+ assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char) 0x400));
+ assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char) 0x4ff));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char) 0x500));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char) 0x52f));
+ assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char) 0x530));
+ assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char) 0x58f));
+ assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char) 0x590));
+ assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char) 0x5ff));
+ assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char) 0x600));
+ assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char) 0x6ff));
+ assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char) 0x700));
+ assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char) 0x74f));
+ assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char) 0x780));
+ assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char) 0x7bf));
+ assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char) 0x900));
+ assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char) 0x97f));
+ assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char) 0x980));
+ assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char) 0x9ff));
+ assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char) 0xa00));
+ assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char) 0xa7f));
+ assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char) 0xa80));
+ assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char) 0xaff));
+ assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char) 0xb00));
+ assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char) 0xb7f));
+ assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char) 0xb80));
+ assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char) 0xbff));
+ assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char) 0xc00));
+ assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char) 0xc7f));
+ assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char) 0xc80));
+ assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char) 0xcff));
+ assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char) 0xd00));
+ assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char) 0xd7f));
+ assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char) 0xd80));
+ assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char) 0xdff));
+ assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char) 0xe00));
+ assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char) 0xe7f));
+ assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char) 0xe80));
+ assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char) 0xeff));
+ assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char) 0xf00));
+ assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char) 0xfff));
+ assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char) 0x1000));
+ assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char) 0x109f));
+ assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char) 0x10a0));
+ assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char) 0x10ff));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char) 0x1100));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char) 0x11ff));
+ assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char) 0x1200));
+ assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char) 0x137f));
+ assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char) 0x13a0));
+ assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char) 0x13ff));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char) 0x1400));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char) 0x167f));
+ assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char) 0x1680));
+ assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char) 0x169f));
+ assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char) 0x16a0));
+ assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char) 0x16ff));
+ assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char) 0x1700));
+ assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char) 0x171f));
+ assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char) 0x1720));
+ assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char) 0x173f));
+ assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char) 0x1740));
+ assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char) 0x175f));
+ assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char) 0x1760));
+ assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char) 0x177f));
+ assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char) 0x1780));
+ assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char) 0x17ff));
+ assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char) 0x1800));
+ assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char) 0x18af));
+ assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char) 0x1900));
+ assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char) 0x194f));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char) 0x1950));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char) 0x197f));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char) 0x19e0));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char) 0x19ff));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x1d00));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x1d7f));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char) 0x1e00));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char) 0x1eff));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char) 0x1f00));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char) 0x1fff));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char) 0x2000));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char) 0x206f));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char) 0x2070));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char) 0x209f));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char) 0x20a0));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char) 0x20cf));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char) 0x20d0));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char) 0x20ff));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char) 0x2100));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char) 0x214f));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char) 0x2150));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char) 0x218f));
+ assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char) 0x2190));
+ assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char) 0x21ff));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2200));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x22ff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char) 0x2300));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char) 0x23ff));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char) 0x2400));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char) 0x243f));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char) 0x2440));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char) 0x245f));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char) 0x2460));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char) 0x24ff));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char) 0x2500));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char) 0x257f));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char) 0x2580));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char) 0x259f));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char) 0x25a0));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char) 0x25ff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char) 0x2600));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char) 0x26ff));
+ assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char) 0x2700));
+ assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char) 0x27bf));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char) 0x27c0));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char) 0x27ef));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char) 0x27f0));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char) 0x27ff));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char) 0x2800));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char) 0x28ff));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char) 0x2900));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char) 0x297f));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char) 0x2980));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char) 0x29ff));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2a00));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2aff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char) 0x2b00));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char) 0x2bff));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x2e80));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x2eff));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char) 0x2f00));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char) 0x2fdf));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char) 0x2ff0));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char) 0x2fff));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char) 0x3000));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char) 0x303f));
+ assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char) 0x3040));
+ assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char) 0x309f));
+ assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char) 0x30a0));
+ assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char) 0x30ff));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char) 0x3100));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char) 0x312f));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char) 0x3130));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char) 0x318f));
+ assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char) 0x3190));
+ assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char) 0x319f));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char) 0x31a0));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char) 0x31bf));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x31f0));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x31ff));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char) 0x3200));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char) 0x32ff));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char) 0x3300));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char) 0x33ff));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char) 0x3400));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char) 0x4dbf));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char) 0x4dc0));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char) 0x4dff));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0x4e00));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0x9fff));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char) 0xa000));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char) 0xa48f));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char) 0xa490));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char) 0xa4cf));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char) 0xac00));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char) 0xd7af));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char) 0xd800));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char) 0xdb7f));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char) 0xdb80));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char) 0xdbff));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char) 0xdc00));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char) 0xdfff));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char) 0xe000));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char) 0xf8ff));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0xf900));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0xfaff));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char) 0xfb00));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char) 0xfb4f));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char) 0xfb50));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char) 0xfdff));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char) 0xfe00));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char) 0xfe0f));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char) 0xfe20));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char) 0xfe2f));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char) 0xfe30));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char) 0xfe4f));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char) 0xfe50));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char) 0xfe6f));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char) 0xfe70));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char) 0xfeff));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char) 0xff00));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char) 0xffef));
+ assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char) 0xfff0));
+ assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char) 0xffff));
+
+ // Negative test: The range [0x0860, 0x08A0) is currently unassigned.
+ assertEquals(null, Character.UnicodeBlock.of((char) 0x0860));
+ assertEquals(null, Character.UnicodeBlock.of((char) 0x089F));
+ }
+
+ public void test_ofI() {
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x0));
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x7f));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0x80));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0xff));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x100));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x17f));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x180));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x24f));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x250));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x2af));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2b0));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2ff));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x300));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x36f));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x370));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x3ff));
+ assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x400));
+ assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x4ff));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x500));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x52f));
+ assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x530));
+ assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x58f));
+ assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x590));
+ assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x5ff));
+ assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x600));
+ assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x6ff));
+ assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x700));
+ assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x74f));
+ assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x780));
+ assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x7bf));
+ assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x900));
+ assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x97f));
+ assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x980));
+ assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x9ff));
+ assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa00));
+ assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa7f));
+ assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xa80));
+ assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xaff));
+ assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb00));
+ assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb7f));
+ assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xb80));
+ assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xbff));
+ assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc00));
+ assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc7f));
+ assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xc80));
+ assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xcff));
+ assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd00));
+ assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd7f));
+ assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xd80));
+ assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xdff));
+ assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe00));
+ assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe7f));
+ assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xe80));
+ assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xeff));
+ assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xf00));
+ assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xfff));
+ assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x1000));
+ assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x109f));
+ assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10a0));
+ assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10ff));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x1100));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x11ff));
+ assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x1200));
+ assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x137f));
+ assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13a0));
+ assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13ff));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x1400));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x167f));
+ assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x1680));
+ assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x169f));
+ assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16a0));
+ assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16ff));
+ assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x1700));
+ assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x171f));
+ assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x1720));
+ assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x173f));
+ assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x1740));
+ assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x175f));
+ assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x1760));
+ assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x177f));
+ assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x1780));
+ assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x17ff));
+ assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x1800));
+ assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x18af));
+ assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x1900));
+ assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x194f));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x1950));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x197f));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19e0));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19ff));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d00));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d7f));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1e00));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1eff));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1f00));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1fff));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x2000));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x206f));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x2070));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x209f));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20a0));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20cf));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20d0));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20ff));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x2100));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x214f));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x2150));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x218f));
+ assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x2190));
+ assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x21ff));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2200));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x22ff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x2300));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x23ff));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x2400));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x243f));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x2440));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x245f));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x2460));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x24ff));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x2500));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x257f));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x2580));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x259f));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25a0));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25ff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x2600));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x26ff));
+ assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x2700));
+ assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x27bf));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27c0));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27ef));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27f0));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27ff));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x2800));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x28ff));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x2900));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x297f));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x2980));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x29ff));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2a00));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2aff));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2b00));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2bff));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2e80));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2eff));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2f00));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2fdf));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2ff0));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2fff));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x3000));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x303f));
+ assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x3040));
+ assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x309f));
+ assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30a0));
+ assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30ff));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x3100));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x312f));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x3130));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x318f));
+ assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x3190));
+ assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x319f));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31a0));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31bf));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31f0));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31ff));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x3200));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x32ff));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x3300));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x33ff));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x3400));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x4dbf));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dc0));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dff));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x4e00));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x9fff));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa000));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa48f));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa490));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa4cf));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xac00));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xd7af));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xd800));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xdb7f));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdb80));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdbff));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdc00));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdfff));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xe000));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xf8ff));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xf900));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xfaff));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb00));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb4f));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfb50));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfdff));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe00));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe0f));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe20));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe2f));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe30));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe4f));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe50));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe6f));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfe70));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfeff));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xff00));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xffef));
+ assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xfff0));
+ assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xffff));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x10000));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x1007f));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x10080));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x100ff));
+ assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x10100));
+ assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x1013f));
+ assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x10300));
+ assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x1032f));
+ assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x10330));
+ assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x1034f));
+ assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x10380));
+ assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x1039f));
+ assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x10400));
+ assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x1044f));
+ assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x10450));
+ assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x1047f));
+ assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x10480));
+ assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x104af));
+ assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x10800));
+ assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x1083f));
+ assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d000));
+ assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d0ff));
+ assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d100));
+ assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d1ff));
+ assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d300));
+ assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d35f));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d400));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d7ff));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x20000));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x2a6df));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2f800));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2fa1f));
+ assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe0000));
+ assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe007f));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe0100));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe01ef));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xf0000));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xfffff));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x100000));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x10ffff));
+
+ // Negative test: The range [0x0860, 0x08A0) is currently unassigned.
+ assertEquals(null, Character.UnicodeBlock.of((char) 0x0860));
+ assertEquals(null, Character.UnicodeBlock.of((char) 0x089F));
+ }
+
+ public void test_ofIExceptions() {
+ try {
+ Character.UnicodeBlock.of(Character.MAX_CODE_POINT + 1);
+ fail("No illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ public void test_forNameLjava_lang_String() {
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BASIC_LATIN"));
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("Basic Latin"));
+ assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BasicLatin"));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("LATIN_1_SUPPLEMENT"));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1 Supplement"));
+ assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1Supplement"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LATIN_EXTENDED_A"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("Latin Extended-A"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LatinExtended-A"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LATIN_EXTENDED_B"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("Latin Extended-B"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LatinExtended-B"));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA_EXTENSIONS"));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA Extensions"));
+ assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPAExtensions"));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SPACING_MODIFIER_LETTERS"));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("Spacing Modifier Letters"));
+ assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SpacingModifierLetters"));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("COMBINING_DIACRITICAL_MARKS"));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("Combining Diacritical Marks"));
+ assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("CombiningDiacriticalMarks"));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GREEK"));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek and Coptic"));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GreekandCoptic"));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek"));
+ assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek"));
+ assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.forName("CYRILLIC"));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CYRILLIC_SUPPLEMENTARY"));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("Cyrillic Supplementary"));
+ assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CyrillicSupplementary"));
+ assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.forName("ARMENIAN"));
+ assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.forName("HEBREW"));
+ assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.forName("ARABIC"));
+ assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.forName("SYRIAC"));
+ assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.forName("THAANA"));
+ assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.forName("DEVANAGARI"));
+ assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.forName("BENGALI"));
+ assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.forName("GURMUKHI"));
+ assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.forName("GUJARATI"));
+ assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.forName("ORIYA"));
+ assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.forName("TAMIL"));
+ assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.forName("TELUGU"));
+ assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.forName("KANNADA"));
+ assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.forName("MALAYALAM"));
+ assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.forName("SINHALA"));
+ assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.forName("THAI"));
+ assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.forName("LAO"));
+ assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.forName("TIBETAN"));
+ assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.forName("MYANMAR"));
+ assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.forName("GEORGIAN"));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HANGUL_JAMO"));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("Hangul Jamo"));
+ assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HangulJamo"));
+ assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.forName("ETHIOPIC"));
+ assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.forName("CHEROKEE"));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS"));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("Unified Canadian Aboriginal Syllabics"));
+ assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UnifiedCanadianAboriginalSyllabics"));
+ assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.forName("OGHAM"));
+ assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.forName("RUNIC"));
+ assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.forName("TAGALOG"));
+ assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.forName("HANUNOO"));
+ assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.forName("BUHID"));
+ assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.forName("TAGBANWA"));
+ assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.forName("KHMER"));
+ assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.forName("MONGOLIAN"));
+ assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.forName("LIMBU"));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TAI_LE"));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("Tai Le"));
+ assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TaiLe"));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KHMER_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("Khmer Symbols"));
+ assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KhmerSymbols"));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PHONETIC_EXTENSIONS"));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Phonetic Extensions"));
+ assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PhoneticExtensions"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LATIN_EXTENDED_ADDITIONAL"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("Latin Extended Additional"));
+ assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LatinExtendedAdditional"));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GREEK_EXTENDED"));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("Greek Extended"));
+ assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GreekExtended"));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GENERAL_PUNCTUATION"));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("General Punctuation"));
+ assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GeneralPunctuation"));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SUPERSCRIPTS_AND_SUBSCRIPTS"));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("Superscripts and Subscripts"));
+ assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SuperscriptsandSubscripts"));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CURRENCY_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("Currency Symbols"));
+ assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CurrencySymbols"));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("COMBINING_MARKS_FOR_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Diacritical Marks for Symbols"));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningDiacriticalMarksforSymbols"));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Marks for Symbols"));
+ assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningMarksforSymbols"));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LETTERLIKE_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("Letterlike Symbols"));
+ assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LetterlikeSymbols"));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NUMBER_FORMS"));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("Number Forms"));
+ assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NumberForms"));
+ assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.forName("ARROWS"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MATHEMATICAL_OPERATORS"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Mathematical Operators"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MathematicalOperators"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MISCELLANEOUS_TECHNICAL"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("Miscellaneous Technical"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MiscellaneousTechnical"));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("CONTROL_PICTURES"));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("Control Pictures"));
+ assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("ControlPictures"));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OPTICAL_CHARACTER_RECOGNITION"));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("Optical Character Recognition"));
+ assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OpticalCharacterRecognition"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("ENCLOSED_ALPHANUMERICS"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("Enclosed Alphanumerics"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("EnclosedAlphanumerics"));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BOX_DRAWING"));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("Box Drawing"));
+ assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BoxDrawing"));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BLOCK_ELEMENTS"));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("Block Elements"));
+ assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BlockElements"));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GEOMETRIC_SHAPES"));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("Geometric Shapes"));
+ assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GeometricShapes"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("Miscellaneous Symbols"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MiscellaneousSymbols"));
+ assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.forName("DINGBATS"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-A"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("Supplemental Arrows-A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SupplementalArrows-A"));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BRAILLE_PATTERNS"));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("Braille Patterns"));
+ assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BraillePatterns"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_B"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("Supplemental Arrows-B"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SupplementalArrows-B"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-B"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-B"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SUPPLEMENTAL_MATHEMATICAL_OPERATORS"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Supplemental Mathematical Operators"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SupplementalMathematicalOperators"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS_AND_ARROWS"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("Miscellaneous Symbols and Arrows"));
+ assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MiscellaneousSymbolsandArrows"));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_RADICALS_SUPPLEMENT"));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Radicals Supplement"));
+ assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKRadicalsSupplement"));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KANGXI_RADICALS"));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("Kangxi Radicals"));
+ assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KangxiRadicals"));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IDEOGRAPHIC_DESCRIPTION_CHARACTERS"));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("Ideographic Description Characters"));
+ assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IdeographicDescriptionCharacters"));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK_SYMBOLS_AND_PUNCTUATION"));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK Symbols and Punctuation"));
+ assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJKSymbolsandPunctuation"));
+ assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.forName("HIRAGANA"));
+ assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.forName("KATAKANA"));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.forName("BOPOMOFO"));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HANGUL_COMPATIBILITY_JAMO"));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("Hangul Compatibility Jamo"));
+ assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HangulCompatibilityJamo"));
+ assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.forName("KANBUN"));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BOPOMOFO_EXTENDED"));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("Bopomofo Extended"));
+ assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BopomofoExtended"));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KATAKANA_PHONETIC_EXTENSIONS"));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Katakana Phonetic Extensions"));
+ assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KatakanaPhoneticExtensions"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("ENCLOSED_CJK_LETTERS_AND_MONTHS"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("Enclosed CJK Letters and Months"));
+ assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("EnclosedCJKLettersandMonths"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK_COMPATIBILITY"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK Compatibility"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJKCompatibility"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension A"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionA"));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YIJING_HEXAGRAM_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("Yijing Hexagram Symbols"));
+ assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YijingHexagramSymbols"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Unified Ideographs"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKUnifiedIdeographs"));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YI_SYLLABLES"));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("Yi Syllables"));
+ assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YiSyllables"));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YI_RADICALS"));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("Yi Radicals"));
+ assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YiRadicals"));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HANGUL_SYLLABLES"));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("Hangul Syllables"));
+ assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HangulSyllables"));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HIGH_SURROGATES"));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("High Surrogates"));
+ assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HighSurrogates"));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HIGH_PRIVATE_USE_SURROGATES"));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("High Private Use Surrogates"));
+ assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HighPrivateUseSurrogates"));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LOW_SURROGATES"));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("Low Surrogates"));
+ assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LowSurrogates"));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PRIVATE_USE_AREA"));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("Private Use Area"));
+ assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PrivateUseArea"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Compatibility Ideographs"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKCompatibilityIdeographs"));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("ALPHABETIC_PRESENTATION_FORMS"));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("Alphabetic Presentation Forms"));
+ assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("AlphabeticPresentationForms"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_A"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("Arabic Presentation Forms-A"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ArabicPresentationForms-A"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VARIATION_SELECTORS"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("Variation Selectors"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VariationSelectors"));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("COMBINING_HALF_MARKS"));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("Combining Half Marks"));
+ assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("CombiningHalfMarks"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_FORMS"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK Compatibility Forms"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJKCompatibilityForms"));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SMALL_FORM_VARIANTS"));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("Small Form Variants"));
+ assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SmallFormVariants"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_B"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("Arabic Presentation Forms-B"));
+ assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ArabicPresentationForms-B"));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HALFWIDTH_AND_FULLWIDTH_FORMS"));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("Halfwidth and Fullwidth Forms"));
+ assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HalfwidthandFullwidthForms"));
+ assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.forName("SPECIALS"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LINEAR_B_SYLLABARY"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("Linear B Syllabary"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LinearBSyllabary"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LINEAR_B_IDEOGRAMS"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("Linear B Ideograms"));
+ assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LinearBIdeograms"));
+ assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AEGEAN_NUMBERS"));
+ assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("Aegean Numbers"));
+ assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AegeanNumbers"));
+ assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OLD_ITALIC"));
+ assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("Old Italic"));
+ assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OldItalic"));
+ assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.forName("GOTHIC"));
+ assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.forName("UGARITIC"));
+ assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.forName("DESERET"));
+ assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.forName("SHAVIAN"));
+ assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.forName("OSMANYA"));
+ assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CYPRIOT_SYLLABARY"));
+ assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("Cypriot Syllabary"));
+ assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CypriotSyllabary"));
+ assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("BYZANTINE_MUSICAL_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Byzantine Musical Symbols"));
+ assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("ByzantineMusicalSymbols"));
+ assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MUSICAL_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Musical Symbols"));
+ assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MusicalSymbols"));
+ assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TAI_XUAN_JING_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("Tai Xuan Jing Symbols"));
+ assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TaiXuanJingSymbols"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MATHEMATICAL_ALPHANUMERIC_SYMBOLS"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("Mathematical Alphanumeric Symbols"));
+ assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MathematicalAlphanumericSymbols"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension B"));
+ assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionB"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Compatibility Ideographs Supplement"));
+ assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKCompatibilityIdeographsSupplement"));
+ assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.forName("TAGS"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VARIATION_SELECTORS_SUPPLEMENT"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("Variation Selectors Supplement"));
+ assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VariationSelectorsSupplement"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("Supplementary Private Use Area-A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-A"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_B"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("Supplementary Private Use Area-B"));
+ assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-B"));
+ }
+
+ public void test_forNameLjava_lang_StringExceptions() {
+ try {
+ Character.UnicodeBlock.forName(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ Character.UnicodeBlock.forName("INVALID_NAME");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ // We don't map "SURROGATES_AREA" to the deprecated SURROGATES_AREA
+ // enum value. ICU doesn't have any block corresponding to this since it's
+ // now split into low surrogates and the high (normal/private use)
+ // surrogates. Also, the only API that makes any reference to this goes
+ // directly to ICU anyway.
+ try {
+ Character.UnicodeBlock.forName("SURROGATES_AREA");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCastExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCastExceptionTest.java
new file mode 100644
index 0000000..2863bd6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCastExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ClassCastExceptionTest extends TestCase {
+
+ /**
+ * java.lang.ClassCastException#ClassCastException()
+ */
+ public void test_Constructor() {
+ ClassCastException e = new ClassCastException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCircularityErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCircularityErrorTest.java
new file mode 100644
index 0000000..54c5c4d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassCircularityErrorTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ClassCircularityErrorTest extends TestCase {
+ // Thrown when a circularity has been detected while initializing a class.
+
+ /**
+ * java.lang.ClassCircularityError#ClassCircularityError()
+ */
+ public void test_ClassCircularityError() {
+ new ClassCircularityError();
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassFormatErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassFormatErrorTest.java
new file mode 100644
index 0000000..f811c9a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassFormatErrorTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ClassFormatErrorTest extends TestCase {
+ /**
+ * 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.
+ */
+
+ /**
+ * java.lang.ClassFormatError#ClassFormatError()
+ */
+ public void test_ClassFormatError() {
+ new ClassFormatError();
+ }
+
+ /**
+ * 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());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassLoaderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassLoaderTest.java
new file mode 100644
index 0000000..2caab39
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassLoaderTest.java
@@ -0,0 +1,158 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+public class ClassLoaderTest extends TestCase {
+
+ /** A resource known to be present in the boot classpath. */
+ private static final String BOOT_RESOURCE_NAME = "java/util/logging/logging.properties";
+
+ /** A resource known to be present in the classpath associated with the test class. */
+ private static final String TEST_RESOURCE_NAME = ClassTest.RESOURCE_ABS_NAME;
+
+ private ClassLoader testClassLoader;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ testClassLoader = getClass().getClassLoader();
+ }
+
+ /**
+ * java.lang.ClassLoader#getSystemClassLoader()
+ */
+ public void test_getSystemClassLoader() {
+ // Test for method java.lang.ClassLoader
+ // java.lang.ClassLoader.getSystemClassLoader()
+ ClassLoader cl = ClassLoader.getSystemClassLoader();
+ assertNotNull(cl);
+
+ // The SystemClassLoader's parent should be the Boot classloader, which is used to load
+ // the various libcore classes.
+ assertNotNull(cl.getParent());
+ Class<?> libcoreClass = Integer.class;
+ assertSame(cl.getParent(), libcoreClass.getClassLoader());
+
+ // It is difficult to test further because the CTS tests run as an instrumented TestCase.
+ // Android apps do not have a system classpath, and rely on an application classloader to
+ // load app classes and resources, not the System ClassLoader. The System ClassLoader is not
+ // usually the parent of the application class loader.
+ }
+
+ /**
+ * java.lang.ClassLoader#getSystemResource(java.lang.String)
+ */
+ public void test_getSystemResourceLjava_lang_String() {
+ // Test for method java.net.URL
+ // java.lang.ClassLoader.getSystemResource(java.lang.String)
+
+ // It is difficult to test this because the CTS tests run as an instrumented TestCase.
+ // Android apps do not have a system classpath, and rely on an application classloader to
+ // load app classes and resources, not the System ClassLoader.
+ }
+
+ /**
+ * java.lang.ClassLoader#getResource(java.lang.String)
+ */
+ public void test_testClassLoader_getResourceLjava_lang_String() {
+ // Test for method java.net.URL
+ // java.lang.ClassLoader.getResource(java.lang.String)
+
+ // Test basic class loader behavior for the ClassLoader that was used to load the test
+ // class while being deliberately vague about which classloader it actually is.
+
+ ClassLoader parentClassLoader = testClassLoader.getParent();
+ assertNull(parentClassLoader.getResource(TEST_RESOURCE_NAME));
+ assertGetResourceIsValid(parentClassLoader, BOOT_RESOURCE_NAME);
+
+ assertGetResourceIsValid(testClassLoader, TEST_RESOURCE_NAME);
+ assertGetResourceIsValid(testClassLoader, BOOT_RESOURCE_NAME);
+ }
+
+ /**
+ * java.lang.ClassLoader#getResourceAsStream(java.lang.String)
+ */
+ public void test_testClassLoader_getResourceAsStreamLjava_lang_String() throws Exception {
+ // Test for method java.io.InputStream
+ // java.lang.ClassLoader.getResourceAsStream(java.lang.String)
+
+ // Test basic class loader behavior for the ClassLoader that was used to load the test
+ // class while being deliberately vague about which classloader it actually is.
+
+ ClassLoader parentClassLoader = testClassLoader.getParent();
+ assertGetResourceAsStreamNotNull(parentClassLoader, BOOT_RESOURCE_NAME);
+ assertNull(parentClassLoader.getResourceAsStream(TEST_RESOURCE_NAME));
+
+ assertGetResourceAsStreamNotNull(testClassLoader, BOOT_RESOURCE_NAME);
+ assertGetResourceAsStreamNotNull(testClassLoader, TEST_RESOURCE_NAME);
+ }
+
+ public void test_testClassLoader_loadClass() throws Exception {
+ // Test basic class loader behavior for the ClassLoader that was used to load the test
+ // class while being deliberately vague about which classloader it actually is.
+ String integerClassName = Integer.class.getName();
+ String testClassName = ClassLoaderTest.class.getName();
+
+ ClassLoader parentClassLoader = testClassLoader.getParent();
+ assertSame(Integer.class, parentClassLoader.loadClass(integerClassName));
+ try {
+ parentClassLoader.loadClass(testClassName);
+ fail();
+ } catch (ClassNotFoundException expected) {
+ }
+
+ assertSame(Integer.class, testClassLoader.loadClass(integerClassName));
+ assertSame(this.getClass(), testClassLoader.loadClass(testClassName));
+ }
+
+ //Regression Test for JIRA-2047
+ public void test_testClassLoader_getResourceAsStream_withSharpChar() throws Exception {
+ assertGetResourceAsStreamNotNull(testClassLoader, ClassTest.SHARP_RESOURCE_ABS_NAME);
+ }
+
+ private static void assertGetResourceAsStreamNotNull(ClassLoader classLoader,
+ String resourceName) throws IOException {
+ InputStream is = null;
+ try {
+ is = classLoader.getResourceAsStream(resourceName);
+ assertNotNull(is);
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+
+ private static void assertGetResourceIsValid(ClassLoader classLoader, String resourceName) {
+ java.net.URL u = classLoader.getResource(resourceName);
+ assertNotNull(u);
+ InputStream is = null;
+ try {
+ is = u.openStream();
+ assertNotNull(is);
+ is.close();
+ } catch (IOException e) {
+ fail("IOException getting stream for resource : " + e.getMessage());
+ }
+ }
+} \ No newline at end of file
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassNotFoundExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassNotFoundExceptionTest.java
new file mode 100644
index 0000000..e199aa2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassNotFoundExceptionTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+public class ClassNotFoundExceptionTest extends TestCase {
+ /**
+ * Thrown when an application tries to load in a class through its string
+ * name using the forName method in class Class.
+ */
+
+ /**
+ * java.lang.ClassNotFoundException#ClassNotFoundException()
+ */
+ public void test_Constructor() {
+ ClassNotFoundException e = new ClassNotFoundException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassTest.java
new file mode 100644
index 0000000..379dad2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ClassTest.java
@@ -0,0 +1,642 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.BasicPermission;
+import java.security.DomainCombiner;
+import java.security.Permission;
+import java.security.ProtectionDomain;
+import java.security.Security;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Vector;
+
+public class ClassTest extends junit.framework.TestCase {
+
+ // Relative resource paths.
+ private static final String SHARP_RESOURCE_RELATIVE_NAME = "test#.properties";
+ private static final String RESOURCE_RELATIVE_NAME = "test.properties";
+
+ // Absolute resource paths.
+ private static final String ABS_PATH =
+ ClassTest.class.getPackage().getName().replace('.', '/');
+ public static final String SHARP_RESOURCE_ABS_NAME =
+ ABS_PATH + "/" + SHARP_RESOURCE_RELATIVE_NAME;
+ public static final String RESOURCE_ABS_NAME = ABS_PATH + "/" + RESOURCE_RELATIVE_NAME;
+
+ public static class TestClass {
+ @SuppressWarnings("unused")
+ private int privField = 1;
+
+ public int pubField = 2;
+
+ private Object cValue = null;
+
+ public Object ack = new Object();
+
+ @SuppressWarnings("unused")
+ private int privMethod() {
+ return 1;
+ }
+
+ public int pubMethod() {
+ return 2;
+ }
+
+ public Object cValue() {
+ return cValue;
+ }
+
+ public TestClass() {
+ }
+
+ @SuppressWarnings("unused")
+ private TestClass(Object o) {
+ }
+ }
+
+ public static class SubTestClass extends TestClass {
+ }
+
+ /**
+ * java.lang.Class#forName(java.lang.String)
+ */
+ public void test_forNameLjava_lang_String() throws Exception {
+ assertSame("Class for name failed for java.lang.Object",
+ Object.class, Class.forName("java.lang.Object"));
+ assertSame("Class for name failed for [[Ljava.lang.Object;",
+ Object[][].class, Class.forName("[[Ljava.lang.Object;"));
+
+ assertSame("Class for name failed for [I",
+ int[].class, Class.forName("[I"));
+
+ try {
+ Class.forName("int");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+
+ try {
+ Class.forName("byte");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+ try {
+ Class.forName("char");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+
+ try {
+ Class.forName("void");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+
+ try {
+ Class.forName("short");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+ try {
+ Class.forName("long");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+
+ try {
+ Class.forName("boolean");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+ try {
+ Class.forName("float");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+ try {
+ Class.forName("double");
+ fail();
+ } catch (ClassNotFoundException e) {
+ }
+
+ //regression test for JIRA 2162
+ try {
+ Class.forName("%");
+ fail("should throw ClassNotFoundException.");
+ } catch (ClassNotFoundException e) {
+ }
+
+ //Regression Test for HARMONY-3332
+ String securityProviderClassName;
+ int count = 1;
+ while ((securityProviderClassName = Security
+ .getProperty("security.provider." + count++)) != null) {
+ Class.forName(securityProviderClassName);
+ }
+ }
+
+ /**
+ * java.lang.Class#getClasses()
+ */
+ public void test_getClasses() {
+ assertEquals("Incorrect class array returned",
+ 2, ClassTest.class.getClasses().length);
+ }
+
+ /**
+ * java.lang.Class#getClasses()
+ */
+ public void test_getClasses_subtest0() {
+ final Permission privCheckPermission = new BasicPermission("Privilege check") {
+ private static final long serialVersionUID = 1L;
+ };
+
+ class MyCombiner implements DomainCombiner {
+ boolean combine;
+
+ public ProtectionDomain[] combine(ProtectionDomain[] executionDomains,
+ ProtectionDomain[] parentDomains) {
+ combine = true;
+ return new ProtectionDomain[0];
+ }
+
+ private boolean recurring = false;
+
+ public boolean isPriviledged() {
+ if (recurring) {
+ return true;
+ }
+ try {
+ recurring = true;
+ combine = false;
+ try {
+ AccessController.checkPermission(privCheckPermission);
+ } catch (SecurityException e) {
+ }
+ return !combine;
+ } finally {
+ recurring = false;
+ }
+ }
+ }
+ }
+
+ /**
+ * java.lang.Class#getComponentType()
+ */
+ public void test_getComponentType() {
+ assertSame("int array does not have int component type", int.class, int[].class
+ .getComponentType());
+ assertSame("Object array does not have Object component type", Object.class,
+ Object[].class.getComponentType());
+ assertNull("Object has non-null component type", Object.class.getComponentType());
+ }
+
+ /**
+ * java.lang.Class#getConstructor(java.lang.Class[])
+ */
+ public void test_getConstructor$Ljava_lang_Class()
+ throws NoSuchMethodException {
+ TestClass.class.getConstructor(new Class[0]);
+ try {
+ TestClass.class.getConstructor(Object.class);
+ fail("Found private constructor");
+ } catch (NoSuchMethodException e) {
+ // Correct - constructor with obj is private
+ }
+ }
+
+ /**
+ * java.lang.Class#getConstructors()
+ */
+ public void test_getConstructors() throws Exception {
+ Constructor[] c = TestClass.class.getConstructors();
+ assertEquals("Incorrect number of constructors returned", 1, c.length);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredClasses()
+ */
+ public void test_getDeclaredClasses() {
+ assertEquals("Incorrect class array returned", 2, ClassTest.class.getClasses().length);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredConstructor(java.lang.Class[])
+ */
+ public void test_getDeclaredConstructor$Ljava_lang_Class() throws Exception {
+ Constructor<TestClass> c = TestClass.class.getDeclaredConstructor(new Class[0]);
+ assertNull("Incorrect constructor returned", c.newInstance().cValue());
+ c = TestClass.class.getDeclaredConstructor(Object.class);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredConstructors()
+ */
+ public void test_getDeclaredConstructors() throws Exception {
+ Constructor[] c = TestClass.class.getDeclaredConstructors();
+ assertEquals("Incorrect number of constructors returned", 2, c.length);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredField(java.lang.String)
+ */
+ public void test_getDeclaredFieldLjava_lang_String() throws Exception {
+ Field f = TestClass.class.getDeclaredField("pubField");
+ assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
+ }
+
+ /**
+ * java.lang.Class#getDeclaredFields()
+ */
+ public void test_getDeclaredFields() throws Exception {
+ Field[] f = TestClass.class.getDeclaredFields();
+ assertEquals("Returned incorrect number of fields", 4, f.length);
+ f = SubTestClass.class.getDeclaredFields();
+ // Declared fields do not include inherited
+ assertEquals("Returned incorrect number of fields", 0, f.length);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredMethod(java.lang.String,
+ *java.lang.Class[])
+ */
+ public void test_getDeclaredMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
+ Method m = TestClass.class.getDeclaredMethod("pubMethod", new Class[0]);
+ assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
+ .intValue());
+ m = TestClass.class.getDeclaredMethod("privMethod", new Class[0]);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredMethods()
+ */
+ public void test_getDeclaredMethods() throws Exception {
+ Method[] m = TestClass.class.getDeclaredMethods();
+ assertEquals("Returned incorrect number of methods", 3, m.length);
+ m = SubTestClass.class.getDeclaredMethods();
+ assertEquals("Returned incorrect number of methods", 0, m.length);
+ }
+
+ /**
+ * java.lang.Class#getDeclaringClass()
+ */
+ public void test_getDeclaringClass() {
+ assertEquals(ClassTest.class, TestClass.class.getDeclaringClass());
+ }
+
+ /**
+ * java.lang.Class#getField(java.lang.String)
+ */
+ public void test_getFieldLjava_lang_String() throws Exception {
+ Field f = TestClass.class.getField("pubField");
+ assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
+ try {
+ f = TestClass.class.getField("privField");
+ fail("Private field access failed to throw exception");
+ } catch (NoSuchFieldException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * java.lang.Class#getFields()
+ */
+ public void test_getFields() throws Exception {
+ Field[] f = TestClass.class.getFields();
+ assertEquals("Incorrect number of fields", 2, f.length);
+ f = SubTestClass.class.getFields();
+ // Check inheritance of pub fields
+ assertEquals("Incorrect number of fields", 2, f.length);
+ }
+
+ /**
+ * java.lang.Class#getInterfaces()
+ */
+ public void test_getInterfaces() {
+ Class[] interfaces;
+ List<?> interfaceList;
+ interfaces = Object.class.getInterfaces();
+ assertEquals("Incorrect interface list for Object", 0, interfaces.length);
+ interfaceList = Arrays.asList(Vector.class.getInterfaces());
+ assertTrue("Incorrect interface list for Vector", interfaceList
+ .contains(Cloneable.class)
+ && interfaceList.contains(Serializable.class)
+ && interfaceList.contains(List.class));
+ }
+
+ /**
+ * java.lang.Class#getMethod(java.lang.String, java.lang.Class[])
+ */
+ public void test_getMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
+ Method m = TestClass.class.getMethod("pubMethod", new Class[0]);
+ assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
+ .intValue());
+ try {
+ m = TestClass.class.getMethod("privMethod", new Class[0]);
+ fail("Failed to throw exception accessing private method");
+ } catch (NoSuchMethodException e) {
+ // Correct
+ return;
+ }
+ }
+
+ /**
+ * java.lang.Class#getMethods()
+ */
+ public void test_getMethods() throws Exception {
+ Method[] m = TestClass.class.getMethods();
+ assertEquals("Returned incorrect number of methods",
+ 2 + Object.class.getMethods().length, m.length);
+ m = SubTestClass.class.getMethods();
+ assertEquals("Returned incorrect number of sub-class methods",
+ 2 + Object.class.getMethods().length, m.length);
+ // Number of inherited methods
+ }
+
+ private static final class PrivateClass {
+ }
+
+ /**
+ * java.lang.Class#getModifiers()
+ */
+ public void test_getModifiers() {
+ int dcm = PrivateClass.class.getModifiers();
+ assertFalse("default class is public", Modifier.isPublic(dcm));
+ assertFalse("default class is protected", Modifier.isProtected(dcm));
+ assertTrue("default class is not private", Modifier.isPrivate(dcm));
+
+ int ocm = Object.class.getModifiers();
+ assertTrue("public class is not public", Modifier.isPublic(ocm));
+ assertFalse("public class is protected", Modifier.isProtected(ocm));
+ assertFalse("public class is private", Modifier.isPrivate(ocm));
+ }
+
+ /**
+ * java.lang.Class#getName()
+ */
+ public void test_getName() throws Exception {
+ String className = Class.forName("java.lang.Object").getName();
+ assertNotNull(className);
+
+ assertEquals("Class getName printed wrong value", "java.lang.Object", className);
+ assertEquals("Class getName printed wrong value", "int", int.class.getName());
+ className = Class.forName("[I").getName();
+ assertNotNull(className);
+ assertEquals("Class getName printed wrong value", "[I", className);
+
+ className = Class.forName("[Ljava.lang.Object;").getName();
+ assertNotNull(className);
+
+ assertEquals("Class getName printed wrong value", "[Ljava.lang.Object;", className);
+ }
+
+ /**
+ * java.lang.Class#getResource(java.lang.String)
+ */
+ public void test_getResourceLjava_lang_String() {
+ final String name = "/resources/test_resource.txt";
+ URL res = getClass().getResource(name);
+ assertNotNull(res);
+ }
+
+ /**
+ * java.lang.Class#getResourceAsStream(java.lang.String)
+ */
+ public void test_getResourceAsStreamLjava_lang_String() throws Exception {
+ final String name = "/resources/test_resource.txt";
+ InputStream str2 = getClass().getResourceAsStream(name);
+ assertNotNull("the file " + name + " can not be found in this directory", str2);
+
+ final String nameBadURI = "org/apache/harmony/luni/tests/test_resource.txt";
+ assertNull("the file " + nameBadURI + " should not be found in this directory",
+ getClass().getResourceAsStream(nameBadURI));
+
+ assertTrue("Cannot read single byte", str2.read() != -1);
+ assertEquals("Cannot read multiple bytes", 5, str2.read(new byte[5]));
+ str2.close();
+ }
+
+ /**
+ * java.lang.Class#getSuperclass()
+ */
+ public void test_getSuperclass() {
+ assertNull("Object has a superclass???", Object.class.getSuperclass());
+ assertSame("Normal class has bogus superclass", InputStream.class,
+ FileInputStream.class.getSuperclass());
+ assertSame("Array class has bogus superclass", Object.class, FileInputStream[].class
+ .getSuperclass());
+ assertNull("Base class has a superclass", int.class.getSuperclass());
+ assertNull("Interface class has a superclass", Cloneable.class.getSuperclass());
+ }
+
+ /**
+ * java.lang.Class#isArray()
+ */
+ public void test_isArray() throws ClassNotFoundException {
+ assertTrue("Non-array type claims to be.", !int.class.isArray());
+ Class<?> clazz = null;
+ clazz = Class.forName("[I");
+ assertTrue("int Array type claims not to be.", clazz.isArray());
+
+ clazz = Class.forName("[Ljava.lang.Object;");
+ assertTrue("Object Array type claims not to be.", clazz.isArray());
+
+ clazz = Class.forName("java.lang.Object");
+ assertTrue("Non-array Object type claims to be.", !clazz.isArray());
+ }
+
+ /**
+ * java.lang.Class#isAssignableFrom(java.lang.Class)
+ */
+ public void test_isAssignableFromLjava_lang_Class() {
+ Class<?> clazz1 = null;
+ Class<?> clazz2 = null;
+
+ clazz1 = Object.class;
+ clazz2 = Class.class;
+ assertTrue("returned false for superclass", clazz1.isAssignableFrom(clazz2));
+
+ clazz1 = TestClass.class;
+ assertTrue("returned false for same class", clazz1.isAssignableFrom(clazz1));
+
+ clazz1 = Runnable.class;
+ clazz2 = Thread.class;
+ assertTrue("returned false for implemented interface", clazz1.isAssignableFrom(clazz2));
+ }
+
+ /**
+ * java.lang.Class#isInterface()
+ */
+ public void test_isInterface() throws ClassNotFoundException {
+ assertTrue("Prim type claims to be interface.", !int.class.isInterface());
+ Class<?> clazz = null;
+ clazz = Class.forName("[I");
+ assertTrue("Prim Array type claims to be interface.", !clazz.isInterface());
+
+ clazz = Class.forName("java.lang.Runnable");
+ assertTrue("Interface type claims not to be interface.", clazz.isInterface());
+ clazz = Class.forName("java.lang.Object");
+ assertTrue("Object type claims to be interface.", !clazz.isInterface());
+
+ clazz = Class.forName("[Ljava.lang.Object;");
+ assertTrue("Array type claims to be interface.", !clazz.isInterface());
+ }
+
+ /**
+ * java.lang.Class#isPrimitive()
+ */
+ public void test_isPrimitive() {
+ assertFalse("Interface type claims to be primitive.", Runnable.class.isPrimitive());
+ assertFalse("Object type claims to be primitive.", Object.class.isPrimitive());
+ assertFalse("Prim Array type claims to be primitive.", int[].class.isPrimitive());
+ assertFalse("Array type claims to be primitive.", Object[].class.isPrimitive());
+ assertTrue("Prim type claims not to be primitive.", int.class.isPrimitive());
+ assertFalse("Object type claims to be primitive.", Object.class.isPrimitive());
+ }
+
+ /**
+ * java.lang.Class#newInstance()
+ */
+ public void test_newInstance() throws Exception {
+ Class<?> clazz = null;
+ clazz = Class.forName("java.lang.Object");
+ assertNotNull("new object instance was null", clazz.newInstance());
+
+ clazz = Class.forName("java.lang.Throwable");
+ assertSame("new Throwable instance was not a throwable",
+ clazz, clazz.newInstance().getClass());
+
+ clazz = Class.forName("java.lang.Integer");
+ try {
+ clazz.newInstance();
+ fail("Exception for instantiating a newInstance with no default constructor is not thrown");
+ } catch (InstantiationException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.Class#toString()
+ */
+ public void test_toString() throws ClassNotFoundException {
+ assertEquals("Class toString printed wrong value",
+ "int", int.class.toString());
+ Class<?> clazz = null;
+ clazz = Class.forName("[I");
+ assertEquals("Class toString printed wrong value",
+ "class [I", clazz.toString());
+
+ clazz = Class.forName("java.lang.Object");
+ assertEquals("Class toString printed wrong value",
+ "class java.lang.Object", clazz.toString());
+
+ clazz = Class.forName("[Ljava.lang.Object;");
+ assertEquals("Class toString printed wrong value",
+ "class [Ljava.lang.Object;", clazz.toString());
+ }
+
+
+ // Regression Test for JIRA-2047
+ public void test_getResourceAsStream_withSharpChar() throws Exception {
+ // Class.getResourceAsStream() requires a leading "/" for absolute paths.
+ assertNull(getClass().getResourceAsStream(SHARP_RESOURCE_ABS_NAME));
+ assertResourceExists("/" + SHARP_RESOURCE_ABS_NAME);
+ assertResourceExists(SHARP_RESOURCE_RELATIVE_NAME);
+
+
+ InputStream in =
+ this.getClass().getClassLoader().getResourceAsStream(SHARP_RESOURCE_ABS_NAME);
+ assertNotNull(in);
+ in.close();
+ }
+
+ public void test_getResourceAsStream() throws Exception {
+ // Class.getResourceAsStream() requires a leading "/" for absolute paths.
+ assertNull(getClass().getResourceAsStream(RESOURCE_ABS_NAME));
+ assertResourceExists("/" + RESOURCE_ABS_NAME);
+ assertResourceExists(RESOURCE_RELATIVE_NAME);
+
+ InputStream in = this.getClass().getClassLoader().getResourceAsStream(RESOURCE_ABS_NAME);
+ assertNotNull(in);
+ in.close();
+ }
+
+ private void assertResourceExists(String resourceName) throws IOException {
+ InputStream in = getClass().getResourceAsStream(resourceName);
+ assertNotNull(in);
+ in.close();
+ }
+
+ /*
+ * Regression test for HARMONY-2644:
+ * Load system and non-system array classes via Class.forName()
+ */
+ public void test_forName_arrays() throws Exception {
+ Class c1 = getClass();
+ String s = c1.getName();
+ Class a1 = Class.forName("[L" + s + ";");
+ Class a2 = Class.forName("[[L" + s + ";");
+ assertSame(c1, a1.getComponentType());
+ assertSame(a1, a2.getComponentType());
+ Class l4 = Class.forName("[[[[[J");
+ assertSame(long[][][][][].class, l4);
+
+ try {
+ System.out.println(Class.forName("[;"));
+ fail("1");
+ } catch (ClassNotFoundException ok) {
+ }
+ try {
+ System.out.println(Class.forName("[["));
+ fail("2");
+ } catch (ClassNotFoundException ok) {
+ }
+ try {
+ System.out.println(Class.forName("[L"));
+ fail("3");
+ } catch (ClassNotFoundException ok) {
+ }
+ try {
+ System.out.println(Class.forName("[L;"));
+ fail("4");
+ } catch (ClassNotFoundException ok) {
+ }
+ try {
+ System.out.println(Class.forName(";"));
+ fail("5");
+ } catch (ClassNotFoundException ok) {
+ }
+ try {
+ System.out.println(Class.forName(""));
+ fail("6");
+ } catch (ClassNotFoundException ok) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CloneNotSupportedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CloneNotSupportedExceptionTest.java
new file mode 100644
index 0000000..0af1dbc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CloneNotSupportedExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class CloneNotSupportedExceptionTest extends TestCase {
+
+ /**
+ * java.lang.CloneNotSupportedException#CloneNotSupportedException()
+ */
+ public void test_Constructor() {
+ CloneNotSupportedException e = new CloneNotSupportedException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CompilerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CompilerTest.java
new file mode 100644
index 0000000..8584ce4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/CompilerTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class CompilerTest extends TestCase {
+
+ /**
+ * java.lang.Compiler#command(java.lang.Object)
+ */
+ public void test_commandLjava_lang_Object() {
+ assertNull("Incorrect behavior.", Compiler.command(new Object()));
+ }
+
+ /**
+ * java.lang.Compiler#compileClass(java.lang.Class)
+ */
+ public void test_compileClassLjava_lang_Class() {
+ // 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);
+ }
+
+ /**
+ * java.lang.Compiler#compileClasses(java.lang.String)
+ */
+ public void test_compileClassesLjava_lang_String() {
+ // 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");
+ }
+
+ /**
+ * java.lang.Compiler#disable()
+ */
+ public void test_disable() {
+ Compiler.disable();
+ Compiler.compileClass(Compiler.class);
+ }
+
+ /**
+ * java.lang.Compiler#enable()
+ */
+ public void test_enable() {
+ Compiler.disable();
+ Compiler.enable();
+ Compiler.compileClass(Compiler.class);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/DoubleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/DoubleTest.java
new file mode 100644
index 0000000..79d81e8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/DoubleTest.java
@@ -0,0 +1,1444 @@
+/* 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.tests.java.lang;
+
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+public class DoubleTest extends TestCase {
+ private static final long rawBitsFor3_4en324ToN1[] = { 0x1L, 0x7L, 0x45L, 0x2b0L, 0x1ae2L,
+ 0x10cd1L, 0xa8028L, 0x69018dL, 0x41a0f7eL, 0x29049aedL, 0x19a2e0d44L,
+ 0x1005cc84acL, 0xa039fd2ebdL, 0x64243e3d361L, 0x3e96a6e641c6L, 0x271e284fe91b8L,
+ 0x1872d931f1b131L, 0x4e8f8f7e6e1d7dL, 0x8319b9af04d26eL, 0xb7e0281ac6070aL,
+ 0xedd832217788ccL, 0x122a71f54eab580L, 0x15750e72a2562e0L, 0x18d2520f4aebb98L,
+ 0x1c2373498ed353fL, 0x1f6c501bf28828eL, 0x22c76422ef2a332L, 0x261c9e95d57a5ffL,
+ 0x2963c63b4ad8f7fL, 0x2cbcb7ca1d8f35fL, 0x3015f2de527981bL, 0x335b6f95e717e22L,
+ 0x36b24b7b60dddabL, 0x3a0f6f2d1c8aa8bL, 0x3d534af863ad52dL, 0x40a81db67c98a79L,
+ 0x440912920ddf68bL, 0x474b5736915742eL, 0x4a9e2d0435ad13aL, 0x4e02dc22a18c2c4L,
+ 0x5143932b49ef375L, 0x549477f61c6b052L, 0x57f995f3a385c67L, 0x5b3bfdb846339c0L,
+ 0x5e8afd2657c0830L, 0x61edbc6fedb0a3dL, 0x653495c5f48e666L, 0x6881bb3771b1fffL,
+ 0x6be22a054e1e7ffL, 0x6f2d5a4350d30ffL, 0x7278b0d42507d3fL, 0x75d6dd092e49c8fL,
+ 0x79264a25bcee1daL, 0x7c6fdcaf2c29a50L, 0x7fcbd3daf7340e4L, 0x831f6468da8088eL,
+ 0x86673d831120ab2L, 0x89c10ce3d568d5fL, 0x8d18a80e656185bL, 0x905ed211feb9e72L,
+ 0x93b686967e6860eL, 0x9712141e0f013c9L, 0x9a56992592c18bbL, 0x9dac3f6ef771eeaL,
+ 0xa10ba7a55aa7352L, 0xa44e918eb151027L, 0xa7a235f25da5430L, 0xab0561b77a8749eL,
+ 0xae46ba2559291c6L, 0xb19868aeaf73637L, 0xb4fe82da5b503c5L, 0xb83f11c8791225bL,
+ 0xbb8ed63a9756af2L, 0xbef28bc93d2c5afL, 0xc237975dc63bb8dL, 0xc5857d3537caa70L,
+ 0xc8e6dc8285bd50cL, 0xcc3049d19396528L, 0xcf7c5c45f87be72L, 0xd2db7357769ae0eL,
+ 0xd6292816aa20cc9L, 0xd973721c54a8ffbL, 0xdcd04ea369d33faL, 0xe0223126222407cL,
+ 0xe36abd6faaad09bL, 0xe6c56ccb95584c2L, 0xea1b63ff3d572f9L, 0xed623cff0cacfb8L,
+ 0xf0bacc3ecfd83a5L, 0xf414bfa741e7247L, 0xf759ef911260ed9L, 0xfab06b7556f9290L,
+ 0xfe0e4329565bb9aL, 0x10151d3f3abf2a80L, 0x104a648f096ef520L, 0x10807ed965e55934L,
+ 0x10b49e8fbf5eaf81L, 0x10e9c633af365b61L, 0x11201be04d81f91dL, 0x115422d860e27764L,
+ 0x11892b8e791b153dL, 0x11bf76721761da8cL, 0x11f3aa074e9d2898L, 0x12289489224472beL,
+ 0x125eb9ab6ad58f6dL, 0x1293340b22c579a4L, 0x12c8010deb76d80dL, 0x12fe015166548e11L,
+ 0x1332c0d2dff4d8caL, 0x1367710797f20efdL, 0x139d4d497dee92bcL, 0x13d2504deeb51bb6L,
+ 0x1406e4616a6262a3L, 0x143c9d79c4fafb4cL, 0x1471e26c1b1cdd0fL, 0x14a65b0721e41453L,
+ 0x14dbf1c8ea5d1968L, 0x1511771d927a2fe1L, 0x1545d4e4f718bbd9L, 0x157b4a1e34deead0L,
+ 0x15b10e52e10b52c2L, 0x15e551e7994e2772L, 0x161aa6617fa1b14fL, 0x1650a7fcefc50ed1L,
+ 0x1684d1fc2bb65286L, 0x16ba067b36a3e727L, 0x16f0440d02267078L, 0x1724551042b00c96L,
+ 0x17596a54535c0fbcL, 0x178fc4e9683313abL, 0x17c3db11e11fec4bL, 0x17f8d1d65967e75eL,
+ 0x182f064befc1e135L, 0x186363ef75d92cc1L, 0x18983ceb534f77f1L, 0x18ce4c26282355eeL,
+ 0x1902ef97d91615b5L, 0x1937ab7dcf5b9b22L, 0x196d965d433281eaL, 0x19a27dfa49ff9132L,
+ 0x19d71d78dc7f757fL, 0x1a0ce4d7139f52dfL, 0x1a420f066c4393cbL, 0x1a7692c8075478beL,
+ 0x1aac377a092996edL, 0x1ae1a2ac45b9fe54L, 0x1b160b5757287de9L, 0x1b4b8e2d2cf29d64L,
+ 0x1b8138dc3c17a25eL, 0x1bb587134b1d8af6L, 0x1beae8d81de4edb4L, 0x1c20d18712af1490L,
+ 0x1c5505e8d75ad9b4L, 0x1c8a47630d319021L, 0x1cc06c9de83efa15L, 0x1cf487c5624eb89aL,
+ 0x1d29a9b6bae266c1L, 0x1d600a1234cd8038L, 0x1d940c96c200e046L, 0x1dc90fbc72811858L,
+ 0x1dff53ab8f215e6eL, 0x1e33944b3974db05L, 0x1e68795e07d211c6L, 0x1e9e97b589c69637L,
+ 0x1ed31ed1761c1de3L, 0x1f07e685d3a3255bL, 0x1f3de027488beeb2L, 0x1f72ac188d57752fL,
+ 0x1fa7571eb0ad527bL, 0x1fdd2ce65cd8a71aL, 0x20123c0ffa076870L, 0x2046cb13f889428cL,
+ 0x207c7dd8f6ab932fL, 0x20b1cea79a2b3bfeL, 0x20e6425180b60afdL, 0x211bd2e5e0e38dbcL,
+ 0x215163cfac8e3896L, 0x2185bcc397b1c6bbL, 0x21bb2bf47d9e386aL, 0x21f0fb78ce82e342L,
+ 0x22253a5702239c13L, 0x225a88ecc2ac8317L, 0x22909593f9abd1efL, 0x22c4baf8f816c66aL,
+ 0x22f9e9b7361c7805L, 0x2330321281d1cb03L, 0x23643e9722463dc4L, 0x23994e3cead7cd35L,
+ 0x23cfa1cc258dc082L, 0x2403c51f97789851L, 0x2438b6677d56be65L, 0x246ee4015cac6dffL,
+ 0x24a34e80d9ebc4bfL, 0x24d822211066b5efL, 0x250e2aa95480636bL, 0x2542daa9d4d03e23L,
+ 0x257791544a044dabL, 0x25ad75a95c856116L, 0x25e26989d9d35caeL, 0x261703ec504833d9L,
+ 0x264cc4e7645a40d0L, 0x2681fb109eb86882L, 0x26b679d4c66682a2L, 0x26ec1849f800234bL,
+ 0x27218f2e3b00160fL, 0x2755f2f9c9c01b93L, 0x278b6fb83c302277L, 0x27c125d3259e158bL,
+ 0x27f56f47ef059aedL, 0x282acb19eac701a8L, 0x2860bef032bc6109L, 0x2894eeac3f6b794cL,
+ 0x28ca2a574f46579eL, 0x29005a76918bf6c3L, 0x2934711435eef474L, 0x29698d59436ab191L,
+ 0x299ff0af94455df5L, 0x29d3f66dbcab5ab9L, 0x2a08f4092bd63167L, 0x2a3f310b76cbbdc1L,
+ 0x2a737ea72a3f5699L, 0x2aa85e50f4cf2c3fL, 0x2ade75e53202f74fL, 0x2b1309af3f41da91L,
+ 0x2b47cc1b0f125135L, 0x2b7dbf21d2d6e583L, 0x2bb2977523c64f72L, 0x2be73d526cb7e34eL,
+ 0x2c1d0ca707e5dc22L, 0x2c5227e864efa995L, 0x2c86b1e27e2b93faL, 0x2cbc5e5b1db678f9L,
+ 0x2cf1baf8f2920b9cL, 0x2d2629b72f368e83L, 0x2d5bb424fb043223L, 0x2d9150971ce29f56L,
+ 0x2dc5a4bce41b472bL, 0x2dfb0dec1d2218f6L, 0x2e30e8b392354f9aL, 0x2e6522e076c2a380L,
+ 0x2e9a6b9894734c61L, 0x2ed0833f5cc80fbcL, 0x2f04a40f33fa13abL, 0x2f39cd1300f89896L,
+ 0x2f70202be09b5f5eL, 0x2fa42836d8c23735L, 0x2fd932448ef2c503L, 0x300f7ed5b2af7643L,
+ 0x3043af458fada9eaL, 0x30789b16f3991465L, 0x30aec1dcb07f597eL, 0x30e33929ee4f97efL,
+ 0x3118077469e37deaL, 0x314e0951845c5d65L, 0x3182c5d2f2b9ba5fL, 0x31b77747af6828f7L,
+ 0x31ed55199b423335L, 0x3222553001096001L, 0x3256ea7c014bb801L, 0x328ca51b019ea601L,
+ 0x32c1e730e10327c1L, 0x32f660fd1943f1b1L, 0x332bf93c5f94ee1dL, 0x33617bc5bbbd14d2L,
+ 0x3395dab72aac5a07L, 0x33cb5164f5577089L, 0x340112df1956a655L, 0x34355796dfac4febL,
+ 0x346aad7c979763e5L, 0x34a0ac6ddebe9e6fL, 0x34d4d789566e460bL, 0x350a0d6bac09d78eL,
+ 0x354048634b8626b9L, 0x35745a7c1e67b067L, 0x35a9711b26019c81L, 0x35dfcd61ef8203a1L,
+ 0x3613e05d35b14245L, 0x3648d874831d92d6L, 0x367f0e91a3e4f78bL, 0x36b3691b066f1ab7L,
+ 0x36e84361c80ae165L, 0x371e543a3a0d99beL, 0x3752f4a464488017L, 0x3787b1cd7d5aa01cL,
+ 0x37bd9e40dcb14823L, 0x37f282e889eecd16L, 0x382723a2ac6a805cL, 0x385cec8b57852073L,
+ 0x389213d716b33448L, 0x38c698ccdc60015aL, 0x38fc3f00137801b0L, 0x3931a7600c2b010eL,
+ 0x396611380f35c151L, 0x399b9586130331a6L, 0x39d13d73cbe1ff08L, 0x3a058cd0beda7ec9L,
+ 0x3a3af004ee911e7cL, 0x3a70d603151ab30dL, 0x3aa50b83da615fd1L, 0x3ada4e64d0f9b7c5L,
+ 0x3b1070ff029c12dbL, 0x3b448d3ec3431792L, 0x3b79b08e7413dd76L, 0x3bb00e59088c6a6aL,
+ 0x3be411ef4aaf8504L, 0x3c19166b1d5b6646L, 0x3c4f5c05e4b23fd7L, 0x3c839983aeef67e6L,
+ 0x3cb87fe49aab41e0L, 0x3cee9fddc1561258L, 0x3d2323ea98d5cb77L, 0x3d57ece53f0b3e55L,
+ 0x3d8de81e8ece0deaL, 0x3dc2b1131940c8b2L, 0x3df75d57df90fadfL, 0x3e2d34add7753996L,
+ 0x3e6240eca6a943feL, 0x3e96d127d05394fdL, 0x3ecc8571c4687a3dL, 0x3f01d3671ac14c66L,
+ 0x3f364840e1719f80L, 0x3f6bda5119ce075fL, 0x3fa16872b020c49cL, 0x3fd5c28f5c28f5c3L,
+ 0x400B333333333333L };
+
+ private static final long rawBitsFor1_2e0To309[] = { 0x3ff3333333333333L, 0x4028000000000000L,
+ 0x405e000000000000L, 0x4092c00000000000L, 0x40c7700000000000L, 0x40fd4c0000000000L,
+ 0x41324f8000000000L, 0x4166e36000000000L, 0x419c9c3800000000L, 0x41d1e1a300000000L,
+ 0x42065a0bc0000000L, 0x423bf08eb0000000L, 0x427176592e000000L, 0x42a5d3ef79800000L,
+ 0x42db48eb57e00000L, 0x43110d9316ec0000L, 0x434550f7dca70000L, 0x437aa535d3d0c000L,
+ 0x43b0a741a4627800L, 0x43e4d1120d7b1600L, 0x441a055690d9db80L, 0x445043561a882930L,
+ 0x4484542ba12a337cL, 0x44b969368974c05bL, 0x44efc3842bd1f072L, 0x4523da329b633647L,
+ 0x4558d0bf423c03d9L, 0x458f04ef12cb04cfL, 0x45c363156bbee301L, 0x45f83bdac6ae9bc2L,
+ 0x462e4ad1785a42b2L, 0x4662eec2eb3869afL, 0x4697aa73a606841bL, 0x46cd95108f882522L,
+ 0x47027d2a59b51735L, 0x47371c74f0225d03L, 0x476ce3922c2af443L, 0x47a20e3b5b9ad8aaL,
+ 0x47d691ca32818ed5L, 0x480c363cbf21f28aL, 0x4841a1e5f7753796L, 0x48760a5f7552857cL,
+ 0x48ab8cf752a726daL, 0x48e1381a93a87849L, 0x491586213892965bL, 0x494ae7a986b73bf1L,
+ 0x4980d0c9f4328577L, 0x49b504fc713f26d5L, 0x49ea463b8d8ef08aL, 0x4a206be538795656L,
+ 0x4a5486de8697abecL, 0x4a89a896283d96e6L, 0x4ac0095dd9267e50L, 0x4af40bb54f701de4L,
+ 0x4b290ea2a34c255dL, 0x4b5f524b4c1f2eb4L, 0x4b93936f0f937d31L, 0x4bc8784ad3785c7dL,
+ 0x4bfe965d8856739cL, 0x4c331dfa75360842L, 0x4c67e57912838a52L, 0x4c9dded757246ce6L,
+ 0x4cd2ab469676c410L, 0x4d0756183c147514L, 0x4d3d2b9e4b199259L, 0x4d723b42eeeffb78L,
+ 0x4da6ca13aaabfa56L, 0x4ddc7c989556f8ebL, 0x4e11cddf5d565b93L, 0x4e46415734abf278L,
+ 0x4e7bd1ad01d6ef15L, 0x4eb1630c2126556dL, 0x4ee5bbcf296feac9L, 0x4f1b2ac2f3cbe57bL,
+ 0x4f50fab9d85f6f6dL, 0x4f8539684e774b48L, 0x4fba87c262151e1aL, 0x4ff094d97d4d32d0L,
+ 0x5024ba0fdca07f84L, 0x5059e893d3c89f65L, 0x5090315c645d639fL, 0x50c43db37d74bc87L,
+ 0x50f94d205cd1eba9L, 0x512fa06874066693L, 0x5163c4414884001cL, 0x5198b5519aa50023L,
+ 0x51cee2a6014e402cL, 0x52034da7c0d0e81bL, 0x52382111b1052222L, 0x526e29561d466aabL,
+ 0x52a2d9d5d24c02abL, 0x52d7904b46df0355L, 0x530d745e1896c42bL, 0x534268bacf5e3a9bL,
+ 0x537702e98335c941L, 0x53acc3a3e4033b92L, 0x53e1fa466e82053bL, 0x541678d80a22868aL,
+ 0x544c170e0cab282cL, 0x54818e68c7eaf91cL, 0x54b5f202f9e5b763L, 0x54eb6e83b85f253bL,
+ 0x55212512533b7745L, 0x55556e56e80a5516L, 0x558ac9eca20cea5cL, 0x55c0be33e5481279L,
+ 0x55f4edc0de9a1718L, 0x562a293116409cdeL, 0x566059beade8620bL, 0x5694702e59627a8dL,
+ 0x56c98c39efbb1931L, 0x56ffef486ba9df7dL, 0x5733f58d434a2baeL, 0x5768f2f0941cb699L,
+ 0x579f2facb923e440L, 0x57d37dcbf3b66ea8L, 0x58085d3ef0a40a52L, 0x583e748eaccd0ce6L,
+ 0x587308d92c002810L, 0x58a7cb0f77003214L, 0x58ddbdd354c03e99L, 0x591296a414f82720L,
+ 0x59473c4d1a3630e8L, 0x597d0b6060c3bd21L, 0x59b2271c3c7a5635L, 0x59e6b0e34b98ebc2L,
+ 0x5a1c5d1c1e7f26b3L, 0x5a51ba31930f7830L, 0x5a8628bdf7d3563cL, 0x5abbb2ed75c82bcaL,
+ 0x5af14fd4699d1b5fL, 0x5b25a3c984046236L, 0x5b5b0cbbe5057ac4L, 0x5b90e7f56f236cbaL,
+ 0x5bc521f2caec47e9L, 0x5bfa6a6f7da759e3L, 0x5c308285ae88982eL, 0x5c64a3271a2abe39L,
+ 0x5c99cbf0e0b56dc8L, 0x5cd01f768c71649dL, 0x5d0427542f8dbdc4L, 0x5d3931293b712d35L,
+ 0x5d6f7d738a4d7882L, 0x5da3ae6836706b51L, 0x5dd89a02440c8626L, 0x5e0ec082d50fa7afL,
+ 0x5e433851c529c8ceL, 0x5e78066636743b01L, 0x5eae07ffc41149c1L, 0x5ee2c4ffda8ace19L,
+ 0x5f17763fd12d819fL, 0x5f4d53cfc578e207L, 0x5f825461db6b8d44L, 0x5fb6e97a52467095L,
+ 0x5feca3d8e6d80cbbL, 0x6021e667904707f5L, 0x605660017458c9f2L, 0x608bf801d16efc6eL,
+ 0x60c17b0122e55dc5L, 0x60f5d9c16b9eb536L, 0x612b5031c6866284L, 0x6161121f1c13fd92L,
+ 0x619556a6e318fcf7L, 0x61caac509bdf3c34L, 0x6200abb2616b85a1L, 0x6234d69ef9c66709L,
+ 0x626a0c46b83800cbL, 0x62a047ac3323007fL, 0x62d459973febc09fL, 0x63096ffd0fe6b0c6L,
+ 0x633fcbfc53e05cf8L, 0x6373df7db46c3a1bL, 0x63a8d75d218748a2L, 0x63df0d3469e91acaL,
+ 0x64136840c231b0beL, 0x64484250f2be1ceeL, 0x647e52e52f6da42aL, 0x64b2f3cf3da4869aL,
+ 0x64e7b0c30d0da840L, 0x651d9cf3d0511251L, 0x655282186232ab72L, 0x6587229e7abf564fL,
+ 0x65bceb46196f2be3L, 0x65f2130bcfe57b6eL, 0x662697cec3deda49L, 0x665c3dc274d690dbL,
+ 0x6691a69989061a89L, 0x66c6103feb47a12bL, 0x66fb944fe6198976L, 0x67313cb1efcff5eaL,
+ 0x67658bde6bc3f364L, 0x679aeed606b4f03dL, 0x67d0d545c4311626L, 0x68050a97353d5bb0L,
+ 0x683a4d3d028cb29cL, 0x687070462197efa2L, 0x68a48c57a9fdeb8aL, 0x68d9af6d947d666cL,
+ 0x69100da47cce6004L, 0x6944110d9c01f805L, 0x6979155103027606L, 0x69af5aa543c31387L,
+ 0x69e398a74a59ec35L, 0x6a187ed11cf06742L, 0x6a4e9e85642c8112L, 0x6a8323135e9bd0abL,
+ 0x6ab7ebd83642c4d6L, 0x6aede6ce43d3760cL, 0x6b22b040ea6429c7L, 0x6b575c5124fd3439L,
+ 0x6b8d33656e3c8147L, 0x6bc2401f64e5d0cdL, 0x6bf6d0273e1f4500L, 0x6c2c84310da71640L,
+ 0x6c61d29ea8886de8L, 0x6c96474652aa8962L, 0x6ccbd917e7552bbaL, 0x6d0167aef0953b54L,
+ 0x6d35c19aacba8a29L, 0x6d6b320157e92cb4L, 0x6da0ff40d6f1bbf0L, 0x6dd53f110cae2aedL,
+ 0x6e0a8ed54fd9b5a8L, 0x6e40994551e81189L, 0x6e74bf96a66215ebL, 0x6ea9ef7c4ffa9b66L,
+ 0x6ee035adb1fca120L, 0x6f1443191e7bc967L, 0x6f4953df661abbc1L, 0x6f7fa8d73fa16ab2L,
+ 0x6fb3c98687c4e2afL, 0x6fe8bbe829b61b5bL, 0x701eeae23423a232L, 0x705352cd6096455fL,
+ 0x70882780b8bbd6b7L, 0x70be3160e6eacc64L, 0x70f2dedc9052bfbfL, 0x71279693b4676faeL,
+ 0x715d7c38a1814b9aL, 0x71926da364f0cf40L, 0x71c7090c3e2d0310L, 0x71fccb4f4db843d4L,
+ 0x7231ff1190932a65L, 0x72667ed5f4b7f4feL, 0x729c1e8b71e5f23dL, 0x72d19317272fb766L,
+ 0x7305f7dcf0fba540L, 0x733b75d42d3a8e90L, 0x737129a49c44991aL, 0x73a5740dc355bf60L,
+ 0x73dad111342b2f39L, 0x7410c2aac09afd83L, 0x7444f35570c1bce4L, 0x747a302accf22c1dL,
+ 0x74b05e1ac0175b92L, 0x74e475a1701d3277L, 0x75199309cc247f15L, 0x754ff7cc3f2d9edaL,
+ 0x7583fadfa77c8348L, 0x75b8f997915ba41aL, 0x75ef37fd75b28d21L, 0x762382fe698f9834L,
+ 0x765863be03f37e41L, 0x768e7cad84f05dd2L, 0x76c30dec73163aa3L, 0x76f7d1678fdbc94cL,
+ 0x772dc5c173d2bb9fL, 0x77629b98e863b543L, 0x7797427f227ca294L, 0x77cd131eeb1bcb39L,
+ 0x78022bf352f15f04L, 0x7836b6f027adb6c5L, 0x786c64ac31992476L, 0x78a1beeb9effb6caL,
+ 0x78d62ea686bfa47cL, 0x790bba50286f8d9bL, 0x794154721945b881L, 0x7975a98e9f9726a1L,
+ 0x79ab13f2477cf049L, 0x79e0ec776cae162eL, 0x7a15279547d99bb9L, 0x7a4a717a99d002a8L,
+ 0x7a8086eca02201a9L, 0x7ab4a8a7c82a8213L, 0x7ae9d2d1ba352298L, 0x7b2023c31461359fL,
+ 0x7b542cb3d9798307L, 0x7b8937e0cfd7e3c8L, 0x7bbf85d903cddcbaL, 0x7bf3b3a7a260a9f4L,
+ 0x7c28a0918af8d472L, 0x7c5ec8b5edb7098eL, 0x7c933d71b49265f9L, 0x7cc80cce21b6ff77L,
+ 0x7cfe1001aa24bf55L, 0x7d32ca010a56f795L, 0x7d677c814cecb57aL, 0x7d9d5ba1a027e2d9L,
+ 0x7dd259450418edc7L, 0x7e06ef96451f2939L, 0x7e3cab7bd666f388L, 0x7e71eb2d66005835L,
+ 0x7ea665f8bf806e42L, 0x7edbff76ef6089d2L, 0x7f117faa559c5623L, 0x7f45df94eb036bacL,
+ 0x7f7b577a25c44697L, 0x7fb116ac579aac1fL, 0x7fe55c576d815726L, 0x7ff0000000000000L };
+
+ private void doTestCompareRawBits(String originalDoubleString, long expectedRawBits,
+ String expectedString) {
+ double result;
+ long rawBits;
+ String convertedString;
+ result = Double.parseDouble(originalDoubleString);
+ rawBits = Double.doubleToLongBits(result);
+ convertedString = new Double(result).toString();
+ assertEquals(expectedRawBits, rawBits);
+ assertEquals(expectedString.toLowerCase(Locale.US), convertedString
+ .toLowerCase(Locale.US));
+ }
+
+ private void test_toString(double dd, String answer) {
+ assertEquals(answer, Double.toString(dd));
+ Double d = new Double(dd);
+ assertEquals(answer, Double.toString(d.doubleValue()));
+ assertEquals(answer, d.toString());
+ }
+
+ /**
+ * java.lang.Double#Double(double)
+ */
+ public void test_ConstructorD() {
+ Double d = new Double(39089.88888888888888888888888888888888);
+ assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d
+ .doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Double#Double(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ Double d = new Double("39089.88888888888888888888888888888888");
+ assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d
+ .doubleValue(), 0D);
+
+ // Regression test for HARMONY-489
+ try {
+ d = new Double("1E+-20");
+ fail("new Double(\"1E+-20\") should throw exception");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ // Regression test for HARMONY-329
+ d = Double.parseDouble("-1.233999999999999965116738099630936817275852021384209929081813042837802886790127428328465579708849276001782791006814286802871737087810957327493372866733334925806221045495205250590286471187577636646208155890426896101636282423463443661040209738873506655844025580428394216030152374941053494694642722606658935546875E-112");
+ assertEquals("Failed to parse long string", -1.234E-112D, d.doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Double#byteValue()
+ */
+ public void test_byteValue() {
+ Double d = new Double(1923311.47712);
+ assertEquals("Returned incorrect byte value", (byte) -17, d.byteValue());
+ }
+
+ /**
+ * java.lang.Double#compareTo(java.lang.Double)
+ * java.lang.Double#compare(double, double)
+ */
+ public void test_compare() {
+ double[] values = 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 < values.length; i++) {
+ double d1 = values[i];
+ assertTrue("compare() should be equal: " + d1, Double.compare(d1, d1) == 0);
+ Double D1 = new Double(d1);
+ assertTrue("compareTo() should be equal: " + d1, D1.compareTo(D1) == 0);
+ for (int j = i + 1; j < values.length; j++) {
+ double d2 = values[j];
+ assertTrue("compare() " + d1 + " should be less " + d2,
+ Double.compare(d1, d2) == -1);
+ assertTrue("compare() " + d2 + " should be greater " + d1, Double.compare(d2,
+ d1) == 1);
+ Double D2 = new Double(d2);
+ assertTrue("compareTo() " + d1 + " should be less " + d2,
+ D1.compareTo(D2) == -1);
+ assertTrue("compareTo() " + d2 + " should be greater " + d1,
+ D2.compareTo(D1) == 1);
+ }
+ }
+
+ try {
+ new Double(0.0D).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Double#doubleToLongBits(double)
+ */
+ public void test_doubleToLongBitsD() {
+ // Test for method long java.lang.Double.doubleToLongBits(double)
+ Double d = new Double(Double.MAX_VALUE);
+ long lbits = Double.doubleToLongBits(d.doubleValue());
+ double r = Double.longBitsToDouble(lbits);
+
+ assertTrue("Bit conversion failed", d.doubleValue() == r);
+ }
+
+ /**
+ * java.lang.Double#doubleToRawLongBits(double)
+ */
+ public void test_doubleToRawLongBitsD() {
+ long l = 0x7ff80000000004d2L;
+ double d = Double.longBitsToDouble(l);
+ assertTrue("Wrong raw bits", Double.doubleToRawLongBits(d) == l);
+ }
+
+ /**
+ * java.lang.Double#doubleValue()
+ */
+ public void test_doubleValue() {
+ assertEquals("Incorrect double value returned", 999999999999999.9999999999999,
+ new Double(999999999999999.9999999999999).doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Double#floatValue()
+ */
+ public void test_floatValue() {
+ // Test for method float java.lang.Double.floatValue()
+ assertTrue(
+ "Incorrect float value returned ",
+ Math
+ .abs(new Double(999999999999999.9999999999999d).floatValue() - 999999999999999.9999999999999f) < 1);
+ }
+
+ /**
+ * java.lang.Double#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.lang.Double.hashCode()
+ for (int i = -1000; i < 1000; i++) {
+ Double d = new Double(i);
+ Double dd = new Double(i);
+ assertTrue("Should not be identical ", d != dd);
+ assertTrue("Should be equals 1 ", d.equals(dd));
+ assertTrue("Should be equals 2 ", dd.equals(d));
+ assertTrue("Should have identical values ", dd.doubleValue() == d.doubleValue());
+ assertTrue("Invalid hash for equal but not identical doubles ", d.hashCode() == dd
+ .hashCode());
+ }
+ assertEquals("Magic assumption hasCode (0.0) = 0 failed", 0, new Double(0.0).hashCode());
+ }
+
+ /**
+ * java.lang.Double#intValue()
+ */
+ public void test_intValue() {
+ // Test for method int java.lang.Double.intValue()
+ Double d = new Double(1923311.47712);
+ assertEquals("Returned incorrect int value", 1923311, d.intValue());
+ }
+
+ /**
+ * java.lang.Double#isInfinite()
+ */
+ public void test_isInfinite() {
+ // Test for method boolean java.lang.Double.isInfinite()
+ assertTrue("NEGATIVE_INFINITY returned false", new Double(Double.NEGATIVE_INFINITY)
+ .isInfinite());
+ assertTrue("POSITIVE_INFINITY returned false", new Double(Double.POSITIVE_INFINITY)
+ .isInfinite());
+ assertTrue("Non infinite number returned true", !(new Double(1000).isInfinite()));
+ }
+
+ /**
+ * java.lang.Double#isInfinite(double)
+ */
+ public void test_isInfiniteD() {
+ // Test for method boolean java.lang.Double.isInfinite(double)
+ assertTrue("Infinity check failed", Double.isInfinite(Double.NEGATIVE_INFINITY)
+ && (Double.isInfinite(Double.POSITIVE_INFINITY))
+ && !(Double.isInfinite(Double.MAX_VALUE)));
+ }
+
+ /**
+ * java.lang.Double#isNaN()
+ */
+ public void test_isNaN() {
+ // Test for method boolean java.lang.Double.isNaN()
+ Double d = new Double(0.0 / 0.0);
+ assertTrue("NAN returned false", d.isNaN());
+ d = new Double(0);
+ assertTrue("Non NAN returned true", !d.isNaN());
+ }
+
+ /**
+ * java.lang.Double#isNaN(double)
+ */
+ public void test_isNaND() {
+ // Test for method boolean java.lang.Double.isNaN(double)
+
+ Double d = new Double(0.0 / 0.0);
+ assertTrue("NAN check failed", Double.isNaN(d.doubleValue()));
+ }
+
+ /**
+ * java.lang.Double#longBitsToDouble(long)
+ */
+ public void test_longBitsToDoubleJ() {
+ // Test for method double java.lang.Double.longBitsToDouble(long)
+
+ Double d = new Double(Double.MAX_VALUE);
+ long lbits = Double.doubleToLongBits(d.doubleValue());
+ double r = Double.longBitsToDouble(lbits);
+
+ assertTrue("Bit conversion failed", d.doubleValue() == r);
+ }
+
+ /**
+ * java.lang.Double#longValue()
+ */
+ public void test_longValue() {
+ // Test for method long java.lang.Double.longValue()
+ Double d = new Double(1923311.47712);
+ assertEquals("Returned incorrect long value", 1923311, d.longValue());
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDoubleLjava_lang_String() {
+ assertEquals("Incorrect double returned, expected zero.", 0.0, Double
+ .parseDouble("2.4703282292062327208828439643411e-324"), 0.0);
+ assertTrue("Incorrect double returned, expected minimum double.", Double
+ .parseDouble("2.4703282292062327208828439643412e-324") == Double.MIN_VALUE);
+
+ for (int i = 324; i > 0; i--) {
+ Double.parseDouble("3.4e-" + i);
+ }
+ for (int i = 0; i <= 309; i++) {
+ Double.parseDouble("1.2e" + i);
+ }
+
+ /*
+ * The first two cases and the last four cases have to placed outside
+ * the loop due to the difference in the expected output string.
+ */
+ doTestCompareRawBits("3.4e-324", rawBitsFor3_4en324ToN1[0], "4.9e-324");
+ doTestCompareRawBits("3.4e-323", rawBitsFor3_4en324ToN1[1], "3.5e-323");
+ for (int i = 322; i > 3; i--) {
+ String testString, expectedString;
+ testString = expectedString = "3.4e-" + i;
+ doTestCompareRawBits(testString, rawBitsFor3_4en324ToN1[324 - i], expectedString);
+ }
+ doTestCompareRawBits("3.4e-3", rawBitsFor3_4en324ToN1[321], "0.0034");
+ doTestCompareRawBits("3.4e-2", rawBitsFor3_4en324ToN1[322], "0.034");
+ doTestCompareRawBits("3.4e-1", rawBitsFor3_4en324ToN1[323], "0.34");
+ doTestCompareRawBits("3.4e-0", rawBitsFor3_4en324ToN1[324], "3.4");
+
+ doTestCompareRawBits("1.2e0", rawBitsFor1_2e0To309[0], "1.2");
+ doTestCompareRawBits("1.2e1", rawBitsFor1_2e0To309[1], "12.0");
+ doTestCompareRawBits("1.2e2", rawBitsFor1_2e0To309[2], "120.0");
+ doTestCompareRawBits("1.2e3", rawBitsFor1_2e0To309[3], "1200.0");
+ doTestCompareRawBits("1.2e4", rawBitsFor1_2e0To309[4], "12000.0");
+ doTestCompareRawBits("1.2e5", rawBitsFor1_2e0To309[5], "120000.0");
+ doTestCompareRawBits("1.2e6", rawBitsFor1_2e0To309[6], "1200000.0");
+ for (int i = 7; i <= 308; i++) {
+ String testString, expectedString;
+ testString = expectedString = "1.2e" + i;
+ doTestCompareRawBits(testString, rawBitsFor1_2e0To309[i], expectedString);
+ }
+ doTestCompareRawBits("1.2e309", rawBitsFor1_2e0To309[309], "Infinity");
+
+ doTestCompareRawBits(
+ "111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807",
+ 0x7e054218c295e43fL, "1.1122233344455567E299");
+ doTestCompareRawBits(
+ "-111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807",
+ 0xfe054218c295e43fL, "-1.1122233344455567E299");
+
+ doTestCompareRawBits("1.234123412431233E107", 0x562ae7a25fe706ebL,
+ "1.234123412431233E107");
+ doTestCompareRawBits("1.2341234124312331E107", 0x562ae7a25fe706ecL,
+ "1.2341234124312331E107");
+ doTestCompareRawBits("1.2341234124312332E107", 0x562ae7a25fe706ecL,
+ "1.2341234124312331E107");
+ doTestCompareRawBits("-1.234123412431233E107", 0xd62ae7a25fe706ebL,
+ "-1.234123412431233E107");
+ doTestCompareRawBits("-1.2341234124312331E107", 0xd62ae7a25fe706ecL,
+ "-1.2341234124312331E107");
+ doTestCompareRawBits("-1.2341234124312332E107", 0xd62ae7a25fe706ecL,
+ "-1.2341234124312331E107");
+
+ doTestCompareRawBits("1e23", 0x44b52d02c7e14af6L, "1.0e23");
+
+ /*
+ * These particular tests verify that the extreme boundary conditions
+ * are converted correctly.
+ */
+ doTestCompareRawBits("0.0e-309", 0L, "0.0");
+ doTestCompareRawBits("-0.0e-309", 0x8000000000000000L, "-0.0");
+ doTestCompareRawBits("0.0e309", 0L, "0.0");
+ doTestCompareRawBits("-0.0e309", 0x8000000000000000L, "-0.0");
+ doTestCompareRawBits("0.1e309", 0x7fe1ccf385ebc8a0L, "1.0e308");
+ doTestCompareRawBits("0.2e309", 0x7ff0000000000000L, "Infinity");
+ doTestCompareRawBits("65e-325", 1L, "4.9e-324");
+ doTestCompareRawBits("1000e-326", 2L, "1.0e-323");
+
+ doTestCompareRawBits("4.0e-306", 0x86789e3750f791L, "4.0e-306");
+ doTestCompareRawBits("2.22507e-308", 0xffffe2e8159d0L, "2.22507e-308");
+ doTestCompareRawBits(
+ "111222333444555666777888999000111228999000.92233720368547758079223372036854775807",
+ 0x48746da623f1dd8bL, "1.1122233344455567E41");
+ doTestCompareRawBits(
+ "-111222333444555666777888999000111228999000.92233720368547758079223372036854775807",
+ 0xc8746da623f1dd8bL, "-1.1122233344455567E41");
+ doTestCompareRawBits(
+ "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210",
+ 0x54820fe0ba17f469L, "1.2345678901234567E99");
+ doTestCompareRawBits(
+ "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210",
+ 0xd4820fe0ba17f469L, "-1.2345678901234567E99");
+
+ doTestCompareRawBits(
+ "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
+ 0x7fefffffffffffffL, "1.7976931348623157E308");
+ doTestCompareRawBits(
+ "-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
+ 0xffefffffffffffffL, "-1.7976931348623157E308");
+ doTestCompareRawBits(
+ "1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890",
+ 0x7ff0000000000000L, "Infinity");
+ doTestCompareRawBits(
+ "-1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890",
+ 0xfff0000000000000L, "-Infinity");
+ doTestCompareRawBits(
+ "179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
+ 0x7ff0000000000000L, "Infinity");
+ doTestCompareRawBits(
+ "-179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
+ 0xfff0000000000000L, "-Infinity");
+ doTestCompareRawBits(
+ "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x2b392a32afcc661eL, "1.7976931348623157E-100");
+ doTestCompareRawBits(
+ "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0xab392a32afcc661eL, "-1.7976931348623157E-100");
+ doTestCompareRawBits(
+ "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x1b3432f0cb68e61L, "1.7976931348623157E-300");
+ doTestCompareRawBits(
+ "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x81b3432f0cb68e61L, "-1.7976931348623157E-300");
+ doTestCompareRawBits(
+ "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x2117b590b942L, "1.79769313486234E-310");
+ doTestCompareRawBits(
+ "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x80002117b590b942L, "-1.79769313486234E-310");
+ doTestCompareRawBits(
+ "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0xe37L, "1.798E-320");
+ doTestCompareRawBits(
+ "-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
+ 0x8000000000000e37L, "-1.798E-320");
+ doTestCompareRawBits(
+ "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+ 0x2L, "1.0E-323");
+ doTestCompareRawBits(
+ "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+ 0x8000000000000002L, "-1.0E-323");
+ doTestCompareRawBits(
+ "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578",
+ 0x1L, "4.9E-324");
+ doTestCompareRawBits(
+ "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578",
+ 0x8000000000000001L, "-4.9E-324");
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_Illegal() {
+ try {
+ Double.parseDouble("0.0p0D");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble("+0x.p1d");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble("0Xg.gp1D");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble("-0x1.1p");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble("+0x 1.1 p2d");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble("x1.1p2d");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble(" 0x-2.1p2");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble(" 0x2.1pad");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ try {
+ Double.parseDouble(" 0x111.222p 22d");
+ fail("Should throw NumberFormatException.");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_FromHexString() {
+ double actual;
+ double expected;
+
+ actual = Double.parseDouble("0x0.0p0D");
+ assertEquals("Returned incorrect value", 0.0d, actual, 0.0D);
+
+ actual = Double.parseDouble("0xa.ap+9d");
+ assertEquals("Returned incorrect value", 5440.0d, actual, 0.0D);
+
+ actual = Double.parseDouble("+0Xb.10ap8");
+ assertEquals("Returned incorrect value", 2832.625d, actual, 0.0D);
+
+ actual = Double.parseDouble("-0X.a0P2D");
+ assertEquals("Returned incorrect value", -2.5d, actual, 0.0D);
+
+ actual = Double.parseDouble("\r 0x22.1p2d \t");
+ assertEquals("Returned incorrect value", 136.25d, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.0p-1");
+ assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
+
+ actual = Double
+ .parseDouble("0x00000000000000000000000000000000001.0p-1");
+ assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.0p-00000000000000000000000000001");
+ assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
+
+ actual = Double.parseDouble("0x.100000000000000000000000000000000p1");
+ assertEquals("Returned incorrect value", 0.125, actual, 0.0D);
+
+ actual = Double.parseDouble("0x0.0p999999999999999999999999999999999999999999999999999999999999999");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0xf1.0p9999999999999999999999999999999999999999999999999999999999999999");
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
+
+ actual = Double.parseDouble("0xffffffffffffffffffffffffffffffffffff.ffffffffffffffffffffffffffffffffffffffffffffffp1");
+ expected = Double.longBitsToDouble(0x4900000000000000L);
+ assertEquals("Returned incorrect value", expected, actual, 0.0D);
+
+ actual = Double.parseDouble("0x0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001p1600");
+ expected = Double.longBitsToDouble(0x7f30000000000000L);
+ assertEquals("Returned incorrect value", expected, actual, 0.0D);
+
+ actual = Double.parseDouble("0x0.0p-999999999999999999999999999999999999999999999999999999");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0xf1.0p-9999999999999999999999999999999999999999999999999999999999999999");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000p-1600");
+ expected = Double.longBitsToDouble(0xf0000000000000L);
+ assertEquals("Returned incorrect value", expected, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.p9223372036854775807");
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.p9223372036854775808");
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
+
+ actual = Double.parseDouble("0x10.p9223372036854775808");
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
+
+ actual = Double.parseDouble("0xabcd.ffffffffp+2000");
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.p-9223372036854775808");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0x1.p-9223372036854775809");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0x.1p-9223372036854775809");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+
+ actual = Double.parseDouble("0xabcd.ffffffffffffffp-2000");
+ assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_NormalPositiveExponent() {
+ long[] expecteds = {
+ 0x3f323456789abcdfL, 0x40e111012345678aL, 0x41a1110091a2b3c5L,
+ 0x4259998091a2b3c5L, 0x4311110048d159e2L, 0x43c5554048d159e2L,
+ 0x4479998048d159e2L, 0x452dddc048d159e2L, 0x45e111002468acf1L,
+ 0x469333202468acf1L, 0x4751011001234568L, 0x4802112101234568L,
+ 0x48b3213201234568L, 0x4964314301234568L, 0x4a15415401234568L,
+ 0x4ac6516501234568L, 0x4b77617601234568L, 0x4c28718701234568L,
+ 0x4cd9819801234568L, 0x4d9049048091a2b4L, 0x4e4101100091a2b4L,
+ 0x4ef189188091a2b4L, 0x4fa211210091a2b4L, 0x505299298091a2b4L,
+ 0x510321320091a2b4L, 0x51b3a93a8091a2b4L, 0x526431430091a2b4L,
+ 0x5314b94b8091a2b4L, 0x53c841840091a2b4L, 0x5478c98c8091a2b4L,
+ 0x552981980091a2b4L, 0x55da09a08091a2b4L, 0x568a91a90091a2b4L,
+ 0x573b19b18091a2b4L, 0x57eba1ba0091a2b4L, 0x589c29c28091a2b4L,
+ 0x594cb1cb0091a2b4L, 0x5a001d01c048d15aL, 0x5ab061060048d15aL,
+ 0x5b60a50a4048d15aL, 0x5c1101100048d15aL, 0x5cc145144048d15aL,
+ 0x5d7189188048d15aL, 0x5e21cd1cc048d15aL, 0x5ed211210048d15aL,
+ 0x5f8255254048d15aL, 0x603419418048d15aL, 0x60e45d45c048d15aL,
+ 0x6194a14a0048d15aL, 0x6244e54e4048d15aL, 0x62f541540048d15aL,
+ 0x63a585584048d15aL, 0x6455c95c8048d15aL, 0x65060d60c048d15aL,
+ 0x65b651650048d15aL, 0x666815814048d15aL, 0x671859858048d15aL,
+ 0x67c89d89c048d15aL, 0x6878e18e0048d15aL, 0x692925924048d15aL,
+ 0x69d981980048d15aL, 0x6a89c59c4048d15aL, 0x6b3a09a08048d15aL,
+ 0x6bea4da4c048d15aL, 0x6c9c11c10048d15aL, 0x6d4c55c54048d15aL,
+ 0x6dfc99c98048d15aL, 0x6eacddcdc048d15aL, 0x6f5d21d20048d15aL,
+ 0x700d65d64048d15aL, 0x70bdc1dc0048d15aL, 0x716e05e04048d15aL,
+ 0x721e49e48048d15aL, 0x72d00700602468adL, 0x73802902802468adL,
+ 0x74304b04a02468adL, 0x74e06d06c02468adL, 0x75908f08e02468adL,
+ 0x7640b10b002468adL, 0x76f0d30d202468adL, 0x77a10110002468adL,
+ 0x78512312202468adL, 0x79020520402468adL, 0x79b22722602468adL,
+ 0x7a624924802468adL, 0x7b126b26a02468adL, 0x7bc28d28c02468adL,
+ 0x7c72af2ae02468adL, 0x7d22d12d002468adL, 0x7dd2f32f202468adL,
+ 0x7e832132002468adL, 0x7f40011001012345L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L };
+
+ for (int i = 0; i < expecteds.length; i++) {
+ int part = i * 11;
+ String inputString = "0x" + part + "." + part + "0123456789abcdefp" + part;
+
+ double actual = Double.parseDouble(inputString);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputString
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_NormalNegativeExponent() {
+ long[] expecteds = {
+ 0x3f323456789abcdfL, 0x3f8111012345678aL, 0x3ee1110091a2b3c5L,
+ 0x3e39998091a2b3c5L, 0x3d91110048d159e2L, 0x3ce5554048d159e2L,
+ 0x3c39998048d159e2L, 0x3b8dddc048d159e2L, 0x3ae111002468acf1L,
+ 0x3a3333202468acf1L, 0x3991011001234568L, 0x38e2112101234568L,
+ 0x3833213201234568L, 0x3784314301234568L, 0x36d5415401234568L,
+ 0x3626516501234568L, 0x3577617601234568L, 0x34c8718701234568L,
+ 0x3419819801234568L, 0x337049048091a2b4L, 0x32c101100091a2b4L,
+ 0x321189188091a2b4L, 0x316211210091a2b4L, 0x30b299298091a2b4L,
+ 0x300321320091a2b4L, 0x2f53a93a8091a2b4L, 0x2ea431430091a2b4L,
+ 0x2df4b94b8091a2b4L, 0x2d4841840091a2b4L, 0x2c98c98c8091a2b4L,
+ 0x2be981980091a2b4L, 0x2b3a09a08091a2b4L, 0x2a8a91a90091a2b4L,
+ 0x29db19b18091a2b4L, 0x292ba1ba0091a2b4L, 0x287c29c28091a2b4L,
+ 0x27ccb1cb0091a2b4L, 0x27201d01c048d15aL, 0x267061060048d15aL,
+ 0x25c0a50a4048d15aL, 0x251101100048d15aL, 0x246145144048d15aL,
+ 0x23b189188048d15aL, 0x2301cd1cc048d15aL, 0x225211210048d15aL,
+ 0x21a255254048d15aL, 0x20f419418048d15aL, 0x20445d45c048d15aL,
+ 0x1f94a14a0048d15aL, 0x1ee4e54e4048d15aL, 0x1e3541540048d15aL,
+ 0x1d8585584048d15aL, 0x1cd5c95c8048d15aL, 0x1c260d60c048d15aL,
+ 0x1b7651650048d15aL, 0x1ac815814048d15aL, 0x1a1859858048d15aL,
+ 0x19689d89c048d15aL, 0x18b8e18e0048d15aL, 0x180925924048d15aL,
+ 0x175981980048d15aL, 0x16a9c59c4048d15aL, 0x15fa09a08048d15aL,
+ 0x154a4da4c048d15aL, 0x149c11c10048d15aL, 0x13ec55c54048d15aL,
+ 0x133c99c98048d15aL, 0x128cddcdc048d15aL, 0x11dd21d20048d15aL,
+ 0x112d65d64048d15aL, 0x107dc1dc0048d15aL, 0xfce05e04048d15aL,
+ 0xf1e49e48048d15aL, 0xe700700602468adL, 0xdc02902802468adL,
+ 0xd104b04a02468adL, 0xc606d06c02468adL, 0xbb08f08e02468adL,
+ 0xb00b10b002468adL, 0xa50d30d202468adL, 0x9a10110002468adL,
+ 0x8f12312202468adL, 0x8420520402468adL, 0x7922722602468adL,
+ 0x6e24924802468adL, 0x6326b26a02468adL, 0x5828d28c02468adL,
+ 0x4d2af2ae02468adL, 0x422d12d002468adL, 0x372f32f202468adL,
+ 0x2c32132002468adL, 0x220011001012345L, 0x170121012012345L,
+ 0xc0231023012345L, 0x10341034012345L, 0x208a208a024L,
+ 0x41584158L, 0x83388L, 0x108L,
+ 0x0L, 0x0L, 0x0L,
+ 0x0L, 0x0L, 0x0L,
+ 0x0L, 0x0L, 0x0L,
+ 0x0L, 0x0L, 0x0L,
+ 0x0L, 0x0L };
+
+ for (int i = 0; i < expecteds.length; i++) {
+ int part = i * 11;
+ String inputString = "0x" + part + "." + part + "0123456789abcdefp-" + part;
+
+ double actual = Double.parseDouble(inputString);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputString
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_MaxNormalBoundary() {
+ long[] expecteds = {
+ 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL,
+ 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL,
+ 0x7fefffffffffffffL, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+ 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
+
+ 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL,
+ 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL,
+ 0xffefffffffffffffL, 0xfff0000000000000L, 0xfff0000000000000L,
+ 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L,
+ 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L };
+
+ String[] inputs = {
+ "0x1.fffffffffffffp1023",
+ "0x1.fffffffffffff000000000000000000000000001p1023",
+ "0x1.fffffffffffff1p1023",
+ "0x1.fffffffffffff100000000000000000000000001p1023",
+ "0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023",
+ "0x1.fffffffffffff7p1023",
+ "0x1.fffffffffffff700000000000000000000000001p1023",
+ "0x1.fffffffffffff8p1023",
+ "0x1.fffffffffffff800000000000000000000000001p1023",
+ "0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023",
+ "0x1.fffffffffffff9p1023",
+ "0x1.fffffffffffff900000000000000000000000001p1023",
+ "0x1.ffffffffffffffp1023",
+ "0x1.ffffffffffffff00000000000000000000000001p1023",
+ "0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023",
+
+ "-0x1.fffffffffffffp1023",
+ "-0x1.fffffffffffff000000000000000000000000001p1023",
+ "-0x1.fffffffffffff1p1023",
+ "-0x1.fffffffffffff100000000000000000000000001p1023",
+ "-0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023",
+ "-0x1.fffffffffffff7p1023",
+ "-0x1.fffffffffffff700000000000000000000000001p1023",
+ "-0x1.fffffffffffff8p1023",
+ "-0x1.fffffffffffff800000000000000000000000001p1023",
+ "-0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023",
+ "-0x1.fffffffffffff9p1023",
+ "-0x1.fffffffffffff900000000000000000000000001p1023",
+ "-0x1.ffffffffffffffp1023",
+ "-0x1.ffffffffffffff00000000000000000000000001p1023",
+ "-0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023" };
+
+ for (int i = 0; i < inputs.length; i++) {
+ double actual = Double.parseDouble(inputs[i]);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_MinNormalBoundary() {
+ long[] expecteds = {
+ 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
+ 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
+ 0x10000000000000L, 0x10000000000000L, 0x10000000000001L,
+ 0x10000000000001L, 0x10000000000001L, 0x10000000000001L,
+ 0x10000000000001L, 0x10000000000001L, 0x10000000000001L,
+
+ 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
+ 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
+ 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000001L,
+ 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L,
+ 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L };
+
+ String[] inputs = {
+ "0x1.0p-1022",
+ "0x1.00000000000001p-1022",
+ "0x1.000000000000010000000000000000001p-1022",
+ "0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022",
+ "0x1.00000000000007p-1022",
+ "0x1.000000000000070000000000000000001p-1022",
+ "0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022",
+ "0x1.00000000000008p-1022",
+ "0x1.000000000000080000000000000000001p-1022",
+ "0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022",
+ "0x1.00000000000009p-1022",
+ "0x1.000000000000090000000000000000001p-1022",
+ "0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022",
+ "0x1.0000000000000fp-1022",
+ "0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022",
+
+ "-0x1.0p-1022",
+ "-0x1.00000000000001p-1022",
+ "-0x1.000000000000010000000000000000001p-1022",
+ "-0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022",
+ "-0x1.00000000000007p-1022",
+ "-0x1.000000000000070000000000000000001p-1022",
+ "-0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022",
+ "-0x1.00000000000008p-1022",
+ "-0x1.000000000000080000000000000000001p-1022",
+ "-0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022",
+ "-0x1.00000000000009p-1022",
+ "-0x1.000000000000090000000000000000001p-1022",
+ "-0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022",
+ "-0x1.0000000000000fp-1022",
+ "-0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022" };
+
+ for (int i = 0; i < inputs.length; i++) {
+ double actual = Double.parseDouble(inputs[i]);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_MaxSubNormalBoundary() {
+ long[] expecteds = {
+ 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL,
+ 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL,
+ 0xfffffffffffffL, 0x10000000000000L, 0x10000000000000L,
+ 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
+ 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
+
+ 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL,
+ 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL,
+ 0x800fffffffffffffL, 0x8010000000000000L, 0x8010000000000000L,
+ 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
+ 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L };
+
+ String[] inputs = {
+ "0x0.fffffffffffffp-1022",
+ "0x0.fffffffffffff00000000000000000000000000000000001p-1022",
+ "0x0.fffffffffffff1p-1022",
+ "0x0.fffffffffffff10000000000000000000000000000000001p-1022",
+ "0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "0x0.fffffffffffff7p-1022",
+ "0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "0x0.fffffffffffff8p-1022",
+ "0x0.fffffffffffff80000000000000000000000000000000001p-1022",
+ "0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "0x0.fffffffffffff9p-1022",
+ "0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "0x0.ffffffffffffffp-1022",
+ "0x0.ffffffffffffff0000000000000000000000000000000001p-1022",
+ "0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+
+ "-0x0.fffffffffffffp-1022",
+ "-0x0.fffffffffffff00000000000000000000000000000000001p-1022",
+ "-0x0.fffffffffffff1p-1022",
+ "-0x0.fffffffffffff10000000000000000000000000000000001p-1022",
+ "-0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.fffffffffffff7p-1022",
+ "-0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.fffffffffffff8p-1022",
+ "-0x0.fffffffffffff80000000000000000000000000000000001p-1022",
+ "-0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.fffffffffffff9p-1022",
+ "-0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.ffffffffffffffp-1022",
+ "-0x0.ffffffffffffff0000000000000000000000000000000001p-1022",
+ "-0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022" };
+
+ for (int i = 0; i < inputs.length; i++) {
+ double actual = Double.parseDouble(inputs[i]);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_MinSubNormalBoundary() {
+ long[] expecteds = {
+ 0x1L, 0x1L, 0x2L,
+ 0x1L, 0x1L, 0x1L,
+ 0x2L, 0x2L, 0x2L,
+ 0x2L, 0x2L, 0x2L,
+ 0x2L, 0x2L, 0x2L,
+
+ 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000002L,
+ 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L,
+ 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L,
+ 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L,
+ 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L };
+
+ String[] inputs = {
+ "0x0.0000000000001p-1022",
+ "0x0.00000000000010000000000000000001p-1022",
+ "0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022",
+ "0x0.00000000000017p-1022",
+ "0x0.000000000000170000000000000000001p-1022",
+ "0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022",
+ "0x0.00000000000018p-1022",
+ "0x0.000000000000180000000000000000001p-1022",
+ "0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022",
+ "0x0.00000000000019p-1022",
+ "0x0.000000000000190000000000000000001p-1022",
+ "0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022",
+ "0x0.0000000000001fp-1022",
+ "0x0.0000000000001f0000000000000000001p-1022",
+ "0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022",
+
+ "-0x0.0000000000001p-1022",
+ "-0x0.00000000000010000000000000000001p-1022",
+ "-0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.00000000000017p-1022",
+ "-0x0.000000000000170000000000000000001p-1022",
+ "-0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.00000000000018p-1022",
+ "-0x0.000000000000180000000000000000001p-1022",
+ "-0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.00000000000019p-1022",
+ "-0x0.000000000000190000000000000000001p-1022",
+ "-0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.0000000000001fp-1022",
+ "-0x0.0000000000001f0000000000000000001p-1022",
+ "-0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022" };
+
+ for (int i = 0; i < inputs.length; i++) {
+ double actual = Double.parseDouble(inputs[i]);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#parseDouble(java.lang.String)
+ */
+ public void test_parseDouble_LString_ZeroBoundary() {
+ long[] expecteds = {
+ 0x0L, 0x0L, 0x0L,
+ 0x1L, 0x1L, 0x1L,
+ 0x1L, 0x1L, 0x1L,
+ 0x8000000000000000L, 0x8000000000000000L, 0x8000000000000000L,
+ 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L,
+ 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L };
+
+ String[] inputs = {
+ "0x0.00000000000004p-1022",
+ "0x0.00000000000007ffffffffffffffffffffffp-1022",
+ "0x0.00000000000008p-1022",
+ "0x0.000000000000080000000000000000001p-1022",
+ "0x0.00000000000008fffffffffffffffffffffffffffffffp-1022",
+ "0x0.00000000000009p-1022",
+ "0x0.000000000000090000000000000000001p-1022",
+ "0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022",
+ "0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022",
+
+ "-0x0.00000000000004p-1022",
+ "-0x0.00000000000007ffffffffffffffffffffffp-1022",
+ "-0x0.00000000000008p-1022",
+ "-0x0.000000000000080000000000000000001p-1022",
+ "-0x0.00000000000008fffffffffffffffffffffffffffffffp-1022",
+ "-0x0.00000000000009p-1022",
+ "-0x0.000000000000090000000000000000001p-1022",
+ "-0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022",
+ "-0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022" };
+
+ for (int i = 0; i < inputs.length; i++) {
+ double actual = Double.parseDouble(inputs[i]);
+ double expected = Double.longBitsToDouble(expecteds[i]);
+
+ String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
+ String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0D);
+ }
+ }
+
+ /**
+ * java.lang.Double#shortValue()
+ */
+ public void test_shortValue() {
+ // Test for method short java.lang.Double.shortValue()
+ Double d = new Double(1923311.47712);
+ assertEquals("Returned incorrect short value", 22767, d.shortValue());
+ }
+
+ /**
+ * java.lang.Double#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.Double.toString()
+ test_toString(1.7976931348623157E308, "1.7976931348623157E308");
+ test_toString(5.0E-4, "5.0E-4");
+ }
+
+ /**
+ * java.lang.Double#toString(double)
+ */
+ public void test_toStringD() {
+ // Test for method java.lang.String java.lang.Double.toString(double)
+ test_toString(1.7976931348623157E308, "1.7976931348623157E308");
+ test_toString(1.0 / 0.0, "Infinity");
+ test_toString(0.0 / 0.0, "NaN");
+ test_toString(-1.0 / 0.0, "-Infinity");
+
+ double d;
+ d = Double.longBitsToDouble(0x470fffffffffffffL);
+ test_toString(d, "2.0769187434139308E34");
+ d = Double.longBitsToDouble(0x4710000000000000L);
+ test_toString(d, "2.076918743413931E34");
+
+ d = Double.longBitsToDouble(0x470000000000000aL);
+ test_toString(d, "1.0384593717069678E34");
+ d = Double.longBitsToDouble(0x470000000000000bL);
+ test_toString(d, "1.038459371706968E34");
+
+ d = Double.longBitsToDouble(0x4700000000000017L);
+ test_toString(d, "1.0384593717069708E34");
+ d = Double.longBitsToDouble(0x4700000000000018L);
+ test_toString(d, "1.038459371706971E34");
+
+ d = Double.longBitsToDouble(0x4700000000000024L);
+ test_toString(d, "1.0384593717069738E34");
+ d = Double.longBitsToDouble(0x4700000000000025L);
+ test_toString(d, "1.038459371706974E34");
+
+ d = Double.longBitsToDouble(0x4700000000000031L);
+ test_toString(d, "1.0384593717069768E34");
+ d = Double.longBitsToDouble(0x4700000000000032L);
+ test_toString(d, "1.038459371706977E34");
+
+ d = Double.longBitsToDouble(0x470000000000003eL);
+ test_toString(d, "1.0384593717069798E34");
+ d = Double.longBitsToDouble(0x470000000000003fL);
+ test_toString(d, "1.03845937170698E34");
+
+ d = Double.longBitsToDouble(0x7e00000000000003L);
+ test_toString(d, "8.371160993642719E298");
+ d = Double.longBitsToDouble(0x7e00000000000004L);
+ test_toString(d, "8.37116099364272E298");
+
+ d = Double.longBitsToDouble(0x7e00000000000008L);
+ test_toString(d, "8.371160993642728E298");
+ d = Double.longBitsToDouble(0x7e00000000000009L);
+ test_toString(d, "8.37116099364273E298");
+
+ d = Double.longBitsToDouble(0x7e00000000000013L);
+ test_toString(d, "8.371160993642749E298");
+ d = Double.longBitsToDouble(0x7e00000000000014L);
+ test_toString(d, "8.37116099364275E298");
+
+ d = Double.longBitsToDouble(0x7e00000000000023L);
+ test_toString(d, "8.371160993642779E298");
+ d = Double.longBitsToDouble(0x7e00000000000024L);
+ test_toString(d, "8.37116099364278E298");
+
+ d = Double.longBitsToDouble(0x7e0000000000002eL);
+ test_toString(d, "8.371160993642799E298");
+ d = Double.longBitsToDouble(0x7e0000000000002fL);
+ test_toString(d, "8.3711609936428E298");
+
+ d = Double.longBitsToDouble(0xda00000000000001L);
+ test_toString(d, "-3.3846065602060736E125");
+ d = Double.longBitsToDouble(0xda00000000000002L);
+ test_toString(d, "-3.384606560206074E125");
+
+ d = Double.longBitsToDouble(0xda00000000000005L);
+ test_toString(d, "-3.3846065602060766E125");
+ d = Double.longBitsToDouble(0xda00000000000006L);
+ test_toString(d, "-3.384606560206077E125");
+
+ d = Double.longBitsToDouble(0xda00000000000009L);
+ test_toString(d, "-3.3846065602060796E125");
+ d = Double.longBitsToDouble(0xda0000000000000aL);
+ test_toString(d, "-3.38460656020608E125");
+
+ d = Double.longBitsToDouble(0xda0000000000000dL);
+ test_toString(d, "-3.3846065602060826E125");
+ d = Double.longBitsToDouble(0xda0000000000000eL);
+ test_toString(d, "-3.384606560206083E125");
+ }
+
+ /**
+ * java.lang.Double#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ // Test for method java.lang.Double
+ // java.lang.Double.valueOf(java.lang.String)
+ assertTrue("Incorrect double returned", Math.abs(Double.valueOf("999999999999.999")
+ .doubleValue() - 999999999999.999d) < 1);
+
+ try {
+ Double.valueOf(null);
+ fail("Expected Double.valueOf(null) to throw NPE.");
+ } catch (NullPointerException ex) {
+ // expected
+ }
+
+ try {
+ Double.valueOf("");
+ fail("Expected Double.valueOf(\"\") to throw NFE");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ Double pi = Double.valueOf("3.141592654");
+ assertEquals(3.141592654, pi.doubleValue(), 0D);
+
+ Double posZero = Double.valueOf("+0.0");
+ Double negZero = Double.valueOf("-0.0");
+ assertFalse("Doubletest0", posZero.equals(negZero));
+
+ // Tests for double values by name.
+ Double expectedNaN = new Double(Double.NaN);
+
+ Double posNaN = Double.valueOf("NaN");
+ assertTrue("Doubletest1", posNaN.equals(expectedNaN));
+
+ Double posNaNSigned = Double.valueOf("+NaN");
+ assertTrue("Doubletest2", posNaNSigned.equals(expectedNaN));
+
+ Double negNaNSigned = Double.valueOf("-NaN");
+ assertTrue("Doubletest3", negNaNSigned.equals(expectedNaN));
+
+ Double posInfinite = Double.valueOf("Infinity");
+ assertTrue("Doubletest4", posInfinite.equals(new Double(Double.POSITIVE_INFINITY)));
+
+ Double posInfiniteSigned = Double.valueOf("+Infinity");
+ assertTrue("Doubletest5", posInfiniteSigned
+ .equals(new Double(Double.POSITIVE_INFINITY)));
+
+ Double negInfiniteSigned = Double.valueOf("-Infinity");
+ assertTrue("Doubletest6", negInfiniteSigned
+ .equals(new Double(Double.NEGATIVE_INFINITY)));
+ }
+
+ /**
+ * java.lang.Double#compareTo(java.lang.Double)
+ * java.lang.Double#compare(double, double)
+ */
+ public void test_compareToLjava_lang_Double() {
+ // A selection of double values in ascending order.
+ double[] values = 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 < values.length; i++) {
+ double d1 = values[i];
+
+ // Test that each value compares equal to itself; and each object is
+ // equal to another object like itself.
+ assertTrue("Assert 0: compare() should be equal: " + d1,
+ Double.compare(d1, d1) == 0);
+ Double objDouble = new Double(d1);
+ assertTrue("Assert 1: compareTo() should be equal: " + d1, objDouble
+ .compareTo(objDouble) == 0);
+
+ // Test that the Double-defined order is respected
+ for (int j = i + 1; j < values.length; j++) {
+ double d2 = values[j];
+ assertTrue("Assert 2: compare() " + d1 + " should be less " + d2, Double
+ .compare(d1, d2) == -1);
+ assertTrue("Assert 3: compare() " + d2 + " should be greater " + d1, Double
+ .compare(d2, d1) == 1);
+ Double D2 = new Double(d2);
+ assertTrue("Assert 4: compareTo() " + d1 + " should be less " + d2, objDouble
+ .compareTo(D2) == -1);
+ assertTrue("Assert 5: compareTo() " + d2 + " should be greater " + d1, D2
+ .compareTo(objDouble) == 1);
+ }
+ }
+
+ try {
+ new Double(0.0D).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Double#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ Double d1 = new Double(87654321.12345d);
+ Double d2 = new Double(87654321.12345d);
+ Double d3 = new Double(0.0002f);
+ assertTrue("Assert 0: Equality test failed", d1.equals(d2) && !(d1.equals(d3)));
+
+ assertTrue("Assert 2: NaN should not be == Nan", Double.NaN != Double.NaN);
+ assertTrue("Assert 3: NaN should not be == Nan", new Double(Double.NaN)
+ .equals(new Double(Double.NaN)));
+ assertTrue("Assert 4: -0d should be == 0d", 0d == -0d);
+ assertTrue("Assert 5: -0d should not be equals() 0d", !new Double(0d)
+ .equals(new Double(-0d)));
+
+ Double dmax = new Double(Double.MAX_VALUE);
+ Double dmax1 = new Double(Double.MAX_VALUE);
+
+ assertTrue("Equality test failed", dmax.equals(dmax1) && !(dmax.equals(new Object())));
+ }
+
+ /**
+ * java.lang.Double#toHexString(double)
+ */
+ public void test_toHexStringF() {
+ // the follow values come from the Double Javadoc/Spec
+ assertEquals("0x0.0p0", Double.toHexString(0.0D));
+ assertEquals("-0x0.0p0", Double.toHexString(-0.0D));
+ assertEquals("0x1.0p0", Double.toHexString(1.0D));
+ assertEquals("-0x1.0p0", Double.toHexString(-1.0D));
+ assertEquals("0x1.0p1", Double.toHexString(2.0D));
+ assertEquals("0x1.8p1", Double.toHexString(3.0D));
+ assertEquals("0x1.0p-1", Double.toHexString(0.5D));
+ assertEquals("0x1.0p-2", Double.toHexString(0.25D));
+ assertEquals("0x1.fffffffffffffp1023", Double.toHexString(Double.MAX_VALUE));
+ assertEquals("0x0.0000000000001p-1022", Double.toHexString(Double.MIN_VALUE));
+
+ // test edge cases
+ assertEquals("NaN", Double.toHexString(Double.NaN));
+ assertEquals("-Infinity", Double.toHexString(Double.NEGATIVE_INFINITY));
+ assertEquals("Infinity", Double.toHexString(Double.POSITIVE_INFINITY));
+
+ // test various numbers
+ assertEquals("-0x1.da8p6", Double.toHexString(-118.625D));
+ assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65D));
+ assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65000D));
+ assertEquals("0x1.2957874cccf63p23", Double.toHexString(9743299.650001234D));
+ assertEquals("0x1.700d1061d3333p33", Double.toHexString(12349743299.65000D));
+
+ // test HARMONY-2132
+ assertEquals("0x1.01p10", Double.toHexString(0x1.01p10));
+ }
+
+ /**
+ * java.lang.Double#valueOf(double)
+ */
+ public void test_valueOfD() {
+ assertEquals(new Double(Double.MIN_VALUE), Double.valueOf(Double.MIN_VALUE));
+ assertEquals(new Double(Double.MAX_VALUE), Double.valueOf(Double.MAX_VALUE));
+ assertEquals(new Double(0), Double.valueOf(0));
+
+ int s = -128;
+ while (s < 128) {
+ assertEquals(new Double(s), Double.valueOf(s));
+ assertEquals(new Double(s + 0.1D), Double.valueOf(s + 0.1D));
+ s++;
+ }
+ }
+
+ /**
+ * {@link java.lang.Double#MAX_EXPONENT}
+ * @since 1.6
+ */
+ public void test_MAX_EXPONENT() {
+ assertTrue("Wrong value of java.lang.Double.MAX_EXPONENT",
+ Double.MAX_EXPONENT == 1023);
+ assertTrue("Wrong value of java.lang.Double.MAX_EXPONENT",
+ Double.MAX_EXPONENT == Math.getExponent(Double.MAX_VALUE));
+ }
+
+ /**
+ * {@link java.lang.Double#MIN_EXPONENT}
+ * @since 1.6
+ */
+ public void test_MIN_EXPONENT() {
+ assertTrue("Wrong value of java.lang.Double.MIN_EXPONENT",
+ Double.MIN_EXPONENT == -1022);
+ assertTrue("Wrong value of java.lang.Double.MIN_EXPONENT",
+ Double.MIN_EXPONENT == Math.getExponent(Double.MIN_NORMAL));
+ }
+
+ /**
+ * {@link java.lang.Double#MIN_NORMAL}
+ * @since 1.6
+ */
+ public void test_MIN_NORMAL() {
+ assertTrue("Wrong value of java.lang.Double.MIN_NORMAL",
+ Double.MIN_NORMAL == 0x1.0p-1022);
+ assertTrue("Wrong value of java.lang.Double.MIN_NORMAL",
+ Double.MIN_NORMAL == Double
+ .longBitsToDouble(0x0010000000000000L));
+ assertTrue("Wrong value of java.lang.Double.MIN_NORMAL",
+ Double.MIN_NORMAL == 2.2250738585072014E-308);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumConstantNotPresentExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumConstantNotPresentExceptionTest.java
new file mode 100644
index 0000000..e1d8085
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumConstantNotPresentExceptionTest.java
@@ -0,0 +1,45 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class EnumConstantNotPresentExceptionTest extends TestCase {
+
+ public enum Fixture {
+ ONE, TWO, THREE
+ }
+
+ public void test_ConstructorLjava_lang_ClassLjava_lang_String() {
+ try {
+ new EnumConstantNotPresentException(null, "");
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_enumType() {
+ EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR");
+ assertEquals(Fixture.class, e.enumType());
+ }
+
+ public void test_constantName() {
+ EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR");
+ assertEquals("FOUR", e.constantName());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumTest.java
new file mode 100644
index 0000000..3f2754c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/EnumTest.java
@@ -0,0 +1,261 @@
+/* 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.tests.java.lang;
+
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+import tests.util.SerializationTester;
+
+public class EnumTest extends TestCase {
+
+ enum Sample {
+ LARRY, MOE, CURLY
+ }
+
+ Sample larry = Sample.LARRY;
+
+ Sample moe = Sample.MOE;
+
+ enum Empty {
+ }
+
+ enum Bogus {
+ UNUSED
+ }
+
+ enum Color {
+ Red, Green, Blue {};
+ }
+
+ enum MockCloneEnum {
+ ONE;
+
+ public void callClone() throws CloneNotSupportedException {
+ super.clone();
+ }
+ }
+
+ /**
+ * java.lang.Enum#compareTo(java.lang.Enum)
+ */
+ public void test_compareToLjava_lang_Enum() {
+ assertTrue(0 < Sample.MOE.compareTo(Sample.LARRY));
+ assertEquals(0, Sample.MOE.compareTo(Sample.MOE));
+ assertTrue(0 > Sample.MOE.compareTo(Sample.CURLY));
+ try {
+ Sample.MOE.compareTo((Sample) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.Enum#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertFalse(moe.equals("bob"));
+ assertTrue(moe.equals(Sample.MOE));
+ assertFalse(Sample.LARRY.equals(Sample.CURLY));
+ assertTrue(Sample.LARRY.equals(larry));
+ assertFalse(Sample.CURLY.equals(null));
+ }
+
+ /**
+ * java.lang.Enum#getDeclaringClass()
+ */
+ public void test_getDeclaringClass() {
+ assertEquals(Sample.class, moe.getDeclaringClass());
+ }
+
+ /**
+ * java.lang.Enum#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals(moe.hashCode(), moe.hashCode());
+ }
+
+ /**
+ * java.lang.Enum#name()
+ */
+ public void test_name() {
+ assertEquals("MOE", moe.name());
+ }
+
+ /**
+ * java.lang.Enum#ordinal()
+ */
+ public void test_ordinal() {
+ assertEquals(0, larry.ordinal());
+ assertEquals(1, moe.ordinal());
+ assertEquals(2, Sample.CURLY.ordinal());
+ }
+
+ /**
+ * java.lang.Enum#toString()
+ */
+ public void test_toString() {
+ assertTrue(moe.toString().equals("MOE"));
+ }
+
+ /**
+ * java.lang.Enum#valueOf(Class, String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertSame(Sample.CURLY, Sample.valueOf("CURLY"));
+ assertSame(Sample.LARRY, Sample.valueOf("LARRY"));
+ assertSame(moe, Sample.valueOf("MOE"));
+ try {
+ Sample.valueOf("non-existant");
+ fail("Expected an exception");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ Sample.valueOf(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // May be caused by some compilers' code
+ } catch (IllegalArgumentException e) {
+ // other compilers will throw this
+ }
+
+
+ Sample s = Enum.valueOf(Sample.class, "CURLY");
+ assertSame(s, Sample.CURLY);
+ s = Enum.valueOf(Sample.class, "LARRY");
+ assertSame(larry, s);
+ s = Enum.valueOf(Sample.class, "MOE");
+ assertSame(s, moe);
+ try {
+ Enum.valueOf(Bogus.class, "MOE");
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ Enum.valueOf((Class<Sample>) null, "a string");
+ fail("Expected an exception");
+ } catch (NullPointerException e) {
+ // May be caused by some compilers' code
+ } catch (IllegalArgumentException e) {
+ // other compilers will throw this
+ }
+ try {
+ Enum.valueOf(Sample.class, null);
+ fail("Expected an exception");
+ } catch (NullPointerException e) {
+ // May be caused by some compilers' code
+ } catch (IllegalArgumentException e) {
+ // other compilers will throw this
+ }
+ try {
+ Enum.valueOf((Class<Sample>) null, (String) null);
+ fail("Expected an exception");
+ } catch (NullPointerException e) {
+ // May be caused by some compilers' code
+ } catch (IllegalArgumentException e) {
+ // other compilers will throw this
+ }
+ }
+
+ /**
+ * java.lang.Enum#values
+ */
+ public void test_values() {
+ Sample[] myValues = Sample.values();
+ assertEquals(3, myValues.length);
+
+ assertEquals(Sample.LARRY, myValues[0]);
+ assertEquals(Sample.MOE, myValues[1]);
+ assertEquals(Sample.CURLY, myValues[2]);
+
+ assertEquals(0, Empty.values().length);
+ }
+
+ /**
+ * java.lang.Enum#clone()
+ */
+ public void test_clone() {
+ try {
+ MockCloneEnum.ONE.callClone();
+ fail("Should throw CloneNotSupprotedException");
+ } catch (CloneNotSupportedException e1) {
+ // expected
+ }
+
+ }
+
+ 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/tests/java/lang/EnumTest.harmony.ser"));
+ }
+
+ /**
+ * serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ // test a map class that has enums.
+ // regression test for Harmony-1163
+ HashMap<Color, Integer> enumColorMap = new HashMap<Color, Integer>();
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, 3);
+
+ Object[] testCases = { enumColorMap, Sample.CURLY };
+
+ SerializationTest.verifySelf(testCases);
+
+ // test a class that has enums as its fields.
+ MockEnum mock = new MockEnum();
+ MockEnum test = (MockEnum) SerializationTest.copySerializable(mock);
+ assertEquals(mock.i, test.i);
+ assertEquals(mock.str, test.str);
+ assertEquals(mock.samEnum, test.samEnum);
+
+ // test a class that has enums and a string of same name as its fields.
+ MockEnum2 mock2 = new MockEnum2();
+ MockEnum2 test2 = (MockEnum2) SerializationTest.copySerializable(mock2);
+ assertEquals(mock2.i, test2.i);
+ assertEquals(mock2.str, test2.str);
+ assertEquals(mock2.samEnum, test2.samEnum);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ // regression test for Harmony-1163
+ HashMap<Color, Integer> enumColorMap = new HashMap<Color, Integer>();
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, 3);
+
+ Object[] testCases = { Sample.CURLY, new MockEnum(),
+ // test a class that has enums and a string of same name as its fields.
+ new MockEnum2(),
+ // test a map class that has enums.
+ enumColorMap, };
+
+ SerializationTest.verifyGolden(this, testCases);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ErrorTest.java
new file mode 100644
index 0000000..f11cc64
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ErrorTest extends TestCase {
+
+ /**
+ * java.lang.Error#Error()
+ */
+ public void test_Constructor() {
+ Error e = new Error();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.Error#Error(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ Error e = new Error("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionInInitializerErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionInInitializerErrorTest.java
new file mode 100644
index 0000000..b2b034e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionInInitializerErrorTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.tests.java.lang;
+
+public class ExceptionInInitializerErrorTest extends junit.framework.TestCase {
+
+ /**
+ * java.lang.ExceptionInInitializerError#ExceptionInInitializerError()
+ */
+ public void test_Constructor() {
+ ExceptionInInitializerError e = new ExceptionInInitializerError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.ExceptionInInitializerError#ExceptionInInitializerError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ ExceptionInInitializerError e = new ExceptionInInitializerError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionTest.java
new file mode 100644
index 0000000..1a0f1e4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ExceptionTest extends TestCase {
+
+ /**
+ * java.lang.Exception#Exception()
+ */
+ public void test_Constructor() {
+ Exception e = new Exception();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.Exception#Exception(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ Exception e = new Exception("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/FloatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/FloatTest.java
new file mode 100644
index 0000000..db61f1c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/FloatTest.java
@@ -0,0 +1,1077 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class FloatTest extends TestCase {
+
+ private static final int rawBitsFor3_4eN38To38[] = { 0x1394470, 0x2e7958c, 0x490bd77, 0x634ecd5,
+ 0x7e2280b, 0x98d5907, 0xb30af48, 0xcdcdb1a, 0xe8a08f0, 0x102c8b2d, 0x11d7adf8,
+ 0x1386ccbb, 0x15287fe9, 0x16d29fe4, 0x1883a3ee, 0x1a248cea, 0x1bcdb025, 0x1d808e17,
+ 0x1f20b19d, 0x20c8de04, 0x227b1585, 0x241ced73, 0x25c428d0, 0x27753303, 0x29193fe2,
+ 0x2abf8fdb, 0x2c6f73d1, 0x2e15a863, 0x2fbb127c, 0x3169d71a, 0x33122671, 0x34b6b00d,
+ 0x36645c10, 0x380eb98a, 0x39b267ec, 0x3b5f01e8, 0x3d0b6131, 0x3eae397d, 0x4059c7dc,
+ 0x42081cea, 0x43aa2424, 0x4554ad2d, 0x4704ec3c, 0x48a6274b, 0x4a4fb11e, 0x4c01ceb3,
+ 0x4da2425f, 0x4f4ad2f7, 0x50fd87b5, 0x529e74d1, 0x54461205, 0x55f79687, 0x579abe14,
+ 0x59416d99, 0x5af1c900, 0x5c971da0, 0x5e3ce508, 0x5fec1e4a, 0x619392ee, 0x633877a9,
+ 0x64e69594, 0x66901d7c, 0x683424dc, 0x69e12e12, 0x6b8cbccb, 0x6d2febfe, 0x6edbe6fe,
+ 0x7089705f, 0x722bcc76, 0x73d6bf94, 0x758637bc, 0x7727c5ac, 0x78d1b717, 0x7a83126e,
+ 0x7c23d70a, 0x7dcccccc, 0x7f7fffff };
+
+ private static final String expectedStringFor3_4eN38To38[] = { "3.4028235E-38", "3.4028235E-37",
+ "3.4028233E-36", "3.4028234E-35", "3.4028236E-34", "3.4028236E-33",
+ "3.4028234E-32", "3.4028234E-31", "3.4028233E-30", "3.4028236E-29",
+ "3.4028235E-28", "3.4028235E-27", "3.4028233E-26", "3.4028235E-25",
+ "3.4028233E-24", "3.4028235E-23", "3.4028236E-22", "3.4028235E-21",
+ "3.4028236E-20", "3.4028236E-19", "3.4028236E-18", "3.4028235E-17",
+ "3.4028236E-16", "3.4028234E-15", "3.4028234E-14", "3.4028235E-13",
+ "3.4028234E-12", "3.4028235E-11", "3.4028236E-10", "3.4028234E-9", "3.4028236E-8",
+ "3.4028236E-7", "3.4028235E-6", "3.4028235E-5", "3.4028233E-4", "0.0034028236",
+ "0.034028236", "0.34028235", "3.4028234", "34.028236", "340.28235", "3402.8235",
+ "34028.234", "340282.34", "3402823.5", "3.4028236E7", "3.40282336E8",
+ "3.40282342E9", "3.40282348E10", "3.40282343E11", "3.40282337E12", "3.40282353E13",
+ "3.4028234E14", "3.4028234E15", "3.40282356E16", "3.40282356E17", "3.40282356E18",
+ "3.4028236E19", "3.4028235E20", "3.4028233E21", "3.4028235E22", "3.4028233E23",
+ "3.4028236E24", "3.4028234E25", "3.4028233E26", "3.4028234E27", "3.4028235E28",
+ "3.4028236E29", "3.4028233E30", "3.4028235E31", "3.4028233E32", "3.4028236E33",
+ "3.4028236E34", "3.4028234E35", "3.4028236E36", "3.4028235E37", "3.4028235E38" };
+
+ private static final int rawBitsFor1_17eN38To38[] = { 0x80800000, 0x82200000, 0x83c80000,
+ 0x857a0000, 0x871c4000, 0x88c35000, 0x8a742400, 0x8c189680, 0x8dbebc20, 0x8f6e6b28,
+ 0x911502f9, 0x92ba43b7, 0x9468d4a5, 0x961184e7, 0x97b5e621, 0x99635fa9, 0x9b0e1bca,
+ 0x9cb1a2bc, 0x9e5e0b6b, 0xa00ac723, 0xa1ad78ec, 0xa358d727, 0xa5078678, 0xa6a96816,
+ 0xa853c21c, 0xaa045951, 0xaba56fa6, 0xad4ecb8f, 0xaf013f39, 0xb0a18f08, 0xb249f2ca,
+ 0xb3fc6f7c, 0xb59dc5ae, 0xb7453719, 0xb8f684df, 0xba9a130c, 0xbc4097ce, 0xbdf0bdc2,
+ 0xbf967699, 0xc13c1440, 0xc2eb1950, 0xc492efd2, 0xc637abc6, 0xc7e596b8, 0xc98f7e33,
+ 0xcb335dc0, 0xcce0352f, 0xce8c213e, 0xd02f298d, 0xd1daf3f0, 0xd388d876, 0xd52b0e94,
+ 0xd6d5d239, 0xd885a363, 0xda270c3c, 0xdbd0cf4b, 0xdd82818f, 0xdf2321f3, 0xe0cbea70,
+ 0xe27ee50b, 0xe41f4f27, 0xe5c722f1, 0xe778ebad, 0xe91b934c, 0xeac2781f, 0xec731627,
+ 0xee17edd8, 0xefbde94f, 0xf16d63a2, 0xf3145e45, 0xf4b975d7, 0xf667d34c, 0xf810e410,
+ 0xf9b51d14, 0xfb626459, 0xfd0d7eb7, 0xfeb0de65 };
+
+ private static final String expectedStringFor1_17eN38To38[] = { "-1.17549435E-38",
+ "-1.1754944E-37", "-1.17549435E-36", "-1.17549435E-35", "-1.1754944E-34",
+ "-1.17549435E-33", "-1.17549435E-32", "-1.1754944E-31", "-1.17549435E-30",
+ "-1.17549435E-29", "-1.1754944E-28", "-1.1754943E-27", "-1.17549435E-26",
+ "-1.1754943E-25", "-1.1754944E-24", "-1.1754943E-23", "-1.1754944E-22",
+ "-1.1754943E-21", "-1.1754943E-20", "-1.1754943E-19", "-1.1754944E-18",
+ "-1.1754944E-17", "-1.1754943E-16", "-1.1754943E-15", "-1.1754944E-14",
+ "-1.1754943E-13", "-1.1754944E-12", "-1.1754943E-11", "-1.1754943E-10",
+ "-1.1754944E-9", "-1.1754944E-8", "-1.1754943E-7", "-1.1754944E-6",
+ "-1.1754943E-5", "-1.1754943E-4", "-0.0011754944", "-0.011754943", "-0.117549434",
+ "-1.1754943", "-11.754944", "-117.54944", "-1175.4944", "-11754.943", "-117549.44",
+ "-1175494.4", "-1.1754944E7", "-1.17549432E8", "-1.1754944E9", "-1.17549435E10",
+ "-1.17549433E11", "-1.17549433E12", "-1.17549438E13", "-1.17549438E14",
+ "-1.1754943E15", "-1.17549432E16", "-1.17549432E17", "-1.17549434E18",
+ "-1.1754944E19", "-1.1754944E20", "-1.1754943E21", "-1.1754943E22",
+ "-1.1754944E23", "-1.17549434E24", "-1.1754943E25", "-1.1754943E26",
+ "-1.17549434E27", "-1.1754943E28", "-1.1754944E29", "-1.1754943E30",
+ "-1.1754943E31", "-1.1754944E32", "-1.1754943E33", "-1.1754944E34",
+ "-1.1754944E35", "-1.1754944E36", "-1.1754943E37", "-1.1754943E38" };
+
+ private void doTestCompareRawBits(String originalFloatString, int expectedRawBits,
+ String expectedString) {
+ int rawBits;
+ float result = Float.parseFloat(originalFloatString);
+ rawBits = Float.floatToIntBits(result);
+ assertEquals("Original float(" + originalFloatString + ") Converted float(" + result
+ + ") Expecting:" + Integer.toHexString(expectedRawBits) + " Got: "
+ + Integer.toHexString(rawBits), expectedRawBits, rawBits);
+ }
+
+ /**
+ * java.lang.Float#Float(float)
+ */
+ public void test_ConstructorF() {
+ // Test for method java.lang.Float(float)
+
+ Float f = new Float(900.89f);
+ assertTrue("Created incorrect float", f.floatValue() == 900.89f);
+ }
+
+ /**
+ * java.lang.Float#Float(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.lang.Float(java.lang.String)
+
+ Float f = new Float("900.89");
+ assertTrue("Created incorrect Float", f.floatValue() == 900.89f);
+ }
+
+ /**
+ * java.lang.Float#byteValue()
+ */
+ public void test_byteValue() {
+ // Test for method byte java.lang.Float.byteValue()
+ Float f = new Float(0.46874f);
+ Float f2 = new Float(90.8f);
+ assertTrue("Returned incorrect byte value", f.byteValue() == 0 && f2.byteValue() == 90);
+ }
+
+ /**
+ * java.lang.Float#compareTo(java.lang.Float)
+ * java.lang.Float#compare(float, float)
+ */
+ public void test_compare() {
+ float[] values = 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 < values.length; i++) {
+ float f1 = values[i];
+ assertTrue("compare() should be equal: " + f1, Float.compare(f1, f1) == 0);
+ Float F1 = new Float(f1);
+ assertTrue("compareTo() should be equal: " + f1, F1.compareTo(F1) == 0);
+ for (int j = i + 1; j < values.length; j++) {
+ float f2 = values[j];
+ assertTrue("compare() " + f1 + " should be less " + f2,
+ Float.compare(f1, f2) == -1);
+ assertTrue("compare() " + f2 + " should be greater " + f1, Float
+ .compare(f2, f1) == 1);
+ Float F2 = new Float(f2);
+ assertTrue("compareTo() " + f1 + " should be less " + f2,
+ F1.compareTo(F2) == -1);
+ assertTrue("compareTo() " + f2 + " should be greater " + f1,
+ F2.compareTo(F1) == 1);
+ }
+ }
+
+ try {
+ new Float(0.0F).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Float#doubleValue()
+ */
+ public void test_doubleValue() {
+ // Test for method double java.lang.Float.doubleValue()
+ assertTrue("Incorrect double value returned", Math.abs(new Float(999999.999f)
+ .doubleValue() - 999999.999d) < 1);
+ }
+
+ /**
+ * java.lang.Float#floatToIntBits(float)
+ */
+ public void test_floatToIntBitsF() {
+ float f = 9876.2345f;
+ int bits = Float.floatToIntBits(f);
+ float r = Float.intBitsToFloat(bits);
+ assertTrue("Incorrect intBits returned", f == r);
+ }
+
+ /**
+ * java.lang.Float#floatToRawIntBits(float)
+ */
+ public void test_floatToRawIntBitsF() {
+ int i = 0x7fc004d2;
+ float f = Float.intBitsToFloat(i);
+ assertTrue("Wrong raw bits", Float.floatToRawIntBits(f) == i);
+ }
+
+ /**
+ * java.lang.Float#floatValue()
+ */
+ public void test_floatValue() {
+ // Test for method float java.lang.Float.floatValue()
+ Float f = new Float(87.657f);
+ Float f2 = new Float(-0.876f);
+ assertTrue("Returned incorrect floatValue", f.floatValue() == 87.657f
+ && (f2.floatValue() == -0.876f));
+
+ }
+
+ /**
+ * java.lang.Float#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.lang.Float.hashCode()
+ Float f = new Float(1908.8786f);
+ assertTrue("Returned invalid hash code for 1908.8786f", f.hashCode() == Float
+ .floatToIntBits(1908.8786f));
+
+ f = new Float(-1.112f);
+ assertTrue("Returned invalid hash code for -1.112", f.hashCode() == Float
+ .floatToIntBits(-1.112f));
+
+ f = new Float(0f);
+ assertTrue("Returned invalid hash code for 0", f.hashCode() == Float.floatToIntBits(0f));
+
+ }
+
+ /**
+ * java.lang.Float#intBitsToFloat(int)
+ */
+ public void test_intBitsToFloatI() {
+ float f = 9876.2345f;
+ int bits = Float.floatToIntBits(f);
+ float r = Float.intBitsToFloat(bits);
+ assertEquals("Incorrect intBits returned", f, r, 0F);
+ }
+
+ /**
+ * java.lang.Float#intValue()
+ */
+ public void test_intValue() {
+ // Test for method int java.lang.Float.intValue()
+ Float f = new Float(0.46874f);
+ Float f2 = new Float(90.8f);
+ assertTrue("Returned incorrect int value", f.intValue() == 0 && f2.intValue() == 90);
+ }
+
+ /**
+ * java.lang.Float#isInfinite()
+ */
+ public void test_isInfinite() {
+ // Test for method boolean java.lang.Float.isInfinite()
+ assertTrue("Infinity check failed",
+ (new Float(Float.POSITIVE_INFINITY).isInfinite() && new Float(
+ Float.NEGATIVE_INFINITY).isInfinite())
+ && !(new Float(0.13131414f).isInfinite()));
+ }
+
+ /**
+ * java.lang.Float#isInfinite(float)
+ */
+ public void test_isInfiniteF() {
+ // Test for method boolean java.lang.Float.isInfinite(float)
+
+ assertTrue("Infinity check failed", Float.isInfinite(Float.POSITIVE_INFINITY)
+ && (Float.isInfinite(Float.NEGATIVE_INFINITY)) && !(Float.isInfinite(1.0f)));
+ }
+
+ /**
+ * java.lang.Float#isNaN()
+ */
+ public void test_isNaN() {
+ // Test for method boolean java.lang.Float.isNaN()
+ assertTrue("NAN check failed", new Float(Float.NaN).isNaN()
+ && !(new Float(1.0f).isNaN()));
+ }
+
+ /**
+ * java.lang.Float#isNaN(float)
+ */
+ public void test_isNaNF() {
+ // Test for method boolean java.lang.Float.isNaN(float)
+ assertTrue("NaN check failed", Float.isNaN(Float.NaN) && !(Float.isNaN(12.09f)));
+ }
+
+ /**
+ * java.lang.Float#longValue()
+ */
+ public void test_longValue() {
+ // Test for method long java.lang.Float.longValue()
+ Float f = new Float(0.46874f);
+ Float f2 = new Float(90.8f);
+ assertTrue("Returned incorrect long value", f.longValue() == 0 && f2.longValue() == 90);
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloatLjava_lang_String() {
+ assertEquals("Incorrect float returned, expected zero.", 0.0, Float
+ .parseFloat("7.0064923216240853546186479164495e-46"), 0.0);
+ assertEquals("Incorrect float returned, expected minimum float.", Float.MIN_VALUE,
+ Float.parseFloat("7.0064923216240853546186479164496e-46"), 0.0);
+
+ doTestCompareRawBits(
+ "0.000000000000000000000000000000000000011754942807573642917278829910357665133228589927589904276829631184250030649651730385585324256680905818939208984375",
+ 0x800000, "1.17549435E-38");
+ doTestCompareRawBits(
+ "0.00000000000000000000000000000000000001175494280757364291727882991035766513322858992758990427682963118425003064965173038558532425668090581893920898437499999f",
+ 0x7fffff, "1.1754942E-38");
+
+ /* Test a set of regular floats with exponents from -38 to +38 */
+ for (int i = 38; i > 3; i--) {
+ String testString;
+ testString = "3.4028234663852886e-" + i;
+ doTestCompareRawBits(testString, rawBitsFor3_4eN38To38[38 - i],
+ expectedStringFor3_4eN38To38[38 - i]);
+ }
+ doTestCompareRawBits("3.4028234663852886e-3", rawBitsFor3_4eN38To38[38 - 3],
+ expectedStringFor3_4eN38To38[38 - 3]);
+ doTestCompareRawBits("3.4028234663852886e-2", rawBitsFor3_4eN38To38[38 - 2],
+ expectedStringFor3_4eN38To38[38 - 2]);
+ doTestCompareRawBits("3.4028234663852886e-1", rawBitsFor3_4eN38To38[38 - 1],
+ expectedStringFor3_4eN38To38[38 - 1]);
+ doTestCompareRawBits("3.4028234663852886e-0", rawBitsFor3_4eN38To38[38 - 0],
+ expectedStringFor3_4eN38To38[38 - 0]);
+ doTestCompareRawBits("3.4028234663852886e+1", rawBitsFor3_4eN38To38[38 + 1],
+ expectedStringFor3_4eN38To38[38 + 1]);
+ doTestCompareRawBits("3.4028234663852886e+2", rawBitsFor3_4eN38To38[38 + 2],
+ expectedStringFor3_4eN38To38[38 + 2]);
+ doTestCompareRawBits("3.4028234663852886e+3", rawBitsFor3_4eN38To38[38 + 3],
+ expectedStringFor3_4eN38To38[38 + 3]);
+ doTestCompareRawBits("3.4028234663852886e+4", rawBitsFor3_4eN38To38[38 + 4],
+ expectedStringFor3_4eN38To38[38 + 4]);
+ doTestCompareRawBits("3.4028234663852886e+5", rawBitsFor3_4eN38To38[38 + 5],
+ expectedStringFor3_4eN38To38[38 + 5]);
+ doTestCompareRawBits("3.4028234663852886e+6", rawBitsFor3_4eN38To38[38 + 6],
+ expectedStringFor3_4eN38To38[38 + 6]);
+
+ for (int i = 7; i < 39; i++) {
+ String testString;
+ testString = "3.4028234663852886e+" + i;
+ doTestCompareRawBits(testString, rawBitsFor3_4eN38To38[38 + i],
+ expectedStringFor3_4eN38To38[38 + i]);
+ }
+
+ /* Test another set of regular floats with exponents from -38 to +38 */
+ for (int i = 38; i > 3; i--) {
+ String testString;
+ testString = "-1.1754943508222875e-" + i;
+ doTestCompareRawBits(testString, rawBitsFor1_17eN38To38[38 - i],
+ expectedStringFor1_17eN38To38[38 - i]);
+ }
+ doTestCompareRawBits("-1.1754943508222875e-3", rawBitsFor1_17eN38To38[38 - 3],
+ expectedStringFor1_17eN38To38[38 - 3]);
+ doTestCompareRawBits("-1.1754943508222875e-2", rawBitsFor1_17eN38To38[38 - 2],
+ expectedStringFor1_17eN38To38[38 - 2]);
+ doTestCompareRawBits("-1.1754943508222875e-1", rawBitsFor1_17eN38To38[38 - 1],
+ expectedStringFor1_17eN38To38[38 - 1]);
+ doTestCompareRawBits("-1.1754943508222875e-0", rawBitsFor1_17eN38To38[38 - 0],
+ expectedStringFor1_17eN38To38[38 - 0]);
+ doTestCompareRawBits("-1.1754943508222875e+1", rawBitsFor1_17eN38To38[38 + 1],
+ expectedStringFor1_17eN38To38[38 + 1]);
+ doTestCompareRawBits("-1.1754943508222875e+2", rawBitsFor1_17eN38To38[38 + 2],
+ expectedStringFor1_17eN38To38[38 + 2]);
+ doTestCompareRawBits("-1.1754943508222875e+3", rawBitsFor1_17eN38To38[38 + 3],
+ expectedStringFor1_17eN38To38[38 + 3]);
+ doTestCompareRawBits("-1.1754943508222875e+4", rawBitsFor1_17eN38To38[38 + 4],
+ expectedStringFor1_17eN38To38[38 + 4]);
+ doTestCompareRawBits("-1.1754943508222875e+5", rawBitsFor1_17eN38To38[38 + 5],
+ expectedStringFor1_17eN38To38[38 + 5]);
+ doTestCompareRawBits("-1.1754943508222875e+6", rawBitsFor1_17eN38To38[38 + 6],
+ expectedStringFor1_17eN38To38[38 + 6]);
+
+ for (int i = 7; i < 39; i++) {
+ String testString;
+ testString = "-1.1754943508222875e+" + i;
+ doTestCompareRawBits(testString, rawBitsFor1_17eN38To38[38 + i],
+ expectedStringFor1_17eN38To38[38 + i]);
+ }
+
+ /* Test denormalized floats (floats with exponents <= -38 */
+ doTestCompareRawBits("1.1012984643248170E-45", 1, "1.4E-45");
+ doTestCompareRawBits("-1.1012984643248170E-45", 0x80000001, "-1.4E-45");
+ doTestCompareRawBits("1.0E-45", 1, "1.4E-45");
+ doTestCompareRawBits("-1.0E-45", 0x80000001, "-1.4E-45");
+ doTestCompareRawBits("0.9E-45", 1, "1.4E-45");
+ doTestCompareRawBits("-0.9E-45", 0x80000001, "-1.4E-45");
+ doTestCompareRawBits("4.203895392974451e-45", 3, "4.2E-45");
+ doTestCompareRawBits("-4.203895392974451e-45", 0x80000003, "-4.2E-45");
+ doTestCompareRawBits("0.004E-45", 0, "0.0");
+ doTestCompareRawBits("-0.004E-45", 0x80000000, "-0.0");
+
+ /*
+ * Test for large floats close to and greater than 3.4028235E38 and
+ * -3.4028235E38
+ */
+ doTestCompareRawBits("1.2E+38", 0x7eb48e52, "1.2E38");
+ doTestCompareRawBits("-1.2E+38", 0xfeb48e52, "-1.2E38");
+ doTestCompareRawBits("3.2E+38", 0x7f70bdc2, "3.2E38");
+ doTestCompareRawBits("-3.2E+38", 0xff70bdc2, "-3.2E38");
+ doTestCompareRawBits("3.4E+38", 0x7f7fc99e, "3.4E38");
+ doTestCompareRawBits("-3.4E+38", 0xff7fc99e, "-3.4E38");
+ doTestCompareRawBits("3.4028234663852886E+38", 0x7f7fffff, "3.4028235E38");
+ doTestCompareRawBits("-3.4028234663852886E+38", 0xff7fffff, "-3.4028235E38");
+ doTestCompareRawBits("3.405E+38", 0x7f800000, "Infinity");
+ doTestCompareRawBits("-3.405E+38", 0xff800000, "-Infinity");
+ doTestCompareRawBits("3.41E+38", 0x7f800000, "Infinity");
+ doTestCompareRawBits("-3.41E+38", 0xff800000, "-Infinity");
+ doTestCompareRawBits("3.42E+38", 0x7f800000, "Infinity");
+ doTestCompareRawBits("-3.42E+38", 0xff800000, "-Infinity");
+ doTestCompareRawBits("1.0E+39", 0x7f800000, "Infinity");
+ doTestCompareRawBits("-1.0E+39", 0xff800000, "-Infinity");
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_Unusual() {
+ float actual;
+
+ actual = Float.parseFloat("0x00000000000000000000000000000000000000000.0000000000000000000000000000000000000p0000000000000000000000000000000000");
+ assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
+
+ actual = Float.parseFloat("+0Xfffff.fffffffffffffffffffffffffffffffp+99F");
+ assertEquals("Returned incorrect value", 6.64614E35f, actual, 0.0F);
+
+ actual = Float.parseFloat("-0X.123456789abcdefp+99f");
+ assertEquals("Returned incorrect value", -4.5072022E28f, actual, 0.0F);
+
+ actual = Float.parseFloat("-0X123456789abcdef.p+1f");
+ assertEquals("Returned incorrect value", -1.63971062E17f, actual, 0.0F);
+
+ actual = Float.parseFloat("-0X000000000000000000000000000001abcdef.0000000000000000000000000001abefp00000000000000000000000000000000000000000004f");
+ assertEquals("Returned incorrect value", -4.48585472E8f, actual, 0.0F);
+
+ actual = Float.parseFloat("0X0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234p600f");
+ assertEquals("Returned incorrect value", 5.907252E33f, actual, 0.0F);
+
+ actual = Float.parseFloat("0x1.p9223372036854775807");
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
+
+ actual = Float.parseFloat("0x1.p9223372036854775808");
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
+
+ actual = Float.parseFloat("0x10.p9223372036854775808");
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
+
+ actual = Float.parseFloat("0xabcd.ffffffffp+2000");
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
+
+ actual = Float.parseFloat("0x1.p-9223372036854775808");
+ assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
+
+ actual = Float.parseFloat("0x1.p-9223372036854775809");
+ assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
+
+ actual = Float.parseFloat("0x.1p-9223372036854775809");
+ assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_NormalPositiveExponent() {
+ int[] expecteds = {
+ 0x3991a2b4, 0x43cc0247, 0x47909009,
+ 0x4ac0c009, 0x4e109005, 0x5140c005,
+ 0x5458d805, 0x57848402, 0x5a909002,
+ 0x5da8a802, 0x60c0c002, 0x63cccc02,
+ 0x66e4e402, 0x69f0f002, 0x6d048401,
+ 0x70109001, 0x73169601, 0x76810810,
+ 0x79840840, 0x7c8a08a0, 0x7f800000,
+ 0x7f800000, 0x7f800000, 0x7f800000,
+ 0x7f800000,
+ };
+
+ for (int i = 0; i < expecteds.length; i++) {
+ int part = i * 6;
+ String inputString = "0x" + part + "." + part + "0123456789abcdefp" + part;
+
+ float actual = Float.parseFloat(inputString);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputString
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_NormalNegativeExponent() {
+ int[] expecteds = {
+ 0x3991a2b4,
+ 0x3d6e0247,
+ 0x3aa0a009,
+ 0x37848405,
+ 0x3420a005,
+ 0x30d4d405,
+ 0x2d848402,
+ 0x2a129202,
+ 0x26acac02,
+ 0x2346c602,
+ 0x1fe0e002,
+ 0x1c6eee02,
+ 0x19048401,
+ 0x15919101,
+ 0x12189801,
+ 0xf028828,
+ 0xb890890,
+ 0x80c88c8,
+ 0x4930930,
+ 0x1198998,
+ 0x28028,
+ 0x51c,
+ 0xb,
+ 0x0,
+ 0x0,
+ };
+
+ for (int i = 0; i < expecteds.length; i++) {
+ int part = i * 7;
+ String inputString = "0x" + part + "." + part + "0123456789abcdefp-" + part;
+
+ float actual = Float.parseFloat(inputString);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputString
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_MaxNormalBoundary() {
+ int[] expecteds = {
+ 0x7f7fffff,
+ 0x7f7fffff,
+ 0x7f7fffff,
+ 0x7f800000,
+ 0x7f800000,
+ 0x7f800000,
+
+ 0xff7fffff,
+ 0xff7fffff,
+ 0xff7fffff,
+ 0xff800000,
+ 0xff800000,
+ 0xff800000,
+ };
+
+ String[] inputs = {
+ "0x1.fffffep127",
+ "0x1.fffffe000000000000000000000000000000000000000000000001p127",
+ "0x1.fffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
+ "0x1.ffffffp127",
+ "0x1.ffffff000000000000000000000000000000000000000000000001p127",
+ "0x1.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
+
+ "-0x1.fffffep127",
+ "-0x1.fffffe000000000000000000000000000000000000000000000001p127",
+ "-0x1.fffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
+ "-0x1.ffffffp127",
+ "-0x1.ffffff000000000000000000000000000000000000000000000001p127",
+ "-0x1.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
+ };
+
+ for (int i = 0; i < inputs.length; i++) {
+ float actual = Float.parseFloat(inputs[i]);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_MinNormalBoundary() {
+ int expecteds[] = {
+ 0x800000,
+ 0x800000,
+ 0x800000,
+ 0x800000,
+ 0x800001,
+ 0x800001,
+
+ 0x80800000,
+ 0x80800000,
+ 0x80800000,
+ 0x80800000,
+ 0x80800001,
+ 0x80800001,
+ };
+
+ String inputs[] = {
+ "0x1.0p-126",
+ "0x1.00000000000000000000000000000000000000000000001p-126",
+ "0x1.000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "0x1.000001p-126",
+ "0x1.000001000000000000000000000000000000000000000001p-126",
+ "0x1.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+
+ "-0x1.0p-126",
+ "-0x1.00000000000000000000000000000000000000000000001p-126",
+ "-0x1.000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "-0x1.000001p-126",
+ "-0x1.000001000000000000000000000000000000000000000001p-126",
+ "-0x1.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ };
+
+ for (int i = 0; i < inputs.length; i++) {
+ float actual = Float.parseFloat(inputs[i]);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_MaxSubNormalBoundary() {
+ int expecteds[] = {
+ 0x7fffff,
+ 0x7fffff,
+ 0x7fffff,
+ 0x800000,
+ 0x800000,
+ 0x800000,
+
+ 0x807fffff,
+ 0x807fffff,
+ 0x807fffff,
+ 0x80800000,
+ 0x80800000,
+ 0x80800000,
+ };
+
+ String inputs[] = {
+ "0x0.fffffep-126",
+ "0x0.fffffe000000000000000000000000000000000000000000000000000001p-126",
+ "0x0.fffffefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "0x0.ffffffp-126",
+ "0x0.ffffff0000000000000000000000000000000000000000000000000000001p-126",
+ "0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+
+ "-0x0.fffffep-126",
+ "-0x0.fffffe000000000000000000000000000000000000000000000000000001p-126",
+ "-0x0.fffffefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "-0x0.ffffffp-126",
+ "-0x0.ffffff0000000000000000000000000000000000000000000000000000001p-126",
+ "-0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ };
+
+ for (int i = 0; i < inputs.length; i++) {
+ float actual = Float.parseFloat(inputs[i]);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_MinSubNormalBoundary() {
+ int expecteds[] = {
+ 0x1,
+ 0x1,
+ 0x1,
+ 0x2,
+ 0x2,
+ 0x2,
+
+ 0x80000001,
+ 0x80000001,
+ 0x80000001,
+ 0x80000002,
+ 0x80000002,
+ 0x80000002,
+ };
+
+ String inputs[] = {
+ "0x0.000002p-126",
+ "0x0.00000200000000000000000000000000000000000001p-126",
+ "0x0.000002ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "0x0.000003p-126",
+ "0x0.000003000000000000000000000000000000000000001p-126",
+ "0x0.000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+
+ "-0x0.000002p-126",
+ "-0x0.00000200000000000000000000000000000000000001p-126",
+ "-0x0.000002ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "-0x0.000003p-126",
+ "-0x0.000003000000000000000000000000000000000000001p-126",
+ "-0x0.000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ };
+
+ for (int i = 0; i < inputs.length; i++) {
+ float actual = Float.parseFloat(inputs[i]);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_ZeroBoundary() {
+ int expecteds[] = {
+ 0x0,
+ 0x0,
+ 0x0,
+ 0x0,
+ 0x1,
+ 0x1,
+
+ 0x80000000,
+ 0x80000000,
+ 0x80000000,
+ 0x80000000,
+ 0x80000001,
+ 0x80000001,
+ };
+
+ String inputs[] = {
+ "0x0.000000000000000p-126",
+ "0x0.000000000000000000000000000000000000000000000001p-126",
+ "0x0.000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "0x0.000001p-126",
+ "0x0.000001000000000000000000000000000000000000000001p-126",
+ "0x0.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+
+ "-0x0.000000000000000p-126",
+ "-0x0.000000000000000000000000000000000000000000000001p-126",
+ "-0x0.000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ "-0x0.000001p-126",
+ "-0x0.000001000000000000000000000000000000000000000001p-126",
+ "-0x0.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
+ };
+
+ for (int i = 0; i < inputs.length; i++) {
+ float actual = Float.parseFloat(inputs[i]);
+ float expected = Float.intBitsToFloat(expecteds[i]);
+
+ String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
+ String actualString = Integer.toHexString(Float.floatToIntBits(actual));
+ String errorMsg = i + "th input string is:<" + inputs[i]
+ + ">.The expected result should be:<" + expectedString
+ + ">, but was: <" + actualString + ">. ";
+
+ assertEquals(errorMsg, expected, actual, 0.0F);
+ }
+ }
+
+ /**
+ * java.lang.Float#parseFloat(java.lang.String)
+ */
+ public void test_parseFloat_LString_Harmony6261() {
+ // Regression test for HARMONY-6261
+ float f = new Float("2147483648");
+ assertEquals("2.1474836E9", Float.toString(f));
+
+ doTestCompareRawBits("123456790528.000000000000000f", 0x51e5f4c9, "1.2345679E11");
+ doTestCompareRawBits("8589934592", 0x50000000, "8.5899346E9");
+ doTestCompareRawBits("8606711808", 0x50004000, "8.606712E9");
+ }
+
+ /**
+ * java.lang.Float#shortValue()
+ */
+ public void test_shortValue() {
+ // Test for method short java.lang.Float.shortValue()
+ Float f = new Float(0.46874f);
+ Float f2 = new Float(90.8f);
+ assertTrue("Returned incorrect short value", f.shortValue() == 0
+ && f2.shortValue() == 90);
+ }
+
+ /**
+ * java.lang.Float#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.Float.toString()
+
+ test_toString(12.90898f, "12.90898");
+
+ test_toString(1.7014118346046924e+38F, "1.7014118E38");
+
+ test_toString(1E19F, "1.0E19");
+
+ test_toString(1E-36F, "1.0E-36");
+
+ test_toString(1.0E-38F, "1.0E-38");
+ }
+
+ /**
+ * java.lang.Float#toString(float)
+ */
+ public void test_toStringF() {
+ // Test for method java.lang.String java.lang.Float.toString(float)
+
+ float ff;
+ String answer;
+
+ ff = 12.90898f;
+ answer = "12.90898";
+ assertTrue("Incorrect String representation want " + answer + ", got "
+ + Float.toString(ff), Float.toString(ff).equals(answer));
+
+ ff = Float.MAX_VALUE;
+ answer = "3.4028235E38";
+ assertTrue("Incorrect String representation want " + answer + ", got "
+ + Float.toString(ff), Float.toString(ff).equals(answer));
+ }
+
+ /**
+ * java.lang.Float#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ // Test for method java.lang.Float
+ // java.lang.Float.valueOf(java.lang.String)
+
+ Float wanted = new Float(432.1235f);
+ Float got = Float.valueOf("432.1235");
+ assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
+ .equals(wanted));
+
+ wanted = new Float(0f);
+ got = Float.valueOf("0");
+ assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
+ .equals(wanted));
+
+ wanted = new Float(-1212.3232f);
+ got = Float.valueOf("-1212.3232");
+ assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
+ .equals(wanted));
+
+ try {
+ Float.valueOf(null);
+ fail("Expected Float.valueOf(null) to throw NPE.");
+ } catch (NullPointerException ex) {
+ // expected
+ }
+
+ try {
+ Float.valueOf("");
+ fail("Expected Float.valueOf(\"\") to throw NFE");
+ } catch (NumberFormatException e) {
+ // expected
+ }
+
+ Float posZero = Float.valueOf("+0.0");
+ Float negZero = Float.valueOf("-0.0");
+ assertFalse("Floattest0", posZero.equals(negZero));
+ assertTrue("Floattest1", 0.0f == -0.0f);
+
+ // Tests for float values by name.
+ Float expectedNaN = new Float(Float.NaN);
+
+ Float posNaN = Float.valueOf("NaN");
+ assertTrue("Floattest2", posNaN.equals(expectedNaN));
+
+ Float posNaNSigned = Float.valueOf("+NaN");
+ assertTrue("Floattest3", posNaNSigned.equals(expectedNaN));
+
+ Float negNaNSigned = Float.valueOf("-NaN");
+ assertTrue("Floattest4", negNaNSigned.equals(expectedNaN));
+
+ Float posInfinite = Float.valueOf("Infinity");
+ assertTrue("Floattest5", posInfinite.equals(new Float(Float.POSITIVE_INFINITY)));
+
+ Float posInfiniteSigned = Float.valueOf("+Infinity");
+ assertTrue("Floattest6", posInfiniteSigned.equals(new Float(Float.POSITIVE_INFINITY)));
+
+ Float negInfiniteSigned = Float.valueOf("-Infinity");
+ assertTrue("Floattest7", negInfiniteSigned.equals(new Float(Float.NEGATIVE_INFINITY)));
+
+ // test HARMONY-6641
+ posInfinite = Float.valueOf("320.0E+2147483647");
+ assertEquals("Floattest8", Float.POSITIVE_INFINITY, posInfinite);
+
+ negZero = Float.valueOf("-1.4E-2147483314");
+ assertEquals("Floattest9", -0.0f, negZero);
+ }
+
+ private void test_toString(float ff, String answer) {
+ // Test for method java.lang.String java.lang.Double.toString(double)
+ assertTrue("Incorrect String representation want " + answer + ", got ("
+ + Float.toString(ff) + ")", Float.toString(ff).equals(answer));
+ Float f = new Float(ff);
+ assertTrue("Incorrect String representation want " + answer + ", got ("
+ + Float.toString(f.floatValue()) + ")", Float.toString(f.floatValue()).equals(
+ answer));
+ assertTrue("Incorrect String representation want " + answer + ", got (" + f.toString()
+ + ")", f.toString().equals(answer));
+ }
+
+ /**
+ * java.lang.Float#compareTo(java.lang.Float)
+ * java.lang.Float#compare(float, float)
+ */
+ public void test_compareToLjava_lang_Float() {
+ // A selection of float values in ascending order.
+ float[] values = 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 < values.length; i++) {
+ float f1 = values[i];
+
+ // Test that each value compares equal to itself; and each object is
+ // equal to another object
+ // like itself
+ assertTrue("Assert 0: compare() should be equal: " + f1, Float.compare(f1, f1) == 0);
+ Float objFloat = new Float(f1);
+ assertTrue("Assert 1: compareTo() should be equal: " + objFloat, objFloat
+ .compareTo(objFloat) == 0);
+
+ // Test that the Float-defined order is respected
+ for (int j = i + 1; j < values.length; j++) {
+ float f2 = values[j];
+ assertTrue("Assert 2: compare() " + f1 + " should be less " + f2, Float
+ .compare(f1, f2) == -1);
+ assertTrue("Assert 3: compare() " + f2 + " should be greater " + f1, Float
+ .compare(f2, f1) == 1);
+
+ Float F2 = new Float(f2);
+ assertTrue("Assert 4: compareTo() " + f1 + " should be less " + f2, objFloat
+ .compareTo(F2) == -1);
+ assertTrue("Assert 5: compareTo() " + f2 + " should be greater " + f1, F2
+ .compareTo(objFloat) == 1);
+ }
+ }
+ }
+
+ /**
+ * java.lang.Float#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ Float f1 = new Float(8765.4321f);
+ Float f2 = new Float(8765.4321f);
+ Float f3 = new Float(-1.0f);
+ assertTrue("Assert 0: Equality test failed", f1.equals(f2) && !(f1.equals(f3)));
+
+ assertTrue("Assert 1: NaN should not be == Nan", Float.NaN != Float.NaN);
+ assertTrue("Assert 2: NaN should not be == Nan", new Float(Float.NaN).equals(new Float(
+ Float.NaN)));
+ assertTrue("Assert 3: -0f should be == 0f", 0f == -0f);
+ assertTrue("Assert 4: -0f should not be equals() 0f", !new Float(0f).equals(new Float(
+ -0f)));
+
+ f1 = new Float(1098.576f);
+ f2 = new Float(1098.576f);
+ f3 = new Float(1.0f);
+ assertTrue("Equality test failed", f1.equals(f2) && !(f1.equals(f3)));
+
+ assertTrue("NaN should not be == Nan", Float.NaN != Float.NaN);
+ assertTrue("NaN should not be == Nan", new Float(Float.NaN)
+ .equals(new Float(Float.NaN)));
+ assertTrue("-0f should be == 0f", 0f == -0f);
+ assertTrue("-0f should not be equals() 0f", !new Float(0f).equals(new Float(-0f)));
+ }
+
+ /**
+ * java.lang.Float#toHexString(float)
+ */
+ public void test_toHexStringF() {
+ // the follow values comes from the Float Javadoc/Spec
+ assertEquals("0x0.0p0", Float.toHexString(0.0F));
+ assertEquals("-0x0.0p0", Float.toHexString(-0.0F));
+ assertEquals("0x1.0p0", Float.toHexString(1.0F));
+ assertEquals("-0x1.0p0", Float.toHexString(-1.0F));
+ assertEquals("0x1.0p1", Float.toHexString(2.0F));
+ assertEquals("0x1.8p1", Float.toHexString(3.0F));
+ assertEquals("0x1.0p-1", Float.toHexString(0.5F));
+ assertEquals("0x1.0p-2", Float.toHexString(0.25F));
+ assertEquals("0x1.fffffep127", Float.toHexString(Float.MAX_VALUE));
+ assertEquals("0x0.000002p-126", Float.toHexString(Float.MIN_VALUE));
+
+ // test edge cases
+ assertEquals("NaN", Float.toHexString(Float.NaN));
+ assertEquals("-Infinity", Float.toHexString(Float.NEGATIVE_INFINITY));
+ assertEquals("Infinity", Float.toHexString(Float.POSITIVE_INFINITY));
+
+ // test various numbers
+ assertEquals("-0x1.da8p6", Float.toHexString(-118.625F));
+ assertEquals("0x1.295788p23", Float.toHexString(9743299.65F));
+ assertEquals("0x1.295788p23", Float.toHexString(9743299.65000F));
+ assertEquals("0x1.295788p23", Float.toHexString(9743299.650001234F));
+ assertEquals("0x1.700d1p33", Float.toHexString(12349743299.65000F));
+
+ // test HARMONY-2132
+ assertEquals("0x1.01p10", Float.toHexString(0x1.01p10f));
+ }
+
+ /**
+ * java.lang.Float#valueOf(float)
+ */
+ public void test_valueOfF() {
+ assertEquals(new Float(Float.MIN_VALUE), Float.valueOf(Float.MIN_VALUE));
+ assertEquals(new Float(Float.MAX_VALUE), Float.valueOf(Float.MAX_VALUE));
+ assertEquals(new Float(0), Float.valueOf(0));
+
+ int s = -128;
+ while (s < 128) {
+ assertEquals(new Float(s), Float.valueOf(s));
+ assertEquals(new Float(s + 0.1F), Float.valueOf(s + 0.1F));
+ assertEquals(Float.valueOf(s + 0.1F), Float.valueOf(s + 0.1F));
+ s++;
+ }
+ }
+
+ /**
+ * {@link java.lang.Float#MAX_EXPONENT}
+ * @since 1.6
+ */
+ public void test_MAX_EXPONENT() {
+ assertTrue("Wrong value of java.lang.Float.MAX_EXPONENT",
+ Float.MAX_EXPONENT == 127);
+ assertTrue("Wrong value of java.lang.Float.MAX_EXPONENT",
+ Float.MAX_EXPONENT == Math.getExponent(Float.MAX_VALUE));
+ }
+
+ /**
+ * {@link java.lang.Float#MIN_EXPONENT}
+ * @since 1.6
+ */
+ public void test_MIN_EXPONENT() {
+ assertTrue("Wrong value of java.lang.Float.MIN_EXPONENT",
+ Float.MIN_EXPONENT == -126);
+ assertTrue("Wrong value of java.lang.Float.MIN_EXPONENT",
+ Float.MIN_EXPONENT == Math.getExponent(Float.MIN_NORMAL));
+ }
+
+ /**
+ * {@link java.lang.Float#MIN_NORMAL}
+ * @since 1.6
+ */
+ public void test_MIN_NORMAL() {
+ assertTrue("Wrong value of java.lang.Float.MIN_NORMAL",
+ Float.MIN_NORMAL == 0x1.0p-126f);
+ assertTrue("Wrong value of java.lang.Float.MIN_NORMAL",
+ Float.MIN_NORMAL == Float.intBitsToFloat(0x00800000));
+ assertTrue("Wrong value of java.lang.Float.MIN_NORMAL",
+ Float.MIN_NORMAL == 1.1754943508222875E-38f);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessErrorTest.java
new file mode 100644
index 0000000..052bca2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IllegalAccessErrorTest extends TestCase {
+
+ /**
+ * java.lang.IllegalAccessError#IllegalAccessError()
+ */
+ public void test_Constructor() {
+ IllegalAccessError e = new IllegalAccessError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IllegalAccessError#IllegalAccessError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IllegalAccessError e = new IllegalAccessError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessExceptionTest.java
new file mode 100644
index 0000000..eb3b021
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalAccessExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IllegalAccessExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IllegalAccessException#IllegalAccessException()
+ */
+ public void test_Constructor() {
+ IllegalAccessException e = new IllegalAccessException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IllegalAccessException#IllegalAccessException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IllegalAccessException e = new IllegalAccessException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalArgumentExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalArgumentExceptionTest.java
new file mode 100644
index 0000000..c126f86
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalArgumentExceptionTest.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class IllegalArgumentExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IllegalArgumentException#IllegalArgumentException()
+ */
+ public void test_Constructor() {
+ IllegalArgumentException e = new IllegalArgumentException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * {@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());
+ }
+
+ /**
+ * java.lang.IllegalArgumentException#IllegalArgumentException(String, Throwable)
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
+ NullPointerException npe = new NullPointerException();
+ IllegalArgumentException e = new IllegalArgumentException("fixture",
+ npe);
+ assertSame("fixture", e.getMessage());
+ assertSame(npe, e.getCause());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new IllegalArgumentException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SerializationTest.verifyGolden(this, new IllegalArgumentException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalMonitorStateExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalMonitorStateExceptionTest.java
new file mode 100644
index 0000000..065b466
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalMonitorStateExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IllegalMonitorStateExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IllegalMonitorStateException#IllegalMonitorStateException()
+ */
+ public void test_Constructor() {
+ IllegalMonitorStateException e = new IllegalMonitorStateException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IllegalMonitorStateException#IllegalMonitorStateException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IllegalMonitorStateException e = new IllegalMonitorStateException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalStateExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalStateExceptionTest.java
new file mode 100644
index 0000000..e02ae18
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalStateExceptionTest.java
@@ -0,0 +1,95 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class IllegalStateExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IllegalStateException#IllegalStateException()
+ */
+ public void test_Constructor() {
+ IllegalStateException e = new IllegalStateException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IllegalStateException#IllegalStateException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IllegalStateException e = new IllegalStateException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * {@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());
+
+ 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());
+ }
+
+ /**
+ * {@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());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalStateException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new IllegalStateException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalThreadStateExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalThreadStateExceptionTest.java
new file mode 100644
index 0000000..c1c3763
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IllegalThreadStateExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IllegalThreadStateExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IllegalThreadStateException#IllegalThreadStateException()
+ */
+ public void test_Constructor() {
+ IllegalThreadStateException e = new IllegalThreadStateException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IllegalThreadStateException#IllegalThreadStateException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IllegalThreadStateException e = new IllegalThreadStateException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IncompatibleClassChangeErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IncompatibleClassChangeErrorTest.java
new file mode 100644
index 0000000..a8ef32f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IncompatibleClassChangeErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IncompatibleClassChangeErrorTest extends TestCase {
+
+ /**
+ * java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError()
+ */
+ public void test_Constructor() {
+ IncompatibleClassChangeError e = new IncompatibleClassChangeError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IncompatibleClassChangeError e = new IncompatibleClassChangeError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IndexOutOfBoundsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IndexOutOfBoundsExceptionTest.java
new file mode 100644
index 0000000..7093d4e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IndexOutOfBoundsExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class IndexOutOfBoundsExceptionTest extends TestCase {
+
+ /**
+ * java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException()
+ */
+ public void test_Constructor() {
+ IndexOutOfBoundsException e = new IndexOutOfBoundsException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ IndexOutOfBoundsException e = new IndexOutOfBoundsException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InheritableThreadLocalTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InheritableThreadLocalTest.java
new file mode 100644
index 0000000..d693acd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InheritableThreadLocalTest.java
@@ -0,0 +1,41 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class InheritableThreadLocalTest extends TestCase {
+
+ /**
+ * java.lang.InheritableThreadLocal#InheritableThreadLocal()
+ */
+ public void test_Constructor() {
+ InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>();
+ assertNull(itl.get());
+ }
+
+ public void test_initialValue() {
+ InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>() {
+ @Override
+ protected String initialValue() {
+ return "initial";
+ }
+ };
+ assertEquals("initial", itl.get());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationErrorTest.java
new file mode 100644
index 0000000..a069dba
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class InstantiationErrorTest extends TestCase {
+
+ /**
+ * java.lang.InstantiationError#InstantiationError()
+ */
+ public void test_Constructor() {
+ InstantiationError e = new InstantiationError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.InstantiationError#InstantiationError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ InstantiationError e = new InstantiationError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationExceptionTest.java
new file mode 100644
index 0000000..757b209
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InstantiationExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class InstantiationExceptionTest extends TestCase {
+
+ /**
+ * java.lang.InstantiationException#InstantiationException()
+ */
+ public void test_Constructor() {
+ InstantiationException e = new InstantiationException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.InstantiationException#InstantiationException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ InstantiationException e = new InstantiationException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IntegerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IntegerTest.java
new file mode 100644
index 0000000..3c7faa3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/IntegerTest.java
@@ -0,0 +1,1231 @@
+/* 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.tests.java.lang;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+public class IntegerTest extends TestCase {
+ private Properties orgProps;
+
+ @Override
+ protected void setUp() {
+ orgProps = System.getProperties();
+ }
+
+ @Override
+ protected void tearDown() {
+ System.setProperties(orgProps);
+ }
+
+ /**
+ * java.lang.Integer#byteValue()
+ */
+ public void test_byteValue() {
+ // Test for method byte java.lang.Integer.byteValue()
+ assertEquals("Returned incorrect byte value", -1, new Integer(65535)
+ .byteValue());
+ assertEquals("Returned incorrect byte value", 127, new Integer(127)
+ .byteValue());
+ }
+
+ /**
+ * java.lang.Integer#compareTo(java.lang.Integer)
+ */
+ public void test_compareToLjava_lang_Integer() {
+ // Test for method int java.lang.Integer.compareTo(java.lang.Integer)
+ assertTrue("-2 compared to 1 gave non-negative answer", new Integer(-2)
+ .compareTo(new Integer(1)) < 0);
+ assertEquals("-2 compared to -2 gave non-zero answer", 0, new Integer(-2)
+ .compareTo(new Integer(-2)));
+ assertTrue("3 compared to 2 gave non-positive answer", new Integer(3)
+ .compareTo(new Integer(2)) > 0);
+
+ try {
+ new Integer(0).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#decode(java.lang.String)
+ */
+ public void test_decodeLjava_lang_String2() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.decode(java.lang.String)
+ assertEquals("Failed for 132233",
+ 132233, Integer.decode("132233").intValue());
+ assertEquals("Failed for 07654321",
+ 07654321, Integer.decode("07654321").intValue());
+ assertTrue("Failed for #1234567",
+ Integer.decode("#1234567").intValue() == 0x1234567);
+ assertTrue("Failed for 0xdAd",
+ Integer.decode("0xdAd").intValue() == 0xdad);
+ assertEquals("Failed for -23", -23, Integer.decode("-23").intValue());
+ assertEquals("Returned incorrect value for 0 decimal", 0, Integer
+ .decode("0").intValue());
+ assertEquals("Returned incorrect value for 0 hex", 0, Integer.decode("0x0")
+ .intValue());
+ assertTrue("Returned incorrect value for most negative value decimal",
+ Integer.decode("-2147483648").intValue() == 0x80000000);
+ assertTrue("Returned incorrect value for most negative value hex",
+ Integer.decode("-0x80000000").intValue() == 0x80000000);
+ assertTrue("Returned incorrect value for most positive value decimal",
+ Integer.decode("2147483647").intValue() == 0x7fffffff);
+ assertTrue("Returned incorrect value for most positive value hex",
+ Integer.decode("0x7fffffff").intValue() == 0x7fffffff);
+
+ boolean exception = false;
+ try {
+ Integer.decode("0a");
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw NumberFormatException for \"Oa\"",
+ exception);
+
+ exception = false;
+ try {
+ Integer.decode("2147483648");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.decode("-2147483649");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Integer.decode("0x80000000");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.decode("-0x80000001");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Integer.decode("9999999999");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for 9999999999", exception);
+
+ try {
+ Integer.decode("-");
+ fail("Expected exception for -");
+ } catch (NumberFormatException e) {
+ // Expected
+ }
+
+ try {
+ Integer.decode("0x");
+ fail("Expected exception for 0x");
+ } catch (NumberFormatException e) {
+ // Expected
+ }
+
+ try {
+ Integer.decode("#");
+ fail("Expected exception for #");
+ } catch (NumberFormatException e) {
+ // Expected
+ }
+
+ try {
+ Integer.decode("x123");
+ fail("Expected exception for x123");
+ } catch (NumberFormatException e) {
+ // Expected
+ }
+
+ try {
+ Integer.decode(null);
+ fail("Expected exception for null");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ Integer.decode("");
+ fail("Expected exception for empty string");
+ } catch (NumberFormatException ex) {
+ // Expected
+ }
+
+ try {
+ Integer.decode(" ");
+ fail("Expected exception for single space");
+ } catch (NumberFormatException ex) {
+ // Expected
+ }
+
+ }
+
+ /**
+ * java.lang.Integer#doubleValue()
+ */
+ public void test_doubleValue2() {
+ // Test for method double java.lang.Integer.doubleValue()
+ assertEquals("Returned incorrect double value", 2147483647.0, new Integer(2147483647)
+ .doubleValue(), 0.0D);
+ assertEquals("Returned incorrect double value", -2147483647.0, new Integer(-2147483647)
+ .doubleValue(), 0.0D);
+ }
+
+ /**
+ * java.lang.Integer#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object2() {
+ // Test for method boolean java.lang.Integer.equals(java.lang.Object)
+ Integer i1 = new Integer(1000);
+ Integer i2 = new Integer(1000);
+ Integer i3 = new Integer(-1000);
+ assertTrue("Equality test failed", i1.equals(i2) && !(i1.equals(i3)));
+ }
+
+ /**
+ * java.lang.Integer#floatValue()
+ */
+ public void test_floatValue2() {
+ // Test for method float java.lang.Integer.floatValue()
+ assertTrue("Returned incorrect float value", new Integer(65535)
+ .floatValue() == 65535.0f);
+ assertTrue("Returned incorrect float value", new Integer(-65535)
+ .floatValue() == -65535.0f);
+ }
+
+ /**
+ * java.lang.Integer#getInteger(java.lang.String)
+ */
+ public void test_getIntegerLjava_lang_String() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.getInteger(java.lang.String)
+ Properties tProps = new Properties();
+ tProps.put("testInt", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Integer", Integer.getInteger("testInt")
+ .equals(new Integer(99)));
+ assertNull("returned incorrect default Integer", Integer
+ .getInteger("ff"));
+ }
+
+ /**
+ * java.lang.Integer#getInteger(java.lang.String, int)
+ */
+ public void test_getIntegerLjava_lang_StringI() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.getInteger(java.lang.String, int)
+ Properties tProps = new Properties();
+ tProps.put("testInt", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Integer", Integer.getInteger("testInt",
+ 4).equals(new Integer(99)));
+ assertTrue("returned incorrect default Integer", Integer.getInteger(
+ "ff", 4).equals(new Integer(4)));
+ }
+
+ /**
+ * java.lang.Integer#getInteger(java.lang.String, java.lang.Integer)
+ */
+ public void test_getIntegerLjava_lang_StringLjava_lang_Integer() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.getInteger(java.lang.String, java.lang.Integer)
+ Properties tProps = new Properties();
+ tProps.put("testInt", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Integer", Integer.getInteger("testInt",
+ new Integer(4)).equals(new Integer(99)));
+ assertTrue("returned incorrect default Integer", Integer.getInteger(
+ "ff", new Integer(4)).equals(new Integer(4)));
+ }
+
+ /**
+ * java.lang.Integer#hashCode()
+ */
+ public void test_hashCode2() {
+ // Test for method int java.lang.Integer.hashCode()
+
+ Integer i1 = new Integer(1000);
+ Integer i2 = new Integer(-1000);
+ assertTrue("Returned incorrect hashcode", i1.hashCode() == 1000
+ && (i2.hashCode() == -1000));
+ }
+
+ /**
+ * java.lang.Integer#intValue()
+ */
+ public void test_intValue2() {
+ // Test for method int java.lang.Integer.intValue()
+
+ Integer i = new Integer(8900);
+ assertEquals("Returned incorrect int value", 8900, i.intValue());
+ }
+
+ /**
+ * java.lang.Integer#longValue()
+ */
+ public void test_longValue2() {
+ // Test for method long java.lang.Integer.longValue()
+ Integer i = new Integer(8900);
+ assertEquals("Returned incorrect long value", 8900L, i.longValue());
+ }
+
+ /**
+ * java.lang.Integer#parseInt(java.lang.String)
+ */
+ public void test_parseIntLjava_lang_String2() {
+ // Test for method int java.lang.Integer.parseInt(java.lang.String)
+
+ int i = Integer.parseInt("-8900");
+ assertEquals("Returned incorrect int", -8900, i);
+ assertEquals("Returned incorrect value for 0", 0, Integer.parseInt("0"));
+ assertTrue("Returned incorrect value for most negative value", Integer
+ .parseInt("-2147483648") == 0x80000000);
+ assertTrue("Returned incorrect value for most positive value", Integer
+ .parseInt("2147483647") == 0x7fffffff);
+
+ boolean exception = false;
+ try {
+ Integer.parseInt("999999999999");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for value > int", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("2147483648");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("-2147483649");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Integer#parseInt(java.lang.String, int)
+ */
+ public void test_parseIntLjava_lang_StringI2() {
+ // Test for method int java.lang.Integer.parseInt(java.lang.String, int)
+ assertEquals("Parsed dec val incorrectly",
+ -8000, Integer.parseInt("-8000", 10));
+ assertEquals("Parsed hex val incorrectly",
+ 255, Integer.parseInt("FF", 16));
+ assertEquals("Parsed oct val incorrectly",
+ 16, Integer.parseInt("20", 8));
+ assertEquals("Returned incorrect value for 0 hex", 0, Integer.parseInt("0",
+ 16));
+ assertTrue("Returned incorrect value for most negative value hex",
+ Integer.parseInt("-80000000", 16) == 0x80000000);
+ assertTrue("Returned incorrect value for most positive value hex",
+ Integer.parseInt("7fffffff", 16) == 0x7fffffff);
+ assertEquals("Returned incorrect value for 0 decimal", 0, Integer.parseInt(
+ "0", 10));
+ assertTrue("Returned incorrect value for most negative value decimal",
+ Integer.parseInt("-2147483648", 10) == 0x80000000);
+ assertTrue("Returned incorrect value for most positive value decimal",
+ Integer.parseInt("2147483647", 10) == 0x7fffffff);
+
+ boolean exception = false;
+ try {
+ Integer.parseInt("FFFF", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue(
+ "Failed to throw exception when passes hex string and dec parm",
+ exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("2147483648", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("-2147483649", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("80000000", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("-80000001", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.parseInt("9999999999", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for 9999999999", exception);
+ }
+
+ /**
+ * java.lang.Integer#shortValue()
+ */
+ public void test_shortValue2() {
+ // Test for method short java.lang.Integer.shortValue()
+ Integer i = new Integer(2147450880);
+ assertEquals("Returned incorrect long value", -32768, i.shortValue());
+ }
+
+ /**
+ * java.lang.Integer#toBinaryString(int)
+ */
+ public void test_toBinaryStringI() {
+ // Test for method java.lang.String
+ // java.lang.Integer.toBinaryString(int)
+ assertEquals("Incorrect string returned", "1111111111111111111111111111111", Integer.toBinaryString(
+ Integer.MAX_VALUE));
+ assertEquals("Incorrect string returned", "10000000000000000000000000000000", Integer.toBinaryString(
+ Integer.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.Integer#toHexString(int)
+ */
+ public void test_toHexStringI() {
+ // Test for method java.lang.String java.lang.Integer.toHexString(int)
+
+ String[] hexvals = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
+ "a", "b", "c", "d", "e", "f" };
+
+ for (int i = 0; i < 16; i++) {
+ assertTrue("Incorrect string returned " + hexvals[i], Integer
+ .toHexString(i).equals(hexvals[i]));
+ }
+
+ assertTrue("Returned incorrect hex string: "
+ + Integer.toHexString(Integer.MAX_VALUE), Integer.toHexString(
+ Integer.MAX_VALUE).equals("7fffffff"));
+ assertTrue("Returned incorrect hex string: "
+ + Integer.toHexString(Integer.MIN_VALUE), Integer.toHexString(
+ Integer.MIN_VALUE).equals("80000000"));
+ }
+
+ /**
+ * java.lang.Integer#toOctalString(int)
+ */
+ public void test_toOctalStringI() {
+ // Test for method java.lang.String java.lang.Integer.toOctalString(int)
+ // Spec states that the int arg is treated as unsigned
+ assertEquals("Returned incorrect octal string", "17777777777", Integer.toOctalString(
+ Integer.MAX_VALUE));
+ assertEquals("Returned incorrect octal string", "20000000000", Integer.toOctalString(
+ Integer.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.Integer#toString()
+ */
+ public void test_toString2() {
+ // Test for method java.lang.String java.lang.Integer.toString()
+
+ Integer i = new Integer(-80001);
+
+ assertEquals("Returned incorrect String", "-80001", i.toString());
+ }
+
+ /**
+ * java.lang.Integer#toString(int)
+ */
+ public void test_toStringI2() {
+ // Test for method java.lang.String java.lang.Integer.toString(int)
+
+ assertEquals("Returned incorrect String", "-80765", Integer.toString(-80765)
+ );
+ assertEquals("Returned incorrect octal string", "2147483647", Integer.toString(
+ Integer.MAX_VALUE));
+ assertEquals("Returned incorrect octal string", "-2147483647", Integer.toString(
+ -Integer.MAX_VALUE));
+ assertEquals("Returned incorrect octal string", "-2147483648", Integer.toString(
+ Integer.MIN_VALUE));
+
+ // Test for HARMONY-6068
+ assertEquals("Returned incorrect octal String", "-1000", Integer.toString(-1000));
+ assertEquals("Returned incorrect octal String", "1000", Integer.toString(1000));
+ assertEquals("Returned incorrect octal String", "0", Integer.toString(0));
+ assertEquals("Returned incorrect octal String", "708", Integer.toString(708));
+ assertEquals("Returned incorrect octal String", "-100", Integer.toString(-100));
+ assertEquals("Returned incorrect octal String", "-1000000008", Integer.toString(-1000000008));
+ assertEquals("Returned incorrect octal String", "2000000008", Integer.toString(2000000008));
+ }
+
+ /**
+ * java.lang.Integer#toString(int, int)
+ */
+ public void test_toStringII() {
+ // Test for method java.lang.String java.lang.Integer.toString(int, int)
+ assertEquals("Returned incorrect octal string", "17777777777", Integer.toString(
+ 2147483647, 8));
+ assertTrue("Returned incorrect hex string--wanted 7fffffff but got: "
+ + Integer.toString(2147483647, 16), Integer.toString(
+ 2147483647, 16).equals("7fffffff"));
+ assertEquals("Incorrect string returned", "1111111111111111111111111111111", Integer.toString(2147483647, 2)
+ );
+ assertEquals("Incorrect string returned", "2147483647", Integer
+ .toString(2147483647, 10));
+
+ assertEquals("Returned incorrect octal string", "-17777777777", Integer.toString(
+ -2147483647, 8));
+ assertTrue("Returned incorrect hex string--wanted -7fffffff but got: "
+ + Integer.toString(-2147483647, 16), Integer.toString(
+ -2147483647, 16).equals("-7fffffff"));
+ assertEquals("Incorrect string returned",
+ "-1111111111111111111111111111111", Integer
+ .toString(-2147483647, 2));
+ assertEquals("Incorrect string returned", "-2147483647", Integer.toString(-2147483647,
+ 10));
+
+ assertEquals("Returned incorrect octal string", "-20000000000", Integer.toString(
+ -2147483648, 8));
+ assertTrue("Returned incorrect hex string--wanted -80000000 but got: "
+ + Integer.toString(-2147483648, 16), Integer.toString(
+ -2147483648, 16).equals("-80000000"));
+ assertEquals("Incorrect string returned",
+ "-10000000000000000000000000000000", Integer
+ .toString(-2147483648, 2));
+ assertEquals("Incorrect string returned", "-2147483648", Integer.toString(-2147483648,
+ 10));
+ }
+
+ /**
+ * java.lang.Integer#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String2() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.valueOf(java.lang.String)
+ assertEquals("Returned incorrect int", 8888888, Integer.valueOf("8888888")
+ .intValue());
+ assertTrue("Returned incorrect int", Integer.valueOf("2147483647")
+ .intValue() == Integer.MAX_VALUE);
+ assertTrue("Returned incorrect int", Integer.valueOf("-2147483648")
+ .intValue() == Integer.MIN_VALUE);
+
+ boolean exception = false;
+ try {
+ Integer.valueOf("2147483648");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.valueOf("-2147483649");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Integer#valueOf(java.lang.String, int)
+ */
+ public void test_valueOfLjava_lang_StringI2() {
+ // Test for method java.lang.Integer
+ // java.lang.Integer.valueOf(java.lang.String, int)
+ assertEquals("Returned incorrect int for hex string", 255, Integer.valueOf(
+ "FF", 16).intValue());
+ assertEquals("Returned incorrect int for oct string", 16, Integer.valueOf(
+ "20", 8).intValue());
+ assertEquals("Returned incorrect int for bin string", 4, Integer.valueOf(
+ "100", 2).intValue());
+
+ assertEquals("Returned incorrect int for - hex string", -255, Integer.valueOf(
+ "-FF", 16).intValue());
+ assertEquals("Returned incorrect int for - oct string", -16, Integer.valueOf(
+ "-20", 8).intValue());
+ assertEquals("Returned incorrect int for - bin string", -4, Integer.valueOf(
+ "-100", 2).intValue());
+ assertTrue("Returned incorrect int", Integer.valueOf("2147483647", 10)
+ .intValue() == Integer.MAX_VALUE);
+ assertTrue("Returned incorrect int", Integer.valueOf("-2147483648", 10)
+ .intValue() == Integer.MIN_VALUE);
+ assertTrue("Returned incorrect int", Integer.valueOf("7fffffff", 16)
+ .intValue() == Integer.MAX_VALUE);
+ assertTrue("Returned incorrect int", Integer.valueOf("-80000000", 16)
+ .intValue() == Integer.MIN_VALUE);
+
+ boolean exception = false;
+ try {
+ Integer.valueOf("FF", 2);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue(
+ "Failed to throw exception with hex string and base 2 radix",
+ exception);
+
+ exception = false;
+ try {
+ Integer.valueOf("2147483648", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Integer.valueOf("-2147483649", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Integer.valueOf("80000000", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with hex MAX_VALUE + 1",
+ exception);
+
+ exception = false;
+ try {
+ Integer.valueOf("-80000001", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception with hex MIN_VALUE - 1",
+ exception);
+ }
+
+ /**
+ * java.lang.Integer#valueOf(byte)
+ */
+ public void test_valueOfI() {
+ assertEquals(new Integer(Integer.MIN_VALUE), Integer.valueOf(Integer.MIN_VALUE));
+ assertEquals(new Integer(Integer.MAX_VALUE), Integer.valueOf(Integer.MAX_VALUE));
+ assertEquals(new Integer(0), Integer.valueOf(0));
+
+ short s = -128;
+ while (s < 128) {
+ assertEquals(new Integer(s), Integer.valueOf(s));
+ assertSame(Integer.valueOf(s), Integer.valueOf(s));
+ s++;
+ }
+ }
+
+ /**
+ * java.lang.Integer#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals(1, new Integer(1).hashCode());
+ assertEquals(2, new Integer(2).hashCode());
+ assertEquals(0, new Integer(0).hashCode());
+ assertEquals(-1, new Integer(-1).hashCode());
+ }
+
+ /**
+ * java.lang.Integer#Integer(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertEquals(new Integer(0), new Integer("0"));
+ assertEquals(new Integer(1), new Integer("1"));
+ assertEquals(new Integer(-1), new Integer("-1"));
+
+ try {
+ new Integer("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Integer("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Integer("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Integer(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#Integer
+ */
+ public void test_ConstructorI() {
+ assertEquals(1, new Integer(1).intValue());
+ assertEquals(2, new Integer(2).intValue());
+ assertEquals(0, new Integer(0).intValue());
+ assertEquals(-1, new Integer(-1).intValue());
+
+ Integer i = new Integer(-89000);
+ assertEquals("Incorrect Integer created", -89000, i.intValue());
+ }
+
+ /**
+ * java.lang.Integer#byteValue()
+ */
+ public void test_booleanValue() {
+ assertEquals(1, new Integer(1).byteValue());
+ assertEquals(2, new Integer(2).byteValue());
+ assertEquals(0, new Integer(0).byteValue());
+ assertEquals(-1, new Integer(-1).byteValue());
+ }
+
+ /**
+ * java.lang.Integer#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertEquals(new Integer(0), Integer.valueOf(0));
+ assertEquals(new Integer(1), Integer.valueOf(1));
+ assertEquals(new Integer(-1), Integer.valueOf(-1));
+
+ Integer fixture = new Integer(25);
+ assertEquals(fixture, fixture);
+ assertFalse(fixture.equals(null));
+ assertFalse(fixture.equals("Not a Integer"));
+ }
+
+ /**
+ * java.lang.Integer#toString()
+ */
+ public void test_toString() {
+ assertEquals("-1", new Integer(-1).toString());
+ assertEquals("0", new Integer(0).toString());
+ assertEquals("1", new Integer(1).toString());
+ assertEquals("-1", new Integer(0xFFFFFFFF).toString());
+ }
+
+ /**
+ * java.lang.Integer#toString
+ */
+ public void test_toStringI() {
+ assertEquals("-1", Integer.toString(-1));
+ assertEquals("0", Integer.toString(0));
+ assertEquals("1", Integer.toString(1));
+ assertEquals("-1", Integer.toString(0xFFFFFFFF));
+ }
+
+ /**
+ * java.lang.Integer#valueOf(String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertEquals(new Integer(0), Integer.valueOf("0"));
+ assertEquals(new Integer(1), Integer.valueOf("1"));
+ assertEquals(new Integer(-1), Integer.valueOf("-1"));
+
+ try {
+ Integer.valueOf("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#valueOf(String, int)
+ */
+ public void test_valueOfLjava_lang_StringI() {
+ assertEquals(new Integer(0), Integer.valueOf("0", 10));
+ assertEquals(new Integer(1), Integer.valueOf("1", 10));
+ assertEquals(new Integer(-1), Integer.valueOf("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Integer.valueOf("1", 2).byteValue());
+ assertEquals(Character.digit('F', 16), Integer.valueOf("F", 16).byteValue());
+
+ try {
+ Integer.valueOf("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.valueOf(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#parseInt(String)
+ */
+ public void test_parseIntLjava_lang_String() {
+ assertEquals(0, Integer.parseInt("0"));
+ assertEquals(1, Integer.parseInt("1"));
+ assertEquals(-1, Integer.parseInt("-1"));
+
+ try {
+ Integer.parseInt("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#parseInt(String, int)
+ */
+ public void test_parseIntLjava_lang_StringI() {
+ assertEquals(0, Integer.parseInt("0", 10));
+ assertEquals(1, Integer.parseInt("1", 10));
+ assertEquals(-1, Integer.parseInt("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Integer.parseInt("1", 2));
+ assertEquals(Character.digit('F', 16), Integer.parseInt("F", 16));
+
+ try {
+ Integer.parseInt("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.parseInt(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#decode(String)
+ */
+ public void test_decodeLjava_lang_String() {
+ assertEquals(new Integer(0), Integer.decode("0"));
+ assertEquals(new Integer(1), Integer.decode("1"));
+ assertEquals(new Integer(-1), Integer.decode("-1"));
+ assertEquals(new Integer(0xF), Integer.decode("0xF"));
+ assertEquals(new Integer(0xF), Integer.decode("#F"));
+ assertEquals(new Integer(0xF), Integer.decode("0XF"));
+ assertEquals(new Integer(07), Integer.decode("07"));
+
+ try {
+ Integer.decode("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.decode("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Integer.decode(null);
+ //undocumented NPE, but seems consistent across JREs
+ fail("Expected NullPointerException with null string.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Integer#doubleValue()
+ */
+ public void test_doubleValue() {
+ assertEquals(-1D, new Integer(-1).doubleValue(), 0D);
+ assertEquals(0D, new Integer(0).doubleValue(), 0D);
+ assertEquals(1D, new Integer(1).doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Integer#floatValue()
+ */
+ public void test_floatValue() {
+ assertEquals(-1F, new Integer(-1).floatValue(), 0F);
+ assertEquals(0F, new Integer(0).floatValue(), 0F);
+ assertEquals(1F, new Integer(1).floatValue(), 0F);
+ }
+
+ /**
+ * java.lang.Integer#intValue()
+ */
+ public void test_intValue() {
+ assertEquals(-1, new Integer(-1).intValue());
+ assertEquals(0, new Integer(0).intValue());
+ assertEquals(1, new Integer(1).intValue());
+ }
+
+ /**
+ * java.lang.Integer#longValue()
+ */
+ public void test_longValue() {
+ assertEquals(-1L, new Integer(-1).longValue());
+ assertEquals(0L, new Integer(0).longValue());
+ assertEquals(1L, new Integer(1).longValue());
+ }
+
+ /**
+ * java.lang.Integer#shortValue()
+ */
+ public void test_shortValue() {
+ assertEquals(-1, new Integer(-1).shortValue());
+ assertEquals(0, new Integer(0).shortValue());
+ assertEquals(1, new Integer(1).shortValue());
+ }
+
+ /**
+ * java.lang.Integer#highestOneBit(int)
+ */
+ public void test_highestOneBitI() {
+ assertEquals(0x08, Integer.highestOneBit(0x0A));
+ assertEquals(0x08, Integer.highestOneBit(0x0B));
+ assertEquals(0x08, Integer.highestOneBit(0x0C));
+ assertEquals(0x08, Integer.highestOneBit(0x0F));
+ assertEquals(0x80, Integer.highestOneBit(0xFF));
+
+ assertEquals(0x080000, Integer.highestOneBit(0x0F1234));
+ assertEquals(0x800000, Integer.highestOneBit(0xFF9977));
+
+ assertEquals(0x80000000, Integer.highestOneBit(0xFFFFFFFF));
+
+ assertEquals(0, Integer.highestOneBit(0));
+ assertEquals(1, Integer.highestOneBit(1));
+ assertEquals(0x80000000, Integer.highestOneBit(-1));
+ }
+
+ /**
+ * java.lang.Integer#lowestOneBit(int)
+ */
+ public void test_lowestOneBitI() {
+ assertEquals(0x10, Integer.lowestOneBit(0xF0));
+
+ assertEquals(0x10, Integer.lowestOneBit(0x90));
+ assertEquals(0x10, Integer.lowestOneBit(0xD0));
+
+ assertEquals(0x10, Integer.lowestOneBit(0x123490));
+ assertEquals(0x10, Integer.lowestOneBit(0x1234D0));
+
+ assertEquals(0x100000, Integer.lowestOneBit(0x900000));
+ assertEquals(0x100000, Integer.lowestOneBit(0xD00000));
+
+ assertEquals(0x40, Integer.lowestOneBit(0x40));
+ assertEquals(0x40, Integer.lowestOneBit(0xC0));
+
+ assertEquals(0x4000, Integer.lowestOneBit(0x4000));
+ assertEquals(0x4000, Integer.lowestOneBit(0xC000));
+
+ assertEquals(0x4000, Integer.lowestOneBit(0x99994000));
+ assertEquals(0x4000, Integer.lowestOneBit(0x9999C000));
+
+ assertEquals(0, Integer.lowestOneBit(0));
+ assertEquals(1, Integer.lowestOneBit(1));
+ assertEquals(1, Integer.lowestOneBit(-1));
+ }
+
+ /**
+ * java.lang.Integer#numberOfLeadingZeros(int)
+ */
+ public void test_numberOfLeadingZerosI() {
+ assertEquals(32, Integer.numberOfLeadingZeros(0x0));
+ assertEquals(31, Integer.numberOfLeadingZeros(0x1));
+ assertEquals(30, Integer.numberOfLeadingZeros(0x2));
+ assertEquals(30, Integer.numberOfLeadingZeros(0x3));
+ assertEquals(29, Integer.numberOfLeadingZeros(0x4));
+ assertEquals(29, Integer.numberOfLeadingZeros(0x5));
+ assertEquals(29, Integer.numberOfLeadingZeros(0x6));
+ assertEquals(29, Integer.numberOfLeadingZeros(0x7));
+ assertEquals(28, Integer.numberOfLeadingZeros(0x8));
+ assertEquals(28, Integer.numberOfLeadingZeros(0x9));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xA));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xB));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xC));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xD));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xE));
+ assertEquals(28, Integer.numberOfLeadingZeros(0xF));
+ assertEquals(27, Integer.numberOfLeadingZeros(0x10));
+ assertEquals(24, Integer.numberOfLeadingZeros(0x80));
+ assertEquals(24, Integer.numberOfLeadingZeros(0xF0));
+ assertEquals(23, Integer.numberOfLeadingZeros(0x100));
+ assertEquals(20, Integer.numberOfLeadingZeros(0x800));
+ assertEquals(20, Integer.numberOfLeadingZeros(0xF00));
+ assertEquals(19, Integer.numberOfLeadingZeros(0x1000));
+ assertEquals(16, Integer.numberOfLeadingZeros(0x8000));
+ assertEquals(16, Integer.numberOfLeadingZeros(0xF000));
+ assertEquals(15, Integer.numberOfLeadingZeros(0x10000));
+ assertEquals(12, Integer.numberOfLeadingZeros(0x80000));
+ assertEquals(12, Integer.numberOfLeadingZeros(0xF0000));
+ assertEquals(11, Integer.numberOfLeadingZeros(0x100000));
+ assertEquals(8, Integer.numberOfLeadingZeros(0x800000));
+ assertEquals(8, Integer.numberOfLeadingZeros(0xF00000));
+ assertEquals(7, Integer.numberOfLeadingZeros(0x1000000));
+ assertEquals(4, Integer.numberOfLeadingZeros(0x8000000));
+ assertEquals(4, Integer.numberOfLeadingZeros(0xF000000));
+ assertEquals(3, Integer.numberOfLeadingZeros(0x10000000));
+ assertEquals(0, Integer.numberOfLeadingZeros(0x80000000));
+ assertEquals(0, Integer.numberOfLeadingZeros(0xF0000000));
+
+ assertEquals(1, Integer.numberOfLeadingZeros(Integer.MAX_VALUE));
+ assertEquals(0, Integer.numberOfLeadingZeros(Integer.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.Integer#numberOfTrailingZeros(int)
+ */
+ public void test_numberOfTrailingZerosI() {
+ assertEquals(32, Integer.numberOfTrailingZeros(0x0));
+ assertEquals(31, Integer.numberOfTrailingZeros(Integer.MIN_VALUE));
+ assertEquals(0, Integer.numberOfTrailingZeros(Integer.MAX_VALUE));
+
+ assertEquals(0, Integer.numberOfTrailingZeros(0x1));
+ assertEquals(3, Integer.numberOfTrailingZeros(0x8));
+ assertEquals(0, Integer.numberOfTrailingZeros(0xF));
+
+ assertEquals(4, Integer.numberOfTrailingZeros(0x10));
+ assertEquals(7, Integer.numberOfTrailingZeros(0x80));
+ assertEquals(4, Integer.numberOfTrailingZeros(0xF0));
+
+ assertEquals(8, Integer.numberOfTrailingZeros(0x100));
+ assertEquals(11, Integer.numberOfTrailingZeros(0x800));
+ assertEquals(8, Integer.numberOfTrailingZeros(0xF00));
+
+ assertEquals(12, Integer.numberOfTrailingZeros(0x1000));
+ assertEquals(15, Integer.numberOfTrailingZeros(0x8000));
+ assertEquals(12, Integer.numberOfTrailingZeros(0xF000));
+
+ assertEquals(16, Integer.numberOfTrailingZeros(0x10000));
+ assertEquals(19, Integer.numberOfTrailingZeros(0x80000));
+ assertEquals(16, Integer.numberOfTrailingZeros(0xF0000));
+
+ assertEquals(20, Integer.numberOfTrailingZeros(0x100000));
+ assertEquals(23, Integer.numberOfTrailingZeros(0x800000));
+ assertEquals(20, Integer.numberOfTrailingZeros(0xF00000));
+
+ assertEquals(24, Integer.numberOfTrailingZeros(0x1000000));
+ assertEquals(27, Integer.numberOfTrailingZeros(0x8000000));
+ assertEquals(24, Integer.numberOfTrailingZeros(0xF000000));
+
+ assertEquals(28, Integer.numberOfTrailingZeros(0x10000000));
+ assertEquals(31, Integer.numberOfTrailingZeros(0x80000000));
+ assertEquals(28, Integer.numberOfTrailingZeros(0xF0000000));
+ }
+
+ /**
+ * java.lang.Integer#bitCount(int)
+ */
+ public void test_bitCountI() {
+ assertEquals(0, Integer.bitCount(0x0));
+ assertEquals(1, Integer.bitCount(0x1));
+ assertEquals(1, Integer.bitCount(0x2));
+ assertEquals(2, Integer.bitCount(0x3));
+ assertEquals(1, Integer.bitCount(0x4));
+ assertEquals(2, Integer.bitCount(0x5));
+ assertEquals(2, Integer.bitCount(0x6));
+ assertEquals(3, Integer.bitCount(0x7));
+ assertEquals(1, Integer.bitCount(0x8));
+ assertEquals(2, Integer.bitCount(0x9));
+ assertEquals(2, Integer.bitCount(0xA));
+ assertEquals(3, Integer.bitCount(0xB));
+ assertEquals(2, Integer.bitCount(0xC));
+ assertEquals(3, Integer.bitCount(0xD));
+ assertEquals(3, Integer.bitCount(0xE));
+ assertEquals(4, Integer.bitCount(0xF));
+
+ assertEquals(8, Integer.bitCount(0xFF));
+ assertEquals(12, Integer.bitCount(0xFFF));
+ assertEquals(16, Integer.bitCount(0xFFFF));
+ assertEquals(20, Integer.bitCount(0xFFFFF));
+ assertEquals(24, Integer.bitCount(0xFFFFFF));
+ assertEquals(28, Integer.bitCount(0xFFFFFFF));
+ assertEquals(32, Integer.bitCount(0xFFFFFFFF));
+ }
+
+ /**
+ * java.lang.Integer#rotateLeft(int, int)
+ */
+ public void test_rotateLeftII() {
+ assertEquals(0xF, Integer.rotateLeft(0xF, 0));
+ assertEquals(0xF0, Integer.rotateLeft(0xF, 4));
+ assertEquals(0xF00, Integer.rotateLeft(0xF, 8));
+ assertEquals(0xF000, Integer.rotateLeft(0xF, 12));
+ assertEquals(0xF0000, Integer.rotateLeft(0xF, 16));
+ assertEquals(0xF00000, Integer.rotateLeft(0xF, 20));
+ assertEquals(0xF000000, Integer.rotateLeft(0xF, 24));
+ assertEquals(0xF0000000, Integer.rotateLeft(0xF, 28));
+ assertEquals(0xF0000000, Integer.rotateLeft(0xF0000000, 32));
+ }
+
+ /**
+ * java.lang.Integer#rotateRight(int, int)
+ */
+ public void test_rotateRightII() {
+ assertEquals(0xF, Integer.rotateRight(0xF0, 4));
+ assertEquals(0xF, Integer.rotateRight(0xF00, 8));
+ assertEquals(0xF, Integer.rotateRight(0xF000, 12));
+ assertEquals(0xF, Integer.rotateRight(0xF0000, 16));
+ assertEquals(0xF, Integer.rotateRight(0xF00000, 20));
+ assertEquals(0xF, Integer.rotateRight(0xF000000, 24));
+ assertEquals(0xF, Integer.rotateRight(0xF0000000, 28));
+ assertEquals(0xF0000000, Integer.rotateRight(0xF0000000, 32));
+ assertEquals(0xF0000000, Integer.rotateRight(0xF0000000, 0));
+
+ }
+
+ /**
+ * java.lang.Integer#reverseBytes(int)
+ */
+ public void test_reverseBytesI() {
+ assertEquals(0xAABBCCDD, Integer.reverseBytes(0xDDCCBBAA));
+ assertEquals(0x11223344, Integer.reverseBytes(0x44332211));
+ assertEquals(0x00112233, Integer.reverseBytes(0x33221100));
+ assertEquals(0x20000002, Integer.reverseBytes(0x02000020));
+ }
+
+ /**
+ * java.lang.Integer#reverse(int)
+ */
+ public void test_reverseI() {
+ assertEquals(-1, Integer.reverse(-1));
+ assertEquals(0x80000000, Integer.reverse(1));
+ }
+
+ /**
+ * java.lang.Integer#signum(int)
+ */
+ public void test_signumI() {
+ for (int i = -128; i < 0; i++) {
+ assertEquals(-1, Integer.signum(i));
+ }
+ assertEquals(0, Integer.signum(0));
+ for (int i = 1; i <= 127; i++) {
+ assertEquals(1, Integer.signum(i));
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InternalErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InternalErrorTest.java
new file mode 100644
index 0000000..d2ea2de
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InternalErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class InternalErrorTest extends TestCase {
+
+ /**
+ * java.lang.InternalError#InternalError()
+ */
+ public void test_Constructor() {
+ InternalError e = new InternalError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.InternalError#InternalError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ InternalError e = new InternalError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InterruptedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InterruptedExceptionTest.java
new file mode 100644
index 0000000..ecaac75
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/InterruptedExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class InterruptedExceptionTest extends TestCase {
+
+ /**
+ * java.lang.InterruptedException#InterruptedException()
+ */
+ public void test_Constructor() {
+ InterruptedException e = new InterruptedException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.InterruptedException#InterruptedException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ InterruptedException e = new InterruptedException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LinkageErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LinkageErrorTest.java
new file mode 100644
index 0000000..33ecc16
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LinkageErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class LinkageErrorTest extends TestCase {
+
+ /**
+ * java.lang.LinkageError#LinkageError()
+ */
+ public void test_Constructor() {
+ LinkageError e = new LinkageError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.LinkageError#LinkageError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ LinkageError e = new LinkageError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LongTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LongTest.java
new file mode 100644
index 0000000..9da75cf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/LongTest.java
@@ -0,0 +1,1067 @@
+/* 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.tests.java.lang;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+public class LongTest extends TestCase {
+ private Properties orgProps;
+
+ @Override
+ protected void setUp() {
+ orgProps = System.getProperties();
+ }
+
+ @Override
+ protected void tearDown() {
+ System.setProperties(orgProps);
+ }
+
+ /**
+ * java.lang.Long#byteValue()
+ */
+ public void test_byteValue() {
+ // Test for method byte java.lang.Long.byteValue()
+ Long l = new Long(127);
+ assertEquals("Returned incorrect byte value", 127, l.byteValue());
+ assertEquals("Returned incorrect byte value", -1, new Long(Long.MAX_VALUE)
+ .byteValue());
+ }
+
+ /**
+ * java.lang.Long#compareTo(java.lang.Long)
+ */
+ public void test_compareToLjava_lang_Long() {
+ // Test for method int java.lang.Long.compareTo(java.lang.Long)
+ assertTrue("-2 compared to 1 gave non-negative answer", new Long(-2L)
+ .compareTo(new Long(1L)) < 0);
+ assertEquals("-2 compared to -2 gave non-zero answer", 0, new Long(-2L)
+ .compareTo(new Long(-2L)));
+ assertTrue("3 compared to 2 gave non-positive answer", new Long(3L)
+ .compareTo(new Long(2L)) > 0);
+
+ try {
+ new Long(0).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#decode(java.lang.String)
+ */
+ public void test_decodeLjava_lang_String2() {
+ // Test for method java.lang.Long
+ // java.lang.Long.decode(java.lang.String)
+ assertEquals("Returned incorrect value for hex string", 255L, Long.decode(
+ "0xFF").longValue());
+ assertEquals("Returned incorrect value for dec string", -89000L, Long.decode(
+ "-89000").longValue());
+ assertEquals("Returned incorrect value for 0 decimal", 0, Long.decode("0")
+ .longValue());
+ assertEquals("Returned incorrect value for 0 hex", 0, Long.decode("0x0")
+ .longValue());
+ assertTrue(
+ "Returned incorrect value for most negative value decimal",
+ Long.decode("-9223372036854775808").longValue() == 0x8000000000000000L);
+ assertTrue(
+ "Returned incorrect value for most negative value hex",
+ Long.decode("-0x8000000000000000").longValue() == 0x8000000000000000L);
+ assertTrue(
+ "Returned incorrect value for most positive value decimal",
+ Long.decode("9223372036854775807").longValue() == 0x7fffffffffffffffL);
+ assertTrue(
+ "Returned incorrect value for most positive value hex",
+ Long.decode("0x7fffffffffffffff").longValue() == 0x7fffffffffffffffL);
+ assertTrue("Failed for 07654321765432", Long.decode("07654321765432")
+ .longValue() == 07654321765432l);
+
+ boolean exception = false;
+ try {
+ Long
+ .decode("999999999999999999999999999999999999999999999999999999");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for value > ilong", exception);
+
+ exception = false;
+ try {
+ Long.decode("9223372036854775808");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.decode("-9223372036854775809");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Long.decode("0x8000000000000000");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.decode("-0x8000000000000001");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Long.decode("42325917317067571199");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for 42325917317067571199",
+ exception);
+ }
+
+ /**
+ * java.lang.Long#getLong(java.lang.String)
+ */
+ public void test_getLongLjava_lang_String() {
+ // Test for method java.lang.Long
+ // java.lang.Long.getLong(java.lang.String)
+ Properties tProps = new Properties();
+ tProps.put("testLong", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Long", Long.getLong("testLong").equals(
+ new Long(99)));
+ assertNull("returned incorrect default Long",
+ Long.getLong("ff"));
+ }
+
+ /**
+ * java.lang.Long#getLong(java.lang.String, long)
+ */
+ public void test_getLongLjava_lang_StringJ() {
+ // Test for method java.lang.Long
+ // java.lang.Long.getLong(java.lang.String, long)
+ Properties tProps = new Properties();
+ tProps.put("testLong", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Long", Long.getLong("testLong", 4L)
+ .equals(new Long(99)));
+ assertTrue("returned incorrect default Long", Long.getLong("ff", 4L)
+ .equals(new Long(4)));
+ }
+
+ /**
+ * java.lang.Long#getLong(java.lang.String, java.lang.Long)
+ */
+ public void test_getLongLjava_lang_StringLjava_lang_Long() {
+ // Test for method java.lang.Long
+ // java.lang.Long.getLong(java.lang.String, java.lang.Long)
+ Properties tProps = new Properties();
+ tProps.put("testLong", "99");
+ System.setProperties(tProps);
+ assertTrue("returned incorrect Long", Long.getLong("testLong",
+ new Long(4)).equals(new Long(99)));
+ assertTrue("returned incorrect default Long", Long.getLong("ff",
+ new Long(4)).equals(new Long(4)));
+ }
+
+ /**
+ * java.lang.Long#parseLong(java.lang.String)
+ */
+ public void test_parseLongLjava_lang_String2() {
+ // Test for method long java.lang.Long.parseLong(java.lang.String)
+
+ long l = Long.parseLong("89000000005");
+ assertEquals("Parsed to incorrect long value", 89000000005L, l);
+ assertEquals("Returned incorrect value for 0", 0, Long.parseLong("0"));
+ assertTrue("Returned incorrect value for most negative value", Long
+ .parseLong("-9223372036854775808") == 0x8000000000000000L);
+ assertTrue("Returned incorrect value for most positive value", Long
+ .parseLong("9223372036854775807") == 0x7fffffffffffffffL);
+
+ boolean exception = false;
+ try {
+ Long.parseLong("9223372036854775808");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.parseLong("-9223372036854775809");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Long#parseLong(java.lang.String, int)
+ */
+ public void test_parseLongLjava_lang_StringI() {
+ // Test for method long java.lang.Long.parseLong(java.lang.String, int)
+ assertEquals("Returned incorrect value",
+ 100000000L, Long.parseLong("100000000", 10));
+ assertEquals("Returned incorrect value from hex string", 68719476735L, Long.parseLong(
+ "FFFFFFFFF", 16));
+ assertTrue("Returned incorrect value from octal string: "
+ + Long.parseLong("77777777777"), Long.parseLong("77777777777",
+ 8) == 8589934591L);
+ assertEquals("Returned incorrect value for 0 hex", 0, Long
+ .parseLong("0", 16));
+ assertTrue("Returned incorrect value for most negative value hex", Long
+ .parseLong("-8000000000000000", 16) == 0x8000000000000000L);
+ assertTrue("Returned incorrect value for most positive value hex", Long
+ .parseLong("7fffffffffffffff", 16) == 0x7fffffffffffffffL);
+ assertEquals("Returned incorrect value for 0 decimal", 0, Long.parseLong(
+ "0", 10));
+ assertTrue(
+ "Returned incorrect value for most negative value decimal",
+ Long.parseLong("-9223372036854775808", 10) == 0x8000000000000000L);
+ assertTrue(
+ "Returned incorrect value for most positive value decimal",
+ Long.parseLong("9223372036854775807", 10) == 0x7fffffffffffffffL);
+
+ boolean exception = false;
+ try {
+ Long.parseLong("999999999999", 8);
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+
+ exception = false;
+ try {
+ Long.parseLong("9223372036854775808", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.parseLong("-9223372036854775809", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Long.parseLong("8000000000000000", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.parseLong("-8000000000000001", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Long.parseLong("42325917317067571199", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for 42325917317067571199",
+ exception);
+ }
+
+ /**
+ * java.lang.Long#toBinaryString(long)
+ */
+ public void test_toBinaryStringJ() {
+ // Test for method java.lang.String java.lang.Long.toBinaryString(long)
+ assertEquals("Incorrect binary string returned", "11011001010010010000", Long.toBinaryString(
+ 890000L));
+ assertEquals("Incorrect binary string returned",
+
+ "1000000000000000000000000000000000000000000000000000000000000000", Long
+ .toBinaryString(Long.MIN_VALUE)
+ );
+ assertEquals("Incorrect binary string returned",
+
+ "111111111111111111111111111111111111111111111111111111111111111", Long
+ .toBinaryString(Long.MAX_VALUE)
+ );
+ }
+
+ /**
+ * java.lang.Long#toHexString(long)
+ */
+ public void test_toHexStringJ() {
+ // Test for method java.lang.String java.lang.Long.toHexString(long)
+ assertEquals("Incorrect hex string returned", "54e0845", Long.toHexString(89000005L)
+ );
+ assertEquals("Incorrect hex string returned", "8000000000000000", Long.toHexString(
+ Long.MIN_VALUE));
+ assertEquals("Incorrect hex string returned", "7fffffffffffffff", Long.toHexString(
+ Long.MAX_VALUE));
+ }
+
+ /**
+ * java.lang.Long#toOctalString(long)
+ */
+ public void test_toOctalStringJ() {
+ // Test for method java.lang.String java.lang.Long.toOctalString(long)
+ assertEquals("Returned incorrect oct string", "77777777777", Long.toOctalString(
+ 8589934591L));
+ assertEquals("Returned incorrect oct string", "1000000000000000000000", Long.toOctalString(
+ Long.MIN_VALUE));
+ assertEquals("Returned incorrect oct string", "777777777777777777777", Long.toOctalString(
+ Long.MAX_VALUE));
+ }
+
+ /**
+ * java.lang.Long#toString()
+ */
+ public void test_toString2() {
+ // Test for method java.lang.String java.lang.Long.toString()
+ Long l = new Long(89000000005L);
+ assertEquals("Returned incorrect String",
+ "89000000005", l.toString());
+ assertEquals("Returned incorrect String", "-9223372036854775808", new Long(Long.MIN_VALUE)
+ .toString());
+ assertEquals("Returned incorrect String", "9223372036854775807", new Long(Long.MAX_VALUE)
+ .toString());
+ }
+
+ /**
+ * java.lang.Long#toString(long)
+ */
+ public void test_toStringJ2() {
+ // Test for method java.lang.String java.lang.Long.toString(long)
+
+ assertEquals("Returned incorrect String", "89000000005", Long.toString(89000000005L)
+ );
+ assertEquals("Returned incorrect String", "-9223372036854775808", Long.toString(Long.MIN_VALUE)
+ );
+ assertEquals("Returned incorrect String", "9223372036854775807", Long.toString(Long.MAX_VALUE)
+ );
+ }
+
+ /**
+ * java.lang.Long#toString(long, int)
+ */
+ public void test_toStringJI() {
+ // Test for method java.lang.String java.lang.Long.toString(long, int)
+ assertEquals("Returned incorrect dec string", "100000000", Long.toString(100000000L,
+ 10));
+ assertEquals("Returned incorrect hex string", "fffffffff", Long.toString(68719476735L,
+ 16));
+ assertEquals("Returned incorrect oct string", "77777777777", Long.toString(8589934591L,
+ 8));
+ assertEquals("Returned incorrect bin string",
+ "1111111111111111111111111111111111111111111", Long.toString(
+ 8796093022207L, 2));
+ assertEquals("Returned incorrect min string", "-9223372036854775808", Long.toString(
+ 0x8000000000000000L, 10));
+ assertEquals("Returned incorrect max string", "9223372036854775807", Long.toString(
+ 0x7fffffffffffffffL, 10));
+ assertEquals("Returned incorrect min string", "-8000000000000000", Long.toString(
+ 0x8000000000000000L, 16));
+ assertEquals("Returned incorrect max string", "7fffffffffffffff", Long.toString(
+ 0x7fffffffffffffffL, 16));
+ }
+
+ /**
+ * java.lang.Long#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String2() {
+ // Test for method java.lang.Long
+ // java.lang.Long.valueOf(java.lang.String)
+ assertEquals("Returned incorrect value", 100000000L, Long.valueOf("100000000")
+ .longValue());
+ assertTrue("Returned incorrect value", Long.valueOf(
+ "9223372036854775807").longValue() == Long.MAX_VALUE);
+ assertTrue("Returned incorrect value", Long.valueOf(
+ "-9223372036854775808").longValue() == Long.MIN_VALUE);
+
+ boolean exception = false;
+ try {
+ Long
+ .valueOf("999999999999999999999999999999999999999999999999999999999999");
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+
+ exception = false;
+ try {
+ Long.valueOf("9223372036854775808");
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+
+ exception = false;
+ try {
+ Long.valueOf("-9223372036854775809");
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+ }
+
+ /**
+ * java.lang.Long#valueOf(java.lang.String, int)
+ */
+ public void test_valueOfLjava_lang_StringI() {
+ // Test for method java.lang.Long
+ // java.lang.Long.valueOf(java.lang.String, int)
+ assertEquals("Returned incorrect value", 100000000L, Long.valueOf("100000000", 10)
+ .longValue());
+ assertEquals("Returned incorrect value from hex string", 68719476735L, Long.valueOf(
+ "FFFFFFFFF", 16).longValue());
+ assertTrue("Returned incorrect value from octal string: "
+ + Long.valueOf("77777777777", 8).toString(), Long.valueOf(
+ "77777777777", 8).longValue() == 8589934591L);
+ assertTrue("Returned incorrect value", Long.valueOf(
+ "9223372036854775807", 10).longValue() == Long.MAX_VALUE);
+ assertTrue("Returned incorrect value", Long.valueOf(
+ "-9223372036854775808", 10).longValue() == Long.MIN_VALUE);
+ assertTrue("Returned incorrect value", Long.valueOf("7fffffffffffffff",
+ 16).longValue() == Long.MAX_VALUE);
+ assertTrue("Returned incorrect value", Long.valueOf(
+ "-8000000000000000", 16).longValue() == Long.MIN_VALUE);
+
+ boolean exception = false;
+ try {
+ Long.valueOf("999999999999", 8);
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+
+ exception = false;
+ try {
+ Long.valueOf("9223372036854775808", 10);
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+
+ exception = false;
+ try {
+ Long.valueOf("-9223372036854775809", 10);
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception when passed invalid string",
+ exception);
+ }
+
+ /**
+ * java.lang.Long#valueOf(long)
+ */
+ public void test_valueOfJ() {
+ assertEquals(new Long(Long.MIN_VALUE), Long.valueOf(Long.MIN_VALUE));
+ assertEquals(new Long(Long.MAX_VALUE), Long.valueOf(Long.MAX_VALUE));
+ assertEquals(new Long(0), Long.valueOf(0));
+
+ long lng = -128;
+ while (lng < 128) {
+ assertEquals(new Long(lng), Long.valueOf(lng));
+ assertSame(Long.valueOf(lng), Long.valueOf(lng));
+ lng++;
+ }
+ }
+
+ /**
+ * java.lang.Long#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals((int) (1L ^ (1L >>> 32)), new Long(1).hashCode());
+ assertEquals((int) (2L ^ (2L >>> 32)), new Long(2).hashCode());
+ assertEquals((int) (0L ^ (0L >>> 32)), new Long(0).hashCode());
+ assertEquals((int) (-1L ^ (-1L >>> 32)), new Long(-1).hashCode());
+ }
+
+ /**
+ * java.lang.Long#Long(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertEquals(new Long(0), new Long("0"));
+ assertEquals(new Long(1), new Long("1"));
+ assertEquals(new Long(-1), new Long("-1"));
+
+ try {
+ new Long("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Long("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Long("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Long(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#Long
+ */
+ public void test_ConstructorJ() {
+ assertEquals(1, new Long(1).intValue());
+ assertEquals(2, new Long(2).intValue());
+ assertEquals(0, new Long(0).intValue());
+ assertEquals(-1, new Long(-1).intValue());
+ }
+
+ /**
+ * java.lang.Long#byteValue()
+ */
+ public void test_booleanValue() {
+ assertEquals(1, new Long(1).byteValue());
+ assertEquals(2, new Long(2).byteValue());
+ assertEquals(0, new Long(0).byteValue());
+ assertEquals(-1, new Long(-1).byteValue());
+ }
+
+ /**
+ * java.lang.Long#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertEquals(new Long(0), Long.valueOf(0));
+ assertEquals(new Long(1), Long.valueOf(1));
+ assertEquals(new Long(-1), Long.valueOf(-1));
+
+ Long fixture = new Long(25);
+ assertEquals(fixture, fixture);
+ assertFalse(fixture.equals(null));
+ assertFalse(fixture.equals("Not a Long"));
+ }
+
+ /**
+ * java.lang.Long#toString()
+ */
+ public void test_toString() {
+ assertEquals("-1", new Long(-1).toString());
+ assertEquals("0", new Long(0).toString());
+ assertEquals("1", new Long(1).toString());
+ assertEquals("-1", new Long(0xFFFFFFFF).toString());
+ }
+
+ /**
+ * java.lang.Long#toString
+ */
+ public void test_toStringJ() {
+ assertEquals("-1", Long.toString(-1));
+ assertEquals("0", Long.toString(0));
+ assertEquals("1", Long.toString(1));
+ assertEquals("-1", Long.toString(0xFFFFFFFF));
+ }
+
+ /**
+ * java.lang.Long#valueOf(String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertEquals(new Long(0), Long.valueOf("0"));
+ assertEquals(new Long(1), Long.valueOf("1"));
+ assertEquals(new Long(-1), Long.valueOf("-1"));
+
+ try {
+ Long.valueOf("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#valueOf(String, long)
+ */
+ public void test_valueOfLjava_lang_StringJ() {
+ assertEquals(new Long(0), Long.valueOf("0", 10));
+ assertEquals(new Long(1), Long.valueOf("1", 10));
+ assertEquals(new Long(-1), Long.valueOf("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Long.valueOf("1", 2).byteValue());
+ assertEquals(Character.digit('F', 16), Long.valueOf("F", 16).byteValue());
+
+ try {
+ Long.valueOf("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.valueOf(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#parseLong(String)
+ */
+ public void test_parseLongLjava_lang_String() {
+ assertEquals(0, Long.parseLong("0"));
+ assertEquals(1, Long.parseLong("1"));
+ assertEquals(-1, Long.parseLong("-1"));
+
+ try {
+ Long.parseLong("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#parseLong(String, long)
+ */
+ public void test_parseLongLjava_lang_StringJ() {
+ assertEquals(0, Long.parseLong("0", 10));
+ assertEquals(1, Long.parseLong("1", 10));
+ assertEquals(-1, Long.parseLong("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Long.parseLong("1", 2));
+ assertEquals(Character.digit('F', 16), Long.parseLong("F", 16));
+
+ try {
+ Long.parseLong("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.parseLong(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#decode(String)
+ */
+ public void test_decodeLjava_lang_String() {
+ assertEquals(new Long(0), Long.decode("0"));
+ assertEquals(new Long(1), Long.decode("1"));
+ assertEquals(new Long(-1), Long.decode("-1"));
+ assertEquals(new Long(0xF), Long.decode("0xF"));
+ assertEquals(new Long(0xF), Long.decode("#F"));
+ assertEquals(new Long(0xF), Long.decode("0XF"));
+ assertEquals(new Long(07), Long.decode("07"));
+
+ try {
+ Long.decode("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.decode("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Long.decode(null);
+ //undocumented NPE, but seems consistent across JREs
+ fail("Expected NullPointerException with null string.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Long#doubleValue()
+ */
+ public void test_doubleValue() {
+ assertEquals(-1D, new Long(-1).doubleValue(), 0D);
+ assertEquals(0D, new Long(0).doubleValue(), 0D);
+ assertEquals(1D, new Long(1).doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Long#floatValue()
+ */
+ public void test_floatValue() {
+ assertEquals(-1F, new Long(-1).floatValue(), 0F);
+ assertEquals(0F, new Long(0).floatValue(), 0F);
+ assertEquals(1F, new Long(1).floatValue(), 0F);
+ }
+
+ /**
+ * java.lang.Long#intValue()
+ */
+ public void test_intValue() {
+ assertEquals(-1, new Long(-1).intValue());
+ assertEquals(0, new Long(0).intValue());
+ assertEquals(1, new Long(1).intValue());
+ }
+
+ /**
+ * java.lang.Long#longValue()
+ */
+ public void test_longValue() {
+ assertEquals(-1L, new Long(-1).longValue());
+ assertEquals(0L, new Long(0).longValue());
+ assertEquals(1L, new Long(1).longValue());
+ }
+
+ /**
+ * java.lang.Long#shortValue()
+ */
+ public void test_shortValue() {
+ assertEquals(-1, new Long(-1).shortValue());
+ assertEquals(0, new Long(0).shortValue());
+ assertEquals(1, new Long(1).shortValue());
+ }
+
+ /**
+ * java.lang.Long#highestOneBit(long)
+ */
+ public void test_highestOneBitJ() {
+ assertEquals(0x08, Long.highestOneBit(0x0A));
+ assertEquals(0x08, Long.highestOneBit(0x0B));
+ assertEquals(0x08, Long.highestOneBit(0x0C));
+ assertEquals(0x08, Long.highestOneBit(0x0F));
+ assertEquals(0x80, Long.highestOneBit(0xFF));
+
+ assertEquals(0x080000, Long.highestOneBit(0x0F1234));
+ assertEquals(0x800000, Long.highestOneBit(0xFF9977));
+
+ assertEquals(0x8000000000000000L, Long.highestOneBit(0xFFFFFFFFFFFFFFFFL));
+
+ assertEquals(0, Long.highestOneBit(0));
+ assertEquals(1, Long.highestOneBit(1));
+ assertEquals(0x8000000000000000L, Long.highestOneBit(-1));
+ }
+
+ /**
+ * java.lang.Long#lowestOneBit(long)
+ */
+ public void test_lowestOneBitJ() {
+ assertEquals(0x10, Long.lowestOneBit(0xF0));
+
+ assertEquals(0x10, Long.lowestOneBit(0x90));
+ assertEquals(0x10, Long.lowestOneBit(0xD0));
+
+ assertEquals(0x10, Long.lowestOneBit(0x123490));
+ assertEquals(0x10, Long.lowestOneBit(0x1234D0));
+
+ assertEquals(0x100000, Long.lowestOneBit(0x900000));
+ assertEquals(0x100000, Long.lowestOneBit(0xD00000));
+
+ assertEquals(0x40, Long.lowestOneBit(0x40));
+ assertEquals(0x40, Long.lowestOneBit(0xC0));
+
+ assertEquals(0x4000, Long.lowestOneBit(0x4000));
+ assertEquals(0x4000, Long.lowestOneBit(0xC000));
+
+ assertEquals(0x4000, Long.lowestOneBit(0x99994000));
+ assertEquals(0x4000, Long.lowestOneBit(0x9999C000));
+
+ assertEquals(0, Long.lowestOneBit(0));
+ assertEquals(1, Long.lowestOneBit(1));
+ assertEquals(1, Long.lowestOneBit(-1));
+ }
+
+ /**
+ * java.lang.Long#numberOfLeadingZeros(long)
+ */
+ public void test_numberOfLeadingZerosJ() {
+ assertEquals(64, Long.numberOfLeadingZeros(0x0L));
+ assertEquals(63, Long.numberOfLeadingZeros(0x1));
+ assertEquals(62, Long.numberOfLeadingZeros(0x2));
+ assertEquals(62, Long.numberOfLeadingZeros(0x3));
+ assertEquals(61, Long.numberOfLeadingZeros(0x4));
+ assertEquals(61, Long.numberOfLeadingZeros(0x5));
+ assertEquals(61, Long.numberOfLeadingZeros(0x6));
+ assertEquals(61, Long.numberOfLeadingZeros(0x7));
+ assertEquals(60, Long.numberOfLeadingZeros(0x8));
+ assertEquals(60, Long.numberOfLeadingZeros(0x9));
+ assertEquals(60, Long.numberOfLeadingZeros(0xA));
+ assertEquals(60, Long.numberOfLeadingZeros(0xB));
+ assertEquals(60, Long.numberOfLeadingZeros(0xC));
+ assertEquals(60, Long.numberOfLeadingZeros(0xD));
+ assertEquals(60, Long.numberOfLeadingZeros(0xE));
+ assertEquals(60, Long.numberOfLeadingZeros(0xF));
+ assertEquals(59, Long.numberOfLeadingZeros(0x10));
+ assertEquals(56, Long.numberOfLeadingZeros(0x80));
+ assertEquals(56, Long.numberOfLeadingZeros(0xF0));
+ assertEquals(55, Long.numberOfLeadingZeros(0x100));
+ assertEquals(52, Long.numberOfLeadingZeros(0x800));
+ assertEquals(52, Long.numberOfLeadingZeros(0xF00));
+ assertEquals(51, Long.numberOfLeadingZeros(0x1000));
+ assertEquals(48, Long.numberOfLeadingZeros(0x8000));
+ assertEquals(48, Long.numberOfLeadingZeros(0xF000));
+ assertEquals(47, Long.numberOfLeadingZeros(0x10000));
+ assertEquals(44, Long.numberOfLeadingZeros(0x80000));
+ assertEquals(44, Long.numberOfLeadingZeros(0xF0000));
+ assertEquals(43, Long.numberOfLeadingZeros(0x100000));
+ assertEquals(40, Long.numberOfLeadingZeros(0x800000));
+ assertEquals(40, Long.numberOfLeadingZeros(0xF00000));
+ assertEquals(39, Long.numberOfLeadingZeros(0x1000000));
+ assertEquals(36, Long.numberOfLeadingZeros(0x8000000));
+ assertEquals(36, Long.numberOfLeadingZeros(0xF000000));
+ assertEquals(35, Long.numberOfLeadingZeros(0x10000000));
+ assertEquals(0, Long.numberOfLeadingZeros(0x80000000));
+ assertEquals(0, Long.numberOfLeadingZeros(0xF0000000));
+
+ assertEquals(1, Long.numberOfLeadingZeros(Long.MAX_VALUE));
+ assertEquals(0, Long.numberOfLeadingZeros(Long.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.Long#numberOfTrailingZeros(long)
+ */
+ public void test_numberOfTrailingZerosJ() {
+ assertEquals(64, Long.numberOfTrailingZeros(0x0));
+ assertEquals(63, Long.numberOfTrailingZeros(Long.MIN_VALUE));
+ assertEquals(0, Long.numberOfTrailingZeros(Long.MAX_VALUE));
+
+ assertEquals(0, Long.numberOfTrailingZeros(0x1));
+ assertEquals(3, Long.numberOfTrailingZeros(0x8));
+ assertEquals(0, Long.numberOfTrailingZeros(0xF));
+
+ assertEquals(4, Long.numberOfTrailingZeros(0x10));
+ assertEquals(7, Long.numberOfTrailingZeros(0x80));
+ assertEquals(4, Long.numberOfTrailingZeros(0xF0));
+
+ assertEquals(8, Long.numberOfTrailingZeros(0x100));
+ assertEquals(11, Long.numberOfTrailingZeros(0x800));
+ assertEquals(8, Long.numberOfTrailingZeros(0xF00));
+
+ assertEquals(12, Long.numberOfTrailingZeros(0x1000));
+ assertEquals(15, Long.numberOfTrailingZeros(0x8000));
+ assertEquals(12, Long.numberOfTrailingZeros(0xF000));
+
+ assertEquals(16, Long.numberOfTrailingZeros(0x10000));
+ assertEquals(19, Long.numberOfTrailingZeros(0x80000));
+ assertEquals(16, Long.numberOfTrailingZeros(0xF0000));
+
+ assertEquals(20, Long.numberOfTrailingZeros(0x100000));
+ assertEquals(23, Long.numberOfTrailingZeros(0x800000));
+ assertEquals(20, Long.numberOfTrailingZeros(0xF00000));
+
+ assertEquals(24, Long.numberOfTrailingZeros(0x1000000));
+ assertEquals(27, Long.numberOfTrailingZeros(0x8000000));
+ assertEquals(24, Long.numberOfTrailingZeros(0xF000000));
+
+ assertEquals(28, Long.numberOfTrailingZeros(0x10000000));
+ assertEquals(31, Long.numberOfTrailingZeros(0x80000000));
+ assertEquals(28, Long.numberOfTrailingZeros(0xF0000000));
+ }
+
+ /**
+ * java.lang.Long#bitCount(long)
+ */
+ public void test_bitCountJ() {
+ assertEquals(0, Long.bitCount(0x0));
+ assertEquals(1, Long.bitCount(0x1));
+ assertEquals(1, Long.bitCount(0x2));
+ assertEquals(2, Long.bitCount(0x3));
+ assertEquals(1, Long.bitCount(0x4));
+ assertEquals(2, Long.bitCount(0x5));
+ assertEquals(2, Long.bitCount(0x6));
+ assertEquals(3, Long.bitCount(0x7));
+ assertEquals(1, Long.bitCount(0x8));
+ assertEquals(2, Long.bitCount(0x9));
+ assertEquals(2, Long.bitCount(0xA));
+ assertEquals(3, Long.bitCount(0xB));
+ assertEquals(2, Long.bitCount(0xC));
+ assertEquals(3, Long.bitCount(0xD));
+ assertEquals(3, Long.bitCount(0xE));
+ assertEquals(4, Long.bitCount(0xF));
+
+ assertEquals(8, Long.bitCount(0xFF));
+ assertEquals(12, Long.bitCount(0xFFF));
+ assertEquals(16, Long.bitCount(0xFFFF));
+ assertEquals(20, Long.bitCount(0xFFFFF));
+ assertEquals(24, Long.bitCount(0xFFFFFF));
+ assertEquals(28, Long.bitCount(0xFFFFFFF));
+ assertEquals(64, Long.bitCount(0xFFFFFFFFFFFFFFFFL));
+ }
+
+ /**
+ * java.lang.Long#rotateLeft(long, long)
+ */
+ public void test_rotateLeftJI() {
+ assertEquals(0xF, Long.rotateLeft(0xF, 0));
+ assertEquals(0xF0, Long.rotateLeft(0xF, 4));
+ assertEquals(0xF00, Long.rotateLeft(0xF, 8));
+ assertEquals(0xF000, Long.rotateLeft(0xF, 12));
+ assertEquals(0xF0000, Long.rotateLeft(0xF, 16));
+ assertEquals(0xF00000, Long.rotateLeft(0xF, 20));
+ assertEquals(0xF000000, Long.rotateLeft(0xF, 24));
+ assertEquals(0xF0000000L, Long.rotateLeft(0xF, 28));
+ assertEquals(0xF000000000000000L, Long.rotateLeft(0xF000000000000000L, 64));
+ }
+
+ /**
+ * java.lang.Long#rotateRight(long, long)
+ */
+ public void test_rotateRightJI() {
+ assertEquals(0xF, Long.rotateRight(0xF0, 4));
+ assertEquals(0xF, Long.rotateRight(0xF00, 8));
+ assertEquals(0xF, Long.rotateRight(0xF000, 12));
+ assertEquals(0xF, Long.rotateRight(0xF0000, 16));
+ assertEquals(0xF, Long.rotateRight(0xF00000, 20));
+ assertEquals(0xF, Long.rotateRight(0xF000000, 24));
+ assertEquals(0xF, Long.rotateRight(0xF0000000L, 28));
+ assertEquals(0xF000000000000000L, Long.rotateRight(0xF000000000000000L, 64));
+ assertEquals(0xF000000000000000L, Long.rotateRight(0xF000000000000000L, 0));
+
+ }
+
+ /**
+ * java.lang.Long#reverseBytes(long)
+ */
+ public void test_reverseBytesJ() {
+ assertEquals(0xAABBCCDD00112233L, Long.reverseBytes(0x33221100DDCCBBAAL));
+ assertEquals(0x1122334455667788L, Long.reverseBytes(0x8877665544332211L));
+ assertEquals(0x0011223344556677L, Long.reverseBytes(0x7766554433221100L));
+ assertEquals(0x2000000000000002L, Long.reverseBytes(0x0200000000000020L));
+ }
+
+ /**
+ * java.lang.Long#reverse(long)
+ */
+ public void test_reverseJ() {
+ assertEquals(0, Long.reverse(0));
+ assertEquals(-1, Long.reverse(-1));
+ assertEquals(0x8000000000000000L, Long.reverse(1));
+ }
+
+ /**
+ * java.lang.Long#signum(long)
+ */
+ public void test_signumJ() {
+ for (int i = -128; i < 0; i++) {
+ assertEquals(-1, Long.signum(i));
+ }
+ assertEquals(0, Long.signum(0));
+ for (int i = 1; i <= 127; i++) {
+ assertEquals(1, Long.signum(i));
+ }
+ }
+} \ No newline at end of file
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MathTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MathTest.java
new file mode 100644
index 0000000..ed8e2b5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MathTest.java
@@ -0,0 +1,1960 @@
+/*
+ * 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.tests.java.lang;
+
+public class MathTest extends junit.framework.TestCase {
+
+ double HYP = Math.sqrt(2.0);
+
+ double OPP = 1.0;
+
+ double ADJ = 1.0;
+
+ /* Required to make previous preprocessor flags work - do not remove */
+ int unused = 0;
+
+ /**
+ * java.lang.Math#abs(double)
+ */
+ public void test_absD() {
+ // Test for method double java.lang.Math.abs(double)
+
+ assertTrue("Incorrect double abs value",
+ (Math.abs(-1908.8976) == 1908.8976));
+ assertTrue("Incorrect double abs value",
+ (Math.abs(1908.8976) == 1908.8976));
+ }
+
+ /**
+ * java.lang.Math#abs(float)
+ */
+ public void test_absF() {
+ // Test for method float java.lang.Math.abs(float)
+ assertTrue("Incorrect float abs value",
+ (Math.abs(-1908.8976f) == 1908.8976f));
+ assertTrue("Incorrect float abs value",
+ (Math.abs(1908.8976f) == 1908.8976f));
+ }
+
+ /**
+ * java.lang.Math#abs(int)
+ */
+ public void test_absI() {
+ // Test for method int java.lang.Math.abs(int)
+ assertTrue("Incorrect int abs value", (Math.abs(-1908897) == 1908897));
+ assertTrue("Incorrect int abs value", (Math.abs(1908897) == 1908897));
+ }
+
+ /**
+ * java.lang.Math#abs(long)
+ */
+ public void test_absJ() {
+ // Test for method long java.lang.Math.abs(long)
+ assertTrue("Incorrect long abs value",
+ (Math.abs(-19088976000089L) == 19088976000089L));
+ assertTrue("Incorrect long abs value",
+ (Math.abs(19088976000089L) == 19088976000089L));
+ }
+
+ /**
+ * java.lang.Math#acos(double)
+ */
+ public void test_acosD() {
+ // Test for method double java.lang.Math.acos(double)
+ double r = Math.cos(Math.acos(ADJ / HYP));
+ long lr = Double.doubleToLongBits(r);
+ long t = Double.doubleToLongBits(ADJ / HYP);
+ assertTrue("Returned incorrect arc cosine", lr == t || (lr + 1) == t
+ || (lr - 1) == t);
+ }
+
+ /**
+ * java.lang.Math#asin(double)
+ */
+ public void test_asinD() {
+ // Test for method double java.lang.Math.asin(double)
+ double r = Math.sin(Math.asin(OPP / HYP));
+ long lr = Double.doubleToLongBits(r);
+ long t = Double.doubleToLongBits(OPP / HYP);
+ assertTrue("Returned incorrect arc sine", lr == t || (lr + 1) == t
+ || (lr - 1) == t);
+ }
+
+ /**
+ * java.lang.Math#atan(double)
+ */
+ public void test_atanD() {
+ // Test for method double java.lang.Math.atan(double)
+ double answer = Math.tan(Math.atan(1.0));
+ assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
+ && answer >= 9.9999999999999983E-1);
+ }
+
+ /**
+ * java.lang.Math#atan2(double, double)
+ */
+ public void test_atan2DD() {
+ // Test for method double java.lang.Math.atan2(double, double)
+ double answer = Math.atan(Math.tan(1.0));
+ assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
+ && answer >= 9.9999999999999983E-1);
+ }
+
+ /**
+ * java.lang.Math#cbrt(double)
+ */
+ public void test_cbrt_D() {
+ //Test for special situations
+ assertTrue(Double.isNaN(Math.cbrt(Double.NaN)));
+ assertEquals(Double.POSITIVE_INFINITY, Math.cbrt(Double.POSITIVE_INFINITY), 0D);
+ assertEquals(Double.NEGATIVE_INFINITY, Math.cbrt(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math.cbrt(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double.doubleToLongBits(Math.cbrt(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double.doubleToLongBits(Math.cbrt(-0.0)));
+
+ assertEquals(3.0, Math.cbrt(27.0), 0D);
+ assertEquals(23.111993172558684, Math.cbrt(12345.6), Math.ulp(23.111993172558684));
+ assertEquals(5.643803094122362E102, Math.cbrt(Double.MAX_VALUE), 0D);
+ assertEquals(0.01, Math.cbrt(0.000001), 0D);
+
+ assertEquals(-3.0, Math.cbrt(-27.0), 0D);
+ assertEquals(-23.111993172558684, Math.cbrt(-12345.6), Math.ulp(-23.111993172558684));
+ assertEquals(1.7031839360032603E-108, Math.cbrt(Double.MIN_VALUE), 0D);
+ assertEquals(-0.01, Math.cbrt(-0.000001), 0D);
+ }
+
+ /**
+ * java.lang.Math#ceil(double)
+ */
+ public void test_ceilD() {
+ // Test for method double java.lang.Math.ceil(double)
+ assertEquals("Incorrect ceiling for double",
+ 79, Math.ceil(78.89), 0);
+ assertEquals("Incorrect ceiling for double",
+ -78, Math.ceil(-78.89), 0);
+ }
+
+ /**
+ * cases for test_copySign_DD in MathTest/StrictMathTest
+ */
+ static final double[] COPYSIGN_DD_CASES = new double[] {
+ Double.POSITIVE_INFINITY, Double.MAX_VALUE, 3.4E302, 2.3,
+ Double.MIN_NORMAL, Double.MIN_NORMAL / 2, Double.MIN_VALUE, +0.0,
+ 0.0, -0.0, -Double.MIN_VALUE, -Double.MIN_NORMAL / 2,
+ -Double.MIN_NORMAL, -4.5, -3.4E102, -Double.MAX_VALUE,
+ Double.NEGATIVE_INFINITY };
+
+ /**
+ * {@link java.lang.Math#copySign(double, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_copySign_DD() {
+ for (int i = 0; i < COPYSIGN_DD_CASES.length; i++) {
+ final double magnitude = COPYSIGN_DD_CASES[i];
+ final long absMagnitudeBits = Double.doubleToLongBits(Math
+ .abs(magnitude));
+ final long negMagnitudeBits = Double.doubleToLongBits(-Math
+ .abs(magnitude));
+
+ // cases for NaN
+ assertEquals("If the sign is NaN, the result should be positive.",
+ absMagnitudeBits, Double.doubleToLongBits(Math.copySign(
+ magnitude, Double.NaN)));
+ assertTrue("The result should be NaN.", Double.isNaN(Math.copySign(
+ Double.NaN, magnitude)));
+
+ for (int j = 0; j < COPYSIGN_DD_CASES.length; j++) {
+ final double sign = COPYSIGN_DD_CASES[j];
+ final long resultBits = Double.doubleToLongBits(Math.copySign(
+ magnitude, sign));
+
+ if (sign > 0 || Double.valueOf(+0.0).equals(sign)
+ || Double.valueOf(0.0).equals(sign)) {
+ assertEquals(
+ "If the sign is positive, the result should be positive.",
+ absMagnitudeBits, resultBits);
+ }
+ if (sign < 0 || Double.valueOf(-0.0).equals(sign)) {
+ assertEquals(
+ "If the sign is negative, the result should be negative.",
+ negMagnitudeBits, resultBits);
+ }
+ }
+ }
+
+ assertTrue("The result should be NaN.", Double.isNaN(Math.copySign(
+ Double.NaN, Double.NaN)));
+
+ try {
+ Math.copySign((Double) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.copySign(2.3, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.copySign((Double) null, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * cases for test_copySign_FF in MathTest/StrictMathTest
+ */
+ static final float[] COPYSIGN_FF_CASES = new float[] {
+ Float.POSITIVE_INFINITY, Float.MAX_VALUE, 3.4E12f, 2.3f,
+ Float.MIN_NORMAL, Float.MIN_NORMAL / 2, Float.MIN_VALUE, +0.0f,
+ 0.0f, -0.0f, -Float.MIN_VALUE, -Float.MIN_NORMAL / 2,
+ -Float.MIN_NORMAL, -4.5f, -5.6442E21f, -Float.MAX_VALUE,
+ Float.NEGATIVE_INFINITY };
+
+ /**
+ * {@link java.lang.Math#copySign(float, float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_copySign_FF() {
+ for (int i = 0; i < COPYSIGN_FF_CASES.length; i++) {
+ final float magnitude = COPYSIGN_FF_CASES[i];
+ final int absMagnitudeBits = Float.floatToIntBits(Math
+ .abs(magnitude));
+ final int negMagnitudeBits = Float.floatToIntBits(-Math
+ .abs(magnitude));
+
+ // cases for NaN
+ assertEquals("If the sign is NaN, the result should be positive.",
+ absMagnitudeBits, Float.floatToIntBits(Math.copySign(
+ magnitude, Float.NaN)));
+ assertTrue("The result should be NaN.", Float.isNaN(Math.copySign(
+ Float.NaN, magnitude)));
+
+ for (int j = 0; j < COPYSIGN_FF_CASES.length; j++) {
+ final float sign = COPYSIGN_FF_CASES[j];
+ final int resultBits = Float.floatToIntBits(Math.copySign(
+ magnitude, sign));
+ if (sign > 0 || Float.valueOf(+0.0f).equals(sign)
+ || Float.valueOf(0.0f).equals(sign)) {
+ assertEquals(
+ "If the sign is positive, the result should be positive.",
+ absMagnitudeBits, resultBits);
+ }
+ if (sign < 0 || Float.valueOf(-0.0f).equals(sign)) {
+ assertEquals(
+ "If the sign is negative, the result should be negative.",
+ negMagnitudeBits, resultBits);
+ }
+ }
+ }
+
+ assertTrue("The result should be NaN.", Float.isNaN(Math.copySign(
+ Float.NaN, Float.NaN)));
+
+ try {
+ Math.copySign((Float) null, 2.3f);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.copySign(2.3f, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.copySign((Float) null, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.Math#cos(double)
+ */
+ public void test_cosD() {
+ // Test for method double java.lang.Math.cos(double)
+ assertEquals("Incorrect answer", 1.0, Math.cos(0), 0D);
+ assertEquals("Incorrect answer", 0.5403023058681398, Math.cos(1), 0D);
+ }
+
+ /**
+ * java.lang.Math#cosh(double)
+ */
+ public void test_cosh_D() {
+ // Test for special situations
+ assertTrue(Double.isNaN(Math.cosh(Double.NaN)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.cosh(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.cosh(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals("Should return 1.0", 1.0, Math.cosh(+0.0), 0D);
+ assertEquals("Should return 1.0", 1.0, Math.cosh(-0.0), 0D);
+
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.cosh(1234.56), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.cosh(-1234.56), 0D);
+ assertEquals("Should return 1.0000000000005", 1.0000000000005, Math
+ .cosh(0.000001), 0D);
+ assertEquals("Should return 1.0000000000005", 1.0000000000005, Math
+ .cosh(-0.000001), 0D);
+ assertEquals("Should return 5.212214351945598", 5.212214351945598, Math
+ .cosh(2.33482), 0D);
+
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.cosh(Double.MAX_VALUE), 0D);
+ assertEquals("Should return 1.0", 1.0, Math.cosh(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#exp(double)
+ */
+ public void test_expD() {
+ // Test for method double java.lang.Math.exp(double)
+ assertTrue("Incorrect answer returned for simple power", Math.abs(Math
+ .exp(4D)
+ - Math.E * Math.E * Math.E * Math.E) < 0.1D);
+ assertTrue("Incorrect answer returned for larger power", Math.log(Math
+ .abs(Math.exp(5.5D)) - 5.5D) < 10.0D);
+ }
+
+ /**
+ * java.lang.Math#expm1(double)
+ */
+ public void test_expm1_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(Math.expm1(Double.NaN)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.expm1(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return -1.0", -1.0, Math
+ .expm1(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
+ .expm1(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(Math.expm1(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(Math.expm1(-0.0)));
+
+ assertEquals("Should return -9.999950000166666E-6",
+ -9.999950000166666E-6, Math.expm1(-0.00001), 0D);
+ assertEquals("Should return 1.0145103074469635E60",
+ 1.0145103074469635E60, Math.expm1(138.16951162), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math
+ .expm1(123456789123456789123456789.4521584223), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.expm1(Double.MAX_VALUE), 0D);
+ assertEquals("Should return MIN_VALUE", Double.MIN_VALUE, Math
+ .expm1(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#floor(double)
+ */
+ public void test_floorD() {
+ assertEquals("Incorrect floor for int", 42, Math.floor(42), 0);
+ assertEquals("Incorrect floor for -int", -2, Math.floor(-2), 0);
+ assertEquals("Incorrect floor for zero", 0d, Math.floor(0d), 0);
+
+ assertEquals("Incorrect floor for +double", 78, Math.floor(78.89), 0);
+ assertEquals("Incorrect floor for -double", -79, Math.floor(-78.89), 0);
+ assertEquals("floor large +double", 3.7314645675925406E19, Math.floor(3.7314645675925406E19), 0);
+ assertEquals("floor large -double", -8.173521839218E12, Math.floor(-8.173521839218E12), 0);
+ assertEquals("floor small double", 0.0d, Math.floor(1.11895241315E-102), 0);
+
+ // Compare toString representations here since -0.0 = +0.0, and
+ // NaN != NaN and we need to distinguish
+ assertEquals("Floor failed for NaN",
+ Double.toString(Double.NaN), Double.toString(Math.floor(Double.NaN)));
+ assertEquals("Floor failed for +0.0",
+ Double.toString(+0.0d), Double.toString(Math.floor(+0.0d)));
+ assertEquals("Floor failed for -0.0",
+ Double.toString(-0.0d), Double.toString(Math.floor(-0.0d)));
+ assertEquals("Floor failed for +infinity",
+ Double.toString(Double.POSITIVE_INFINITY), Double.toString(Math.floor(Double.POSITIVE_INFINITY)));
+ assertEquals("Floor failed for -infinity",
+ Double.toString(Double.NEGATIVE_INFINITY), Double.toString(Math.floor(Double.NEGATIVE_INFINITY)));
+ }
+
+ /**
+ * cases for test_getExponent_D in MathTest/StrictMathTest
+ */
+ static final double GETEXPONENT_D_CASES[] = new double[] {
+ Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY,
+ Double.MAX_VALUE, -Double.MAX_VALUE, 2.342E231, -2.342E231, 2800.0,
+ -2800.0, 5.323, -5.323, 1.323, -1.323, 0.623, -0.623, 0.323,
+ -0.323, Double.MIN_NORMAL * 24, -Double.MIN_NORMAL * 24,
+ Double.MIN_NORMAL, -Double.MIN_NORMAL, Double.MIN_NORMAL / 2,
+ -Double.MIN_NORMAL / 2, Double.MIN_VALUE, -Double.MIN_VALUE, +0.0,
+ 0.0, -0.0, Double.NaN };
+
+ /**
+ * result for test_getExponent_D in MathTest/StrictMathTest
+ */
+ static final int GETEXPONENT_D_RESULTS[] = new int[] {
+ Double.MAX_EXPONENT + 1, Double.MAX_EXPONENT + 1,
+ Double.MAX_EXPONENT, Double.MAX_EXPONENT, 768, 768, 11, 11, 2, 2,
+ 0, 0, -1, -1, -2, -2, -1018, -1018, Double.MIN_EXPONENT,
+ Double.MIN_EXPONENT, Double.MIN_EXPONENT - 1,
+ Double.MIN_EXPONENT - 1, Double.MIN_EXPONENT - 1,
+ Double.MIN_EXPONENT - 1, Double.MIN_EXPONENT - 1,
+ Double.MIN_EXPONENT - 1, Double.MIN_EXPONENT - 1,
+ Double.MAX_EXPONENT + 1 };
+
+ /**
+ * {@link java.lang.Math#getExponent(double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_getExponent_D() {
+ for (int i = 0; i < GETEXPONENT_D_CASES.length; i++) {
+ final double number = GETEXPONENT_D_CASES[i];
+ final int result = GETEXPONENT_D_RESULTS[i];
+ assertEquals("Wrong result of getExponent(double).", result, Math
+ .getExponent(number));
+ }
+
+ try {
+ Math.getExponent((Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * cases for test_getExponent_F in MathTest/StrictMathTest
+ */
+ static final float GETEXPONENT_F_CASES[] = new float[] {
+ Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.MAX_VALUE,
+ -Float.MAX_VALUE, 3.4256E23f, -3.4256E23f, 2800.0f, -2800.0f,
+ 5.323f, -5.323f, 1.323f, -1.323f, 0.623f, -0.623f, 0.323f, -0.323f,
+ Float.MIN_NORMAL * 24, -Float.MIN_NORMAL * 24, Float.MIN_NORMAL,
+ -Float.MIN_NORMAL, Float.MIN_NORMAL / 2, -Float.MIN_NORMAL / 2,
+ Float.MIN_VALUE, -Float.MIN_VALUE, +0.0f, 0.0f, -0.0f, Float.NaN, 1, Float.MIN_NORMAL * 1.5f };
+
+ /**
+ * result for test_getExponent_F in MathTest/StrictMathTest
+ */
+ static final int GETEXPONENT_F_RESULTS[] = new int[] {
+ Float.MAX_EXPONENT + 1, Float.MAX_EXPONENT + 1, Float.MAX_EXPONENT,
+ Float.MAX_EXPONENT, 78, 78, 11, 11, 2, 2, 0, 0, -1, -1, -2, -2,
+ -122, -122, Float.MIN_EXPONENT, Float.MIN_EXPONENT,
+ Float.MIN_EXPONENT - 1, Float.MIN_EXPONENT - 1,
+ Float.MIN_EXPONENT - 1, Float.MIN_EXPONENT - 1,
+ Float.MIN_EXPONENT - 1, Float.MIN_EXPONENT - 1,
+ Float.MIN_EXPONENT - 1, Float.MAX_EXPONENT + 1, 0, Float.MIN_EXPONENT };
+
+ /**
+ * {@link java.lang.Math#getExponent(float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_getExponent_F() {
+ for (int i = 0; i < GETEXPONENT_F_CASES.length; i++) {
+ final float number = GETEXPONENT_F_CASES[i];
+ final int result = GETEXPONENT_F_RESULTS[i];
+ assertEquals("Wrong result of getExponent(float).", result, Math
+ .getExponent(number));
+ }
+ try {
+ Math.getExponent((Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.Math#hypot(double, double)
+ */
+ public void test_hypot_DD() {
+ // Test for special cases
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(Double.POSITIVE_INFINITY,
+ 1.0), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(Double.NEGATIVE_INFINITY,
+ 123.324), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(-758.2587,
+ Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(5687.21,
+ Double.NEGATIVE_INFINITY), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(Double.POSITIVE_INFINITY,
+ Double.NEGATIVE_INFINITY), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.hypot(Double.NEGATIVE_INFINITY,
+ Double.POSITIVE_INFINITY), 0D);
+ assertTrue("Should be NaN", Double.isNaN(Math.hypot(Double.NaN,
+ 2342301.89843)));
+ assertTrue("Should be NaN", Double.isNaN(Math.hypot(-345.2680,
+ Double.NaN)));
+
+ assertEquals("Should return 2396424.905416697", 2396424.905416697, Math
+ .hypot(12322.12, -2396393.2258), 0D);
+ assertEquals("Should return 138.16958070558556", 138.16958070558556,
+ Math.hypot(-138.16951162, 0.13817035864), 0D);
+ assertEquals("Should return 1.7976931348623157E308",
+ 1.7976931348623157E308, Math.hypot(Double.MAX_VALUE, 211370.35), 0D);
+ assertEquals("Should return 5413.7185", 5413.7185, Math.hypot(
+ -5413.7185, Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#IEEEremainder(double, double)
+ */
+ public void test_IEEEremainderDD() {
+ // Test for method double java.lang.Math.IEEEremainder(double, double)
+ assertEquals("Incorrect remainder returned",
+ 0.0, Math.IEEEremainder(1.0, 1.0), 0D);
+ assertTrue("Incorrect remainder returned", Math.IEEEremainder(1.32,
+ 89.765) >= 1.4705063220631647E-2
+ || Math.IEEEremainder(1.32, 89.765) >= 1.4705063220631649E-2);
+ }
+
+ /**
+ * java.lang.Math#log(double)
+ */
+ public void test_logD() {
+ // Test for method double java.lang.Math.log(double)
+ for (double d = 10; d >= -10; d -= 0.5) {
+ double answer = Math.log(Math.exp(d));
+ assertTrue("Answer does not equal expected answer for d = " + d
+ + " answer = " + answer, Math.abs(answer - d) <= Math
+ .abs(d * 0.00000001));
+ }
+ }
+
+ /**
+ * java.lang.Math#log10(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_log10_D() {
+ // Test for special cases
+ assertTrue(Double.isNaN(Math.log10(Double.NaN)));
+ assertTrue(Double.isNaN(Math.log10(-2541.05745687234187532)));
+ assertTrue(Double.isNaN(Math.log10(-0.1)));
+ assertEquals(Double.POSITIVE_INFINITY, Math.log10(Double.POSITIVE_INFINITY));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.log10(0.0));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.log10(+0.0));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.log10(-0.0));
+
+ assertEquals(3.0, Math.log10(1000.0));
+ assertEquals(14.0, Math.log10(Math.pow(10, 14)));
+ assertEquals(3.7389561269540406, Math.log10(5482.2158));
+ assertEquals(14.661551142893833, Math.log10(458723662312872.125782332587));
+ assertEquals(-0.9083828622192334, Math.log10(0.12348583358871));
+ assertEquals(308.25471555991675, Math.log10(Double.MAX_VALUE));
+ assertEquals(-323.3062153431158, Math.log10(Double.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.Math#log1p(double)
+ */
+ public void test_log1p_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(Math.log1p(Double.NaN)));
+ assertTrue("Should return NaN", Double.isNaN(Math.log1p(-32.0482175)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, Math.log1p(Double.POSITIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
+ .log1p(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(Math.log1p(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(Math.log1p(-0.0)));
+
+ assertEquals("Should return -0.2941782295312541", -0.2941782295312541,
+ Math.log1p(-0.254856327), 0D);
+ assertEquals("Should return 7.368050685564151", 7.368050685564151, Math
+ .log1p(1583.542), 0D);
+ assertEquals("Should return 0.4633708685409921", 0.4633708685409921,
+ Math.log1p(0.5894227), 0D);
+ assertEquals("Should return 709.782712893384", 709.782712893384, Math
+ .log1p(Double.MAX_VALUE), 0D);
+ assertEquals("Should return Double.MIN_VALUE", Double.MIN_VALUE, Math
+ .log1p(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#max(double, double)
+ */
+ public void test_maxDD() {
+ // Test for method double java.lang.Math.max(double, double)
+ assertEquals("Incorrect double max value", 1908897.6000089, Math.max(-1908897.6000089,
+ 1908897.6000089), 0D);
+ assertEquals("Incorrect double max value",
+ 1908897.6000089, Math.max(2.0, 1908897.6000089), 0D);
+ assertEquals("Incorrect double max value", -2.0, Math.max(-2.0,
+ -1908897.6000089), 0D);
+
+ // Compare toString representations here since -0.0 = +0.0, and
+ // NaN != NaN and we need to distinguish
+ assertEquals("Max failed for NaN",
+ Double.toString(Double.NaN), Double.toString(Math.max(Double.NaN, 42.0d)));
+ assertEquals("Max failed for NaN",
+ Double.toString(Double.NaN), Double.toString(Math.max(42.0d, Double.NaN)));
+ assertEquals("Max failed for 0.0",
+ Double.toString(+0.0d), Double.toString(Math.max(+0.0d, -0.0d)));
+ assertEquals("Max failed for 0.0",
+ Double.toString(+0.0d), Double.toString(Math.max(-0.0d, +0.0d)));
+ assertEquals("Max failed for -0.0d",
+ Double.toString(-0.0d), Double.toString(Math.max(-0.0d, -0.0d)));
+ assertEquals("Max failed for 0.0",
+ Double.toString(+0.0d), Double.toString(Math.max(+0.0d, +0.0d)));
+ }
+
+ /**
+ * java.lang.Math#max(float, float)
+ */
+ public void test_maxFF() {
+ // Test for method float java.lang.Math.max(float, float)
+ assertTrue("Incorrect float max value", Math.max(-1908897.600f,
+ 1908897.600f) == 1908897.600f);
+ assertTrue("Incorrect float max value",
+ Math.max(2.0f, 1908897.600f) == 1908897.600f);
+ assertTrue("Incorrect float max value",
+ Math.max(-2.0f, -1908897.600f) == -2.0f);
+
+ // Compare toString representations here since -0.0 = +0.0, and
+ // NaN != NaN and we need to distinguish
+ assertEquals("Max failed for NaN",
+ Float.toString(Float.NaN), Float.toString(Math.max(Float.NaN, 42.0f)));
+ assertEquals("Max failed for NaN",
+ Float.toString(Float.NaN), Float.toString(Math.max(42.0f, Float.NaN)));
+ assertEquals("Max failed for 0.0",
+ Float.toString(+0.0f), Float.toString(Math.max(+0.0f, -0.0f)));
+ assertEquals("Max failed for 0.0",
+ Float.toString(+0.0f), Float.toString(Math.max(-0.0f, +0.0f)));
+ assertEquals("Max failed for -0.0f",
+ Float.toString(-0.0f), Float.toString(Math.max(-0.0f, -0.0f)));
+ assertEquals("Max failed for 0.0",
+ Float.toString(+0.0f), Float.toString(Math.max(+0.0f, +0.0f)));
+ }
+
+ /**
+ * java.lang.Math#max(int, int)
+ */
+ public void test_maxII() {
+ // Test for method int java.lang.Math.max(int, int)
+ assertEquals("Incorrect int max value",
+ 19088976, Math.max(-19088976, 19088976));
+ assertEquals("Incorrect int max value",
+ 19088976, Math.max(20, 19088976));
+ assertEquals("Incorrect int max value", -20, Math.max(-20, -19088976));
+ }
+
+ /**
+ * java.lang.Math#max(long, long)
+ */
+ public void test_maxJJ() {
+ // Test for method long java.lang.Math.max(long, long)
+ assertEquals("Incorrect long max value", 19088976000089L, Math.max(-19088976000089L,
+ 19088976000089L));
+ assertEquals("Incorrect long max value",
+ 19088976000089L, Math.max(20, 19088976000089L));
+ assertEquals("Incorrect long max value",
+ -20, Math.max(-20, -19088976000089L));
+ }
+
+ /**
+ * java.lang.Math#min(double, double)
+ */
+ public void test_minDD() {
+ // Test for method double java.lang.Math.min(double, double)
+ assertEquals("Incorrect double min value", -1908897.6000089, Math.min(-1908897.6000089,
+ 1908897.6000089), 0D);
+ assertEquals("Incorrect double min value",
+ 2.0, Math.min(2.0, 1908897.6000089), 0D);
+ assertEquals("Incorrect double min value", -1908897.6000089, Math.min(-2.0,
+ -1908897.6000089), 0D);
+ assertEquals("Incorrect double min value", 1.0d, Math.min(1.0d, 1.0d));
+
+ // Compare toString representations here since -0.0 = +0.0, and
+ // NaN != NaN and we need to distinguish
+ assertEquals("Min failed for NaN",
+ Double.toString(Double.NaN), Double.toString(Math.min(Double.NaN, 42.0d)));
+ assertEquals("Min failed for NaN",
+ Double.toString(Double.NaN), Double.toString(Math.min(42.0d, Double.NaN)));
+ assertEquals("Min failed for -0.0",
+ Double.toString(-0.0d), Double.toString(Math.min(+0.0d, -0.0d)));
+ assertEquals("Min failed for -0.0",
+ Double.toString(-0.0d), Double.toString(Math.min(-0.0d, +0.0d)));
+ assertEquals("Min failed for -0.0d",
+ Double.toString(-0.0d), Double.toString(Math.min(-0.0d, -0.0d)));
+ assertEquals("Min failed for 0.0",
+ Double.toString(+0.0d), Double.toString(Math.min(+0.0d, +0.0d)));
+ }
+
+ /**
+ * java.lang.Math#min(float, float)
+ */
+ public void test_minFF() {
+ // Test for method float java.lang.Math.min(float, float)
+ assertTrue("Incorrect float min value", Math.min(-1908897.600f,
+ 1908897.600f) == -1908897.600f);
+ assertTrue("Incorrect float min value",
+ Math.min(2.0f, 1908897.600f) == 2.0f);
+ assertTrue("Incorrect float min value",
+ Math.min(-2.0f, -1908897.600f) == -1908897.600f);
+ assertEquals("Incorrect float min value", 1.0f, Math.min(1.0f, 1.0f));
+
+ // Compare toString representations here since -0.0 = +0.0, and
+ // NaN != NaN and we need to distinguish
+ assertEquals("Min failed for NaN",
+ Float.toString(Float.NaN), Float.toString(Math.min(Float.NaN, 42.0f)));
+ assertEquals("Min failed for NaN",
+ Float.toString(Float.NaN), Float.toString(Math.min(42.0f, Float.NaN)));
+ assertEquals("Min failed for -0.0",
+ Float.toString(-0.0f), Float.toString(Math.min(+0.0f, -0.0f)));
+ assertEquals("Min failed for -0.0",
+ Float.toString(-0.0f), Float.toString(Math.min(-0.0f, +0.0f)));
+ assertEquals("Min failed for -0.0f",
+ Float.toString(-0.0f), Float.toString(Math.min(-0.0f, -0.0f)));
+ assertEquals("Min failed for 0.0",
+ Float.toString(+0.0f), Float.toString(Math.min(+0.0f, +0.0f)));
+ }
+
+ /**
+ * java.lang.Math#min(int, int)
+ */
+ public void test_minII() {
+ // Test for method int java.lang.Math.min(int, int)
+ assertEquals("Incorrect int min value",
+ -19088976, Math.min(-19088976, 19088976));
+ assertEquals("Incorrect int min value", 20, Math.min(20, 19088976));
+ assertEquals("Incorrect int min value",
+ -19088976, Math.min(-20, -19088976));
+
+ }
+
+ /**
+ * java.lang.Math#min(long, long)
+ */
+ public void test_minJJ() {
+ // Test for method long java.lang.Math.min(long, long)
+ assertEquals("Incorrect long min value", -19088976000089L, Math.min(-19088976000089L,
+ 19088976000089L));
+ assertEquals("Incorrect long min value",
+ 20, Math.min(20, 19088976000089L));
+ assertEquals("Incorrect long min value",
+ -19088976000089L, Math.min(-20, -19088976000089L));
+ }
+
+ /**
+ * start number cases for test_nextAfter_DD in MathTest/StrictMathTest
+ * NEXTAFTER_DD_START_CASES[i][0] is the start number
+ * NEXTAFTER_DD_START_CASES[i][1] is the nextUp of start number
+ * NEXTAFTER_DD_START_CASES[i][2] is the nextDown of start number
+ */
+ static final double NEXTAFTER_DD_START_CASES[][] = new double[][] {
+ { 3.4, 3.4000000000000004, 3.3999999999999995 },
+ { -3.4, -3.3999999999999995, -3.4000000000000004 },
+ { 3.4233E109, 3.4233000000000005E109, 3.4232999999999996E109 },
+ { -3.4233E109, -3.4232999999999996E109, -3.4233000000000005E109 },
+ { +0.0, Double.MIN_VALUE, -Double.MIN_VALUE },
+ { 0.0, Double.MIN_VALUE, -Double.MIN_VALUE },
+ { -0.0, Double.MIN_VALUE, -Double.MIN_VALUE },
+ { Double.MIN_VALUE, 1.0E-323, +0.0 },
+ { -Double.MIN_VALUE, -0.0, -1.0E-323 },
+ { Double.MIN_NORMAL, 2.225073858507202E-308, 2.225073858507201E-308 },
+ { -Double.MIN_NORMAL, -2.225073858507201E-308,
+ -2.225073858507202E-308 },
+ { Double.MAX_VALUE, Double.POSITIVE_INFINITY,
+ 1.7976931348623155E308 },
+ { -Double.MAX_VALUE, -1.7976931348623155E308,
+ Double.NEGATIVE_INFINITY },
+ { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,
+ Double.MAX_VALUE },
+ { Double.NEGATIVE_INFINITY, -Double.MAX_VALUE,
+ Double.NEGATIVE_INFINITY } };
+
+ /**
+ * direction number cases for test_nextAfter_DD/test_nextAfter_FD in
+ * MathTest/StrictMathTest
+ */
+ static final double NEXTAFTER_DD_FD_DIRECTION_CASES[] = new double[] {
+ Double.POSITIVE_INFINITY, Double.MAX_VALUE, 8.8, 3.4, 1.4,
+ Double.MIN_NORMAL, Double.MIN_NORMAL / 2, Double.MIN_VALUE, +0.0,
+ 0.0, -0.0, -Double.MIN_VALUE, -Double.MIN_NORMAL / 2,
+ -Double.MIN_NORMAL, -1.4, -3.4, -8.8, -Double.MAX_VALUE,
+ Double.NEGATIVE_INFINITY };
+
+ /**
+ * {@link java.lang.Math#nextAfter(double, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextAfter_DD() {
+ // test for most cases without exception
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ final double start = NEXTAFTER_DD_START_CASES[i][0];
+ final long nextUpBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][1]);
+ final long nextDownBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][2]);
+
+ for (int j = 0; j < NEXTAFTER_DD_FD_DIRECTION_CASES.length; j++) {
+ final double direction = NEXTAFTER_DD_FD_DIRECTION_CASES[j];
+ final long resultBits = Double.doubleToLongBits(Math.nextAfter(
+ start, direction));
+ final long directionBits = Double.doubleToLongBits(direction);
+ if (direction > start) {
+ assertEquals("Result should be next up-number.",
+ nextUpBits, resultBits);
+ } else if (direction < start) {
+ assertEquals("Result should be next down-number.",
+ nextDownBits, resultBits);
+ } else {
+ assertEquals("Result should be direction.", directionBits,
+ resultBits);
+ }
+ }
+ }
+
+ // test for cases with NaN
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Double.isNaN(Math
+ .nextAfter(NEXTAFTER_DD_START_CASES[i][0], Double.NaN)));
+ }
+ for (int i = 0; i < NEXTAFTER_DD_FD_DIRECTION_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Double.isNaN(Math
+ .nextAfter(Double.NaN, NEXTAFTER_DD_FD_DIRECTION_CASES[i])));
+ }
+ assertTrue("The result should be NaN.", Double.isNaN(Math.nextAfter(
+ Double.NaN, Double.NaN)));
+
+ // test for exception
+ try {
+ Math.nextAfter((Double) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.nextAfter(2.3, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.nextAfter((Double) null, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * start number cases for test_nextAfter_FD in MathTest/StrictMathTest
+ * NEXTAFTER_FD_START_CASES[i][0] is the start number
+ * NEXTAFTER_FD_START_CASES[i][1] is the nextUp of start number
+ * NEXTAFTER_FD_START_CASES[i][2] is the nextDown of start number
+ */
+ static final float NEXTAFTER_FD_START_CASES[][] = new float[][] {
+ { 3.4f, 3.4000003f, 3.3999999f },
+ { -3.4f, -3.3999999f, -3.4000003f },
+ { 3.4233E19f, 3.4233002E19f, 3.4232998E19f },
+ { -3.4233E19f, -3.4232998E19f, -3.4233002E19f },
+ { +0.0f, Float.MIN_VALUE, -Float.MIN_VALUE },
+ { 0.0f, Float.MIN_VALUE, -Float.MIN_VALUE },
+ { -0.0f, Float.MIN_VALUE, -Float.MIN_VALUE },
+ { Float.MIN_VALUE, 2.8E-45f, +0.0f },
+ { -Float.MIN_VALUE, -0.0f, -2.8E-45f },
+ { Float.MIN_NORMAL, 1.1754945E-38f, 1.1754942E-38f },
+ { -Float.MIN_NORMAL, -1.1754942E-38f, -1.1754945E-38f },
+ { Float.MAX_VALUE, Float.POSITIVE_INFINITY, 3.4028233E38f },
+ { -Float.MAX_VALUE, -3.4028233E38f, Float.NEGATIVE_INFINITY },
+ { Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.MAX_VALUE },
+ { Float.NEGATIVE_INFINITY, -Float.MAX_VALUE,
+ Float.NEGATIVE_INFINITY } };
+
+ /**
+ * {@link java.lang.Math#nextAfter(float, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextAfter_FD() {
+ // test for most cases without exception
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ final float start = NEXTAFTER_FD_START_CASES[i][0];
+ final int nextUpBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][1]);
+ final int nextDownBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][2]);
+
+ for (int j = 0; j < NEXTAFTER_DD_FD_DIRECTION_CASES.length; j++) {
+ final double direction = NEXTAFTER_DD_FD_DIRECTION_CASES[j];
+ final int resultBits = Float.floatToIntBits(Math.nextAfter(
+ start, direction));
+ if (direction > start) {
+ assertEquals("Result should be next up-number.",
+ nextUpBits, resultBits);
+ } else if (direction < start) {
+ assertEquals("Result should be next down-number.",
+ nextDownBits, resultBits);
+ } else {
+ final int equivalentBits = Float.floatToIntBits(new Float(
+ direction));
+ assertEquals(
+ "Result should be a number equivalent to direction.",
+ equivalentBits, resultBits);
+ }
+ }
+ }
+
+ // test for cases with NaN
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Float.isNaN(Math.nextAfter(
+ NEXTAFTER_FD_START_CASES[i][0], Float.NaN)));
+ }
+ for (int i = 0; i < NEXTAFTER_DD_FD_DIRECTION_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Float.isNaN(Math.nextAfter(
+ Float.NaN, NEXTAFTER_DD_FD_DIRECTION_CASES[i])));
+ }
+ assertTrue("The result should be NaN.", Float.isNaN(Math.nextAfter(
+ Float.NaN, Float.NaN)));
+
+ // test for exception
+ try {
+ Math.nextAfter((Float) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.nextAfter(2.3, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.nextAfter((Float) null, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.Math#nextUp(double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextUp_D() {
+ // This method is semantically equivalent to nextAfter(d,
+ // Double.POSITIVE_INFINITY),
+ // so we use the data of test_nextAfter_DD
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ final double start = NEXTAFTER_DD_START_CASES[i][0];
+ final long nextUpBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][1]);
+ final long resultBits = Double.doubleToLongBits(Math.nextUp(start));
+ assertEquals("Result should be next up-number.", nextUpBits,
+ resultBits);
+ }
+
+ // test for cases with NaN
+ assertTrue("The result should be NaN.", Double.isNaN(Math
+ .nextUp(Double.NaN)));
+
+ // test for exception
+ try {
+ Math.nextUp((Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.Math#nextUp(float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextUp_F() {
+ // This method is semantically equivalent to nextAfter(f,
+ // Float.POSITIVE_INFINITY),
+ // so we use the data of test_nextAfter_FD
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ final float start = NEXTAFTER_FD_START_CASES[i][0];
+ final int nextUpBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][1]);
+ final int resultBits = Float.floatToIntBits(Math.nextUp(start));
+ assertEquals("Result should be next up-number.", nextUpBits,
+ resultBits);
+ }
+
+ // test for cases with NaN
+ assertTrue("The result should be NaN.", Float.isNaN(Math
+ .nextUp(Float.NaN)));
+
+ // test for exception
+ try {
+ Math.nextUp((Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.Math#pow(double, double)
+ */
+ public void test_powDD() {
+ // Test for method double java.lang.Math.pow(double, double)
+ double NZERO = longTodouble(doubleTolong(0.0) ^ 0x8000000000000000L);
+ double p1 = 1.0;
+ double p2 = 2.0;
+ double p3 = 3.0;
+ double p4 = 4.0;
+ double p5 = 5.0;
+ double p6 = 6.0;
+ double p7 = 7.0;
+ double p8 = 8.0;
+ double p9 = 9.0;
+ double p10 = 10.0;
+ double p11 = 11.0;
+ double p12 = 12.0;
+ double p13 = 13.0;
+ double p14 = 14.0;
+ double p15 = 15.0;
+ double p16 = 16.0;
+ double[] values = { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12,
+ p13, p14, p15, p16 };
+
+ for (int x = 0; x < values.length; x++) {
+ double dval = values[x];
+ double nagateDval = negateDouble(dval);
+ if (nagateDval == Double.NaN) {
+ continue;
+ }
+
+ // If the second argument is positive or negative zero, then the
+ // result is 1.0.
+ assertEquals("Result should be Math.pow(" + dval
+ + ",-0.0)=+1.0", 1.0, Math.pow(dval, NZERO));
+ assertEquals("Result should be Math.pow(" + nagateDval
+ + ",-0.0)=+1.0", 1.0, Math.pow(nagateDval, NZERO));
+ assertEquals("Result should be Math.pow(" + dval
+ + ",+0.0)=+1.0", 1.0, Math.pow(dval, +0.0));
+ assertEquals("Result should be Math.pow(" + nagateDval
+ + ",+0.0)=+1.0", 1.0, Math.pow(nagateDval, +0.0));
+
+ // If the second argument is 1.0, then the result is the same as the
+ // first argument.
+ assertEquals("Result should be Math.pow(" + dval + "," + 1.0 + ")="
+ + dval, dval, Math.pow(dval, 1.0));
+ assertEquals("Result should be Math.pow(" + nagateDval + "," + 1.0
+ + ")=" + nagateDval, nagateDval, Math.pow(nagateDval, 1.0));
+
+ // If the second argument is NaN, then the result is NaN.
+ assertEquals("Result should be Math.pow(" + dval + "," + Double.NaN
+ + ")=" + Double.NaN, Double.NaN, Math.pow(dval, Double.NaN));
+ assertEquals("Result should be Math.pow(" + nagateDval + ","
+ + Double.NaN + ")=" + Double.NaN, Double.NaN, Math.pow(nagateDval,
+ Double.NaN));
+
+ if (dval > 1) {
+ // If the first argument is NaN and the second argument is
+ // nonzero,
+ // then the result is NaN.
+ assertEquals("Result should be Math.pow(" + Double.NaN + ","
+ + dval + ")=" + Double.NaN, Double.NaN, Math.pow(Double.NaN, dval));
+ assertEquals("Result should be Math.pow(" + Double.NaN + ","
+ + nagateDval + ")=" + Double.NaN, Double.NaN, Math.pow(Double.NaN,
+ nagateDval));
+
+ /*
+ * If the first argument is positive zero and the second
+ * argument is greater than zero, or the first argument is
+ * positive infinity and the second argument is less than zero,
+ * then the result is positive zero.
+ */
+ assertEquals("Result should be Math.pow(" + 0.0 + "," + dval
+ + ")=" + 0.0, +0.0, Math.pow(0.0, dval));
+ assertEquals("Result should be Math.pow("
+ + Double.POSITIVE_INFINITY + "," + nagateDval + ")="
+ + 0.0, +0.0, Math.pow(Double.POSITIVE_INFINITY, nagateDval));
+
+ /*
+ * If the first argument is positive zero and the second
+ * argument is less than zero, or the first argument is positive
+ * infinity and the second argument is greater than zero, then
+ * the result is positive infinity.
+ */
+ assertEquals("Result should be Math.pow(" + 0.0 + ","
+ + nagateDval + ")=" + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,
+ Math.pow(0.0, nagateDval));
+ assertEquals("Result should be Math.pow("
+ + Double.POSITIVE_INFINITY + "," + dval + ")="
+ + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Math.pow(
+ Double.POSITIVE_INFINITY, dval));
+
+ // Not a finite odd integer
+ if (dval % 2 == 0) {
+ /*
+ * If the first argument is negative zero and the second
+ * argument is greater than zero but not a finite odd
+ * integer, or the first argument is negative infinity and
+ * the second argument is less than zero but not a finite
+ * odd integer, then the result is positive zero.
+ */
+ assertEquals("Result should be Math.pow(" + NZERO + ","
+ + dval + ")=" + 0.0, +0.0, Math.pow(NZERO, dval));
+ assertEquals("Result should be Math.pow("
+ + Double.NEGATIVE_INFINITY + "," + nagateDval
+ + ")=" + 0.0, +0.0, Math.pow(Double.NEGATIVE_INFINITY,
+ nagateDval));
+
+ /*
+ * If the first argument is negative zero and the second
+ * argument is less than zero but not a finite odd integer,
+ * or the first argument is negative infinity and the second
+ * argument is greater than zero but not a finite odd
+ * integer, then the result is positive infinity.
+ */
+ assertEquals("Result should be Math.pow(" + NZERO + ","
+ + nagateDval + ")=" + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,
+ Math.pow(NZERO, nagateDval));
+ assertEquals("Result should be Math.pow("
+ + Double.NEGATIVE_INFINITY + "," + dval + ")="
+ + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Math.pow(
+ Double.NEGATIVE_INFINITY, dval));
+ }
+
+ // finite odd integer
+ if (dval % 2 != 0) {
+ /*
+ * If the first argument is negative zero and the second
+ * argument is a positive finite odd integer, or the first
+ * argument is negative infinity and the second argument is
+ * a negative finite odd integer, then the result is
+ * negative zero.
+ */
+ assertEquals("Result should be Math.pow(" + NZERO + ","
+ + dval + ")=" + NZERO, NZERO, Math.pow(NZERO, dval));
+ assertEquals("Result should be Math.pow("
+ + Double.NEGATIVE_INFINITY + "," + nagateDval
+ + ")=" + NZERO, NZERO, Math.pow(Double.NEGATIVE_INFINITY,
+ nagateDval));
+ /*
+ * If the first argument is negative zero and the second
+ * argument is a negative finite odd integer, or the first
+ * argument is negative infinity and the second argument is
+ * a positive finite odd integer then the result is negative
+ * infinity.
+ */
+ assertEquals("Result should be Math.pow(" + NZERO + ","
+ + nagateDval + ")=" + Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY,
+ Math.pow(NZERO, nagateDval));
+ assertEquals("Result should be Math.pow("
+ + Double.NEGATIVE_INFINITY + "," + dval + ")="
+ + Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Math.pow(
+ Double.NEGATIVE_INFINITY, dval));
+ }
+
+ /**
+ * 1. If the first argument is finite and less than zero if the
+ * second argument is a finite even integer, the result is equal
+ * to the result of raising the absolute value of the first
+ * argument to the power of the second argument
+ *
+ * 2. if the second argument is a finite odd integer, the result is equal to the
+ * negative of the result of raising the absolute value of the
+ * first argument to the power of the second argument
+ *
+ * 3. if the second argument is finite and not an integer, then the result
+ * is NaN.
+ */
+ for (int j = 1; j < values.length; j++) {
+ double jval = values[j];
+ if (jval % 2.0 == 0.0) {
+ assertEquals("" + nagateDval + " " + jval, Math.pow(
+ dval, jval), Math.pow(nagateDval, jval));
+ } else {
+ assertEquals("" + nagateDval + " " + jval, -1.0
+ * Math.pow(dval, jval), Math.pow(nagateDval,
+ jval));
+ }
+ assertEquals(Double.NaN, Math
+ .pow(nagateDval, jval / 0.5467));
+ assertEquals(Double.NaN, Math.pow(nagateDval, -1.0 * jval
+ / 0.5467));
+ }
+ }
+
+ // If the absolute value of the first argument equals 1 and the
+ // second argument is infinite, then the result is NaN.
+ if (dval == 1) {
+ assertEquals("Result should be Math.pow(" + dval + ","
+ + Double.POSITIVE_INFINITY + ")=" + Double.NaN, Double.NaN, Math
+ .pow(dval, Double.POSITIVE_INFINITY));
+ assertEquals("Result should be Math.pow(" + dval + ","
+ + Double.NEGATIVE_INFINITY + ")=" + Double.NaN, Double.NaN, Math
+ .pow(dval, Double.NEGATIVE_INFINITY));
+
+ assertEquals("Result should be Math.pow(" + nagateDval + ","
+ + Double.POSITIVE_INFINITY + ")=" + Double.NaN, Double.NaN, Math
+ .pow(nagateDval, Double.POSITIVE_INFINITY));
+ assertEquals("Result should be Math.pow(" + nagateDval + ","
+ + Double.NEGATIVE_INFINITY + ")=" + Double.NaN, Double.NaN, Math
+ .pow(nagateDval, Double.NEGATIVE_INFINITY));
+ }
+
+ if (dval > 1) {
+ /*
+ * If the absolute value of the first argument is greater than 1
+ * and the second argument is positive infinity, or the absolute
+ * value of the first argument is less than 1 and the second
+ * argument is negative infinity, then the result is positive
+ * infinity.
+ */
+ assertEquals("Result should be Math.pow(" + dval + ","
+ + Double.POSITIVE_INFINITY + ")="
+ + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Math.pow(dval,
+ Double.POSITIVE_INFINITY));
+
+ assertEquals("Result should be Math.pow(" + nagateDval + ","
+ + Double.NEGATIVE_INFINITY + ")="
+ + Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Math.pow(-0.13456,
+ Double.NEGATIVE_INFINITY));
+
+ /*
+ * If the absolute value of the first argument is greater than 1
+ * and the second argument is negative infinity, or the absolute
+ * value of the first argument is less than 1 and the second
+ * argument is positive infinity, then the result is positive
+ * zero.
+ */
+ assertEquals("Result should be Math.pow(" + dval + ","
+ + Double.NEGATIVE_INFINITY + ")= +0.0", +0.0, Math.pow(dval,
+ Double.NEGATIVE_INFINITY));
+ assertEquals("Result should be Math.pow(" + nagateDval + ","
+ + Double.POSITIVE_INFINITY + ")= +0.0", +0.0, Math.pow(
+ -0.13456, Double.POSITIVE_INFINITY));
+ }
+
+ assertEquals("Result should be Math.pow(" + 0.0 + "," + dval + ")="
+ + 0.0, 0.0, Math.pow(0.0, dval));
+ assertEquals("Result should be Math.pow(" + Double.NaN + "," + dval
+ + ")=" + Double.NaN, Double.NaN, Math.pow(Double.NaN, dval));
+ }
+ assertTrue("pow returned incorrect value",
+ (long) Math.pow(2, 8) == 256l);
+ assertTrue("pow returned incorrect value",
+ Math.pow(2, -8) == 0.00390625d);
+ assertEquals("Incorrect root returned1",
+ 2, Math.sqrt(Math.pow(Math.sqrt(2), 4)), 0);
+
+ assertEquals(Double.NEGATIVE_INFINITY, Math.pow(-10.0, 3.093403029238847E15));
+ assertEquals(Double.POSITIVE_INFINITY, Math.pow(10.0, 3.093403029238847E15));
+ }
+
+ private double longTodouble(long longvalue) {
+ return Double.longBitsToDouble(longvalue);
+ }
+
+ private long doubleTolong(double doublevalue) {
+ return Double.doubleToLongBits(doublevalue);
+ }
+
+ private double negateDouble(double doublevalue) {
+ return doublevalue * -1.0;
+ }
+
+ /**
+ * java.lang.Math#rint(double)
+ */
+ public void test_rintD() {
+ // Test for method double java.lang.Math.rint(double)
+ assertEquals("Failed to round properly - up to odd",
+ 3.0, Math.rint(2.9), 0D);
+ assertTrue("Failed to round properly - NaN", Double.isNaN(Math
+ .rint(Double.NaN)));
+ assertEquals("Failed to round properly down to even",
+ 2.0, Math.rint(2.1), 0D);
+ assertTrue("Failed to round properly " + 2.5 + " to even", Math
+ .rint(2.5) == 2.0);
+ assertTrue("Failed to round properly " + (+0.0d),
+ Math.rint(+0.0d) == +0.0d);
+ assertTrue("Failed to round properly " + (-0.0d),
+ Math.rint(-0.0d) == -0.0d);
+ }
+
+ /**
+ * java.lang.Math#round(double)
+ */
+ public void test_roundD() {
+ // Test for method long java.lang.Math.round(double)
+ assertEquals("Incorrect rounding of a float", -91, Math.round(-90.89d));
+ }
+
+ /**
+ * java.lang.Math#round(float)
+ */
+ public void test_roundF() {
+ // Test for method int java.lang.Math.round(float)
+ assertEquals("Incorrect rounding of a float", -91, Math.round(-90.89f));
+ }
+
+ /**
+ * {@link java.lang.Math#scalb(double, int)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_scalb_DI() {
+ // result is normal
+ assertEquals(4.1422946304E7, Math.scalb(1.2345, 25));
+ assertEquals(3.679096698760986E-8, Math.scalb(1.2345, -25));
+ assertEquals(1.2345, Math.scalb(1.2345, 0));
+ assertEquals(7868514.304, Math.scalb(0.2345, 25));
+
+ double normal = Math.scalb(0.2345, -25);
+ assertEquals(6.98864459991455E-9, normal);
+ // precision kept
+ assertEquals(0.2345, Math.scalb(normal, 25));
+
+ assertEquals(0.2345, Math.scalb(0.2345, 0));
+ assertEquals(-4.1422946304E7, Math.scalb(-1.2345, 25));
+ assertEquals(-6.98864459991455E-9, Math.scalb(-0.2345, -25));
+ assertEquals(2.0, Math.scalb(Double.MIN_NORMAL / 2, 1024));
+ assertEquals(64.0, Math.scalb(Double.MIN_VALUE, 1080));
+ assertEquals(234, Math.getExponent(Math.scalb(1.0, 234)));
+ assertEquals(3.9999999999999996, Math.scalb(Double.MAX_VALUE,
+ Double.MIN_EXPONENT));
+
+ // result is near infinity
+ double halfMax = Math.scalb(1.0, Double.MAX_EXPONENT);
+ assertEquals(8.98846567431158E307, halfMax);
+ assertEquals(Double.MAX_VALUE, halfMax - Math.ulp(halfMax) + halfMax);
+ assertEquals(Double.POSITIVE_INFINITY, halfMax + halfMax);
+ assertEquals(1.7976931348623155E308, Math.scalb(1.0 - Math.ulp(1.0),
+ Double.MAX_EXPONENT + 1));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(1.0 - Math.ulp(1.0),
+ Double.MAX_EXPONENT + 2));
+
+ halfMax = Math.scalb(-1.0, Double.MAX_EXPONENT);
+ assertEquals(-8.98846567431158E307, halfMax);
+ assertEquals(-Double.MAX_VALUE, halfMax + Math.ulp(halfMax) + halfMax);
+ assertEquals(Double.NEGATIVE_INFINITY, halfMax + halfMax);
+
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(0.345, 1234));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(44.345E102, 934));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.scalb(-44.345E102, 934));
+
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(
+ Double.MIN_NORMAL / 2, 4000));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(Double.MIN_VALUE,
+ 8000));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(Double.MAX_VALUE, 1));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(
+ Double.POSITIVE_INFINITY, 0));
+ assertEquals(Double.POSITIVE_INFINITY, Math.scalb(
+ Double.POSITIVE_INFINITY, -1));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.scalb(
+ Double.NEGATIVE_INFINITY, -1));
+ assertEquals(Double.NEGATIVE_INFINITY, Math.scalb(
+ Double.NEGATIVE_INFINITY, Double.MIN_EXPONENT));
+
+ // result is subnormal/zero
+ long posZeroBits = Double.doubleToLongBits(+0.0);
+ long negZeroBits = Double.doubleToLongBits(-0.0);
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(+0.0,
+ Integer.MAX_VALUE)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math
+ .scalb(+0.0, -123)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(+0.0, 0)));
+ assertEquals(negZeroBits, Double
+ .doubleToLongBits(Math.scalb(-0.0, 123)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(-0.0,
+ Integer.MIN_VALUE)));
+
+ assertEquals(Double.MIN_VALUE, Math.scalb(1.0, -1074));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math
+ .scalb(1.0, -1075)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(-1.0,
+ -1075)));
+
+ // precision lost
+ assertEquals(Math.scalb(21.405, -1078), Math.scalb(21.405, -1079));
+ assertEquals(Double.MIN_VALUE, Math.scalb(21.405, -1079));
+ assertEquals(-Double.MIN_VALUE, Math.scalb(-21.405, -1079));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(21.405,
+ -1080)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(-21.405,
+ -1080)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(
+ Double.MIN_VALUE, -1)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(
+ -Double.MIN_VALUE, -1)));
+ assertEquals(Double.MIN_VALUE, Math.scalb(Double.MIN_NORMAL, -52));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(
+ Double.MIN_NORMAL, -53)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(
+ -Double.MIN_NORMAL, -53)));
+ assertEquals(Double.MIN_VALUE, Math.scalb(Double.MAX_VALUE, -2098));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(
+ Double.MAX_VALUE, -2099)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(
+ -Double.MAX_VALUE, -2099)));
+ assertEquals(Double.MIN_VALUE, Math.scalb(Double.MIN_NORMAL / 3, -51));
+ assertEquals(posZeroBits, Double.doubleToLongBits(Math.scalb(
+ Double.MIN_NORMAL / 3, -52)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(Math.scalb(
+ -Double.MIN_NORMAL / 3, -52)));
+ double subnormal = Math.scalb(Double.MIN_NORMAL / 3, -25);
+ assertEquals(2.2104123E-316, subnormal);
+ // precision lost
+ assertFalse(Double.MIN_NORMAL / 3 == Math.scalb(subnormal, 25));
+
+ // NaN
+ assertTrue(Double.isNaN(Math.scalb(Double.NaN, 1)));
+ assertTrue(Double.isNaN(Math.scalb(Double.NaN, 0)));
+ assertTrue(Double.isNaN(Math.scalb(Double.NaN, -120)));
+
+ assertEquals(1283457024, Double.doubleToLongBits(Math.scalb(
+ Double.MIN_VALUE * 153, 23)));
+ assertEquals(-9223372035571318784L, Double.doubleToLongBits(Math.scalb(
+ -Double.MIN_VALUE * 153, 23)));
+ assertEquals(36908406321184768L, Double.doubleToLongBits(Math.scalb(
+ Double.MIN_VALUE * 153, 52)));
+ assertEquals(-9186463630533591040L, Double.doubleToLongBits(Math.scalb(
+ -Double.MIN_VALUE * 153, 52)));
+
+ // test for exception
+ try {
+ Math.scalb((Double) null, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.scalb(1.0, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.scalb((Double) null, 1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ long b1em1022 = 0x0010000000000000L; // bit representation of
+ // Double.MIN_NORMAL
+ long b1em1023 = 0x0008000000000000L; // bit representation of half of
+ // Double.MIN_NORMAL
+ // assert exact identity
+ assertEquals(b1em1023, Double.doubleToLongBits(Math.scalb(Double
+ .longBitsToDouble(b1em1022), -1)));
+ }
+
+ /**
+ * {@link java.lang.Math#scalb(float, int)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_scalb_FI() {
+ // result is normal
+ assertEquals(4.1422946304E7f, Math.scalb(1.2345f, 25));
+ assertEquals(3.679096698760986E-8f, Math.scalb(1.2345f, -25));
+ assertEquals(1.2345f, Math.scalb(1.2345f, 0));
+ assertEquals(7868514.304f, Math.scalb(0.2345f, 25));
+
+ float normal = Math.scalb(0.2345f, -25);
+ assertEquals(6.98864459991455E-9f, normal);
+ // precision kept
+ assertEquals(0.2345f, Math.scalb(normal, 25));
+
+ assertEquals(0.2345f, Math.scalb(0.2345f, 0));
+ assertEquals(-4.1422946304E7f, Math.scalb(-1.2345f, 25));
+ assertEquals(-6.98864459991455E-9f, Math.scalb(-0.2345f, -25));
+ assertEquals(2.0f, Math.scalb(Float.MIN_NORMAL / 2, 128));
+ assertEquals(64.0f, Math.scalb(Float.MIN_VALUE, 155));
+ assertEquals(34, Math.getExponent(Math.scalb(1.0f, 34)));
+ assertEquals(3.9999998f, Math
+ .scalb(Float.MAX_VALUE, Float.MIN_EXPONENT));
+
+ // result is near infinity
+ float halfMax = Math.scalb(1.0f, Float.MAX_EXPONENT);
+ assertEquals(1.7014118E38f, halfMax);
+ assertEquals(Float.MAX_VALUE, halfMax - Math.ulp(halfMax) + halfMax);
+ assertEquals(Float.POSITIVE_INFINITY, halfMax + halfMax);
+ assertEquals(3.4028233E38f, Math.scalb(1.0f - Math.ulp(1.0f),
+ Float.MAX_EXPONENT + 1));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(1.0f - Math.ulp(1.0f),
+ Float.MAX_EXPONENT + 2));
+
+ halfMax = Math.scalb(-1.0f, Float.MAX_EXPONENT);
+ assertEquals(-1.7014118E38f, halfMax);
+ assertEquals(-Float.MAX_VALUE, halfMax + Math.ulp(halfMax) + halfMax);
+ assertEquals(Float.NEGATIVE_INFINITY, halfMax + halfMax);
+
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(0.345f, 1234));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(44.345E10f, 934));
+ assertEquals(Float.NEGATIVE_INFINITY, Math.scalb(-44.345E10f, 934));
+
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(Float.MIN_NORMAL / 2,
+ 400));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(Float.MIN_VALUE, 800));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(Float.MAX_VALUE, 1));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(
+ Float.POSITIVE_INFINITY, 0));
+ assertEquals(Float.POSITIVE_INFINITY, Math.scalb(
+ Float.POSITIVE_INFINITY, -1));
+ assertEquals(Float.NEGATIVE_INFINITY, Math.scalb(
+ Float.NEGATIVE_INFINITY, -1));
+ assertEquals(Float.NEGATIVE_INFINITY, Math.scalb(
+ Float.NEGATIVE_INFINITY, Float.MIN_EXPONENT));
+
+ // result is subnormal/zero
+ int posZeroBits = Float.floatToIntBits(+0.0f);
+ int negZeroBits = Float.floatToIntBits(-0.0f);
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(+0.0f,
+ Integer.MAX_VALUE)));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(+0.0f, -123)));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(+0.0f, 0)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(-0.0f, 123)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(-0.0f,
+ Integer.MIN_VALUE)));
+
+ assertEquals(Float.MIN_VALUE, Math.scalb(1.0f, -149));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(1.0f, -150)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(-1.0f, -150)));
+
+ // precision lost
+ assertEquals(Math.scalb(21.405f, -154), Math.scalb(21.405f, -153));
+ assertEquals(Float.MIN_VALUE, Math.scalb(21.405f, -154));
+ assertEquals(-Float.MIN_VALUE, Math.scalb(-21.405f, -154));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math
+ .scalb(21.405f, -155)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(-21.405f,
+ -155)));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(
+ Float.MIN_VALUE, -1)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(
+ -Float.MIN_VALUE, -1)));
+ assertEquals(Float.MIN_VALUE, Math.scalb(Float.MIN_NORMAL, -23));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(
+ Float.MIN_NORMAL, -24)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(
+ -Float.MIN_NORMAL, -24)));
+ assertEquals(Float.MIN_VALUE, Math.scalb(Float.MAX_VALUE, -277));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(
+ Float.MAX_VALUE, -278)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(
+ -Float.MAX_VALUE, -278)));
+ assertEquals(Float.MIN_VALUE, Math.scalb(Float.MIN_NORMAL / 3, -22));
+ assertEquals(posZeroBits, Float.floatToIntBits(Math.scalb(
+ Float.MIN_NORMAL / 3, -23)));
+ assertEquals(negZeroBits, Float.floatToIntBits(Math.scalb(
+ -Float.MIN_NORMAL / 3, -23)));
+ float subnormal = Math.scalb(Float.MIN_NORMAL / 3, -11);
+ assertEquals(1.913E-42f, subnormal);
+ // precision lost
+ assertFalse(Float.MIN_NORMAL / 3 == Math.scalb(subnormal, 11));
+
+ assertEquals(68747264, Float.floatToIntBits(Math.scalb(
+ Float.MIN_VALUE * 153, 23)));
+ assertEquals(-2078736384, Float.floatToIntBits(Math.scalb(
+ -Float.MIN_VALUE * 153, 23)));
+
+ assertEquals(4896, Float.floatToIntBits(Math.scalb(
+ Float.MIN_VALUE * 153, 5)));
+ assertEquals(-2147478752, Float.floatToIntBits(Math.scalb(
+ -Float.MIN_VALUE * 153, 5)));
+
+ // NaN
+ assertTrue(Float.isNaN(Math.scalb(Float.NaN, 1)));
+ assertTrue(Float.isNaN(Math.scalb(Float.NaN, 0)));
+ assertTrue(Float.isNaN(Math.scalb(Float.NaN, -120)));
+
+ // test for exception
+ try {
+ Math.scalb((Float) null, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.scalb(1.0f, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ Math.scalb((Float) null, 1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ int b1em126 = 0x00800000; // bit representation of Float.MIN_NORMAL
+ int b1em127 = 0x00400000; // bit representation of half
+ // Float.MIN_NORMAL
+ // assert exact identity
+ assertEquals(b1em127, Float.floatToIntBits(Math.scalb(Float
+ .intBitsToFloat(b1em126), -1)));
+ }
+
+ /**
+ * java.lang.Math#signum(double)
+ */
+ public void test_signum_D() {
+ assertTrue(Double.isNaN(Math.signum(Double.NaN)));
+ assertTrue(Double.isNaN(Math.signum(Double.NaN)));
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
+ .signum(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(Math.signum(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(Math.signum(-0.0)));
+
+ assertEquals(1.0, Math.signum(253681.2187962), 0D);
+ assertEquals(-1.0, Math.signum(-125874693.56), 0D);
+ assertEquals(1.0, Math.signum(1.2587E-308), 0D);
+ assertEquals(-1.0, Math.signum(-1.2587E-308), 0D);
+
+ assertEquals(1.0, Math.signum(Double.MAX_VALUE), 0D);
+ assertEquals(1.0, Math.signum(Double.MIN_VALUE), 0D);
+ assertEquals(-1.0, Math.signum(-Double.MAX_VALUE), 0D);
+ assertEquals(-1.0, Math.signum(-Double.MIN_VALUE), 0D);
+ assertEquals(1.0, Math.signum(Double.POSITIVE_INFINITY), 0D);
+ assertEquals(-1.0, Math.signum(Double.NEGATIVE_INFINITY), 0D);
+ }
+
+ /**
+ * java.lang.Math#signum(float)
+ */
+ public void test_signum_F() {
+ assertTrue(Float.isNaN(Math.signum(Float.NaN)));
+ assertEquals(Float.floatToIntBits(0.0f), Float
+ .floatToIntBits(Math.signum(0.0f)));
+ assertEquals(Float.floatToIntBits(+0.0f), Float
+ .floatToIntBits(Math.signum(+0.0f)));
+ assertEquals(Float.floatToIntBits(-0.0f), Float
+ .floatToIntBits(Math.signum(-0.0f)));
+
+ assertEquals(1.0f, Math.signum(253681.2187962f), 0f);
+ assertEquals(-1.0f, Math.signum(-125874693.56f), 0f);
+ assertEquals(1.0f, Math.signum(1.2587E-11f), 0f);
+ assertEquals(-1.0f, Math.signum(-1.2587E-11f), 0f);
+
+ assertEquals(1.0f, Math.signum(Float.MAX_VALUE), 0f);
+ assertEquals(1.0f, Math.signum(Float.MIN_VALUE), 0f);
+ assertEquals(-1.0f, Math.signum(-Float.MAX_VALUE), 0f);
+ assertEquals(-1.0f, Math.signum(-Float.MIN_VALUE), 0f);
+ assertEquals(1.0f, Math.signum(Float.POSITIVE_INFINITY), 0f);
+ assertEquals(-1.0f, Math.signum(Float.NEGATIVE_INFINITY), 0f);
+ }
+
+ /**
+ * java.lang.Math#sin(double)
+ */
+ public void test_sinD() {
+ // Test for method double java.lang.Math.sin(double)
+ assertEquals("Incorrect answer", 0.0, Math.sin(0), 0D);
+ assertEquals("Incorrect answer", 0.8414709848078965, Math.sin(1), 0D);
+ }
+
+ /**
+ * java.lang.Math#sinh(double)
+ */
+ public void test_sinh_D() {
+ // Test for special situations
+ assertTrue(Double.isNaN(Math.sinh(Double.NaN)));
+ assertEquals(Double.POSITIVE_INFINITY, Math.sinh(Double.POSITIVE_INFINITY), 0D);
+ assertEquals(Double.NEGATIVE_INFINITY, Math.sinh(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math.sinh(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double.doubleToLongBits(Math.sinh(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double.doubleToLongBits(Math.sinh(-0.0)));
+
+ assertEquals(Double.POSITIVE_INFINITY, Math.sinh(1234.56), 0D);
+ assertEquals(Double.NEGATIVE_INFINITY, Math.sinh(-1234.56), 0D);
+ assertEquals(1.0000000000001666E-6, Math.sinh(0.000001), 0D);
+ assertEquals(-1.0000000000001666E-6, Math.sinh(-0.000001), 0D);
+ assertEquals(5.115386441963859, Math.sinh(2.33482), Math.ulp(5.115386441963859));
+ assertEquals(Double.POSITIVE_INFINITY, Math.sinh(Double.MAX_VALUE), 0D);
+ assertEquals(4.9E-324, Math.sinh(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#sqrt(double)
+ */
+ public void test_sqrtD() {
+ // Test for method double java.lang.Math.sqrt(double)
+ assertEquals("Incorrect root returned2", 7, Math.sqrt(49), 0);
+ }
+
+ /**
+ * java.lang.Math#tan(double)
+ */
+ public void test_tanD() {
+ // Test for method double java.lang.Math.tan(double)
+ assertEquals("Incorrect answer", 0.0, Math.tan(0), 0D);
+ assertEquals("Incorrect answer", 1.5574077246549023, Math.tan(1), 0D);
+
+ }
+
+ /**
+ * java.lang.Math#tanh(double)
+ */
+ public void test_tanh_D() {
+ // Test for special situations
+ assertTrue("Should return NaN", Double.isNaN(Math.tanh(Double.NaN)));
+ assertEquals("Should return +1.0", +1.0, Math
+ .tanh(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return -1.0", -1.0, Math
+ .tanh(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
+ .tanh(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(Math.tanh(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(Math.tanh(-0.0)));
+
+ assertEquals("Should return 1.0", 1.0, Math.tanh(1234.56), 0D);
+ assertEquals("Should return -1.0", -1.0, Math.tanh(-1234.56), 0D);
+ assertEquals("Should return 9.999999999996666E-7",
+ 9.999999999996666E-7, Math.tanh(0.000001), 0D);
+ assertEquals("Should return 0.981422884124941", 0.981422884124941, Math
+ .tanh(2.33482), 0D);
+ assertEquals("Should return 1.0", 1.0, Math.tanh(Double.MAX_VALUE), 0D);
+ assertEquals("Should return 4.9E-324", 4.9E-324, Math
+ .tanh(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.Math#random()
+ */
+ public void test_random() {
+ // There isn't a place for these tests so just stick them here
+ assertEquals("Wrong value E",
+ 4613303445314885481L, Double.doubleToLongBits(Math.E));
+ assertEquals("Wrong value PI",
+ 4614256656552045848L, Double.doubleToLongBits(Math.PI));
+
+ for (int i = 500; i >= 0; i--) {
+ double d = Math.random();
+ assertTrue("Generated number is out of range: " + d, d >= 0.0
+ && d < 1.0);
+ }
+ }
+
+ /**
+ * java.lang.Math#toRadians(double)
+ */
+ public void test_toRadiansD() {
+ for (double d = 500; d >= 0; d -= 1.0) {
+ double converted = Math.toDegrees(Math.toRadians(d));
+ assertTrue("Converted number not equal to original. d = " + d,
+ converted >= d * 0.99999999 && converted <= d * 1.00000001);
+ }
+ }
+
+ /**
+ * java.lang.Math#toDegrees(double)
+ */
+ public void test_toDegreesD() {
+ for (double d = 500; d >= 0; d -= 1.0) {
+ double converted = Math.toRadians(Math.toDegrees(d));
+ assertTrue("Converted number not equal to original. d = " + d,
+ converted >= d * 0.99999999 && converted <= d * 1.00000001);
+ }
+ }
+
+ /**
+ * java.lang.Math#ulp(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_ulp_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(Math.ulp(Double.NaN)));
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, Math
+ .ulp(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, Math
+ .ulp(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
+ .ulp(0.0), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
+ .ulp(+0.0), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
+ .ulp(-0.0), 0D);
+ assertEquals("Returned incorrect value", Math.pow(2, 971), Math
+ .ulp(Double.MAX_VALUE), 0D);
+ assertEquals("Returned incorrect value", Math.pow(2, 971), Math
+ .ulp(-Double.MAX_VALUE), 0D);
+
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
+ .ulp(Double.MIN_VALUE), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
+ .ulp(-Double.MIN_VALUE), 0D);
+
+ assertEquals("Returned incorrect value", 2.220446049250313E-16, Math
+ .ulp(1.0), 0D);
+ assertEquals("Returned incorrect value", 2.220446049250313E-16, Math
+ .ulp(-1.0), 0D);
+ assertEquals("Returned incorrect value", 2.2737367544323206E-13, Math
+ .ulp(1153.0), 0D);
+ }
+
+ /**
+ * java.lang.Math#ulp(float)
+ */
+ @SuppressWarnings("boxing")
+ public void test_ulp_f() {
+ // Test for special cases
+ assertTrue("Should return NaN", Float.isNaN(Math.ulp(Float.NaN)));
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, Math
+ .ulp(Float.POSITIVE_INFINITY), 0f);
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, Math
+ .ulp(Float.NEGATIVE_INFINITY), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
+ .ulp(0.0f), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
+ .ulp(+0.0f), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
+ .ulp(-0.0f), 0f);
+ assertEquals("Returned incorrect value", 2.028241E31f, Math
+ .ulp(Float.MAX_VALUE), 0f);
+ assertEquals("Returned incorrect value", 2.028241E31f, Math
+ .ulp(-Float.MAX_VALUE), 0f);
+
+ assertEquals("Returned incorrect value", 1.4E-45f, Math
+ .ulp(Float.MIN_VALUE), 0f);
+ assertEquals("Returned incorrect value", 1.4E-45f, Math
+ .ulp(-Float.MIN_VALUE), 0f);
+
+ assertEquals("Returned incorrect value", 1.1920929E-7f, Math.ulp(1.0f),
+ 0f);
+ assertEquals("Returned incorrect value", 1.1920929E-7f,
+ Math.ulp(-1.0f), 0f);
+ assertEquals("Returned incorrect value", 1.2207031E-4f, Math
+ .ulp(1153.0f), 0f);
+ assertEquals("Returned incorrect value", 5.6E-45f, Math
+ .ulp(9.403954E-38f), 0f);
+ }
+
+ /**
+ * {@link java.lang.Math#shiftIntBits(int, int)}
+ * @since 1.6
+ */
+ public void test_shiftIntBits_II() {
+ class Tuple {
+ public int result;
+
+ public int value;
+
+ public int factor;
+
+ public Tuple(int result, int value, int factor) {
+ this.result = result;
+ this.value = value;
+ this.factor = factor;
+ }
+ }
+ final Tuple[] TUPLES = new Tuple[] {
+ // sub-normal to sub-normal
+ new Tuple(0x00000000, 0x00000001, -1),
+ // round to even
+ new Tuple(0x00000002, 0x00000003, -1),
+ // round to even
+ new Tuple(0x00000001, 0x00000005, -3),
+ // round to infinity
+ new Tuple(0x00000002, 0x0000000d, -3),
+ // round to infinity
+
+ // normal to sub-normal
+ new Tuple(0x00000002, 0x01a00000, -24),
+ // round to even
+ new Tuple(0x00000004, 0x01e00000, -24),
+ // round to even
+ new Tuple(0x00000003, 0x01c80000, -24),
+ // round to infinity
+ new Tuple(0x00000004, 0x01e80000, -24),
+ // round to infinity
+ };
+ for (int i = 0; i < TUPLES.length; ++i) {
+ Tuple tuple = TUPLES[i];
+ assertEquals(tuple.result, Float.floatToIntBits(Math.scalb(Float
+ .intBitsToFloat(tuple.value), tuple.factor)));
+ assertEquals(tuple.result, Float.floatToIntBits(-Math.scalb(-Float
+ .intBitsToFloat(tuple.value), tuple.factor)));
+ }
+ }
+
+ /**
+ * {@link java.lang.Math#shiftLongBits(long, long)}
+ * <p/>
+ * Round result to nearest value on precision lost.
+ * @since 1.6
+ */
+ public void test_shiftLongBits_LL() {
+ class Tuple {
+ public long result;
+
+ public long value;
+
+ public int factor;
+
+ public Tuple(long result, long value, int factor) {
+ this.result = result;
+ this.value = value;
+ this.factor = factor;
+ }
+ }
+ final Tuple[] TUPLES = new Tuple[] {
+ // sub-normal to sub-normal
+ new Tuple(0x00000000L, 0x00000001L, -1),
+ //round to even
+ new Tuple(0x00000002L, 0x00000003L, -1),
+ //round to even
+ new Tuple(0x00000001L, 0x00000005L, -3),
+ //round to infinity
+ new Tuple(0x00000002L, 0x0000000dL, -3),
+ //round to infinity
+
+ // normal to sub-normal
+ new Tuple(0x0000000000000002L, 0x0034000000000000L, -53), // round to even
+ new Tuple(0x0000000000000004L, 0x003c000000000000L, -53), // round to even
+ new Tuple(0x0000000000000003L, 0x0035000000000000L, -53), // round to infinity
+ new Tuple(0x0000000000000004L, 0x003d000000000000L, -53), // round to infinity
+ };
+ for (int i = 0; i < TUPLES.length; ++i) {
+ Tuple tuple = TUPLES[i];
+ assertEquals(tuple.result, Double.doubleToLongBits(Math.scalb(
+ Double.longBitsToDouble(tuple.value), tuple.factor)));
+ assertEquals(tuple.result, Double.doubleToLongBits(-Math.scalb(
+ -Double.longBitsToDouble(tuple.value), tuple.factor)));
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum.java
new file mode 100644
index 0000000..94260c4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum.java
@@ -0,0 +1,57 @@
+/* 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.tests.java.lang;
+
+import java.io.Serializable;
+
+class MockEnum implements Serializable {
+ private static final long serialVersionUID = -1678507713086705252L;
+
+ enum Sample {
+ LARRY, MOE, CURLY
+ }
+
+ enum Sample2 {
+ RED, BLUE, YELLO
+ }
+
+ String str;
+
+ int i;
+
+ Sample2 samEnum;
+
+ Sample larry = Sample.LARRY;
+
+ MockEnum() {
+ str = "test";
+ i = 99;
+ samEnum = Sample2.BLUE;
+ }
+
+ public boolean equals(Object arg0) {
+ if (!(arg0 instanceof MockEnum)) {
+ return false;
+ }
+ MockEnum test = (MockEnum) arg0;
+ if (str.equals(test.str) && i == test.i && samEnum == test.samEnum) {
+ return true;
+ }
+ return false;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum2.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum2.java
new file mode 100644
index 0000000..1dc5341
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/MockEnum2.java
@@ -0,0 +1,61 @@
+/* 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.tests.java.lang;
+
+import java.io.Serializable;
+
+class MockEnum2 implements Serializable {
+
+ private static final long serialVersionUID = -4812214670022262730L;
+
+ enum Sample {
+ LARRY, MOE, CURLY
+ }
+
+ enum Sample2 {
+ RED, BLUE, YELLO
+ }
+
+ String str;
+
+ int i;
+
+ Sample samEnum;
+
+ Sample larry = Sample.LARRY;
+
+ String myStr = "LARRY";
+
+ MockEnum2() {
+ str = "test";
+ i = 99;
+ samEnum = larry;
+ }
+
+ public boolean equals(Object arg0) {
+ if (!(arg0 instanceof MockEnum2)) {
+ return false;
+ }
+ MockEnum2 test = (MockEnum2) arg0;
+ if (str.equals(test.str) && i == test.i && samEnum == test.samEnum
+ && myStr.equals(test.myStr)) {
+ return true;
+ }
+ return false;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NegativeArraySizeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NegativeArraySizeExceptionTest.java
new file mode 100644
index 0000000..1717f3a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NegativeArraySizeExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NegativeArraySizeExceptionTest extends TestCase {
+
+ /**
+ * java.lang.NegativeArraySizeException#NegativeArraySizeException()
+ */
+ public void test_Constructor() {
+ NegativeArraySizeException e = new NegativeArraySizeException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NegativeArraySizeException#NegativeArraySizeException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NegativeArraySizeException e = new NegativeArraySizeException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoClassDefFoundErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoClassDefFoundErrorTest.java
new file mode 100644
index 0000000..9421a73
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoClassDefFoundErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NoClassDefFoundErrorTest extends TestCase {
+
+ /**
+ * java.lang.NoClassDefFoundError#NoClassDefFoundError()
+ */
+ public void test_Constructor() {
+ NoClassDefFoundError e = new NoClassDefFoundError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NoClassDefFoundError#NoClassDefFoundError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NoClassDefFoundError e = new NoClassDefFoundError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldErrorTest.java
new file mode 100644
index 0000000..e405599
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NoSuchFieldErrorTest extends TestCase {
+
+ /**
+ * java.lang.NoSuchFieldError#NoSuchFieldError()
+ */
+ public void test_Constructor() {
+ NoSuchFieldError e = new NoSuchFieldError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NoSuchFieldError#NoSuchFieldError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NoSuchFieldError e = new NoSuchFieldError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldExceptionTest.java
new file mode 100644
index 0000000..5562669
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchFieldExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NoSuchFieldExceptionTest extends TestCase {
+
+ /**
+ * java.lang.NoSuchFieldException#NoSuchFieldException()
+ */
+ public void test_Constructor() {
+ NoSuchFieldException e = new NoSuchFieldException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NoSuchFieldException#NoSuchFieldException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NoSuchFieldException e = new NoSuchFieldException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodErrorTest.java
new file mode 100644
index 0000000..1367e03
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NoSuchMethodErrorTest extends TestCase {
+
+ /**
+ * java.lang.NoSuchMethodError#NoSuchMethodError()
+ */
+ public void test_Constructor() {
+ NoSuchMethodError e = new NoSuchMethodError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NoSuchMethodError#NoSuchMethodError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NoSuchMethodError e = new NoSuchMethodError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodExceptionTest.java
new file mode 100644
index 0000000..7bd9e0a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NoSuchMethodExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NoSuchMethodExceptionTest extends TestCase {
+
+ /**
+ * java.lang.NoSuchMethodException#NoSuchMethodException()
+ */
+ public void test_Constructor() {
+ NoSuchMethodException e = new NoSuchMethodException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NoSuchMethodException#NoSuchMethodException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NoSuchMethodException e = new NoSuchMethodException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NullPointerExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NullPointerExceptionTest.java
new file mode 100644
index 0000000..9c4a72b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NullPointerExceptionTest.java
@@ -0,0 +1,41 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NullPointerExceptionTest extends TestCase {
+
+ /**
+ * java.lang.NullPointerException#NullPointerException()
+ */
+ public void test_Constructor() {
+ NullPointerException e = new NullPointerException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NullPointerException#NullPointerException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NullPointerException e = new NullPointerException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberFormatExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberFormatExceptionTest.java
new file mode 100644
index 0000000..614c51b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberFormatExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class NumberFormatExceptionTest extends TestCase {
+
+ /**
+ * java.lang.NumberFormatException#NumberFormatException()
+ */
+ public void test_Constructor() {
+ NumberFormatException e = new NumberFormatException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.NumberFormatException#NumberFormatException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ NumberFormatException e = new NumberFormatException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberTest.java
new file mode 100644
index 0000000..809a31a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/NumberTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.tests.java.lang;
+
+public class NumberTest extends junit.framework.TestCase {
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ObjectTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ObjectTest.java
new file mode 100644
index 0000000..9dca8e9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ObjectTest.java
@@ -0,0 +1,388 @@
+/*
+ * 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.tests.java.lang;
+
+public class ObjectTest extends junit.framework.TestCase {
+
+ /**
+ * Test objects.
+ */
+ Object obj1 = new Object();
+
+ Object obj2 = new Object();
+
+ /**
+ * Generic state indicator.
+ */
+ int status = 0;
+
+ int ready = 0;
+
+ /**
+ * java.lang.Object#Object()
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.Object()
+ assertNotNull("Constructor failed !!!", new Object());
+ }
+
+ /**
+ * java.lang.Object#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean java.lang.Object.equals(java.lang.Object)
+ assertTrue("Same object should be equal", obj1.equals(obj1));
+ assertTrue("Different objects should not be equal", !obj1.equals(obj2));
+ }
+
+ /**
+ * java.lang.Object#getClass()
+ */
+ public void test_getClass() throws Exception {
+ // Test for method java.lang.Class java.lang.Object.getClass()
+ String classNames[] = { "java.lang.Object", "java.lang.Throwable",
+ "java.lang.StringBuffer" };
+ Class<?> classToTest = null;
+ Object instanceToTest = null;
+
+ status = 0;
+ for (int i = 0; i < classNames.length; ++i) {
+ classToTest = Class.forName(classNames[i]);
+ instanceToTest = classToTest.newInstance();
+ assertTrue("Instance didn't match creator class.",
+ instanceToTest.getClass() == classToTest);
+ assertTrue("Instance didn't match class with matching name.",
+ instanceToTest.getClass() == Class
+ .forName(classNames[i]));
+ }
+ }
+
+ /**
+ * java.lang.Object#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.lang.Object.hashCode()
+ assertTrue("Same object should have same hash.",
+ obj1.hashCode() == obj1.hashCode());
+ assertTrue("Same object should have same hash.",
+ obj2.hashCode() == obj2.hashCode());
+ }
+
+ /**
+ * java.lang.Object#notify()
+ */
+ public void test_notify() {
+ // Test for method void java.lang.Object.notify()
+
+ // Inner class to run test thread.
+ class TestThread implements Runnable {
+ public void run() {
+ synchronized (obj1) {
+ try {
+ ready += 1;
+ obj1.wait();// Wait for ever.
+ status += 1;
+ } catch (InterruptedException ex) {
+ status = -1000;
+ }
+ }
+ }
+ }
+ ;
+
+ // Start of test code.
+
+ // Warning:
+ // This code relies on each thread getting serviced within
+ // 200 mSec of when it is notified. Although this
+ // seems reasonable, it could lead to false-failures.
+
+ ready = 0;
+ status = 0;
+ final int readyWaitSecs = 3;
+
+ final int threadCount = 20;
+ for (int i = 0; i < threadCount; ++i) {
+ new Thread(new TestThread()).start();
+ }
+ synchronized (obj1) {
+ try {
+
+ // Wait up to readyWaitSeconds for all threads to be waiting on
+ // monitor
+ for (int i = 0; i < readyWaitSecs; i++) {
+ obj1.wait(1000, 0);
+ if (ready == threadCount) {
+ break;
+ }
+ }
+
+ // Check pre-conditions of testing notifyAll
+ assertTrue("Not all launched threads are waiting. (ready = "
+ + ready + ")", ready == threadCount);
+ assertTrue("Thread woke too early. (status = " + status + ")",
+ status == 0);
+
+ for (int i = 1; i <= threadCount; ++i) {
+ obj1.notify();
+ obj1.wait(200, 0);
+ assertTrue("Out of sync. (expected " + i + " but got "
+ + status + ")", status == i);
+ }
+
+ } catch (InterruptedException ex) {
+ fail(
+ "Unexpectedly got an InterruptedException. (status = "
+ + status + ")");
+ }
+ }
+ }
+
+ /**
+ * java.lang.Object#notifyAll()
+ */
+ public void test_notifyAll() {
+ // Test for method void java.lang.Object.notifyAll()
+
+ // Inner class to run test thread.
+ class TestThread implements Runnable {
+ public void run() {
+ synchronized (obj1) {
+ try {
+ ready += 1;
+ obj1.wait();// Wait for ever.
+ status += 1;
+ } catch (InterruptedException ex) {
+ status = -1000;
+ }
+ }
+ }
+ }
+ ;
+
+ // Start of test code.
+
+ // Warning:
+ // This code relies on all threads getting serviced within
+ // 5 seconds of when they are notified. Although this
+ // seems reasonable, it could lead to false-failures.
+
+ status = 0;
+ ready = 0;
+ final int readyWaitSecs = 3;
+ final int threadCount = 20;
+ for (int i = 0; i < threadCount; ++i) {
+ new Thread(new TestThread()).start();
+ }
+
+ synchronized (obj1) {
+
+ try {
+
+ // Wait up to readyWaitSeconds for all threads to be waiting on
+ // monitor
+ for (int i = 0; i < readyWaitSecs; i++) {
+ obj1.wait(1000, 0);
+ if (ready == threadCount) {
+ break;
+ }
+ }
+
+ // Check pre-conditions of testing notifyAll
+ assertTrue("Not all launched threads are waiting. (ready = "
+ + ready + ")", ready == threadCount);
+ assertTrue("At least one thread woke too early. (status = "
+ + status + ")", status == 0);
+
+ obj1.notifyAll();
+
+ obj1.wait(5000, 0);
+
+ assertTrue(
+ "At least one thread did not get notified. (status = "
+ + status + ")", status == threadCount);
+
+ } catch (InterruptedException ex) {
+ fail(
+ "Unexpectedly got an InterruptedException. (status = "
+ + status + ")");
+ }
+
+ }
+ }
+
+ /**
+ * java.lang.Object#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.Object.toString()
+ assertNotNull("Object toString returned null.", obj1.toString());
+ }
+
+ /**
+ * java.lang.Object#wait()
+ */
+ public void test_wait() {
+ // Test for method void java.lang.Object.wait()
+
+ // Inner class to run test thread.
+ class TestThread implements Runnable {
+ public void run() {
+ synchronized (obj1) {
+ try {
+ obj1.wait();// Wait for ever.
+ status = 1;
+ } catch (InterruptedException ex) {
+ status = -1;
+ }
+ }
+ }
+ }
+ ;
+
+ // Start of test code.
+
+ // Warning:
+ // This code relies on threads getting serviced within
+ // 1 second of when they are notified. Although this
+ // seems reasonable, it could lead to false-failures.
+
+ status = 0;
+ new Thread(new TestThread()).start();
+ synchronized (obj1) {
+ try {
+ obj1.wait(1000, 0);
+ assertTrue("Thread woke too early. (status = " + status + ")",
+ status == 0);
+ obj1.notifyAll();
+ obj1.wait(1000, 0);
+ assertTrue("Thread did not get notified. (status = " + status
+ + ")", status == 1);
+ } catch (InterruptedException ex) {
+ fail(
+ "Unexpectedly got an InterruptedException. (status = "
+ + status + ")");
+ }
+ }
+ }
+
+ /**
+ * java.lang.Object#wait(long)
+ */
+ public void test_waitJ() {
+ // Test for method void java.lang.Object.wait(long)
+
+ // Start of test code.
+
+ final int loopCount = 20;
+ final int allowableError = 100; // millesconds
+ final int delay = 200; // milliseconds
+ synchronized (obj1) {
+ try {
+ int count = 0;
+ long[][] toLong = new long[3][3];
+ for (int i = 0; i < loopCount; ++i) {
+ long before = System.currentTimeMillis();
+ obj1.wait(delay, 0);
+ long after = System.currentTimeMillis();
+ long error = (after - before - delay);
+ if (error < 0)
+ error = -error;
+ if (i > 0 && error > allowableError) {
+ // Allow jit to warm up before testing
+ if (count < toLong.length) {
+ toLong[count][0] = i;
+ toLong[count][1] = before;
+ toLong[count][2] = after;
+ count++;
+ }
+ if (error > (1000 + delay) || count == toLong.length) {
+ StringBuffer sb = new StringBuffer();
+ for (int j = 0; j < count; j++) {
+ sb
+ .append("wakeup time too inaccurate, iteration ");
+ sb.append(toLong[j][0]);
+ sb.append(", before: ");
+ sb.append(toLong[j][1]);
+ sb.append(" after: ");
+ sb.append(toLong[j][2]);
+ sb.append(" diff: ");
+ sb.append(toLong[j][2] - toLong[j][1]);
+ sb.append("\n");
+ }
+ fail(sb.toString());
+ }
+ }
+ }
+ } catch (InterruptedException ex) {
+ fail(
+ "Unexpectedly got an InterruptedException. (status = "
+ + status + ")");
+ }
+ }
+ }
+
+ /**
+ * java.lang.Object#wait(long, int)
+ */
+ public void test_waitJI() {
+ // Test for method void java.lang.Object.wait(long, int)
+
+ // Inner class to run test thread.
+ class TestThread implements Runnable {
+ public void run() {
+ synchronized (obj1) {
+ try {
+ obj1.wait(0, 1); // Don't wait very long.
+ status = 1;
+ obj1.wait(0, 0); // Wait for ever.
+ status = 2;
+ } catch (InterruptedException ex) {
+ status = -1;
+ }
+ }
+ }
+ }
+ ;
+
+ // Start of test code.
+
+ // Warning:
+ // This code relies on threads getting serviced within
+ // 1 second of when they are notified. Although this
+ // seems reasonable, it could lead to false-failures.
+
+ status = 0;
+ new Thread(new TestThread()).start();
+ synchronized (obj1) {
+ try {
+ obj1.wait(1000, 0);
+ assertTrue("Thread did not wake after 1 ms. (status = "
+ + status + ")", status == 1);
+ obj1.notifyAll();
+ obj1.wait(1000, 0);
+ assertTrue("Thread did not get notified. (status = " + status
+ + ")", status == 2);
+ } catch (InterruptedException ex) {
+ fail(
+ "Unexpectedly got an InterruptedException. (status = "
+ + status + ")");
+ }
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/OutOfMemoryErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/OutOfMemoryErrorTest.java
new file mode 100644
index 0000000..b962455
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/OutOfMemoryErrorTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.tests.java.lang;
+
+public class OutOfMemoryErrorTest extends junit.framework.TestCase {
+
+ /**
+ * java.lang.OutOfMemoryError#OutOfMemoryError()
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.OutOfMemoryError()
+ Error e = new OutOfMemoryError();
+ assertNull(e.getCause());
+ assertNull(e.getMessage());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Process2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Process2Test.java
new file mode 100644
index 0000000..649488c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/Process2Test.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import dalvik.annotation.AndroidOnly;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import tests.support.Support_Exec;
+import static tests.support.Support_Exec.javaProcessBuilder;
+
+public class Process2Test extends junit.framework.TestCase {
+ /**
+ * java.lang.Process#getInputStream(),
+ * java.lang.Process#getErrorStream()
+ * java.lang.Process#getOutputStream()
+ * Tests if these methods return buffered streams.
+ */
+ @AndroidOnly("dalvikvm specific")
+ public void test_streams()
+ throws IOException, InterruptedException {
+ Process p = javaProcessBuilder().start();
+ assertNotNull(p.getInputStream());
+ assertNotNull(p.getErrorStream());
+ assertNotNull(p.getOutputStream());
+ }
+
+ public void test_getErrorStream() {
+ String[] commands = {"ls"};
+ Process process = null;
+ try {
+ process = Runtime.getRuntime().exec(commands, null, null);
+ InputStream is = process.getErrorStream();
+ StringBuffer msg = new StringBuffer("");
+ while (true) {
+ int c = is.read();
+ if (c == -1)
+ break;
+ msg.append((char) c);
+ }
+ assertEquals("", msg.toString());
+ } catch (IOException e) {
+ fail("IOException was thrown.");
+ } finally {
+ process.destroy();
+ }
+
+ String[] unknownCommands = {"mkdir", "-u", "test"};
+ Process erProcess = null;
+ try {
+ erProcess = Runtime.getRuntime().exec(unknownCommands, null, null);
+ InputStream is = erProcess.getErrorStream();
+ StringBuffer msg = new StringBuffer("");
+ while (true) {
+ int c = is.read();
+ if (c == -1)
+ break;
+ msg.append((char) c);
+ }
+ assertTrue("Error stream should not be empty",
+ !"".equals(msg.toString()));
+ } catch (IOException e) {
+ fail("IOException was thrown.");
+ } finally {
+ erProcess.destroy();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessBuilderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessBuilderTest.java
new file mode 100644
index 0000000..87cf88c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessBuilderTest.java
@@ -0,0 +1,171 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+public class ProcessBuilderTest extends TestCase {
+
+ public void testProcessBuilderStringArray() {
+
+ }
+
+ public void testProcessBuilderListOfString() {
+ try {
+ new ProcessBuilder((List<String>) null);
+ fail("no null pointer exception");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testCommand() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ assertEquals(1, pb.command().size());
+ assertEquals("command", pb.command().get(0));
+
+ // Regression for HARMONY-2675
+ pb = new ProcessBuilder("AAA");
+ pb.command("BBB", "CCC");
+ List<String> list = pb.command();
+ list.add("DDD");
+ String[] command = new String[3];
+ list.toArray(command);
+ assertTrue(Arrays.equals(new String[] { "BBB", "CCC", "DDD" }, command));
+ }
+
+ public void testCommandStringArray() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ ProcessBuilder pbReturn = pb.command("cmd");
+ assertSame(pb, pbReturn);
+ assertEquals(1, pb.command().size());
+ assertEquals("cmd", pb.command().get(0));
+ }
+
+ public void testCommandListOfString() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ List<String> newCmd = new ArrayList<String>();
+ newCmd.add("cmd");
+ ProcessBuilder pbReturn = pb.command(newCmd);
+ assertSame(pb, pbReturn);
+ assertEquals(1, pb.command().size());
+ assertEquals("cmd", pb.command().get(0));
+
+ newCmd.add("arg");
+ assertEquals(2, pb.command().size());
+ assertEquals("cmd", pb.command().get(0));
+ assertEquals("arg", pb.command().get(1));
+ }
+
+ public void testDirectory() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ assertNull(pb.directory());
+ }
+
+ public void testDirectoryFile() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ File dir = new File(System.getProperty("java.io.tmpdir"));
+ ProcessBuilder pbReturn = pb.directory(dir);
+ assertSame(pb, pbReturn);
+ assertEquals(dir, pb.directory());
+
+ pbReturn = pb.directory(null);
+ assertSame(pb, pbReturn);
+ assertNull(pb.directory());
+ }
+
+ public void testEnvironment() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ Map<String, String> env = pb.environment();
+ assertEquals(System.getenv(), env);
+ env.clear();
+ env = pb.environment();
+ assertTrue(env.isEmpty());
+ try {
+ env.put(null, "");
+ fail("should throw NPE.");
+ } catch (NullPointerException e) {
+ // expected;
+ }
+ try {
+ env.put("", null);
+ fail("should throw NPE.");
+ } catch (NullPointerException e) {
+ // expected;
+ }
+ try {
+ env.get(null);
+ fail("should throw NPE.");
+ } catch (NullPointerException e) {
+ // expected;
+ }
+ try {
+ assertNull(env.get(new Object()));
+ // Android's get doesn't throw (because it's just a regular HashMap).
+ // fail("should throw ClassCastException.");
+ } catch (ClassCastException thrownByRi) {
+ }
+ }
+
+ public void testRedirectErrorStream() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ assertFalse(pb.redirectErrorStream());
+ }
+
+ public void testRedirectErrorStreamBoolean() {
+ ProcessBuilder pb = new ProcessBuilder("command");
+ ProcessBuilder pbReturn = pb.redirectErrorStream(true);
+ assertSame(pb, pbReturn);
+ assertTrue(pb.redirectErrorStream());
+ }
+
+ /**
+ * @throws IOException
+ * {@link java.lang.ProcessBuilder#start()}
+ */
+ @SuppressWarnings("nls")
+ public void testStart() throws IOException {
+ ProcessBuilder pb = new ProcessBuilder("ls", "-al");
+
+ // Call the test target
+ Process process = pb.start();
+ InputStream in = process.getInputStream();
+ InputStream err = process.getErrorStream();
+
+ while (true) {
+ try {
+ process.waitFor();
+ break;
+ } catch (InterruptedException e) {
+ // Ignored
+ }
+ }
+
+ byte[] buf = new byte[1024];
+ if (in.available() > 0) {
+ assertTrue(in.read(buf) > 0);
+ } else {
+ assertTrue(err.read(buf) > 0);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessManagerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessManagerTest.java
new file mode 100644
index 0000000..9f7474a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessManagerTest.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+
+public class ProcessManagerTest extends TestCase {
+
+ Thread thread = null;
+ Process process = null;
+ boolean isThrown = false;
+
+ public void testCat() throws IOException, InterruptedException {
+ String[] commands = { "cat" };
+ Process process = Runtime.getRuntime().exec(commands, null, null);
+
+ OutputStream out = process.getOutputStream();
+ String greeting = "Hello, World!";
+ out.write(greeting.getBytes());
+ out.write('\n');
+ out.close();
+
+ assertEquals(greeting, readLine(process));
+ }
+
+ // BrokenTest: Sporadic failures in CTS, but not in CoreTestRunner
+ public void testSleep() throws IOException {
+ String[] commands = { "sleep", "1" };
+ process = Runtime.getRuntime().exec(commands, null, null);
+ try {
+ assertEquals(0, process.waitFor());
+
+ } catch(InterruptedException ie) {
+ fail("InterruptedException was thrown.");
+ }
+
+ isThrown = false;
+ thread = new Thread() {
+ public void run() {
+ String[] commands = { "sleep", "1000"};
+ try {
+ process = Runtime.getRuntime().exec(commands, null, null);
+ } catch (IOException e1) {
+ fail("IOException was thrown.");
+ }
+ try {
+ process.waitFor();
+ fail("InterruptedException was not thrown.");
+ } catch(InterruptedException ie) {
+ isThrown = true;
+ }
+ }
+ };
+
+ Thread interruptThread = new Thread() {
+ public void run() {
+ try {
+ sleep(10);
+ } catch(InterruptedException ie) {
+ fail("InterruptedException was thrown in " +
+ "the interruptThread.");
+ }
+ thread.interrupt();
+ }
+ };
+ thread.start();
+ interruptThread.start();
+ try {
+ interruptThread.join();
+ } catch (InterruptedException e) {
+ fail("InterruptedException was thrown.");
+ }
+ try {
+ Thread.sleep(100);
+ } catch(InterruptedException ie) {
+
+ }
+
+ thread.interrupt();
+ //process.destroy();
+ try {
+ Thread.sleep(100);
+ } catch(InterruptedException ie) {
+
+ }
+
+ assertTrue(isThrown);
+ }
+
+ public void testPwd() throws IOException, InterruptedException {
+ String[] commands = { "sh", "-c", "pwd" };
+ Process process = Runtime.getRuntime().exec(
+ commands, null, new File("/"));
+ logErrors(process);
+ assertEquals("/", readLine(process));
+ }
+
+ public void testEnvironment() throws IOException, InterruptedException {
+ String[] commands = { "sh", "-c", "echo $FOO" };
+
+ // Remember to set the path so we can find sh.
+ String[] environment = { "FOO=foo", "PATH=" + System.getenv("PATH") };
+ Process process = Runtime.getRuntime().exec(
+ commands, environment, null);
+ logErrors(process);
+ assertEquals("foo", readLine(process));
+ }
+
+ String readLine(Process process) throws IOException {
+ InputStream in = process.getInputStream();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ return reader.readLine();
+ }
+
+ void logErrors(final Process process) throws IOException {
+ Thread thread = new Thread() {
+ public void run() {
+ InputStream in = process.getErrorStream();
+ BufferedReader reader
+ = new BufferedReader(new InputStreamReader(in));
+ String line;
+ try {
+ while ((line = reader.readLine()) != null) {
+ System.err.println(line);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ public void testHeavyLoad() {
+ int i;
+ for (i = 0; i < 100; i++)
+ stuff();
+ }
+
+ private static void stuff() {
+ Runtime rt = Runtime.getRuntime();
+ try {
+ Process proc = rt.exec("ls");
+ proc.waitFor();
+ proc = null;
+ } catch (Exception ex) {
+ System.err.println("Failure: " + ex);
+ throw new RuntimeException(ex);
+ }
+ rt.gc();
+ rt = null;
+ }
+
+ InputStream in;
+
+ public void testCloseNonStandardFds()
+ throws IOException, InterruptedException {
+ String[] commands = { "ls", "/proc/self/fd" };
+
+ Process process = Runtime.getRuntime().exec(commands, null, null);
+ int before = countLines(process);
+
+ // Open a new fd.
+ this.in = new FileInputStream("/proc/version");
+
+ try {
+ process = Runtime.getRuntime().exec(commands, null, null);
+ int after = countLines(process);
+
+ // Assert that the new fd wasn't open in the second run.
+ assertEquals(before, after);
+ } finally {
+ this.in = null;
+ }
+ }
+
+ /**
+ * Counts lines of input from the given process. Equivalent to "wc -l".
+ */
+ private int countLines(Process process) throws IOException {
+ logErrors(process);
+ InputStream in = process.getInputStream();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ int count = 0;
+ while (reader.readLine() != null) {
+ count++;
+ }
+ return count;
+ }
+
+ public void testInvalidCommand()
+ throws IOException, InterruptedException {
+ try {
+ String[] commands = { "doesnotexist" };
+ Runtime.getRuntime().exec(commands, null, null);
+ } catch (IOException e) { /* expected */ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessTest.java
new file mode 100644
index 0000000..b87105b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ProcessTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+
+public class ProcessTest extends junit.framework.TestCase {
+
+ public void test_55017() throws Exception {
+ ArrayList<Process> children = new ArrayList<Process>();
+ for (int i = 0; i < 256; ++i) {
+ try {
+ children.add(Runtime.getRuntime().exec(new String[] { "/system/bin/does-not-exist" }, null, null));
+ System.gc();
+ } catch (IOException expected) {
+ }
+ }
+ assertEquals(0, children.size());
+
+ boolean onDevice = new File("/system/bin").exists();
+ String[] psCommand = onDevice ? new String[] { "ps" } : new String[] { "ps", "s" };
+ Process ps = Runtime.getRuntime().exec(psCommand, null, null);
+ int zombieCount = 0;
+ for (String line : readAndCloseStream(ps.getInputStream()).split("\n")) {
+ if (line.contains(" Z ") || line.contains(" Z+ ")) {
+ ++zombieCount;
+ }
+ }
+ assertEquals(0, zombieCount);
+ }
+
+ public void test_getOutputStream() throws Exception {
+ String[] commands = { "cat", "-"};
+ Process p = Runtime.getRuntime().exec(commands, null, null);
+ OutputStream os = p.getOutputStream();
+ // send data, and check if it is echoed back correctly
+ String str1 = "Some data for testing communication between processes\n";
+ String str2 = "More data that serves the same purpose.\n";
+ String str3 = "Here is some more data.\n";
+ os.write(str1.getBytes());
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ os.write(str2.getBytes());
+ os.write(str3.getBytes());
+ os.close();
+
+ String received = readAndCloseStream(p.getInputStream());
+ assertEquals(str1 + str2 + str3, received);
+
+ String stderr = readAndCloseStream(p.getErrorStream());
+ assertEquals("", stderr);
+
+ p.waitFor();
+ p.destroy();
+ }
+
+ public void test_getErrorStream() throws Exception {
+ String[] commands = { "cat", "--no-such-option"};
+ Process p = Runtime.getRuntime().exec(commands, null, null);
+
+ p.getOutputStream().close();
+
+ String received = readAndCloseStream(p.getInputStream());
+ assertEquals("", received);
+
+ String stderr = readAndCloseStream(p.getErrorStream());
+ assertTrue(stderr, stderr.contains("unrecognized option") || stderr.contains("invalid option"));
+
+ p.waitFor();
+ p.destroy();
+ }
+
+ private String readAndCloseStream(InputStream is) throws IOException {
+ StringBuffer result = new StringBuffer();
+ while (true) {
+ int c = is.read();
+ if (c == -1) {
+ break;
+ }
+ result.append((char) c);
+ }
+ is.close();
+ return result.toString();
+ }
+
+ public void test_exitValue() throws Exception {
+ String[] commands = { "ls" };
+ Process process = Runtime.getRuntime().exec(commands, null, null);
+ process.waitFor();
+ assertEquals(0, process.exitValue());
+
+ String[] commandsSleep = { "sleep", "3000" };
+ process = Runtime.getRuntime().exec(commandsSleep, null, null);
+ process.destroy();
+ process.waitFor(); // destroy is asynchronous.
+ assertTrue(process.exitValue() != 0);
+
+ process = Runtime.getRuntime().exec(new String[] { "sleep", "3000" }, null, null);
+ try {
+ process.exitValue();
+ fail();
+ } catch(IllegalThreadStateException expected) {
+ }
+ }
+
+ public void test_destroy() throws Exception {
+ String[] commands = { "ls"};
+ Process process = Runtime.getRuntime().exec(commands, null, null);
+ process.destroy();
+ process.destroy();
+ process.destroy();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeExceptionTest.java
new file mode 100644
index 0000000..748118a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeExceptionTest.java
@@ -0,0 +1,59 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class RuntimeExceptionTest extends TestCase {
+
+ /**
+ * java.lang.RuntimeException#RuntimeException()
+ */
+ public void test_Constructor() {
+ RuntimeException e = new RuntimeException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.RuntimeException#RuntimeException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ RuntimeException e = new RuntimeException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * {@link java.lang.RuntimeException#RuntimeException(Throwable)}
+ */
+ public void test_ConstructorLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ RuntimeException emptyException = new RuntimeException(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");
+ RuntimeException exception = new RuntimeException(throwable);
+ assertEquals(throwable.getClass().getName() + ": " + "msg", exception.getMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getCause().toString());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeTest.java
new file mode 100644
index 0000000..03a4aa0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/RuntimeTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Vector;
+
+public class RuntimeTest extends junit.framework.TestCase {
+
+ Runtime r = Runtime.getRuntime();
+
+ InputStream is;
+
+ String s;
+
+ static boolean flag = false;
+
+ static boolean ranFinalize = false;
+
+ class HasFinalizer {
+ String internalString;
+
+ HasFinalizer(String s) {
+ internalString = s;
+ }
+
+ @Override
+ protected void finalize() {
+ internalString = "hit";
+ }
+ }
+
+ @Override
+ protected void finalize() {
+ if (flag)
+ ranFinalize = true;
+ }
+
+ protected RuntimeTest createInstance() {
+ return new RuntimeTest("FT");
+ }
+
+ /**
+ * java.lang.Runtime#exit(int)
+ */
+ public void test_exitI() {
+ // Test for method void java.lang.Runtime.exit(int)
+ assertTrue("Can't really test this", true);
+ }
+
+ /**
+ * java.lang.Runtime#exec(java.lang.String)
+ */
+ public void test_exec() {
+ boolean success = false;
+
+ /* successful exec's are tested by java.lang.Process */
+ try {
+ Runtime.getRuntime().exec("AnInexistentProgram");
+ } catch (IOException e) {
+ success = true;
+ }
+ assertTrue(
+ "failed to throw IOException when exec'ed inexistent program",
+ success);
+ }
+
+ /**
+ * java.lang.Runtime#getRuntime()
+ */
+ public void test_getRuntime() {
+ // Test for method java.lang.Runtime java.lang.Runtime.getRuntime()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.lang.Runtime#runFinalization()
+ */
+ public void test_runFinalization() {
+ // Test for method void java.lang.Runtime.runFinalization()
+
+ flag = true;
+ createInstance();
+ int count = 10;
+ // the gc below likely bogosifies the test, but will have to do for
+ // the moment
+ while (!ranFinalize && count-- > 0) {
+ r.gc();
+ r.runFinalization();
+ }
+ assertTrue("Failed to run finalization", ranFinalize);
+ }
+
+ /**
+ * java.lang.Runtime#freeMemory() / java.lang.Runtime#totalMemory() /
+ * java.lang.Runtime#maxMemory()
+ */
+ public void test_memory() {
+ assertTrue("freeMemory < 0", r.freeMemory() >= 0);
+ assertTrue("totalMemory() < freeMemory()", r.totalMemory() >= r.freeMemory());
+ assertTrue("maxMemory() < totalMemory()", r.maxMemory() >= r.totalMemory());
+ }
+
+ public RuntimeTest() {
+ }
+
+ public RuntimeTest(String name) {
+ super(name);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SecurityExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SecurityExceptionTest.java
new file mode 100644
index 0000000..a0d1cee
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SecurityExceptionTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class SecurityExceptionTest extends TestCase {
+
+ /**
+ * java.lang.SecurityException#SecurityException()
+ */
+ public void test_Constructor() {
+ SecurityException e = new SecurityException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.SecurityException#SecurityException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ SecurityException e = new SecurityException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.SecurityException#SecurityException(String, Throwable)
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
+ NullPointerException npe = new NullPointerException();
+ SecurityException e = new SecurityException("fixture", npe);
+ assertSame("fixture", e.getMessage());
+ assertSame(npe, e.getCause());
+ }
+
+ /**
+ * java.lang.SecurityException#SecurityException(Throwable)
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_lang_Throwable() {
+ NullPointerException npe = new NullPointerException();
+ SecurityException e = new SecurityException(npe);
+ assertSame(npe, e.getCause());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new SecurityException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new SecurityException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ShortTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ShortTest.java
new file mode 100644
index 0000000..bf747e7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ShortTest.java
@@ -0,0 +1,684 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ShortTest extends TestCase {
+ private Short sp = new Short((short) 18000);
+ private Short sn = new Short((short) -19000);
+
+ /**
+ * java.lang.Short#byteValue()
+ */
+ public void test_byteValue() {
+ // Test for method byte java.lang.Short.byteValue()
+ assertEquals("Returned incorrect byte value", 0, new Short(Short.MIN_VALUE)
+ .byteValue());
+ assertEquals("Returned incorrect byte value", -1, new Short(Short.MAX_VALUE)
+ .byteValue());
+ }
+
+ /**
+ * java.lang.Short#compareTo(java.lang.Short)
+ */
+ public void test_compareToLjava_lang_Short() {
+ // Test for method int java.lang.Short.compareTo(java.lang.Short)
+ Short s = new Short((short) 1);
+ Short x = new Short((short) 3);
+ assertTrue(
+ "Should have returned negative value when compared to greater short",
+ s.compareTo(x) < 0);
+ x = new Short((short) -1);
+ assertTrue(
+ "Should have returned positive value when compared to lesser short",
+ s.compareTo(x) > 0);
+ x = new Short((short) 1);
+ assertEquals("Should have returned zero when compared to equal short",
+ 0, s.compareTo(x));
+
+ try {
+ new Short((short) 0).compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#decode(java.lang.String)
+ */
+ public void test_decodeLjava_lang_String2() {
+ // Test for method java.lang.Short
+ // java.lang.Short.decode(java.lang.String)
+ assertTrue("Did not decode -1 correctly", Short.decode("-1")
+ .shortValue() == (short) -1);
+ assertTrue("Did not decode -100 correctly", Short.decode("-100")
+ .shortValue() == (short) -100);
+ assertTrue("Did not decode 23 correctly", Short.decode("23")
+ .shortValue() == (short) 23);
+ assertTrue("Did not decode 0x10 correctly", Short.decode("0x10")
+ .shortValue() == (short) 16);
+ assertTrue("Did not decode 32767 correctly", Short.decode("32767")
+ .shortValue() == (short) 32767);
+ assertTrue("Did not decode -32767 correctly", Short.decode("-32767")
+ .shortValue() == (short) -32767);
+ assertTrue("Did not decode -32768 correctly", Short.decode("-32768")
+ .shortValue() == (short) -32768);
+
+ boolean exception = false;
+ try {
+ Short.decode("123s");
+ } catch (NumberFormatException e) {
+ // correct
+ exception = true;
+ }
+ assertTrue("Did not throw NumberFormatException decoding 123s",
+ exception);
+
+ exception = false;
+ try {
+ Short.decode("32768");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Short.decode("-32769");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Short.decode("0x8000");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Short.decode("-0x8001");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Short#parseShort(java.lang.String)
+ */
+ public void test_parseShortLjava_lang_String2() {
+ // Test for method short java.lang.Short.parseShort(java.lang.String)
+ short sp = Short.parseShort("32746");
+ short sn = Short.parseShort("-32746");
+
+ assertTrue("Incorrect parse of short", sp == (short) 32746
+ && (sn == (short) -32746));
+ assertEquals("Returned incorrect value for 0", 0, Short.parseShort("0"));
+ assertTrue("Returned incorrect value for most negative value", Short
+ .parseShort("-32768") == (short) 0x8000);
+ assertTrue("Returned incorrect value for most positive value", Short
+ .parseShort("32767") == 0x7fff);
+
+ boolean exception = false;
+ try {
+ Short.parseShort("32768");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Short.parseShort("-32769");
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+ }
+
+ /**
+ * java.lang.Short#parseShort(java.lang.String, int)
+ */
+ public void test_parseShortLjava_lang_StringI2() {
+ // Test for method short java.lang.Short.parseShort(java.lang.String,
+ // int)
+ boolean aThrow = true;
+ assertEquals("Incorrectly parsed hex string",
+ 255, Short.parseShort("FF", 16));
+ assertEquals("Incorrectly parsed oct string",
+ 16, Short.parseShort("20", 8));
+ assertEquals("Incorrectly parsed dec string",
+ 20, Short.parseShort("20", 10));
+ assertEquals("Incorrectly parsed bin string",
+ 4, Short.parseShort("100", 2));
+ assertEquals("Incorrectly parsed -hex string", -255, Short
+ .parseShort("-FF", 16));
+ assertEquals("Incorrectly parsed -oct string",
+ -16, Short.parseShort("-20", 8));
+ assertEquals("Incorrectly parsed -bin string", -4, Short
+ .parseShort("-100", 2));
+ assertEquals("Returned incorrect value for 0 hex", 0, Short.parseShort("0",
+ 16));
+ assertTrue("Returned incorrect value for most negative value hex",
+ Short.parseShort("-8000", 16) == (short) 0x8000);
+ assertTrue("Returned incorrect value for most positive value hex",
+ Short.parseShort("7fff", 16) == 0x7fff);
+ assertEquals("Returned incorrect value for 0 decimal", 0, Short.parseShort(
+ "0", 10));
+ assertTrue("Returned incorrect value for most negative value decimal",
+ Short.parseShort("-32768", 10) == (short) 0x8000);
+ assertTrue("Returned incorrect value for most positive value decimal",
+ Short.parseShort("32767", 10) == 0x7fff);
+
+ try {
+ Short.parseShort("FF", 2);
+ } catch (NumberFormatException e) {
+ // Correct
+ aThrow = false;
+ }
+ if (aThrow) {
+ fail(
+ "Failed to throw exception when passed hex string and base 2 radix");
+ }
+
+ boolean exception = false;
+ try {
+ Short.parseShort("10000000000", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue(
+ "Failed to throw exception when passed string larger than 16 bits",
+ exception);
+
+ exception = false;
+ try {
+ Short.parseShort("32768", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Short.parseShort("-32769", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
+
+ exception = false;
+ try {
+ Short.parseShort("8000", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
+
+ exception = false;
+ try {
+ Short.parseShort("-8001", 16);
+ } catch (NumberFormatException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
+ }
+
+ /**
+ * java.lang.Short#toString()
+ */
+ public void test_toString2() {
+ // Test for method java.lang.String java.lang.Short.toString()
+ assertTrue("Invalid string returned", sp.toString().equals("18000")
+ && (sn.toString().equals("-19000")));
+ assertEquals("Returned incorrect string", "32767", new Short((short) 32767)
+ .toString());
+ assertEquals("Returned incorrect string", "-32767", new Short((short) -32767)
+ .toString());
+ assertEquals("Returned incorrect string", "-32768", new Short((short) -32768)
+ .toString());
+ }
+
+ /**
+ * java.lang.Short#toString(short)
+ */
+ public void test_toStringS2() {
+ // Test for method java.lang.String java.lang.Short.toString(short)
+ assertEquals("Returned incorrect string", "32767", Short.toString((short) 32767)
+ );
+ assertEquals("Returned incorrect string", "-32767", Short.toString((short) -32767)
+ );
+ assertEquals("Returned incorrect string", "-32768", Short.toString((short) -32768)
+ );
+ }
+
+ /**
+ * java.lang.Short#valueOf(java.lang.String)
+ */
+ public void test_valueOfLjava_lang_String2() {
+ // Test for method java.lang.Short
+ // java.lang.Short.valueOf(java.lang.String)
+ assertEquals("Returned incorrect short", -32768, Short.valueOf("-32768")
+ .shortValue());
+ assertEquals("Returned incorrect short", 32767, Short.valueOf("32767")
+ .shortValue());
+ }
+
+ /**
+ * java.lang.Short#valueOf(java.lang.String, int)
+ */
+ public void test_valueOfLjava_lang_StringI2() {
+ // Test for method java.lang.Short
+ // java.lang.Short.valueOf(java.lang.String, int)
+ boolean aThrow = true;
+ assertEquals("Incorrectly parsed hex string", 255, Short.valueOf("FF", 16)
+ .shortValue());
+ assertEquals("Incorrectly parsed oct string", 16, Short.valueOf("20", 8)
+ .shortValue());
+ assertEquals("Incorrectly parsed dec string", 20, Short.valueOf("20", 10)
+ .shortValue());
+ assertEquals("Incorrectly parsed bin string", 4, Short.valueOf("100", 2)
+ .shortValue());
+ assertEquals("Incorrectly parsed -hex string", -255, Short.valueOf("-FF", 16)
+ .shortValue());
+ assertEquals("Incorrectly parsed -oct string", -16, Short.valueOf("-20", 8)
+ .shortValue());
+ assertEquals("Incorrectly parsed -bin string", -4, Short.valueOf("-100", 2)
+ .shortValue());
+ assertTrue("Did not decode 32767 correctly", Short.valueOf("32767", 10)
+ .shortValue() == (short) 32767);
+ assertTrue("Did not decode -32767 correctly", Short.valueOf("-32767",
+ 10).shortValue() == (short) -32767);
+ assertTrue("Did not decode -32768 correctly", Short.valueOf("-32768",
+ 10).shortValue() == (short) -32768);
+ try {
+ Short.valueOf("FF", 2);
+ } catch (NumberFormatException e) {
+ // Correct
+ aThrow = false;
+ }
+ if (aThrow) {
+ fail(
+ "Failed to throw exception when passed hex string and base 2 radix");
+ }
+ try {
+ Short.valueOf("10000000000", 10);
+ } catch (NumberFormatException e) {
+ // Correct
+ return;
+ }
+ fail(
+ "Failed to throw exception when passed string larger than 16 bits");
+ }
+
+ /**
+ * 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++;
+ }
+ }
+
+ /**
+ * java.lang.Short#hashCode()
+ */
+ public void test_hashCode() {
+ assertEquals(1, new Short((short) 1).hashCode());
+ assertEquals(2, new Short((short) 2).hashCode());
+ assertEquals(0, new Short((short) 0).hashCode());
+ assertEquals(-1, new Short((short) -1).hashCode());
+ }
+
+ /**
+ * java.lang.Short#Short(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertEquals(new Short((short) 0), new Short("0"));
+ assertEquals(new Short((short) 1), new Short("1"));
+ assertEquals(new Short((short) -1), new Short("-1"));
+
+ try {
+ new Short("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Short("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Short("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ new Short(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#Short(short)
+ */
+ public void test_ConstructorS() {
+ assertEquals(1, new Short((short) 1).shortValue());
+ assertEquals(2, new Short((short) 2).shortValue());
+ assertEquals(0, new Short((short) 0).shortValue());
+ assertEquals(-1, new Short((short) -1).shortValue());
+ }
+
+ /**
+ * java.lang.Short#byteValue()
+ */
+ 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());
+ assertEquals(-1, new Short((short) -1).byteValue());
+ }
+
+ /**
+ * java.lang.Short#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertEquals(new Short((short) 0), Short.valueOf((short) 0));
+ assertEquals(new Short((short) 1), Short.valueOf((short) 1));
+ assertEquals(new Short((short) -1), Short.valueOf((short) -1));
+
+ Short fixture = new Short((short) 25);
+ assertEquals(fixture, fixture);
+ assertFalse(fixture.equals(null));
+ assertFalse(fixture.equals("Not a Short"));
+ }
+
+ /**
+ * java.lang.Short#toString()
+ */
+ public void test_toString() {
+ assertEquals("-1", new Short((short) -1).toString());
+ assertEquals("0", new Short((short) 0).toString());
+ assertEquals("1", new Short((short) 1).toString());
+ assertEquals("-1", new Short((short) 0xFFFF).toString());
+ }
+
+ /**
+ * java.lang.Short#toString(short)
+ */
+ public void test_toStringS() {
+ assertEquals("-1", Short.toString((short) -1));
+ assertEquals("0", Short.toString((short) 0));
+ assertEquals("1", Short.toString((short) 1));
+ assertEquals("-1", Short.toString((short) 0xFFFF));
+ }
+
+ /**
+ * java.lang.Short#valueOf(String)
+ */
+ public void test_valueOfLjava_lang_String() {
+ assertEquals(new Short((short) 0), Short.valueOf("0"));
+ assertEquals(new Short((short) 1), Short.valueOf("1"));
+ assertEquals(new Short((short) -1), Short.valueOf("-1"));
+
+ try {
+ Short.valueOf("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#valueOf(String, int)
+ */
+ public void test_valueOfLjava_lang_StringI() {
+ assertEquals(new Short((short) 0), Short.valueOf("0", 10));
+ assertEquals(new Short((short) 1), Short.valueOf("1", 10));
+ assertEquals(new Short((short) -1), Short.valueOf("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Short.valueOf("1", 2).byteValue());
+ assertEquals(Character.digit('F', 16), Short.valueOf("F", 16).byteValue());
+
+ try {
+ Short.valueOf("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.valueOf(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#parseShort(String)
+ */
+ public void test_parseShortLjava_lang_String() {
+ assertEquals(0, Short.parseShort("0"));
+ assertEquals(1, Short.parseShort("1"));
+ assertEquals(-1, Short.parseShort("-1"));
+
+ try {
+ Short.parseShort("0x1");
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort(null);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#parseShort(String, int)
+ */
+ public void test_parseShortLjava_lang_StringI() {
+ assertEquals(0, Short.parseShort("0", 10));
+ assertEquals(1, Short.parseShort("1", 10));
+ assertEquals(-1, Short.parseShort("-1", 10));
+
+ //must be consistent with Character.digit()
+ assertEquals(Character.digit('1', 2), Short.parseShort("1", 2));
+ assertEquals(Character.digit('F', 16), Short.parseShort("F", 16));
+
+ try {
+ Short.parseShort("0x1", 10);
+ fail("Expected NumberFormatException with hex string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort("9.2", 10);
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort("", 10);
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.parseShort(null, 10);
+ fail("Expected NumberFormatException with null string.");
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#decode(String)
+ */
+ public void test_decodeLjava_lang_String() {
+ assertEquals(new Short((short) 0), Short.decode("0"));
+ assertEquals(new Short((short) 1), Short.decode("1"));
+ assertEquals(new Short((short) -1), Short.decode("-1"));
+ assertEquals(new Short((short) 0xF), Short.decode("0xF"));
+ assertEquals(new Short((short) 0xF), Short.decode("#F"));
+ assertEquals(new Short((short) 0xF), Short.decode("0XF"));
+ assertEquals(new Short((short) 07), Short.decode("07"));
+
+ try {
+ Short.decode("9.2");
+ fail("Expected NumberFormatException with floating point string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.decode("");
+ fail("Expected NumberFormatException with empty string.");
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Short.decode(null);
+ //undocumented NPE, but seems consistent across JREs
+ fail("Expected NullPointerException with null string.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.Short#doubleValue()
+ */
+ public void test_doubleValue() {
+ assertEquals(-1D, new Short((short) -1).doubleValue(), 0D);
+ assertEquals(0D, new Short((short) 0).doubleValue(), 0D);
+ assertEquals(1D, new Short((short) 1).doubleValue(), 0D);
+ }
+
+ /**
+ * java.lang.Short#floatValue()
+ */
+ public void test_floatValue() {
+ assertEquals(-1F, new Short((short) -1).floatValue(), 0F);
+ assertEquals(0F, new Short((short) 0).floatValue(), 0F);
+ assertEquals(1F, new Short((short) 1).floatValue(), 0F);
+ }
+
+ /**
+ * java.lang.Short#intValue()
+ */
+ public void test_intValue() {
+ assertEquals(-1, new Short((short) -1).intValue());
+ assertEquals(0, new Short((short) 0).intValue());
+ assertEquals(1, new Short((short) 1).intValue());
+ }
+
+ /**
+ * java.lang.Short#longValue()
+ */
+ public void test_longValue() {
+ assertEquals(-1L, new Short((short) -1).longValue());
+ assertEquals(0L, new Short((short) 0).longValue());
+ assertEquals(1L, new Short((short) 1).longValue());
+ }
+
+ /**
+ * java.lang.Short#shortValue()
+ */
+ public void test_shortValue() {
+ assertEquals(-1, new Short((short) -1).shortValue());
+ assertEquals(0, new Short((short) 0).shortValue());
+ assertEquals(1, new Short((short) 1).shortValue());
+ }
+
+ /**
+ * java.lang.Short#reverseBytes(short)
+ */
+ public void test_reverseBytesS() {
+ assertEquals((short) 0xABCD, Short.reverseBytes((short) 0xCDAB));
+ assertEquals((short) 0x1234, Short.reverseBytes((short) 0x3412));
+ assertEquals((short) 0x0011, Short.reverseBytes((short) 0x1100));
+ assertEquals((short) 0x2002, Short.reverseBytes((short) 0x0220));
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StackOverflowErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StackOverflowErrorTest.java
new file mode 100644
index 0000000..b3f6f82
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StackOverflowErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class StackOverflowErrorTest extends TestCase {
+
+ /**
+ * java.lang.StackOverflowError#StackOverflowError()
+ */
+ public void test_Constructor() {
+ StackOverflowError e = new StackOverflowError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.StackOverflowError#StackOverflowError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ StackOverflowError e = new StackOverflowError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StrictMathTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StrictMathTest.java
new file mode 100644
index 0000000..cce8935
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StrictMathTest.java
@@ -0,0 +1,1490 @@
+/*
+ * 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.tests.java.lang;
+
+import static org.apache.harmony.tests.java.lang.MathTest.COPYSIGN_DD_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.COPYSIGN_FF_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.GETEXPONENT_D_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.GETEXPONENT_D_RESULTS;
+import static org.apache.harmony.tests.java.lang.MathTest.GETEXPONENT_F_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.GETEXPONENT_F_RESULTS;
+import static org.apache.harmony.tests.java.lang.MathTest.NEXTAFTER_DD_START_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.NEXTAFTER_DD_FD_DIRECTION_CASES;
+import static org.apache.harmony.tests.java.lang.MathTest.NEXTAFTER_FD_START_CASES;
+
+public class StrictMathTest extends junit.framework.TestCase {
+
+ private static final double HYP = StrictMath.sqrt(2.0);
+
+ private static final double OPP = 1.0;
+
+ private static final double ADJ = 1.0;
+
+ /* Required to make previous preprocessor flags work - do not remove */
+ int unused = 0;
+
+ /**
+ * java.lang.StrictMath#abs(double)
+ */
+ public void test_absD() {
+ // Test for method double java.lang.StrictMath.abs(double)
+
+ assertTrue("Incorrect double abs value",
+ (StrictMath.abs(-1908.8976) == 1908.8976));
+ assertTrue("Incorrect double abs value",
+ (StrictMath.abs(1908.8976) == 1908.8976));
+ }
+
+ /**
+ * java.lang.StrictMath#abs(float)
+ */
+ public void test_absF() {
+ // Test for method float java.lang.StrictMath.abs(float)
+ assertTrue("Incorrect float abs value",
+ (StrictMath.abs(-1908.8976f) == 1908.8976f));
+ assertTrue("Incorrect float abs value",
+ (StrictMath.abs(1908.8976f) == 1908.8976f));
+ }
+
+ /**
+ * java.lang.StrictMath#abs(int)
+ */
+ public void test_absI() {
+ // Test for method int java.lang.StrictMath.abs(int)
+ assertTrue("Incorrect int abs value",
+ (StrictMath.abs(-1908897) == 1908897));
+ assertTrue("Incorrect int abs value",
+ (StrictMath.abs(1908897) == 1908897));
+ }
+
+ /**
+ * java.lang.StrictMath#abs(long)
+ */
+ public void test_absJ() {
+ // Test for method long java.lang.StrictMath.abs(long)
+ assertTrue("Incorrect long abs value", (StrictMath
+ .abs(-19088976000089L) == 19088976000089L));
+ assertTrue("Incorrect long abs value",
+ (StrictMath.abs(19088976000089L) == 19088976000089L));
+ }
+
+ /**
+ * java.lang.StrictMath#acos(double)
+ */
+ public void test_acosD() {
+ // Test for method double java.lang.StrictMath.acos(double)
+ assertTrue("Returned incorrect arc cosine", StrictMath.cos(StrictMath
+ .acos(ADJ / HYP)) == ADJ / HYP);
+ }
+
+ /**
+ * java.lang.StrictMath#asin(double)
+ */
+ public void test_asinD() {
+ // Test for method double java.lang.StrictMath.asin(double)
+ assertTrue("Returned incorrect arc sine", StrictMath.sin(StrictMath
+ .asin(OPP / HYP)) == OPP / HYP);
+ }
+
+ /**
+ * java.lang.StrictMath#atan(double)
+ */
+ public void test_atanD() {
+ // Test for method double java.lang.StrictMath.atan(double)
+ double answer = StrictMath.tan(StrictMath.atan(1.0));
+ assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
+ && answer >= 9.9999999999999983E-1);
+ }
+
+ /**
+ * java.lang.StrictMath#atan2(double, double)
+ */
+ public void test_atan2DD() {
+ // Test for method double java.lang.StrictMath.atan2(double, double)
+ double answer = StrictMath.atan(StrictMath.tan(1.0));
+ assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
+ && answer >= 9.9999999999999983E-1);
+ }
+
+ /**
+ * java.lang.StrictMath#cbrt(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_cbrt_D() {
+ // Test for special situations
+ assertTrue("Should return Double.NaN", Double.isNaN(StrictMath
+ .cbrt(Double.NaN)));
+ assertEquals("Should return Double.POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .cbrt(Double.POSITIVE_INFINITY));
+ assertEquals("Should return Double.NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath
+ .cbrt(Double.NEGATIVE_INFINITY));
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.cbrt(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.cbrt(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.cbrt(-0.0)));
+
+ assertEquals("Should return 3.0", 3.0, StrictMath.cbrt(27.0));
+ assertEquals("Should return 23.111993172558684", 23.111993172558684,
+ StrictMath.cbrt(12345.6));
+ assertEquals("Should return 5.643803094122362E102",
+ 5.643803094122362E102, StrictMath.cbrt(Double.MAX_VALUE));
+ assertEquals("Should return 0.01", 0.01, StrictMath.cbrt(0.000001));
+
+ assertEquals("Should return -3.0", -3.0, StrictMath.cbrt(-27.0));
+ assertEquals("Should return -23.111993172558684", -23.111993172558684,
+ StrictMath.cbrt(-12345.6));
+ assertEquals("Should return 1.7031839360032603E-108",
+ 1.7031839360032603E-108, StrictMath.cbrt(Double.MIN_VALUE));
+ assertEquals("Should return -0.01", -0.01, StrictMath.cbrt(-0.000001));
+
+ try {
+ StrictMath.cbrt((Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#ceil(double)
+ */
+ public void test_ceilD() {
+ // Test for method double java.lang.StrictMath.ceil(double)
+ assertEquals("Incorrect ceiling for double",
+ 79, StrictMath.ceil(78.89), 0.0);
+ assertEquals("Incorrect ceiling for double",
+ -78, StrictMath.ceil(-78.89), 0.0);
+ }
+
+ /**
+ * {@link java.lang.StrictMath#copySign(double, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_copySign_DD() {
+ for (int i = 0; i < COPYSIGN_DD_CASES.length; i++) {
+ final double magnitude = COPYSIGN_DD_CASES[i];
+ final long absMagnitudeBits = Double.doubleToLongBits(StrictMath
+ .abs(magnitude));
+ final long negMagnitudeBits = Double.doubleToLongBits(-StrictMath
+ .abs(magnitude));
+
+ // cases for NaN
+ assertEquals("If the sign is NaN, the result should be positive.",
+ absMagnitudeBits, Double.doubleToLongBits(StrictMath
+ .copySign(magnitude, Double.NaN)));
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .copySign(Double.NaN, magnitude)));
+
+ for (int j = 0; j < COPYSIGN_DD_CASES.length; j++) {
+ final double sign = COPYSIGN_DD_CASES[j];
+ final long resultBits = Double.doubleToLongBits(StrictMath
+ .copySign(magnitude, sign));
+
+ if (sign > 0 || Double.valueOf(+0.0).equals(sign)
+ || Double.valueOf(0.0).equals(sign)) {
+ assertEquals(
+ "If the sign is positive, the result should be positive.",
+ absMagnitudeBits, resultBits);
+ }
+ if (sign < 0 || Double.valueOf(-0.0).equals(sign)) {
+ assertEquals(
+ "If the sign is negative, the result should be negative.",
+ negMagnitudeBits, resultBits);
+ }
+ }
+ }
+
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .copySign(Double.NaN, Double.NaN)));
+
+ try {
+ StrictMath.copySign((Double) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.copySign(2.3, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.copySign((Double) null, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ double d = Double.longBitsToDouble(0xfff8000000000000L);
+ assertEquals(1.0, StrictMath.copySign(1.0, d), 0d);
+ }
+
+ /**
+ * {@link java.lang.StrictMath#copySign(float, float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_copySign_FF() {
+ for (int i = 0; i < COPYSIGN_FF_CASES.length; i++) {
+ final float magnitude = COPYSIGN_FF_CASES[i];
+ final int absMagnitudeBits = Float.floatToIntBits(StrictMath
+ .abs(magnitude));
+ final int negMagnitudeBits = Float.floatToIntBits(-StrictMath
+ .abs(magnitude));
+
+ // cases for NaN
+ assertEquals("If the sign is NaN, the result should be positive.",
+ absMagnitudeBits, Float.floatToIntBits(StrictMath.copySign(
+ magnitude, Float.NaN)));
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .copySign(Float.NaN, magnitude)));
+
+ for (int j = 0; j < COPYSIGN_FF_CASES.length; j++) {
+ final float sign = COPYSIGN_FF_CASES[j];
+ final int resultBits = Float.floatToIntBits(StrictMath
+ .copySign(magnitude, sign));
+ if (sign > 0 || Float.valueOf(+0.0f).equals(sign)
+ || Float.valueOf(0.0f).equals(sign)) {
+ assertEquals(
+ "If the sign is positive, the result should be positive.",
+ absMagnitudeBits, resultBits);
+ }
+ if (sign < 0 || Float.valueOf(-0.0f).equals(sign)) {
+ assertEquals(
+ "If the sign is negative, the result should be negative.",
+ negMagnitudeBits, resultBits);
+ }
+ }
+ }
+
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .copySign(Float.NaN, Float.NaN)));
+
+ try {
+ StrictMath.copySign((Float) null, 2.3f);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.copySign(2.3f, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.copySign((Float) null, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ float f = Float.intBitsToFloat(0xffc00000);
+ assertEquals(1.0f, StrictMath.copySign(1.0f, f), 0f);
+ }
+
+ /**
+ * java.lang.StrictMath#cos(double)
+ */
+ public void test_cosD() {
+ // Test for method double java.lang.StrictMath.cos(double)
+
+ assertTrue("Returned incorrect cosine", StrictMath.cos(StrictMath
+ .acos(ADJ / HYP)) == ADJ / HYP);
+ }
+
+ /**
+ * java.lang.StrictMath#cosh(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_cosh_D() {
+ // Test for special situations
+ assertTrue("Should return NaN", Double.isNaN(StrictMath
+ .cosh(Double.NaN)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .cosh(Double.POSITIVE_INFINITY));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .cosh(Double.NEGATIVE_INFINITY));
+ assertEquals("Should return 1.0", 1.0, StrictMath.cosh(+0.0));
+ assertEquals("Should return 1.0", 1.0, StrictMath.cosh(-0.0));
+
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.cosh(1234.56));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.cosh(-1234.56));
+ assertEquals("Should return 1.0000000000005", 1.0000000000005,
+ StrictMath.cosh(0.000001));
+ assertEquals("Should return 1.0000000000005", 1.0000000000005,
+ StrictMath.cosh(-0.000001));
+ assertEquals("Should return 5.212214351945598", 5.212214351945598,
+ StrictMath.cosh(2.33482));
+
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.cosh(Double.MAX_VALUE));
+ assertEquals("Should return 1.0", 1.0, StrictMath
+ .cosh(Double.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.StrictMath#exp(double)
+ */
+ public void test_expD() {
+ // Test for method double java.lang.StrictMath.exp(double)
+ assertTrue("Incorrect answer returned for simple power", StrictMath
+ .abs(StrictMath.exp(4D) - StrictMath.E * StrictMath.E
+ * StrictMath.E * StrictMath.E) < 0.1D);
+ assertTrue("Incorrect answer returned for larger power", StrictMath
+ .log(StrictMath.abs(StrictMath.exp(5.5D)) - 5.5D) < 10.0D);
+ }
+
+ /**
+ * java.lang.StrictMath#expm1(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_expm1_D() {
+ //Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(StrictMath.expm1(Double.NaN)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.expm1(Double.POSITIVE_INFINITY));
+ assertEquals("Should return -1.0", -1.0, StrictMath
+ .expm1(Double.NEGATIVE_INFINITY));
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.expm1(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.expm1(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.expm1(-0.0)));
+
+ assertEquals("Should return -9.999950000166666E-6",
+ -9.999950000166666E-6, StrictMath.expm1(-0.00001));
+ assertEquals("Should return 1.0145103074469635E60",
+ 1.0145103074469635E60, StrictMath.expm1(138.16951162));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .expm1(123456789123456789123456789.4521584223));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.expm1(Double.MAX_VALUE));
+ assertEquals("Should return MIN_VALUE", Double.MIN_VALUE, StrictMath
+ .expm1(Double.MIN_VALUE));
+
+ }
+
+ /**
+ * java.lang.StrictMath#floor(double)
+ */
+ public void test_floorD() {
+ // Test for method double java.lang.StrictMath.floor(double)
+ assertEquals("Incorrect floor for double",
+ 78, StrictMath.floor(78.89), 0.0);
+ assertEquals("Incorrect floor for double",
+ -79, StrictMath.floor(-78.89), 0.0);
+ }
+
+ /**
+ * {@link java.lang.StrictMath#getExponent(double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_getExponent_D() {
+ for (int i = 0; i < GETEXPONENT_D_CASES.length; i++) {
+ final double number = GETEXPONENT_D_CASES[i];
+ final int result = GETEXPONENT_D_RESULTS[i];
+ assertEquals("Wrong result of getExponent(double).", result,
+ StrictMath.getExponent(number));
+ }
+
+ try {
+ StrictMath.getExponent((Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StrictMath#getExponent(float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_getExponent_F() {
+ for (int i = 0; i < GETEXPONENT_F_CASES.length; i++) {
+ final float number = GETEXPONENT_F_CASES[i];
+ final int result = GETEXPONENT_F_RESULTS[i];
+ assertEquals("Wrong result of getExponent(float).", result,
+ StrictMath.getExponent(number));
+ }
+ try {
+ StrictMath.getExponent((Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#hypot(double, double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_hypot_DD() {
+ // Test for special cases
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(Double.POSITIVE_INFINITY,
+ 1.0));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(Double.NEGATIVE_INFINITY,
+ 123.324));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(-758.2587,
+ Double.POSITIVE_INFINITY));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(5687.21,
+ Double.NEGATIVE_INFINITY));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(Double.POSITIVE_INFINITY,
+ Double.NEGATIVE_INFINITY));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.hypot(Double.NEGATIVE_INFINITY,
+ Double.POSITIVE_INFINITY));
+ assertTrue("Should return NaN", Double.isNaN(StrictMath.hypot(Double.NaN,
+ 2342301.89843)));
+ assertTrue("Should return NaN", Double.isNaN(StrictMath.hypot(-345.2680,
+ Double.NaN)));
+
+ assertEquals("Should return 2396424.905416697", 2396424.905416697, StrictMath
+ .hypot(12322.12, -2396393.2258));
+ assertEquals("Should return 138.16958070558556", 138.16958070558556,
+ StrictMath.hypot(-138.16951162, 0.13817035864));
+ assertEquals("Should return 1.7976931348623157E308",
+ 1.7976931348623157E308, StrictMath.hypot(Double.MAX_VALUE, 211370.35));
+ assertEquals("Should return 5413.7185", 5413.7185, StrictMath.hypot(
+ -5413.7185, Double.MIN_VALUE));
+
+ }
+
+ /**
+ * java.lang.StrictMath#IEEEremainder(double, double)
+ */
+ public void test_IEEEremainderDD() {
+ // Test for method double java.lang.StrictMath.IEEEremainder(double,
+ // double)
+ assertEquals("Incorrect remainder returned", 0.0, StrictMath.IEEEremainder(
+ 1.0, 1.0), 0.0);
+ assertTrue(
+ "Incorrect remainder returned",
+ StrictMath.IEEEremainder(1.32, 89.765) >= 1.4705063220631647E-2
+ || StrictMath.IEEEremainder(1.32, 89.765) >= 1.4705063220631649E-2);
+ }
+
+ /**
+ * java.lang.StrictMath#log(double)
+ */
+ public void test_logD() {
+ // Test for method double java.lang.StrictMath.log(double)
+ for (double d = 10; d >= -10; d -= 0.5) {
+ double answer = StrictMath.log(StrictMath.exp(d));
+ assertTrue("Answer does not equal expected answer for d = " + d
+ + " answer = " + answer,
+ StrictMath.abs(answer - d) <= StrictMath
+ .abs(d * 0.00000001));
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#log10(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_log10_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(StrictMath
+ .log10(Double.NaN)));
+ assertTrue("Should return NaN", Double.isNaN(StrictMath
+ .log10(-2541.05745687234187532)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .log10(Double.POSITIVE_INFINITY));
+ assertEquals("Should return NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath.log10(0.0));
+ assertEquals("Should return NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath.log10(+0.0));
+ assertEquals("Should return NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath.log10(-0.0));
+ assertEquals("Should return 14.0", 14.0, StrictMath.log10(StrictMath
+ .pow(10, 14)));
+
+ assertEquals("Should return 3.7389561269540406", 3.7389561269540406,
+ StrictMath.log10(5482.2158));
+ assertEquals("Should return 14.661551142893833", 14.661551142893833,
+ StrictMath.log10(458723662312872.125782332587));
+ assertEquals("Should return -0.9083828622192334", -0.9083828622192334,
+ StrictMath.log10(0.12348583358871));
+ assertEquals("Should return 308.25471555991675", 308.25471555991675,
+ StrictMath.log10(Double.MAX_VALUE));
+ assertEquals("Should return -323.3062153431158", -323.3062153431158,
+ StrictMath.log10(Double.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.StrictMath#log1p(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_log1p_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double.isNaN(StrictMath
+ .log1p(Double.NaN)));
+ assertTrue("Should return NaN", Double.isNaN(StrictMath
+ .log1p(-32.0482175)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .log1p(Double.POSITIVE_INFINITY));
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.log1p(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.log1p(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.log1p(-0.0)));
+
+ assertEquals("Should return -0.2941782295312541", -0.2941782295312541,
+ StrictMath.log1p(-0.254856327));
+ assertEquals("Should return 7.368050685564151", 7.368050685564151,
+ StrictMath.log1p(1583.542));
+ assertEquals("Should return 0.4633708685409921", 0.4633708685409921,
+ StrictMath.log1p(0.5894227));
+ assertEquals("Should return 709.782712893384", 709.782712893384,
+ StrictMath.log1p(Double.MAX_VALUE));
+ assertEquals("Should return Double.MIN_VALUE", Double.MIN_VALUE,
+ StrictMath.log1p(Double.MIN_VALUE));
+ }
+
+ /**
+ * java.lang.StrictMath#max(double, double)
+ */
+ public void test_maxDD() {
+ // Test for method double java.lang.StrictMath.max(double, double)
+ assertEquals("Incorrect double max value", 1908897.6000089, StrictMath.max(
+ -1908897.6000089, 1908897.6000089), 0D);
+ assertEquals("Incorrect double max value", 1908897.6000089, StrictMath.max(2.0,
+ 1908897.6000089), 0D);
+ assertEquals("Incorrect double max value", -2.0, StrictMath.max(-2.0,
+ -1908897.6000089), 0D);
+
+ }
+
+ /**
+ * java.lang.StrictMath#max(float, float)
+ */
+ public void test_maxFF() {
+ // Test for method float java.lang.StrictMath.max(float, float)
+ assertTrue("Incorrect float max value", StrictMath.max(-1908897.600f,
+ 1908897.600f) == 1908897.600f);
+ assertTrue("Incorrect float max value", StrictMath.max(2.0f,
+ 1908897.600f) == 1908897.600f);
+ assertTrue("Incorrect float max value", StrictMath.max(-2.0f,
+ -1908897.600f) == -2.0f);
+ }
+
+ /**
+ * java.lang.StrictMath#max(int, int)
+ */
+ public void test_maxII() {
+ // Test for method int java.lang.StrictMath.max(int, int)
+ assertEquals("Incorrect int max value", 19088976, StrictMath.max(-19088976,
+ 19088976));
+ assertEquals("Incorrect int max value",
+ 19088976, StrictMath.max(20, 19088976));
+ assertEquals("Incorrect int max value",
+ -20, StrictMath.max(-20, -19088976));
+ }
+
+ /**
+ * java.lang.StrictMath#max(long, long)
+ */
+ public void test_maxJJ() {
+ // Test for method long java.lang.StrictMath.max(long, long)
+ assertEquals("Incorrect long max value", 19088976000089L, StrictMath.max(-19088976000089L,
+ 19088976000089L));
+ assertEquals("Incorrect long max value", 19088976000089L, StrictMath.max(20,
+ 19088976000089L));
+ assertEquals("Incorrect long max value", -20, StrictMath.max(-20,
+ -19088976000089L));
+ }
+
+ /**
+ * java.lang.StrictMath#min(double, double)
+ */
+ public void test_minDD() {
+ // Test for method double java.lang.StrictMath.min(double, double)
+ assertEquals("Incorrect double min value", -1908897.6000089, StrictMath.min(
+ -1908897.6000089, 1908897.6000089), 0D);
+ assertEquals("Incorrect double min value", 2.0, StrictMath.min(2.0,
+ 1908897.6000089), 0D);
+ assertEquals("Incorrect double min value", -1908897.6000089, StrictMath.min(-2.0,
+ -1908897.6000089), 0D);
+ }
+
+ /**
+ * java.lang.StrictMath#min(float, float)
+ */
+ public void test_minFF() {
+ // Test for method float java.lang.StrictMath.min(float, float)
+ assertTrue("Incorrect float min value", StrictMath.min(-1908897.600f,
+ 1908897.600f) == -1908897.600f);
+ assertTrue("Incorrect float min value", StrictMath.min(2.0f,
+ 1908897.600f) == 2.0f);
+ assertTrue("Incorrect float min value", StrictMath.min(-2.0f,
+ -1908897.600f) == -1908897.600f);
+ }
+
+ /**
+ * java.lang.StrictMath#min(int, int)
+ */
+ public void test_minII() {
+ // Test for method int java.lang.StrictMath.min(int, int)
+ assertEquals("Incorrect int min value", -19088976, StrictMath.min(-19088976,
+ 19088976));
+ assertEquals("Incorrect int min value",
+ 20, StrictMath.min(20, 19088976));
+ assertEquals("Incorrect int min value",
+ -19088976, StrictMath.min(-20, -19088976));
+
+ }
+
+ /**
+ * java.lang.StrictMath#min(long, long)
+ */
+ public void test_minJJ() {
+ // Test for method long java.lang.StrictMath.min(long, long)
+ assertEquals("Incorrect long min value", -19088976000089L, StrictMath.min(-19088976000089L,
+ 19088976000089L));
+ assertEquals("Incorrect long min value", 20, StrictMath.min(20,
+ 19088976000089L));
+ assertEquals("Incorrect long min value", -19088976000089L, StrictMath.min(-20,
+ -19088976000089L));
+ }
+
+ /**
+ * {@link java.lang.StrictMath#nextAfter(double, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextAfter_DD() {
+ // test for most cases without exception
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ final double start = NEXTAFTER_DD_START_CASES[i][0];
+ final long nextUpBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][1]);
+ final long nextDownBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][2]);
+
+ for (int j = 0; j < NEXTAFTER_DD_FD_DIRECTION_CASES.length; j++) {
+ final double direction = NEXTAFTER_DD_FD_DIRECTION_CASES[j];
+ final long resultBits = Double.doubleToLongBits(StrictMath
+ .nextAfter(start, direction));
+ final long directionBits = Double.doubleToLongBits(direction);
+ if (direction > start) {
+ assertEquals("Result should be next up-number.",
+ nextUpBits, resultBits);
+ } else if (direction < start) {
+ assertEquals("Result should be next down-number.",
+ nextDownBits, resultBits);
+ } else {
+ assertEquals("Result should be direction.", directionBits,
+ resultBits);
+ }
+ }
+ }
+
+ // test for cases with NaN
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .nextAfter(NEXTAFTER_DD_START_CASES[i][0], Double.NaN)));
+ }
+ for (int i = 0; i < NEXTAFTER_DD_FD_DIRECTION_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .nextAfter(Double.NaN, NEXTAFTER_DD_FD_DIRECTION_CASES[i])));
+ }
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .nextAfter(Double.NaN, Double.NaN)));
+
+ // test for exception
+ try {
+ StrictMath.nextAfter((Double) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.nextAfter(2.3, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.nextAfter((Double) null, (Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StrictMath#nextAfter(float, double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextAfter_FD() {
+ // test for most cases without exception
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ final float start = NEXTAFTER_FD_START_CASES[i][0];
+ final int nextUpBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][1]);
+ final int nextDownBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][2]);
+
+ for (int j = 0; j < NEXTAFTER_DD_FD_DIRECTION_CASES.length; j++) {
+ final double direction = NEXTAFTER_DD_FD_DIRECTION_CASES[j];
+ final int resultBits = Float.floatToIntBits(StrictMath
+ .nextAfter(start, direction));
+ if (direction > start) {
+ assertEquals("Result should be next up-number.",
+ nextUpBits, resultBits);
+ } else if (direction < start) {
+ assertEquals("Result should be next down-number.",
+ nextDownBits, resultBits);
+ } else {
+ final int equivalentBits = Float.floatToIntBits(new Float(
+ direction));
+ assertEquals(
+ "Result should be a number equivalent to direction.",
+ equivalentBits, resultBits);
+ }
+ }
+ }
+
+ // test for cases with NaN
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .nextAfter(NEXTAFTER_FD_START_CASES[i][0], Float.NaN)));
+ }
+ for (int i = 0; i < NEXTAFTER_DD_FD_DIRECTION_CASES.length; i++) {
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .nextAfter(Float.NaN, NEXTAFTER_DD_FD_DIRECTION_CASES[i])));
+ }
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .nextAfter(Float.NaN, Float.NaN)));
+
+ // test for exception
+ try {
+ StrictMath.nextAfter((Float) null, 2.3);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.nextAfter(2.3, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.nextAfter((Float) null, (Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StrictMath#nextUp(double)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextUp_D() {
+ // This method is semantically equivalent to nextAfter(d,
+ // Double.POSITIVE_INFINITY),
+ // so we use the data of test_nextAfter_DD
+ for (int i = 0; i < NEXTAFTER_DD_START_CASES.length; i++) {
+ final double start = NEXTAFTER_DD_START_CASES[i][0];
+ final long nextUpBits = Double
+ .doubleToLongBits(NEXTAFTER_DD_START_CASES[i][1]);
+ final long resultBits = Double.doubleToLongBits(StrictMath
+ .nextUp(start));
+ assertEquals("Result should be next up-number.", nextUpBits,
+ resultBits);
+ }
+
+ // test for cases with NaN
+ assertTrue("The result should be NaN.", Double.isNaN(StrictMath
+ .nextUp(Double.NaN)));
+
+ // test for exception
+ try {
+ StrictMath.nextUp((Double) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StrictMath#nextUp(float)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_nextUp_F() {
+ // This method is semantically equivalent to nextAfter(f,
+ // Float.POSITIVE_INFINITY),
+ // so we use the data of test_nextAfter_FD
+ for (int i = 0; i < NEXTAFTER_FD_START_CASES.length; i++) {
+ final float start = NEXTAFTER_FD_START_CASES[i][0];
+ final int nextUpBits = Float
+ .floatToIntBits(NEXTAFTER_FD_START_CASES[i][1]);
+ final int resultBits = Float.floatToIntBits(StrictMath
+ .nextUp(start));
+ assertEquals("Result should be next up-number.", nextUpBits,
+ resultBits);
+ }
+
+ // test for cases with NaN
+ assertTrue("The result should be NaN.", Float.isNaN(StrictMath
+ .nextUp(Float.NaN)));
+
+ // test for exception
+ try {
+ StrictMath.nextUp((Float) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#pow(double, double)
+ */
+ public void test_powDD() {
+ // Test for method double java.lang.StrictMath.pow(double, double)
+ assertTrue("pow returned incorrect value",
+ (long) StrictMath.pow(2, 8) == 256l);
+ assertTrue("pow returned incorrect value",
+ StrictMath.pow(2, -8) == 0.00390625d);
+ }
+
+ /**
+ * java.lang.StrictMath#rint(double)
+ */
+ public void test_rintD() {
+ // Test for method double java.lang.StrictMath.rint(double)
+ assertEquals("Failed to round properly - up to odd",
+ 3.0, StrictMath.rint(2.9), 0D);
+ assertTrue("Failed to round properly - NaN", Double.isNaN(StrictMath
+ .rint(Double.NaN)));
+ assertEquals("Failed to round properly down to even", 2.0, StrictMath
+ .rint(2.1), 0D);
+ assertTrue("Failed to round properly " + 2.5 + " to even", StrictMath
+ .rint(2.5) == 2.0);
+ }
+
+ /**
+ * java.lang.StrictMath#round(double)
+ */
+ public void test_roundD() {
+ // Test for method long java.lang.StrictMath.round(double)
+ assertEquals("Incorrect rounding of a float",
+ -91, StrictMath.round(-90.89d));
+ }
+
+ /**
+ * java.lang.StrictMath#round(float)
+ */
+ public void test_roundF() {
+ // Test for method int java.lang.StrictMath.round(float)
+ assertEquals("Incorrect rounding of a float",
+ -91, StrictMath.round(-90.89f));
+ }
+
+ /**
+ * {@link java.lang.StrictMath#scalb(double, int)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_scalb_DI() {
+ // result is normal
+ assertEquals(4.1422946304E7, StrictMath.scalb(1.2345, 25));
+ assertEquals(3.679096698760986E-8, StrictMath.scalb(1.2345, -25));
+ assertEquals(1.2345, StrictMath.scalb(1.2345, 0));
+ assertEquals(7868514.304, StrictMath.scalb(0.2345, 25));
+
+ double normal = StrictMath.scalb(0.2345, -25);
+ assertEquals(6.98864459991455E-9, normal);
+ // precision kept
+ assertEquals(0.2345, StrictMath.scalb(normal, 25));
+
+ assertEquals(0.2345, StrictMath.scalb(0.2345, 0));
+ assertEquals(-4.1422946304E7, StrictMath.scalb(-1.2345, 25));
+ assertEquals(-6.98864459991455E-9, StrictMath.scalb(-0.2345, -25));
+ assertEquals(2.0, StrictMath.scalb(Double.MIN_NORMAL / 2, 1024));
+ assertEquals(64.0, StrictMath.scalb(Double.MIN_VALUE, 1080));
+ assertEquals(234, StrictMath.getExponent(StrictMath.scalb(1.0, 234)));
+ assertEquals(3.9999999999999996, StrictMath.scalb(Double.MAX_VALUE,
+ Double.MIN_EXPONENT));
+
+ // result is near infinity
+ double halfMax = StrictMath.scalb(1.0, Double.MAX_EXPONENT);
+ assertEquals(8.98846567431158E307, halfMax);
+ assertEquals(Double.MAX_VALUE, halfMax - StrictMath.ulp(halfMax)
+ + halfMax);
+ assertEquals(Double.POSITIVE_INFINITY, halfMax + halfMax);
+ assertEquals(1.7976931348623155E308, StrictMath.scalb(1.0 - StrictMath
+ .ulp(1.0), Double.MAX_EXPONENT + 1));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ 1.0 - StrictMath.ulp(1.0), Double.MAX_EXPONENT + 2));
+
+ halfMax = StrictMath.scalb(-1.0, Double.MAX_EXPONENT);
+ assertEquals(-8.98846567431158E307, halfMax);
+ assertEquals(-Double.MAX_VALUE, halfMax + StrictMath.ulp(halfMax)
+ + halfMax);
+ assertEquals(Double.NEGATIVE_INFINITY, halfMax + halfMax);
+
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(0.345, 1234));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath
+ .scalb(44.345E102, 934));
+ assertEquals(Double.NEGATIVE_INFINITY, StrictMath.scalb(-44.345E102,
+ 934));
+
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ Double.MIN_NORMAL / 2, 4000));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ Double.MIN_VALUE, 8000));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ Double.MAX_VALUE, 1));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ Double.POSITIVE_INFINITY, 0));
+ assertEquals(Double.POSITIVE_INFINITY, StrictMath.scalb(
+ Double.POSITIVE_INFINITY, -1));
+ assertEquals(Double.NEGATIVE_INFINITY, StrictMath.scalb(
+ Double.NEGATIVE_INFINITY, -1));
+ assertEquals(Double.NEGATIVE_INFINITY, StrictMath.scalb(
+ Double.NEGATIVE_INFINITY, Double.MIN_EXPONENT));
+
+ // result is subnormal/zero
+ long posZeroBits = Double.doubleToLongBits(+0.0);
+ long negZeroBits = Double.doubleToLongBits(-0.0);
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ +0.0, Integer.MAX_VALUE)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ +0.0, -123)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ +0.0, 0)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -0.0, 123)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -0.0, Integer.MIN_VALUE)));
+
+ assertEquals(Double.MIN_VALUE, StrictMath.scalb(1.0, -1074));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(1.0,
+ -1075)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -1.0, -1075)));
+
+ // precision lost
+ assertEquals(StrictMath.scalb(21.405, -1078), StrictMath.scalb(21.405,
+ -1079));
+ assertEquals(Double.MIN_VALUE, StrictMath.scalb(21.405, -1079));
+ assertEquals(-Double.MIN_VALUE, StrictMath.scalb(-21.405, -1079));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ 21.405, -1080)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -21.405, -1080)));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ Double.MIN_VALUE, -1)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -Double.MIN_VALUE, -1)));
+ assertEquals(Double.MIN_VALUE, StrictMath.scalb(Double.MIN_NORMAL, -52));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ Double.MIN_NORMAL, -53)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -Double.MIN_NORMAL, -53)));
+ assertEquals(Double.MIN_VALUE, StrictMath
+ .scalb(Double.MAX_VALUE, -2098));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ Double.MAX_VALUE, -2099)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -Double.MAX_VALUE, -2099)));
+ assertEquals(Double.MIN_VALUE, StrictMath.scalb(Double.MIN_NORMAL / 3,
+ -51));
+ assertEquals(posZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ Double.MIN_NORMAL / 3, -52)));
+ assertEquals(negZeroBits, Double.doubleToLongBits(StrictMath.scalb(
+ -Double.MIN_NORMAL / 3, -52)));
+ double subnormal = StrictMath.scalb(Double.MIN_NORMAL / 3, -25);
+ assertEquals(2.2104123E-316, subnormal);
+ // precision lost
+ assertFalse(Double.MIN_NORMAL / 3 == StrictMath.scalb(subnormal, 25));
+
+ // NaN
+ assertTrue(Double.isNaN(StrictMath.scalb(Double.NaN, 1)));
+ assertTrue(Double.isNaN(StrictMath.scalb(Double.NaN, 0)));
+ assertTrue(Double.isNaN(StrictMath.scalb(Double.NaN, -120)));
+
+ assertEquals(1283457024, Double.doubleToLongBits(StrictMath.scalb(
+ Double.MIN_VALUE * 153, 23)));
+ assertEquals(-9223372035571318784L, Double.doubleToLongBits(StrictMath
+ .scalb(-Double.MIN_VALUE * 153, 23)));
+ assertEquals(36908406321184768L, Double.doubleToLongBits(StrictMath
+ .scalb(Double.MIN_VALUE * 153, 52)));
+ assertEquals(-9186463630533591040L, Double.doubleToLongBits(StrictMath
+ .scalb(-Double.MIN_VALUE * 153, 52)));
+
+ // test for exception
+ try {
+ StrictMath.scalb((Double) null, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.scalb(1.0, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.scalb((Double) null, 1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StrictMath#scalb(float, int)}
+ * @since 1.6
+ */
+ @SuppressWarnings("boxing")
+ public void test_scalb_FI() {
+ // result is normal
+ assertEquals(4.1422946304E7f, StrictMath.scalb(1.2345f, 25));
+ assertEquals(3.679096698760986E-8f, StrictMath.scalb(1.2345f, -25));
+ assertEquals(1.2345f, StrictMath.scalb(1.2345f, 0));
+ assertEquals(7868514.304f, StrictMath.scalb(0.2345f, 25));
+
+ float normal = StrictMath.scalb(0.2345f, -25);
+ assertEquals(6.98864459991455E-9f, normal);
+ // precision kept
+ assertEquals(0.2345f, StrictMath.scalb(normal, 25));
+
+ assertEquals(0.2345f, StrictMath.scalb(0.2345f, 0));
+ assertEquals(-4.1422946304E7f, StrictMath.scalb(-1.2345f, 25));
+ assertEquals(-6.98864459991455E-9f, StrictMath.scalb(-0.2345f, -25));
+ assertEquals(2.0f, StrictMath.scalb(Float.MIN_NORMAL / 2, 128));
+ assertEquals(64.0f, StrictMath.scalb(Float.MIN_VALUE, 155));
+ assertEquals(34, StrictMath.getExponent(StrictMath.scalb(1.0f, 34)));
+ assertEquals(3.9999998f, StrictMath.scalb(Float.MAX_VALUE,
+ Float.MIN_EXPONENT));
+
+ // result is near infinity
+ float halfMax = StrictMath.scalb(1.0f, Float.MAX_EXPONENT);
+ assertEquals(1.7014118E38f, halfMax);
+ assertEquals(Float.MAX_VALUE, halfMax - StrictMath.ulp(halfMax)
+ + halfMax);
+ assertEquals(Float.POSITIVE_INFINITY, halfMax + halfMax);
+ assertEquals(3.4028233E38f, StrictMath.scalb(1.0f - StrictMath
+ .ulp(1.0f), Float.MAX_EXPONENT + 1));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(
+ 1.0f - StrictMath.ulp(1.0f), Float.MAX_EXPONENT + 2));
+
+ halfMax = StrictMath.scalb(-1.0f, Float.MAX_EXPONENT);
+ assertEquals(-1.7014118E38f, halfMax);
+ assertEquals(-Float.MAX_VALUE, halfMax + StrictMath.ulp(halfMax)
+ + halfMax);
+ assertEquals(Float.NEGATIVE_INFINITY, halfMax + halfMax);
+
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(0.345f, 1234));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(44.345E10f, 934));
+ assertEquals(Float.NEGATIVE_INFINITY, StrictMath
+ .scalb(-44.345E10f, 934));
+
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(
+ Float.MIN_NORMAL / 2, 400));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(Float.MIN_VALUE,
+ 800));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(Float.MAX_VALUE,
+ 1));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(
+ Float.POSITIVE_INFINITY, 0));
+ assertEquals(Float.POSITIVE_INFINITY, StrictMath.scalb(
+ Float.POSITIVE_INFINITY, -1));
+ assertEquals(Float.NEGATIVE_INFINITY, StrictMath.scalb(
+ Float.NEGATIVE_INFINITY, -1));
+ assertEquals(Float.NEGATIVE_INFINITY, StrictMath.scalb(
+ Float.NEGATIVE_INFINITY, Float.MIN_EXPONENT));
+
+ // result is subnormal/zero
+ int posZeroBits = Float.floatToIntBits(+0.0f);
+ int negZeroBits = Float.floatToIntBits(-0.0f);
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(+0.0f,
+ Integer.MAX_VALUE)));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(+0.0f,
+ -123)));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(+0.0f,
+ 0)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(-0.0f,
+ 123)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(-0.0f,
+ Integer.MIN_VALUE)));
+
+ assertEquals(Float.MIN_VALUE, StrictMath.scalb(1.0f, -149));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(1.0f,
+ -150)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(-1.0f,
+ -150)));
+
+ // precision lost
+ assertEquals(StrictMath.scalb(21.405f, -154), StrictMath.scalb(21.405f,
+ -153));
+ assertEquals(Float.MIN_VALUE, StrictMath.scalb(21.405f, -154));
+ assertEquals(-Float.MIN_VALUE, StrictMath.scalb(-21.405f, -154));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ 21.405f, -155)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ -21.405f, -155)));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ Float.MIN_VALUE, -1)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MIN_VALUE, -1)));
+ assertEquals(Float.MIN_VALUE, StrictMath.scalb(Float.MIN_NORMAL, -23));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ Float.MIN_NORMAL, -24)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MIN_NORMAL, -24)));
+ assertEquals(Float.MIN_VALUE, StrictMath.scalb(Float.MAX_VALUE, -277));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ Float.MAX_VALUE, -278)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MAX_VALUE, -278)));
+ assertEquals(Float.MIN_VALUE, StrictMath.scalb(Float.MIN_NORMAL / 3,
+ -22));
+ assertEquals(posZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ Float.MIN_NORMAL / 3, -23)));
+ assertEquals(negZeroBits, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MIN_NORMAL / 3, -23)));
+ float subnormal = StrictMath.scalb(Float.MIN_NORMAL / 3, -11);
+ assertEquals(1.913E-42f, subnormal);
+ // precision lost
+ assertFalse(Float.MIN_NORMAL / 3 == StrictMath.scalb(subnormal, 11));
+
+ assertEquals(68747264, Float.floatToIntBits(StrictMath.scalb(
+ Float.MIN_VALUE * 153, 23)));
+ assertEquals(-2078736384, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MIN_VALUE * 153, 23)));
+
+ assertEquals(4896, Float.floatToIntBits(StrictMath.scalb(
+ Float.MIN_VALUE * 153, 5)));
+ assertEquals(-2147478752, Float.floatToIntBits(StrictMath.scalb(
+ -Float.MIN_VALUE * 153, 5)));
+
+ // NaN
+ assertTrue(Float.isNaN(StrictMath.scalb(Float.NaN, 1)));
+ assertTrue(Float.isNaN(StrictMath.scalb(Float.NaN, 0)));
+ assertTrue(Float.isNaN(StrictMath.scalb(Float.NaN, -120)));
+
+ // test for exception
+ try {
+ StrictMath.scalb((Float) null, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.scalb(1.0f, (Integer) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ StrictMath.scalb((Float) null, 1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#signum(double)
+ */
+ public void test_signum_D() {
+ assertTrue(Double.isNaN(StrictMath.signum(Double.NaN)));
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.signum(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.signum(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.signum(-0.0)));
+
+ assertEquals(1.0, StrictMath.signum(253681.2187962), 0D);
+ assertEquals(-1.0, StrictMath.signum(-125874693.56), 0D);
+ assertEquals(1.0, StrictMath.signum(1.2587E-308), 0D);
+ assertEquals(-1.0, StrictMath.signum(-1.2587E-308), 0D);
+
+ assertEquals(1.0, StrictMath.signum(Double.MAX_VALUE), 0D);
+ assertEquals(1.0, StrictMath.signum(Double.MIN_VALUE), 0D);
+ assertEquals(-1.0, StrictMath.signum(-Double.MAX_VALUE), 0D);
+ assertEquals(-1.0, StrictMath.signum(-Double.MIN_VALUE), 0D);
+ assertEquals(1.0, StrictMath.signum(Double.POSITIVE_INFINITY), 0D);
+ assertEquals(-1.0, StrictMath.signum(Double.NEGATIVE_INFINITY), 0D);
+
+ }
+
+ /**
+ * java.lang.StrictMath#signum(float)
+ */
+ public void test_signum_F() {
+ assertTrue(Float.isNaN(StrictMath.signum(Float.NaN)));
+ assertEquals(Float.floatToIntBits(0.0f), Float
+ .floatToIntBits(StrictMath.signum(0.0f)));
+ assertEquals(Float.floatToIntBits(+0.0f), Float
+ .floatToIntBits(StrictMath.signum(+0.0f)));
+ assertEquals(Float.floatToIntBits(-0.0f), Float
+ .floatToIntBits(StrictMath.signum(-0.0f)));
+
+ assertEquals(1.0f, StrictMath.signum(253681.2187962f), 0f);
+ assertEquals(-1.0f, StrictMath.signum(-125874693.56f), 0f);
+ assertEquals(1.0f, StrictMath.signum(1.2587E-11f), 0f);
+ assertEquals(-1.0f, StrictMath.signum(-1.2587E-11f), 0f);
+
+ assertEquals(1.0f, StrictMath.signum(Float.MAX_VALUE), 0f);
+ assertEquals(1.0f, StrictMath.signum(Float.MIN_VALUE), 0f);
+ assertEquals(-1.0f, StrictMath.signum(-Float.MAX_VALUE), 0f);
+ assertEquals(-1.0f, StrictMath.signum(-Float.MIN_VALUE), 0f);
+ assertEquals(1.0f, StrictMath.signum(Float.POSITIVE_INFINITY), 0f);
+ assertEquals(-1.0f, StrictMath.signum(Float.NEGATIVE_INFINITY), 0f);
+ }
+
+ /**
+ * java.lang.StrictMath#sin(double)
+ */
+ public void test_sinD() {
+ // Test for method double java.lang.StrictMath.sin(double)
+ assertTrue("Returned incorrect sine", StrictMath.sin(StrictMath
+ .asin(OPP / HYP)) == OPP / HYP);
+ }
+
+ /**
+ * java.lang.StrictMath#sinh(double)
+ */
+ public void test_sinh_D() {
+ // Test for special situations
+ assertTrue(Double.isNaN(StrictMath.sinh(Double.NaN)));
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath
+ .sinh(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath
+ .sinh(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.sinh(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.sinh(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.sinh(-0.0)));
+
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.sinh(1234.56), 0D);
+ assertEquals("Should return NEGATIVE_INFINITY",
+ Double.NEGATIVE_INFINITY, StrictMath.sinh(-1234.56), 0D);
+ assertEquals("Should return 1.0000000000001666E-6",
+ 1.0000000000001666E-6, StrictMath.sinh(0.000001), 0D);
+ assertEquals("Should return -1.0000000000001666E-6",
+ -1.0000000000001666E-6, StrictMath.sinh(-0.000001), 0D);
+ assertEquals("Should return 5.115386441963859", 5.115386441963859,
+ StrictMath.sinh(2.33482), 0D);
+ assertEquals("Should return POSITIVE_INFINITY",
+ Double.POSITIVE_INFINITY, StrictMath.sinh(Double.MAX_VALUE), 0D);
+ assertEquals("Should return 4.9E-324", 4.9E-324, StrictMath
+ .sinh(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.StrictMath#sqrt(double)
+ */
+ public void test_sqrtD() {
+ // Test for method double java.lang.StrictMath.sqrt(double)
+ assertEquals("Incorrect root returned1",
+ 2, StrictMath.sqrt(StrictMath.pow(StrictMath.sqrt(2), 4)), 0.0);
+ assertEquals("Incorrect root returned2", 7, StrictMath.sqrt(49), 0.0);
+ }
+
+ /**
+ * java.lang.StrictMath#tan(double)
+ */
+ public void test_tanD() {
+ // Test for method double java.lang.StrictMath.tan(double)
+ assertTrue(
+ "Returned incorrect tangent: ",
+ StrictMath.tan(StrictMath.atan(1.0)) <= 1.0
+ || StrictMath.tan(StrictMath.atan(1.0)) >= 9.9999999999999983E-1);
+ }
+
+ /**
+ * java.lang.StrictMath#tanh(double)
+ */
+ public void test_tanh_D() {
+ // Test for special situations
+ assertTrue(Double.isNaN(StrictMath.tanh(Double.NaN)));
+ assertEquals("Should return +1.0", +1.0, StrictMath
+ .tanh(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Should return -1.0", -1.0, StrictMath
+ .tanh(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals(Double.doubleToLongBits(0.0), Double
+ .doubleToLongBits(StrictMath.tanh(0.0)));
+ assertEquals(Double.doubleToLongBits(+0.0), Double
+ .doubleToLongBits(StrictMath.tanh(+0.0)));
+ assertEquals(Double.doubleToLongBits(-0.0), Double
+ .doubleToLongBits(StrictMath.tanh(-0.0)));
+
+ assertEquals("Should return 1.0", 1.0, StrictMath.tanh(1234.56), 0D);
+ assertEquals("Should return -1.0", -1.0, StrictMath.tanh(-1234.56), 0D);
+ assertEquals("Should return 9.999999999996666E-7",
+ 9.999999999996666E-7, StrictMath.tanh(0.000001), 0D);
+ assertEquals("Should return 0.981422884124941", 0.981422884124941,
+ StrictMath.tanh(2.33482), 0D);
+ assertEquals("Should return 1.0", 1.0, StrictMath
+ .tanh(Double.MAX_VALUE), 0D);
+ assertEquals("Should return 4.9E-324", 4.9E-324, StrictMath
+ .tanh(Double.MIN_VALUE), 0D);
+ }
+
+ /**
+ * java.lang.StrictMath#random()
+ */
+ public void test_random() {
+ // There isn't a place for these tests so just stick them here
+ assertEquals("Wrong value E",
+ 4613303445314885481L, Double.doubleToLongBits(StrictMath.E));
+ assertEquals("Wrong value PI",
+ 4614256656552045848L, Double.doubleToLongBits(StrictMath.PI));
+
+ for (int i = 500; i >= 0; i--) {
+ double d = StrictMath.random();
+ assertTrue("Generated number is out of range: " + d, d >= 0.0
+ && d < 1.0);
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#toRadians(double)
+ */
+ public void test_toRadiansD() {
+ for (double d = 500; d >= 0; d -= 1.0) {
+ double converted = StrictMath.toDegrees(StrictMath.toRadians(d));
+ assertTrue("Converted number not equal to original. d = " + d,
+ converted >= d * 0.99999999 && converted <= d * 1.00000001);
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#toDegrees(double)
+ */
+ public void test_toDegreesD() {
+ for (double d = 500; d >= 0; d -= 1.0) {
+ double converted = StrictMath.toRadians(StrictMath.toDegrees(d));
+ assertTrue("Converted number not equal to original. d = " + d,
+ converted >= d * 0.99999999 && converted <= d * 1.00000001);
+ }
+ }
+
+ /**
+ * java.lang.StrictMath#ulp(double)
+ */
+ @SuppressWarnings("boxing")
+ public void test_ulp_D() {
+ // Test for special cases
+ assertTrue("Should return NaN", Double
+ .isNaN(StrictMath.ulp(Double.NaN)));
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY,
+ StrictMath.ulp(Double.POSITIVE_INFINITY), 0D);
+ assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY,
+ StrictMath.ulp(Double.NEGATIVE_INFINITY), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
+ .ulp(0.0), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
+ .ulp(+0.0), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
+ .ulp(-0.0), 0D);
+ assertEquals("Returned incorrect value", StrictMath.pow(2, 971),
+ StrictMath.ulp(Double.MAX_VALUE), 0D);
+ assertEquals("Returned incorrect value", StrictMath.pow(2, 971),
+ StrictMath.ulp(-Double.MAX_VALUE), 0D);
+
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
+ .ulp(Double.MIN_VALUE), 0D);
+ assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
+ .ulp(-Double.MIN_VALUE), 0D);
+
+ assertEquals("Returned incorrect value", 2.220446049250313E-16,
+ StrictMath.ulp(1.0), 0D);
+ assertEquals("Returned incorrect value", 2.220446049250313E-16,
+ StrictMath.ulp(-1.0), 0D);
+ assertEquals("Returned incorrect value", 2.2737367544323206E-13,
+ StrictMath.ulp(1153.0), 0D);
+ }
+
+ /**
+ * java.lang.StrictMath#ulp(float)
+ */
+ @SuppressWarnings("boxing")
+ public void test_ulp_f() {
+ // Test for special cases
+ assertTrue("Should return NaN", Float.isNaN(StrictMath.ulp(Float.NaN)));
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY,
+ StrictMath.ulp(Float.POSITIVE_INFINITY), 0f);
+ assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY,
+ StrictMath.ulp(Float.NEGATIVE_INFINITY), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
+ .ulp(0.0f), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
+ .ulp(+0.0f), 0f);
+ assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
+ .ulp(-0.0f), 0f);
+ assertEquals("Returned incorrect value", 2.028241E31f, StrictMath
+ .ulp(Float.MAX_VALUE), 0f);
+ assertEquals("Returned incorrect value", 2.028241E31f, StrictMath
+ .ulp(-Float.MAX_VALUE), 0f);
+
+ assertEquals("Returned incorrect value", 1.4E-45f, StrictMath
+ .ulp(Float.MIN_VALUE), 0f);
+ assertEquals("Returned incorrect value", 1.4E-45f, StrictMath
+ .ulp(-Float.MIN_VALUE), 0f);
+
+ assertEquals("Returned incorrect value", 1.1920929E-7f, StrictMath
+ .ulp(1.0f), 0f);
+ assertEquals("Returned incorrect value", 1.1920929E-7f, StrictMath
+ .ulp(-1.0f), 0f);
+ assertEquals("Returned incorrect value", 1.2207031E-4f, StrictMath
+ .ulp(1153.0f), 0f);
+ assertEquals("Returned incorrect value", 5.6E-45f, Math
+ .ulp(9.403954E-38f), 0f);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/String2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/String2Test.java
new file mode 100644
index 0000000..eecc601
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/String2Test.java
@@ -0,0 +1,978 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Locale;
+
+public class String2Test extends junit.framework.TestCase {
+
+ String hw1 = "HelloWorld";
+
+ String hw2 = "HelloWorld";
+
+ String hwlc = "helloworld";
+
+ String hwuc = "HELLOWORLD";
+
+ String hello1 = "Hello";
+
+ String world1 = "World";
+
+ String comp11 = "Test String";
+
+ Object obj = new Object();
+
+ char[] buf = { 'W', 'o', 'r', 'l', 'd' };
+
+ char[] rbuf = new char[5];
+
+ /**
+ * java.lang.String#String()
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.String()
+ assertTrue("Created incorrect string", new String().equals(""));
+ }
+
+ /**
+ * java.lang.String#String(byte[])
+ */
+ public void test_Constructor$B() {
+ // Test for method java.lang.String(byte [])
+ assertTrue("Failed to create string", new String(hw1.getBytes())
+ .equals(hw1));
+ }
+
+ /**
+ * java.lang.String#String(byte[], int)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_Constructor$BI() {
+ // Test for method java.lang.String(byte [], int)
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0);
+ assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1);
+ assertTrue("Did not use nonzero hibyte", !s.equals("ABCDE"));
+ }
+
+ /**
+ * java.lang.String#String(byte[], int, int)
+ */
+ public void test_Constructor$BII() {
+ // Test for method java.lang.String(byte [], int, int)
+ assertTrue("Failed to create string", new String(hw1.getBytes(), 0, hw1
+ .getBytes().length).equals(hw1));
+
+ boolean exception = false;
+ try {
+ new String(new byte[0], 0, Integer.MAX_VALUE);
+ } catch (IndexOutOfBoundsException e) {
+ exception = true;
+ }
+ assertTrue("Did not throw exception", exception);
+ }
+
+ /**
+ * java.lang.String#String(byte[], int, int, int)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_Constructor$BIII() {
+ // Test for method java.lang.String(byte [], int, int, int)
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 1, 3);
+ assertTrue("Incorrect string returned: " + s, s.equals("BCD"));
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1, 0, 5);
+ assertTrue("Did not use nonzero hibyte", !s.equals("ABCDE"));
+ }
+
+ /**
+ * java.lang.String#String(byte[], int, int, java.lang.String)
+ */
+ public void test_Constructor$BIILjava_lang_String() throws Exception {
+ // Test for method java.lang.String(byte [], int, int, java.lang.String)
+ String s = null;
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "8859_1");
+ assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
+ // Regression for HARMONY-1111
+ assertNotNull(new String(new byte[] { (byte) 0xC0 }, 0, 1, "UTF-8"));
+ }
+
+ /**
+ * java.lang.String#String(byte[], java.lang.String)
+ */
+ public void test_Constructor$BLjava_lang_String() throws Exception {
+ // Test for method java.lang.String(byte [], java.lang.String)
+ String s = null;
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, "8859_1");
+ assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
+ }
+
+ /**
+ * java.lang.String#String(char[])
+ */
+ public void test_Constructor$C() {
+ // Test for method java.lang.String(char [])
+ assertEquals("Failed Constructor test", "World", new String(buf));
+ }
+
+ /**
+ * java.lang.String#String(char[], int, int)
+ */
+ public void test_Constructor$CII() {
+ // Test for method java.lang.String(char [], int, int)
+ char[] buf = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+ String s = new String(buf, 0, buf.length);
+ assertTrue("Incorrect string created", hw1.equals(s));
+
+ boolean exception = false;
+ try {
+ new String(new char[0], 0, Integer.MAX_VALUE);
+ } catch (IndexOutOfBoundsException e) {
+ exception = true;
+ }
+ assertTrue("Did not throw exception", exception);
+ }
+
+ /**
+ * java.lang.String#String(int[], int, int)
+ */
+ public void test_Constructor$III() {
+ // Test for method java.lang.String(int [], int, int)
+ try {
+ new String(new int[0], 2, Integer.MAX_VALUE);
+ fail("Did not throw exception");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.String#String(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.lang.String(java.lang.String)
+ String s = new String("Hello World");
+ assertEquals("Failed to construct correct string", "Hello World", s);
+ }
+
+ /**
+ * java.lang.String#String(java.lang.StringBuffer)
+ */
+ public void test_ConstructorLjava_lang_StringBuffer() {
+ // Test for method java.lang.String(java.lang.StringBuffer)
+ StringBuffer sb = new StringBuffer();
+ sb.append("HelloWorld");
+ assertEquals("Created incorrect string", "HelloWorld", new String(sb));
+ }
+
+ /**
+ * java.lang.String#charAt(int)
+ */
+ public void test_charAtI() {
+ // Test for method char java.lang.String.charAt(int)
+ assertTrue("Incorrect character returned", hw1.charAt(5) == 'W'
+ && (hw1.charAt(1) != 'Z'));
+ }
+
+ /**
+ * java.lang.String#compareTo(java.lang.String)
+ */
+ public void test_compareToLjava_lang_String() {
+ // Test for method int java.lang.String.compareTo(java.lang.String)
+ assertTrue("Returned incorrect value for first < second", "aaaaab"
+ .compareTo("aaaaac") < 0);
+ assertEquals("Returned incorrect value for first = second", 0, "aaaaac"
+ .compareTo("aaaaac"));
+ assertTrue("Returned incorrect value for first > second", "aaaaac"
+ .compareTo("aaaaab") > 0);
+ assertTrue("Considered case to not be of importance", !("A"
+ .compareTo("a") == 0));
+
+ try {
+ "fixture".compareTo(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.String#compareToIgnoreCase(java.lang.String)
+ */
+ public void test_compareToIgnoreCaseLjava_lang_String() {
+ // Test for method int
+ // java.lang.String.compareToIgnoreCase(java.lang.String)
+ assertTrue("Returned incorrect value for first < second", "aaaaab"
+ .compareToIgnoreCase("aaaaac") < 0);
+ assertEquals("Returned incorrect value for first = second", 0, "aaaaac"
+ .compareToIgnoreCase("aaaaac"));
+ assertTrue("Returned incorrect value for first > second", "aaaaac"
+ .compareToIgnoreCase("aaaaab") > 0);
+ assertEquals("Considered case to not be of importance", 0, "A"
+ .compareToIgnoreCase("a"));
+
+ assertTrue("0xbf should not compare = to 'ss'", "\u00df"
+ .compareToIgnoreCase("ss") != 0);
+ assertEquals("0x130 should compare = to 'i'", 0, "\u0130"
+ .compareToIgnoreCase("i"));
+ assertEquals("0x131 should compare = to 'i'", 0, "\u0131"
+ .compareToIgnoreCase("i"));
+
+ Locale defLocale = Locale.getDefault();
+ try {
+ Locale.setDefault(new Locale("tr", ""));
+ assertEquals("Locale tr: 0x130 should compare = to 'i'", 0,
+ "\u0130".compareToIgnoreCase("i"));
+ assertEquals("Locale tr: 0x131 should compare = to 'i'", 0,
+ "\u0131".compareToIgnoreCase("i"));
+ } finally {
+ Locale.setDefault(defLocale);
+ }
+
+ try {
+ "fixture".compareToIgnoreCase(null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.lang.String#concat(java.lang.String)
+ */
+ public void test_concatLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.lang.String.concat(java.lang.String)
+ assertTrue("Concatenation failed to produce correct string", hello1
+ .concat(world1).equals(hw1));
+ boolean exception = false;
+ try {
+ String a = new String("test");
+ String b = null;
+ a.concat(b);
+ } catch (NullPointerException e) {
+ exception = true;
+ }
+ assertTrue("Concatenation failed to throw NP exception (1)", exception);
+ exception = false;
+ try {
+ String a = new String("");
+ String b = null;
+ a.concat(b);
+ } catch (NullPointerException e) {
+ exception = true;
+ }
+ assertTrue("Concatenation failed to throw NP exception (2)", exception);
+
+ String s1 = "";
+ String s2 = "s2";
+ String s3 = s1.concat(s2);
+ assertEquals(s2, s3);
+ // The RI returns a new string even when it's the same as the argument string.
+ // assertNotSame(s2, s3);
+ s3 = s2.concat(s1);
+ assertEquals(s2, s3);
+ // Neither Android nor the RI returns a new string when it's the same as *this*.
+ // assertNotSame(s2, s3);
+
+ s3 = s2.concat(s1);
+ assertSame(s2, s3);
+ }
+
+ /**
+ * java.lang.String#copyValueOf(char[])
+ */
+ public void test_copyValueOf$C() {
+ // Test for method java.lang.String java.lang.String.copyValueOf(char
+ // [])
+ char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+ assertEquals("copyValueOf returned incorrect String", "HelloWorld",
+ String.copyValueOf(t));
+ }
+
+ /**
+ * java.lang.String#copyValueOf(char[], int, int)
+ */
+ public void test_copyValueOf$CII() {
+ // Test for method java.lang.String java.lang.String.copyValueOf(char
+ // [], int, int)
+ char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+ assertEquals("copyValueOf returned incorrect String", "World", String
+ .copyValueOf(t, 5, 5));
+ }
+
+ /**
+ * java.lang.String#endsWith(java.lang.String)
+ */
+ public void test_endsWithLjava_lang_String() {
+ // Test for method boolean java.lang.String.endsWith(java.lang.String)
+ assertTrue("Failed to fine ending string", hw1.endsWith("ld"));
+ }
+
+ /**
+ * java.lang.String#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertEquals("String not equal", hw1, hw2);
+ assertEquals("Empty string equals check", "", "");
+ assertEquals("Null string equals check", (String) null, (String) null);
+
+ assertFalse("Unequal strings reports as equal", hw1.equals(comp11));
+ assertFalse("Null string comparison failed", hw1.equals((String) null));
+ }
+
+ /**
+ * java.lang.String#equalsIgnoreCase(java.lang.String)
+ */
+ public void test_equalsIgnoreCaseLjava_lang_String() {
+ // Test for method boolean
+ // java.lang.String.equalsIgnoreCase(java.lang.String)
+ assertTrue("lc version returned unequal to uc", hwlc
+ .equalsIgnoreCase(hwuc));
+ }
+
+ /**
+ * java.lang.String#getBytes()
+ */
+ public void test_getBytes() {
+ // Test for method byte [] java.lang.String.getBytes()
+ byte[] sbytes = hw1.getBytes();
+
+ for (int i = 0; i < hw1.length(); i++) {
+ assertTrue("Returned incorrect bytes", sbytes[i] == (byte) hw1.charAt(i));
+ }
+
+ char[] chars = new char[1];
+ for (int i = 0; i < 65536; i++) {
+ // skip surrogates
+ if (i == 0xd800)
+ i = 0xe000;
+ byte[] result = null;
+ chars[0] = (char) i;
+ String string = new String(chars);
+ try {
+ result = string.getBytes("8859_1");
+ if (i < 256) {
+ assertEquals((byte) i, result[0]);
+ } else {
+ /*
+ * Substitute character should be 0x1A [1], but may be '?'
+ * character. [1]
+ * http://en.wikipedia.org/wiki/Substitute_character
+ */
+ assertTrue(result[0] == '?' || result[0] == 0x1a);
+ }
+ } catch (java.io.UnsupportedEncodingException e) {
+ }
+ try {
+ result = string.getBytes("UTF8");
+ int length = i < 0x80 ? 1 : (i < 0x800 ? 2 : 3);
+ assertTrue("Wrong length UTF8: " + Integer.toHexString(i),
+ result.length == length);
+ assertTrue(
+ "Wrong bytes UTF8: " + Integer.toHexString(i),
+ (i < 0x80 && result[0] == i)
+ || (i >= 0x80
+ && i < 0x800
+ && result[0] == (byte) (0xc0 | ((i & 0x7c0) >> 6)) && result[1] == (byte) (0x80 | (i & 0x3f)))
+ || (i >= 0x800
+ && result[0] == (byte) (0xe0 | (i >> 12))
+ && result[1] == (byte) (0x80 | ((i & 0xfc0) >> 6)) && result[2] == (byte) (0x80 | (i & 0x3f))));
+ } catch (java.io.UnsupportedEncodingException e) {
+ }
+
+ String bytes = null;
+ try {
+ bytes = new String(result, "UTF8");
+ assertTrue("Wrong UTF8 byte length: " + bytes.length() + "("
+ + i + ")", bytes.length() == 1);
+ assertTrue(
+ "Wrong char UTF8: "
+ + Integer.toHexString(bytes.charAt(0)) + " ("
+ + i + ")", bytes.charAt(0) == i);
+ } catch (java.io.UnsupportedEncodingException e) {
+ }
+ }
+
+ byte[] bytes = new byte[1];
+ for (int i = 0; i < 256; i++) {
+ bytes[0] = (byte) i;
+ String result = null;
+ try {
+ result = new String(bytes, "8859_1");
+ assertEquals("Wrong char length", 1, result.length());
+ assertTrue("Wrong char value", result.charAt(0) == (char) i);
+ } catch (java.io.UnsupportedEncodingException e) {
+ }
+ }
+ }
+
+ /**
+ * java.lang.String#getBytes(int, int, byte[], int)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_getBytesII$BI() {
+ // Test for method void java.lang.String.getBytes(int, int, byte [],
+ // int)
+ byte[] buf = new byte[5];
+ "Hello World".getBytes(6, 11, buf, 0);
+ assertEquals("Returned incorrect bytes", "World", new String(buf));
+
+ try {
+ "Hello World".getBytes(-1, 1, null, 0);
+ fail("Expected StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ } catch (NullPointerException e) {
+ fail("Threw wrong exception");
+ }
+ }
+
+ /**
+ * java.lang.String#getBytes(java.lang.String)
+ */
+ public void test_getBytesLjava_lang_String() throws Exception {
+ // Test for method byte [] java.lang.String.getBytes(java.lang.String)
+ byte[] buf = "Hello World".getBytes();
+ assertEquals("Returned incorrect bytes", "Hello World", new String(buf));
+
+ try {
+ "string".getBytes("8849_1");
+ fail("No UnsupportedEncodingException");
+ } catch (UnsupportedEncodingException e) {
+ }
+
+ byte[] bytes = "\u3048".getBytes("UTF-8");
+ byte[] expected = new byte[] { (byte) 0xE3, (byte) 0x81, (byte) 0x88 };
+ assertEquals(expected[0], bytes[0]);
+ assertEquals(expected[1], bytes[1]);
+ assertEquals(expected[2], bytes[2]);
+
+ // Regression for HARMONY-663
+ try {
+ "string".getBytes("?Q?D??_??_6ffa?+vG?_??\u951f\ufffd??");
+ fail("No UnsupportedEncodingException");
+ } catch (UnsupportedEncodingException e) {
+ // expected
+ }
+
+ bytes = "-".getBytes("UTF-16");
+ expected = new byte[] { (byte) 0xff, (byte) 0xfe };
+ assertEquals(expected[0], bytes[0]);
+ assertEquals(expected[1], bytes[1]);
+
+ byte[] bytes2 = "-".getBytes("UTF-16LE");
+ assertEquals(bytes2[0], bytes[2]);
+ assertEquals(bytes2[1], bytes[3]);
+ }
+
+ /*
+ * java.lang.String#getBytes()
+ */
+ public void test_getBytes_NPE() throws Exception {
+ try {
+ "abc".getBytes((String) null);
+ fail("Should throw NullPointerException");
+ } catch (UnsupportedEncodingException whatTheRiDocumentsAndWeThrow) {
+ } catch (NullPointerException whatTheRiActuallyThrows) {
+ }
+
+ try {
+ "Hello World".getBytes(1, 2, null, 1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.String#getChars(int, int, char[], int)
+ */
+ public void test_getCharsII$CI() {
+ // Test for method void java.lang.String.getChars(int, int, char [],
+ // int)
+ hw1.getChars(5, hw1.length(), rbuf, 0);
+
+ for (int i = 0; i < rbuf.length; i++)
+ assertTrue("getChars returned incorrect char(s)", rbuf[i] == buf[i]);
+ }
+
+ /**
+ * java.lang.String#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.lang.String.hashCode()
+ int hwHashCode = 0;
+ final int hwLength = hw1.length();
+ int powerOfThirtyOne = 1;
+ for (int counter = hwLength - 1; counter >= 0; counter--) {
+ hwHashCode += hw1.charAt(counter) * powerOfThirtyOne;
+ powerOfThirtyOne *= 31;
+ }
+ assertEquals("String did not hash to correct value", hwHashCode, hw1.hashCode());
+ assertEquals("The empty string \"\" did not hash to zero", 0, "".hashCode());
+ assertEquals("Calculated wrong string hashcode", -1933545242, "Harmony".hashCode());
+ }
+
+ /**
+ * java.lang.String#indexOf(int)
+ */
+ public void test_indexOfI() {
+ // Test for method int java.lang.String.indexOf(int)
+ assertEquals("Invalid index returned", 1, hw1.indexOf('e'));
+ assertEquals("Invalid index returned", 1, "a\ud800\udc00".indexOf(0x10000));
+ }
+
+ /**
+ * java.lang.String#indexOf(int, int)
+ */
+ public void test_indexOfII() {
+ // Test for method int java.lang.String.indexOf(int, int)
+ assertEquals("Invalid character index returned", 5, hw1.indexOf('W', 2));
+ assertEquals("Invalid index returned", 2, "ab\ud800\udc00".indexOf(0x10000, 1));
+ }
+
+ /**
+ * java.lang.String#indexOf(java.lang.String)
+ */
+ public void test_indexOfLjava_lang_String() {
+ // Test for method int java.lang.String.indexOf(java.lang.String)
+ assertTrue("Failed to find string", hw1.indexOf("World") > 0);
+ assertTrue("Failed to find string", !(hw1.indexOf("ZZ") > 0));
+ }
+
+ /**
+ * java.lang.String#indexOf(java.lang.String, int)
+ */
+ public void test_indexOfLjava_lang_StringI() {
+ // Test for method int java.lang.String.indexOf(java.lang.String, int)
+ assertTrue("Failed to find string", hw1.indexOf("World", 0) > 0);
+ assertTrue("Found string outside index", !(hw1.indexOf("Hello", 6) > 0));
+ assertEquals("Did not accept valid negative starting position", 0,
+ hello1.indexOf("", -5));
+ assertEquals("Reported wrong error code", 5, hello1.indexOf("", 5));
+ assertEquals("Wrong for empty in empty", 0, "".indexOf("", 0));
+ }
+
+ /**
+ * java.lang.String#intern()
+ */
+ public void test_intern() {
+ // Test for method java.lang.String java.lang.String.intern()
+ assertTrue("Intern returned incorrect result", hw1.intern() == hw2
+ .intern());
+ }
+
+ /**
+ * java.lang.String#lastIndexOf(int)
+ */
+ public void test_lastIndexOfI() {
+ // Test for method int java.lang.String.lastIndexOf(int)
+ assertEquals("Failed to return correct index", 5, hw1.lastIndexOf('W'));
+ assertEquals("Returned index for non-existent char", -1, hw1
+ .lastIndexOf('Z'));
+ assertEquals("Failed to return correct index", 1, "a\ud800\udc00"
+ .lastIndexOf(0x10000));
+ }
+
+ /**
+ * java.lang.String#lastIndexOf(int, int)
+ */
+ public void test_lastIndexOfII() {
+ // Test for method int java.lang.String.lastIndexOf(int, int)
+ assertEquals("Failed to return correct index", 5, hw1.lastIndexOf('W',
+ 6));
+ assertEquals("Returned index for char out of specified range", -1, hw1
+ .lastIndexOf('W', 4));
+ assertEquals("Returned index for non-existent char", -1, hw1
+ .lastIndexOf('Z', 9));
+
+ }
+
+ /**
+ * java.lang.String#lastIndexOf(java.lang.String)
+ */
+ public void test_lastIndexOfLjava_lang_String() {
+ // Test for method int java.lang.String.lastIndexOf(java.lang.String)
+ assertEquals("Returned incorrect index", 5, hw1.lastIndexOf("World"));
+ assertEquals("Found String outside of index", -1, hw1
+ .lastIndexOf("HeKKKKKKKK"));
+ }
+
+ /**
+ * java.lang.String#lastIndexOf(java.lang.String, int)
+ */
+ public void test_lastIndexOfLjava_lang_StringI() {
+ // Test for method int java.lang.String.lastIndexOf(java.lang.String,
+ // int)
+ assertEquals("Returned incorrect index", 5, hw1.lastIndexOf("World", 9));
+ int result = hw1.lastIndexOf("Hello", 2);
+ assertTrue("Found String outside of index: " + result, result == 0);
+ assertEquals("Reported wrong error code", -1, hello1
+ .lastIndexOf("", -5));
+ assertEquals("Did not accept valid large starting position", 5, hello1
+ .lastIndexOf("", 5));
+ }
+
+ /**
+ * java.lang.String#length()
+ */
+ public void test_length() {
+ // Test for method int java.lang.String.length()
+ assertEquals("Invalid length returned", 11, comp11.length());
+ }
+
+ /**
+ * java.lang.String#regionMatches(int, java.lang.String, int, int)
+ */
+ public void test_regionMatchesILjava_lang_StringII() {
+ // Test for method boolean java.lang.String.regionMatches(int,
+ // java.lang.String, int, int)
+ String bogusString = "xxcedkedkleiorem lvvwr e''' 3r3r 23r";
+
+ assertTrue("identical regions failed comparison", hw1.regionMatches(2,
+ hw2, 2, 5));
+ assertTrue("Different regions returned true", !hw1.regionMatches(2,
+ bogusString, 2, 5));
+ }
+
+ /**
+ * java.lang.String#regionMatches(boolean, int, java.lang.String,
+ *int, int)
+ */
+ public void test_regionMatchesZILjava_lang_StringII() {
+ // Test for method boolean java.lang.String.regionMatches(boolean, int,
+ // java.lang.String, int, int)
+
+ String bogusString = "xxcedkedkleiorem lvvwr e''' 3r3r 23r";
+
+ assertTrue("identical regions failed comparison", hw1.regionMatches(
+ false, 2, hw2, 2, 5));
+ assertTrue("identical regions failed comparison with different cases",
+ hw1.regionMatches(true, 2, hw2, 2, 5));
+ assertTrue("Different regions returned true", !hw1.regionMatches(true,
+ 2, bogusString, 2, 5));
+ assertTrue("identical regions failed comparison with different cases",
+ hw1.regionMatches(false, 2, hw2, 2, 5));
+ }
+
+ /**
+ * java.lang.String#replace(char, char)
+ */
+ public void test_replaceCC() {
+ // Test for method java.lang.String java.lang.String.replace(char, char)
+ assertEquals("Failed replace", "HezzoWorzd", hw1.replace('l', 'z'));
+ }
+
+ /**
+ * java.lang.String#replace(CharSequence, CharSequence)
+ */
+ public void test_replaceLjava_langCharSequenceLjava_langCharSequence() {
+ assertEquals("Failed replace", "aaccdd", "aabbdd".replace(
+ new StringBuffer("bb"), "cc"));
+ assertEquals("Failed replace by bigger seq", "cccbccc", "aba".replace(
+ "a", "ccc"));
+ assertEquals("Failed replace by smaller seq", "$bba^", "$aaaaa^"
+ .replace(new StringBuilder("aa"), "b"));
+ assertEquals("Failed to replace empty string", "%%a%%b%%c%%",
+ "abc".replace("", "%%"));
+ assertEquals("Failed to replace with empty string", "aacc",
+ "aabbcc".replace("b", ""));
+ assertEquals("Failed to replace in empty string", "abc",
+ "".replace("", "abc"));
+ }
+
+ /**
+ * java.lang.String#startsWith(java.lang.String)
+ */
+ public void test_startsWithLjava_lang_String() {
+ // Test for method boolean java.lang.String.startsWith(java.lang.String)
+ assertTrue("Failed to find string", hw1.startsWith("Hello"));
+ assertTrue("Found incorrect string", !hw1.startsWith("T"));
+ }
+
+ /**
+ * java.lang.String#startsWith(java.lang.String, int)
+ */
+ public void test_startsWithLjava_lang_StringI() {
+ // Test for method boolean java.lang.String.startsWith(java.lang.String,
+ // int)
+ assertTrue("Failed to find string", hw1.startsWith("World", 5));
+ assertTrue("Found incorrect string", !hw1.startsWith("Hello", 5));
+ }
+
+ /**
+ * java.lang.String#substring(int)
+ */
+ public void test_substringI() {
+ // Test for method java.lang.String java.lang.String.substring(int)
+ assertEquals("Incorrect substring returned", "World", hw1.substring(5));
+ assertTrue("not identical", hw1.substring(0) == hw1);
+ }
+
+ /**
+ * java.lang.String#substring(int, int)
+ */
+ public void test_substringII() {
+ // Test for method java.lang.String java.lang.String.substring(int, int)
+ assertTrue("Incorrect substring returned", hw1.substring(0, 5).equals(
+ "Hello")
+ && (hw1.substring(5, 10).equals("World")));
+ assertTrue("not identical", hw1.substring(0, hw1.length()) == hw1);
+ }
+
+ /**
+ * java.lang.String#substring(int, int)
+ */
+ public void test_substringErrorMessage() {
+ try {
+ hw1.substring(-1, 1);
+ } catch (StringIndexOutOfBoundsException ex) {
+ String msg = ex.getMessage();
+ assertTrue("Expected message to contain -1: " + msg, msg
+ .indexOf("-1") != -1);
+ }
+ try {
+ hw1.substring(4, 1);
+ } catch (StringIndexOutOfBoundsException ex) {
+ String msg = ex.getMessage();
+ assertTrue("Expected message to contain -3: " + msg, msg
+ .indexOf("-3") != -1);
+ }
+ try {
+ hw1.substring(0, 100);
+ } catch (StringIndexOutOfBoundsException ex) {
+ String msg = ex.getMessage();
+ assertTrue("Expected message to contain 100: " + msg, msg
+ .indexOf("100") != -1);
+ }
+ }
+
+ /**
+ * java.lang.String#toCharArray()
+ */
+ public void test_toCharArray() {
+ // Test for method char [] java.lang.String.toCharArray()
+
+ String s = new String(buf, 0, buf.length);
+ char[] schars = s.toCharArray();
+ for (int i = 0; i < s.length(); i++)
+ assertTrue("Returned incorrect char aray", buf[i] == schars[i]);
+ }
+
+ /**
+ * java.lang.String#toLowerCase()
+ */
+ public void test_toLowerCase() {
+ // Test for method java.lang.String java.lang.String.toLowerCase()
+ assertTrue("toLowerCase case conversion did not succeed", hwuc
+ .toLowerCase().equals(hwlc));
+
+ assertEquals(
+ "a) Sigma has ordinary lower case value when isolated with Unicode 4.0",
+ "\u03c3", "\u03a3".toLowerCase());
+ assertEquals(
+ "b) Sigma has final form lower case value at end of word with Unicode 4.0",
+ "a\u03c2", "a\u03a3".toLowerCase());
+
+ assertEquals("toLowerCase case conversion did not succeed",
+ "\uD801\uDC44", "\uD801\uDC1C".toLowerCase());
+ }
+
+ /**
+ * java.lang.String#toLowerCase(java.util.Locale)
+ */
+ public void test_toLowerCaseLjava_util_Locale() {
+ // Test for method java.lang.String
+ // java.lang.String.toLowerCase(java.util.Locale)
+ assertTrue("toLowerCase case conversion did not succeed", hwuc
+ .toLowerCase(java.util.Locale.getDefault()).equals(hwlc));
+ assertEquals("Invalid \\u0049 for English", "\u0069", "\u0049"
+ .toLowerCase(Locale.ENGLISH));
+ assertEquals("Invalid \\u0049 for Turkish", "\u0131", "\u0049"
+ .toLowerCase(new Locale("tr", "")));
+ }
+
+ /**
+ * java.lang.String#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.String.toString()
+ assertTrue("Incorrect string returned", hw1.toString().equals(hw1));
+ }
+
+ /**
+ * java.lang.String#toUpperCase()
+ */
+ public void test_toUpperCase() {
+ // Test for method java.lang.String java.lang.String.toUpperCase()
+ assertTrue("Returned string is not UpperCase", hwlc.toUpperCase()
+ .equals(hwuc));
+
+ assertEquals("Wrong conversion", "SS", "\u00df".toUpperCase());
+
+ String s = "a\u00df\u1f56";
+ assertTrue("Invalid conversion", !s.toUpperCase().equals(s));
+
+ assertEquals("toUpperCase case conversion did not succeed",
+ "\uD801\uDC1C", "\uD801\uDC44".toUpperCase());
+ }
+
+ /**
+ * java.lang.String#toUpperCase(java.util.Locale)
+ */
+ public void test_toUpperCaseLjava_util_Locale() {
+ // Test for method java.lang.String
+ // java.lang.String.toUpperCase(java.util.Locale)
+ assertTrue("Returned string is not UpperCase", hwlc.toUpperCase()
+ .equals(hwuc));
+ assertEquals("Invalid \\u0069 for English", "\u0049", "\u0069"
+ .toUpperCase(Locale.ENGLISH));
+ assertEquals("Invalid \\u0069 for Turkish", "\u0130", "\u0069"
+ .toUpperCase(new Locale("tr", "")));
+ }
+
+ /**
+ * java.lang.String#toUpperCase(java.util.Locale)
+ */
+ public void test_toUpperCaseLjava_util_Locale_subtest0() {
+ // Test for method java.lang.String
+ // java.lang.String.toUpperCase(java.util.Locale)
+ }
+
+ /**
+ * java.lang.String#trim()
+ */
+ public void test_trim() {
+ // Test for method java.lang.String java.lang.String.trim()
+ assertTrue("Incorrect string returned", " HelloWorld ".trim().equals(
+ hw1));
+ }
+
+ /**
+ * java.lang.String#valueOf(char[])
+ */
+ public void test_valueOf$C() {
+ // Test for method java.lang.String java.lang.String.valueOf(char [])
+ assertEquals("Returned incorrect String", "World", String.valueOf(buf));
+ }
+
+ /**
+ * java.lang.String#valueOf(char[], int, int)
+ */
+ public void test_valueOf$CII() {
+ // Test for method java.lang.String java.lang.String.valueOf(char [],
+ // int, int)
+ char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+ assertEquals("copyValueOf returned incorrect String", "World", String
+ .valueOf(t, 5, 5));
+ }
+
+ /**
+ * java.lang.String#valueOf(char)
+ */
+ public void test_valueOfC() {
+ // Test for method java.lang.String java.lang.String.valueOf(char)
+ for (int i = 0; i < 65536; i++)
+ assertTrue("Incorrect valueOf(char) returned: " + i, String
+ .valueOf((char) i).charAt(0) == (char) i);
+ }
+
+ /**
+ * java.lang.String#valueOf(double)
+ */
+ public void test_valueOfD() {
+ // Test for method java.lang.String java.lang.String.valueOf(double)
+ assertEquals("Incorrect double string returned",
+ "1.7976931348623157E308", String.valueOf(Double.MAX_VALUE));
+ }
+
+ /**
+ * java.lang.String#valueOf(float)
+ */
+ public void test_valueOfF() {
+ // Test for method java.lang.String java.lang.String.valueOf(float)
+ assertTrue("incorrect float string returned--got: "
+ + String.valueOf(1.0F) + " wanted: 1.0", String.valueOf(1.0F)
+ .equals("1.0"));
+ assertTrue("incorrect float string returned--got: "
+ + String.valueOf(0.9F) + " wanted: 0.9", String.valueOf(0.9F)
+ .equals("0.9"));
+ assertTrue("incorrect float string returned--got: "
+ + String.valueOf(109.567F) + " wanted: 109.567", String
+ .valueOf(109.567F).equals("109.567"));
+ }
+
+ /**
+ * java.lang.String#valueOf(int)
+ */
+ public void test_valueOfI() {
+ // Test for method java.lang.String java.lang.String.valueOf(int)
+ assertEquals("returned invalid int string", "1", String.valueOf(1));
+ }
+
+ /**
+ * java.lang.String#valueOf(long)
+ */
+ public void test_valueOfJ() {
+ // Test for method java.lang.String java.lang.String.valueOf(long)
+ assertEquals("returned incorrect long string", "927654321098", String
+ .valueOf(927654321098L));
+ }
+
+ /**
+ * java.lang.String#valueOf(java.lang.Object)
+ */
+ public void test_valueOfLjava_lang_Object() {
+ // Test for method java.lang.String
+ // java.lang.String.valueOf(java.lang.Object)
+ assertTrue("Incorrect Object string returned", obj.toString().equals(
+ String.valueOf(obj)));
+ }
+
+ /**
+ * java.lang.String#valueOf(boolean)
+ */
+ public void test_valueOfZ() {
+ // Test for method java.lang.String java.lang.String.valueOf(boolean)
+ assertTrue("Incorrect boolean string returned", String.valueOf(false)
+ .equals("false")
+ && (String.valueOf(true).equals("true")));
+ }
+
+ /**
+ * java.lang.String#contentEquals(CharSequence cs)
+ */
+ public void test_contentEqualsLjava_lang_CharSequence() {
+ // Test for method java.lang.String
+ // java.lang.String.contentEquals(CharSequence cs)
+ assertFalse("Incorrect result of compare", "qwerty".contentEquals(""));
+ }
+
+ /**
+ * java.lang.String#format(Locale, String, Object[])
+ */
+ @SuppressWarnings("boxing")
+ public void test_format() {
+ assertEquals("13% of sum is 0x11", String.format("%d%% of %s is 0x%x",
+ 13, "sum", 17));
+ assertEquals("empty format", "", String.format("", 123, this));
+ try {
+ String.format(null);
+ fail("NPE is expected on null format");
+ } catch (NullPointerException ok) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuffer2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuffer2Test.java
new file mode 100644
index 0000000..7e8144b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuffer2Test.java
@@ -0,0 +1,610 @@
+/*
+ * 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.tests.java.lang;
+
+public class StringBuffer2Test extends junit.framework.TestCase {
+
+ StringBuffer testBuffer;
+
+ /**
+ * java.lang.StringBuffer#StringBuffer()
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.StringBuffer()
+ new StringBuffer();
+ assertTrue("Invalid buffer created", true);
+ }
+
+ /**
+ * java.lang.StringBuffer#StringBuffer(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.lang.StringBuffer(int)
+ StringBuffer sb = new StringBuffer(8);
+ assertEquals("Newly constructed buffer is of incorrect length", 0, sb
+ .length());
+ }
+
+ /**
+ * java.lang.StringBuffer#StringBuffer(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.lang.StringBuffer(java.lang.String)
+
+ StringBuffer sb = new StringBuffer("HelloWorld");
+
+ assertTrue("Invalid buffer created", sb.length() == 10
+ && (sb.toString().equals("HelloWorld")));
+
+ boolean pass = false;
+ try {
+ new StringBuffer(null);
+ } catch (NullPointerException e) {
+ pass = true;
+ }
+ assertTrue("Should throw NullPointerException", pass);
+ }
+
+ /**
+ * java.lang.StringBuffer#append(char[])
+ */
+ public void test_append$C() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(char [])
+ char buf[] = new char[4];
+ "char".getChars(0, 4, buf, 0);
+ testBuffer.append(buf);
+ assertEquals("Append of char[] failed",
+ "This is a test bufferchar", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#append(char[], int, int)
+ */
+ public void test_append$CII() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(char [], int, int)
+ StringBuffer sb = new StringBuffer();
+ char[] buf1 = { 'H', 'e', 'l', 'l', 'o' };
+ char[] buf2 = { 'W', 'o', 'r', 'l', 'd' };
+ sb.append(buf1, 0, buf1.length);
+ assertEquals("Buffer is invalid length after append", 5, sb.length());
+ sb.append(buf2, 0, buf2.length);
+ assertEquals("Buffer is invalid length after append", 10, sb.length());
+ assertTrue("Buffer contains invalid chars", (sb.toString()
+ .equals("HelloWorld")));
+ }
+
+ /**
+ * java.lang.StringBuffer#append(char)
+ */
+ public void test_appendC() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(char)
+ StringBuffer sb = new StringBuffer();
+ char buf1 = 'H';
+ char buf2 = 'W';
+ sb.append(buf1);
+ assertEquals("Buffer is invalid length after append", 1, sb.length());
+ sb.append(buf2);
+ assertEquals("Buffer is invalid length after append", 2, sb.length());
+ assertTrue("Buffer contains invalid chars",
+ (sb.toString().equals("HW")));
+ }
+
+ /**
+ * java.lang.StringBuffer#append(double)
+ */
+ public void test_appendD() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(double)
+ StringBuffer sb = new StringBuffer();
+ sb.append(Double.MAX_VALUE);
+ assertEquals("Buffer is invalid length after append", 22, sb.length());
+ assertEquals("Buffer contains invalid characters",
+ "1.7976931348623157E308", sb.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#append(float)
+ */
+ public void test_appendF() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(float)
+ StringBuffer sb = new StringBuffer();
+ final float floatNum = 900.87654F;
+ sb.append(floatNum);
+ assertTrue("Buffer is invalid length after append: " + sb.length(), sb
+ .length() == String.valueOf(floatNum).length());
+ assertTrue("Buffer contains invalid characters", sb.toString().equals(
+ String.valueOf(floatNum)));
+ }
+
+ /**
+ * java.lang.StringBuffer#append(int)
+ */
+ public void test_appendI() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(int)
+ StringBuffer sb = new StringBuffer();
+ sb.append(9000);
+ assertEquals("Buffer is invalid length after append", 4, sb.length());
+ sb.append(1000);
+ assertEquals("Buffer is invalid length after append", 8, sb.length());
+ assertEquals("Buffer contains invalid characters",
+ "90001000", sb.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#append(long)
+ */
+ public void test_appendJ() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(long)
+
+ StringBuffer sb = new StringBuffer();
+ long t = 927654321098L;
+ sb.append(t);
+ assertEquals("Buffer is of invlaid length", 12, sb.length());
+ assertEquals("Buffer contains invalid characters",
+ "927654321098", sb.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#append(java.lang.Object)
+ */
+ public void test_appendLjava_lang_Object() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(java.lang.Object)
+ StringBuffer sb = new StringBuffer();
+ Object obj1 = new Object();
+ Object obj2 = new Object();
+ sb.append(obj1);
+ sb.append(obj2);
+ assertTrue("Buffer contains invalid characters", sb.toString().equals(
+ obj1.toString() + obj2.toString()));
+ }
+
+ /**
+ * java.lang.StringBuffer#append(java.lang.String)
+ */
+ public void test_appendLjava_lang_String() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(java.lang.String)
+ StringBuffer sb = new StringBuffer();
+ String buf1 = "Hello";
+ String buf2 = "World";
+ sb.append(buf1);
+ assertEquals("Buffer is invalid length after append", 5, sb.length());
+ sb.append(buf2);
+ assertEquals("Buffer is invalid length after append", 10, sb.length());
+ assertTrue("Buffer contains invalid chars", (sb.toString()
+ .equals("HelloWorld")));
+ }
+
+ /**
+ * java.lang.StringBuffer#append(boolean)
+ */
+ public void test_appendZ() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.append(boolean)
+ StringBuffer sb = new StringBuffer();
+ sb.append(false);
+ assertEquals("Buffer is invalid length after append", 5, sb.length());
+ sb.append(true);
+ assertEquals("Buffer is invalid length after append", 9, sb.length());
+ assertTrue("Buffer is invalid length after append", (sb.toString()
+ .equals("falsetrue")));
+ }
+
+ /**
+ * java.lang.StringBuffer#capacity()
+ */
+ public void test_capacity() {
+ // Test for method int java.lang.StringBuffer.capacity()
+ StringBuffer sb = new StringBuffer(10);
+ assertEquals("Returned incorrect capacity", 10, sb.capacity());
+ sb.ensureCapacity(100);
+ assertTrue("Returned incorrect capacity", sb.capacity() >= 100);
+ }
+
+ /**
+ * java.lang.StringBuffer#charAt(int)
+ */
+ public void test_charAtI() {
+ // Test for method char java.lang.StringBuffer.charAt(int)
+ assertEquals("Returned incorrect char", 's', testBuffer.charAt(3));
+
+ // Test for StringIndexOutOfBoundsException
+ boolean exception = false;
+ try {
+ testBuffer.charAt(-1);
+ } catch (StringIndexOutOfBoundsException e) {
+ exception = true;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ assertTrue("Should throw StringIndexOutOfBoundsException", exception);
+ }
+
+ /**
+ * java.lang.StringBuffer#delete(int, int)
+ */
+ public void test_deleteII() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.delete(int, int)
+ testBuffer.delete(7, 7);
+ assertEquals("Deleted chars when start == end", "This is a test buffer", testBuffer.toString()
+ );
+ testBuffer.delete(4, 14);
+ assertEquals("Deleted incorrect chars",
+ "This buffer", testBuffer.toString());
+
+ testBuffer = new StringBuffer("This is a test buffer");
+ String sharedStr = testBuffer.toString();
+ testBuffer.delete(0, testBuffer.length());
+ assertEquals("Didn't clone shared buffer", "This is a test buffer", sharedStr
+ );
+ assertTrue("Deleted incorrect chars", testBuffer.toString().equals(""));
+ testBuffer.append("more stuff");
+ assertEquals("Didn't clone shared buffer 2", "This is a test buffer", sharedStr
+ );
+ assertEquals("Wrong contents", "more stuff", testBuffer.toString());
+ try {
+ testBuffer.delete(-5, 2);
+ } catch (IndexOutOfBoundsException e) {
+ }
+ assertEquals("Wrong contents 2",
+ "more stuff", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#deleteCharAt(int)
+ */
+ public void test_deleteCharAtI() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.deleteCharAt(int)
+ testBuffer.deleteCharAt(3);
+ assertEquals("Deleted incorrect char",
+ "Thi is a test buffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#ensureCapacity(int)
+ */
+ public void test_ensureCapacityI() {
+ // Test for method void java.lang.StringBuffer.ensureCapacity(int)
+ StringBuffer sb = new StringBuffer(10);
+
+ sb.ensureCapacity(100);
+ assertTrue("Failed to increase capacity", sb.capacity() >= 100);
+ }
+
+ /**
+ * java.lang.StringBuffer#getChars(int, int, char[], int)
+ */
+ public void test_getCharsII$CI() {
+ // Test for method void java.lang.StringBuffer.getChars(int, int, char
+ // [], int)
+
+ char[] buf = new char[10];
+ testBuffer.getChars(4, 8, buf, 2);
+ assertTrue("Returned incorrect chars", new String(buf, 2, 4)
+ .equals(testBuffer.toString().substring(4, 8)));
+
+ boolean exception = false;
+ try {
+ StringBuffer buf2 = new StringBuffer("");
+ buf2.getChars(0, 0, new char[5], 2);
+ } catch (IndexOutOfBoundsException e) {
+ exception = true;
+ }
+ assertTrue("did not expect IndexOutOfBoundsException", !exception);
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, char[])
+ */
+ public void test_insertI$C() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, char [])
+ char buf[] = new char[4];
+ "char".getChars(0, 4, buf, 0);
+ testBuffer.insert(15, buf);
+ assertEquals("Insert test failed",
+ "This is a test charbuffer", testBuffer.toString());
+
+ boolean exception = false;
+ StringBuffer buf1 = new StringBuffer("abcd");
+ try {
+ buf1.insert(-1, (char[]) null);
+ } catch (StringIndexOutOfBoundsException e) {
+ exception = true;
+ } catch (NullPointerException e) {
+ }
+ assertTrue("Should throw StringIndexOutOfBoundsException", exception);
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, char[], int, int)
+ */
+ public void test_insertI$CII() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, char [], int, int)
+ char[] c = new char[] { 'n', 'o', 't', ' ' };
+ testBuffer.insert(8, c, 0, 4);
+ assertEquals("This is not a test buffer", testBuffer.toString());
+
+ StringBuffer buf1 = new StringBuffer("abcd");
+ try {
+ buf1.insert(-1, (char[]) null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+
+ try {
+ testBuffer.insert(testBuffer.length() - 1, c, -1, 1);
+ } catch (StringIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, char)
+ */
+ public void test_insertIC() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, char)
+ testBuffer.insert(15, 'T');
+ assertEquals("Insert test failed",
+ "This is a test Tbuffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, double)
+ */
+ public void test_insertID() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, double)
+ testBuffer.insert(15, Double.MAX_VALUE);
+ assertTrue("Insert test failed", testBuffer.toString().equals(
+ "This is a test " + Double.MAX_VALUE + "buffer"));
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, float)
+ */
+ public void test_insertIF() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, float)
+ testBuffer.insert(15, Float.MAX_VALUE);
+ String testBufferString = testBuffer.toString();
+ String expectedResult = "This is a test "
+ + String.valueOf(Float.MAX_VALUE) + "buffer";
+ assertTrue("Insert test failed, got: " + "\'" + testBufferString + "\'"
+ + " but wanted: " + "\'" + expectedResult + "\'",
+ testBufferString.equals(expectedResult));
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, int)
+ */
+ public void test_insertII() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, int)
+ testBuffer.insert(15, 100);
+ assertEquals("Insert test failed",
+ "This is a test 100buffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, long)
+ */
+ public void test_insertIJ() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, long)
+ testBuffer.insert(15, 88888888888888888L);
+ assertEquals("Insert test failed",
+ "This is a test 88888888888888888buffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, java.lang.Object)
+ */
+ public void test_insertILjava_lang_Object() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, java.lang.Object)
+ Object obj1 = new Object();
+ testBuffer.insert(15, obj1);
+ assertTrue("Insert test failed", testBuffer.toString().equals(
+ "This is a test " + obj1.toString() + "buffer"));
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, java.lang.String)
+ */
+ public void test_insertILjava_lang_String() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, java.lang.String)
+
+ testBuffer.insert(15, "STRING ");
+ assertEquals("Insert test failed",
+ "This is a test STRING buffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#insert(int, boolean)
+ */
+ public void test_insertIZ() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.insert(int, boolean)
+ testBuffer.insert(15, true);
+ assertEquals("Insert test failed",
+ "This is a test truebuffer", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#length()
+ */
+ public void test_length() {
+ // Test for method int java.lang.StringBuffer.length()
+ assertEquals("Incorrect length returned", 21, testBuffer.length());
+ }
+
+ /**
+ * java.lang.StringBuffer#replace(int, int, java.lang.String)
+ */
+ public void test_replaceIILjava_lang_String() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.replace(int, int, java.lang.String)
+ testBuffer.replace(5, 9, "is a replaced");
+ assertTrue("Replace failed, wanted: " + "\'"
+ + "This is a replaced test buffer" + "\'" + " but got: " + "\'"
+ + testBuffer.toString() + "\'", testBuffer.toString().equals(
+ "This is a replaced test buffer"));
+ assertEquals("insert1", "text", new StringBuffer().replace(0, 0, "text")
+ .toString());
+ assertEquals("insert2", "123text", new StringBuffer("123").replace(3, 3, "text")
+ .toString());
+ assertEquals("insert2", "1text23", new StringBuffer("123").replace(1, 1, "text")
+ .toString());
+ }
+
+ private String writeString(String in) {
+ StringBuffer result = new StringBuffer();
+ result.append("\"");
+ for (int i = 0; i < in.length(); i++) {
+ result.append(" 0x" + Integer.toHexString(in.charAt(i)));
+ }
+ result.append("\"");
+ return result.toString();
+ }
+
+ private void reverseTest(String id, String org, String rev, String back) {
+ // create non-shared StringBuffer
+ StringBuffer sb = new StringBuffer(org);
+ sb.reverse();
+ String reversed = sb.toString();
+ assertTrue("reversed surrogate " + id + ": " + writeString(reversed),
+ reversed.equals(rev));
+ // create non-shared StringBuffer
+ sb = new StringBuffer(reversed);
+ sb.reverse();
+ reversed = sb.toString();
+ assertTrue("reversed surrogate " + id + "a: " + writeString(reversed),
+ reversed.equals(back));
+
+ // test algorithm when StringBuffer is shared
+ sb = new StringBuffer(org);
+ String copy = sb.toString();
+ assertEquals(org, copy);
+ sb.reverse();
+ reversed = sb.toString();
+ assertTrue("reversed surrogate " + id + ": " + writeString(reversed),
+ reversed.equals(rev));
+ sb = new StringBuffer(reversed);
+ copy = sb.toString();
+ assertEquals(rev, copy);
+ sb.reverse();
+ reversed = sb.toString();
+ assertTrue("reversed surrogate " + id + "a: " + writeString(reversed),
+ reversed.equals(back));
+
+ }
+
+ /**
+ * java.lang.StringBuffer#reverse()
+ */
+ public void test_reverse() {
+ // Test for method java.lang.StringBuffer
+ // java.lang.StringBuffer.reverse()
+ String org;
+ org = "a";
+ reverseTest("0", org, org, org);
+
+ org = "ab";
+ reverseTest("1", org, "ba", org);
+
+ org = "abcdef";
+ reverseTest("2", org, "fedcba", org);
+
+ org = "abcdefg";
+ reverseTest("3", org, "gfedcba", org);
+
+ }
+
+ /**
+ * java.lang.StringBuffer#setCharAt(int, char)
+ */
+ public void test_setCharAtIC() {
+ // Test for method void java.lang.StringBuffer.setCharAt(int, char)
+ StringBuffer s = new StringBuffer("HelloWorld");
+ s.setCharAt(4, 'Z');
+ assertEquals("Returned incorrect char", 'Z', s.charAt(4));
+ }
+
+ /**
+ * java.lang.StringBuffer#setLength(int)
+ */
+ public void test_setLengthI() {
+ // Test for method void java.lang.StringBuffer.setLength(int)
+ testBuffer.setLength(1000);
+ assertEquals("Failed to increase length", 1000, testBuffer.length());
+ assertTrue("Increase in length trashed buffer", testBuffer.toString()
+ .startsWith("This is a test buffer"));
+ testBuffer.setLength(2);
+ assertEquals("Failed to decrease length", 2, testBuffer.length());
+ assertEquals("Decrease in length failed",
+ "Th", testBuffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer#substring(int)
+ */
+ public void test_substringI() {
+ // Test for method java.lang.String
+ // java.lang.StringBuffer.substring(int)
+ assertEquals("Returned incorrect substring", "is a test buffer", testBuffer.substring(5)
+ );
+ }
+
+ /**
+ * java.lang.StringBuffer#substring(int, int)
+ */
+ public void test_substringII() {
+ // Test for method java.lang.String
+ // java.lang.StringBuffer.substring(int, int)
+ assertEquals("Returned incorrect substring", "is", testBuffer.substring(5, 7)
+ );
+ }
+
+ /**
+ * java.lang.StringBuffer#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.StringBuffer.toString()
+ assertEquals("Incorrect string value returned", "This is a test buffer", testBuffer.toString()
+ );
+ }
+
+ @Override
+ protected void setUp() {
+ testBuffer = new StringBuffer("This is a test buffer");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBufferTest.java
new file mode 100644
index 0000000..112e005
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBufferTest.java
@@ -0,0 +1,623 @@
+/* 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.tests.java.lang;
+
+import java.io.Serializable;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class StringBufferTest extends TestCase {
+
+ /**
+ * java.lang.StringBuffer#setLength(int)
+ */
+ public void test_setLengthI() {
+ // Regression for HARMONY-90
+ StringBuffer buffer = new StringBuffer("abcde");
+ try {
+ buffer.setLength(-1);
+ fail("Assert 0: IndexOutOfBoundsException must be thrown");
+ } 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));
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * StringBuffer.StringBuffer(CharSequence);
+ */
+ public void test_constructorLjava_lang_CharSequence() {
+ try {
+ new StringBuffer((CharSequence) null);
+ fail("Assert 0: NPE must be thrown.");
+ } catch (NullPointerException e) {
+ }
+
+ assertEquals("Assert 1: must equal 'abc'.", "abc", new StringBuffer((CharSequence) "abc").toString());
+ }
+
+ public void test_trimToSize() {
+ StringBuffer buffer = new StringBuffer(25);
+ buffer.append("abc");
+ int origCapacity = buffer.capacity();
+ buffer.trimToSize();
+ int trimCapacity = buffer.capacity();
+ assertTrue("Assert 0: capacity must be smaller.", trimCapacity < origCapacity);
+ assertEquals("Assert 1: length must still be 3", 3, buffer.length());
+ assertEquals("Assert 2: value must still be 'abc'.", "abc", buffer.toString());
+ }
+
+ /**
+ * java.lang.StringBuffer.append(CharSequence)
+ */
+ public void test_appendLjava_lang_CharSequence() {
+ StringBuffer sb = new StringBuffer();
+ 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());
+ }
+
+ /**
+ * java.lang.StringBuffer.append(CharSequence, int, int)
+ */
+ @SuppressWarnings("cast")
+ public void test_appendLjava_lang_CharSequenceII() {
+ StringBuffer sb = new StringBuffer();
+ 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());
+ }
+
+ /**
+ * java.lang.StringBuffer.append(char[], int, int)
+ */
+ public void test_append$CII_2() {
+ StringBuffer obj = new StringBuffer();
+ try {
+ obj.append(new char[0], -1, -1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.append(char[], int, int)
+ */
+ public void test_append$CII_3() throws Exception {
+ StringBuffer obj = new StringBuffer();
+ try {
+ obj.append((char[]) null, -1, -1);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.insert(int, CharSequence)
+ */
+ public void test_insertILjava_lang_CharSequence() {
+ final String fixture = "0000";
+ StringBuffer sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(0, (CharSequence) "ab"));
+ assertEquals("ab0000", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(2, (CharSequence) "ab"));
+ assertEquals("00ab00", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(4, (CharSequence) "ab"));
+ assertEquals("0000ab", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(4, (CharSequence) null));
+ assertEquals("0000null", sb.toString());
+ assertEquals(8, sb.length());
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(-1, (CharSequence) "ab");
+ fail("no IOOBE, negative index");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(5, (CharSequence) "ab");
+ fail("no IOOBE, index too large index");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.insert(int, CharSequence, int, int)
+ */
+ @SuppressWarnings("cast")
+ public void test_insertILjava_lang_CharSequenceII() {
+ final String fixture = "0000";
+ StringBuffer sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 2));
+ assertEquals("ab0000", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 1));
+ assertEquals("a0000", sb.toString());
+ assertEquals(5, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 2));
+ assertEquals("00ab00", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 1));
+ assertEquals("00a00", sb.toString());
+ assertEquals(5, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 2));
+ assertEquals("0000ab", sb.toString());
+ assertEquals(6, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 1));
+ assertEquals("0000a", sb.toString());
+ assertEquals(5, sb.length());
+
+ sb = new StringBuffer(fixture);
+ assertSame(sb, sb.insert(4, (CharSequence) null, 0, 2));
+ assertEquals("0000nu", sb.toString());
+ assertEquals(6, sb.length());
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(-1, (CharSequence) "ab", 0, 2);
+ fail("no IOOBE, negative index");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(5, (CharSequence) "ab", 0, 2);
+ fail("no IOOBE, index too large index");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(5, (CharSequence) "ab", -1, 2);
+ fail("no IOOBE, negative offset");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(5, new char[] { 'a', 'b' }, 0, -1);
+ fail("no IOOBE, negative length");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ sb = new StringBuffer(fixture);
+ sb.insert(5, new char[] { 'a', 'b' }, 0, 3);
+ fail("no IOOBE, too long");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.insert(int, char)
+ */
+ public void test_insertIC() {
+ StringBuffer obj = new StringBuffer();
+ try {
+ obj.insert(-1, ' ');
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.appendCodePoint(int)'
+ */
+ public void test_appendCodePointI() {
+ StringBuffer sb = new StringBuffer();
+ 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());
+ }
+
+ /**
+ * java.lang.StringBuffer.codePointAt(int)
+ */
+ public void test_codePointAtI() {
+ StringBuffer sb = new StringBuffer("abc");
+ assertEquals('a', sb.codePointAt(0));
+ assertEquals('b', sb.codePointAt(1));
+ assertEquals('c', sb.codePointAt(2));
+
+ sb = new StringBuffer("\uD800\uDC00");
+ assertEquals(0x10000, sb.codePointAt(0));
+ assertEquals('\uDC00', sb.codePointAt(1));
+
+ try {
+ sb.codePointAt(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointAt(sb.length());
+ fail("No IOOBE on index equal to length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointAt(sb.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.codePointBefore(int)
+ */
+ public void test_codePointBeforeI() {
+ StringBuffer sb = new StringBuffer("abc");
+ assertEquals('a', sb.codePointBefore(1));
+ assertEquals('b', sb.codePointBefore(2));
+ assertEquals('c', sb.codePointBefore(3));
+
+ sb = new StringBuffer("\uD800\uDC00");
+ assertEquals(0x10000, sb.codePointBefore(2));
+ assertEquals('\uD800', sb.codePointBefore(1));
+
+ try {
+ sb.codePointBefore(0);
+ fail("No IOOBE on zero index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointBefore(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointBefore(sb.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.codePointCount(int, int)
+ */
+ public void test_codePointCountII() {
+ assertEquals(1, new StringBuffer("\uD800\uDC00").codePointCount(0, 2));
+ assertEquals(1, new StringBuffer("\uD800\uDC01").codePointCount(0, 2));
+ assertEquals(1, new StringBuffer("\uD801\uDC01").codePointCount(0, 2));
+ assertEquals(1, new StringBuffer("\uDBFF\uDFFF").codePointCount(0, 2));
+
+ assertEquals(3, new StringBuffer("a\uD800\uDC00b").codePointCount(0, 4));
+ assertEquals(4, new StringBuffer("a\uD800\uDC00b\uD800").codePointCount(0, 5));
+
+ StringBuffer sb = new StringBuffer("abc");
+ try {
+ sb.codePointCount(-1, 2);
+ fail("No IOOBE for negative begin index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointCount(0, 4);
+ fail("No IOOBE for end index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointCount(3, 2);
+ fail("No IOOBE for begin index larger than end index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.getChars(int, int, char[], int)
+ */
+ public void test_getCharsII$CI() {
+ StringBuffer obj = new StringBuffer();
+ try {
+ obj.getChars(0, 0, new char[0], -1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.lang.StringBuffer.offsetByCodePoints(int, int)'
+ */
+ public void test_offsetByCodePointsII() {
+ int result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(0, 2);
+ assertEquals(3, result);
+
+ result = new StringBuffer("abcd").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(0, 3);
+ assertEquals(4, result);
+
+ result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(3, -1);
+ assertEquals(1, result);
+
+ result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new StringBuffer("\uD800\uDC00bc").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new StringBuffer("a\uDC00bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new StringBuffer("a\uD800bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ StringBuffer sb = new StringBuffer("abc");
+ try {
+ sb.offsetByCodePoints(-1, 1);
+ fail("No IOOBE for negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(0, 4);
+ fail("No IOOBE for offset that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(3, -4);
+ fail("No IOOBE for offset that's too small.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(3, 1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(4, -1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * {@link java.lang.StringBuffer#indexOf(String, int)}
+ */
+ @SuppressWarnings("nls")
+ public void test_IndexOfStringInt() {
+ final String fixture = "0123456789";
+ StringBuffer sb = new StringBuffer(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("Should throw a NullPointerExceptionE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * {@link java.lang.StringBuffer#lastIndexOf(String, int)}
+ */
+ @SuppressWarnings("nls")
+ public void test_lastIndexOfLjava_lang_StringI() {
+ final String fixture = "0123456789";
+ StringBuffer sb = new StringBuffer(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("Should throw a NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ // comparator for StringBuffer objects
+ private static final SerializableAssert STRING_BUFFER_COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ StringBuffer init = (StringBuffer) initial;
+ StringBuffer desr = (StringBuffer) deserialized;
+
+ // serializable fields are: 'count', 'shared', 'value'
+ // serialization of 'shared' is not verified
+ // 'count' + 'value' should result in required string
+ assertEquals("toString", init.toString(), desr.toString());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new StringBuffer("0123456789"),
+ STRING_BUFFER_COMPARATOR);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new StringBuffer("0123456789"),
+ STRING_BUFFER_COMPARATOR);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuilderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuilderTest.java
new file mode 100644
index 0000000..febdfc4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringBuilderTest.java
@@ -0,0 +1,1986 @@
+/*
+ * 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.tests.java.lang;
+
+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;
+
+public class StringBuilderTest extends TestCase {
+
+ /**
+ * java.lang.StringBuilder.StringBuilder()
+ */
+ public void test_Constructor() {
+ StringBuilder sb = new StringBuilder();
+ assertNotNull(sb);
+ assertEquals(16, sb.capacity());
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.lang.StringBuilder.capacity()'
+ */
+ public void test_capacity() {
+ StringBuilder sb = new StringBuilder();
+ assertEquals(16, sb.capacity());
+ sb.append("0123456789ABCDEF0123456789ABCDEF");
+ assertTrue(sb.capacity() > 16);
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * java.lang.StringBuilder.codePointAt(int)
+ */
+ public void test_codePointAtI() {
+ StringBuilder sb = new StringBuilder("abc");
+ assertEquals('a', sb.codePointAt(0));
+ assertEquals('b', sb.codePointAt(1));
+ assertEquals('c', sb.codePointAt(2));
+
+ sb = new StringBuilder("\uD800\uDC00");
+ assertEquals(0x10000, sb.codePointAt(0));
+ assertEquals('\uDC00', sb.codePointAt(1));
+
+ sb = new StringBuilder();
+ sb.append("abc");
+ try {
+ sb.codePointAt(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointAt(sb.length());
+ fail("No IOOBE on index equal to length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointAt(sb.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * java.lang.StringBuilder.codePointBefore(int)
+ */
+ public void test_codePointBeforeI() {
+ StringBuilder sb = new StringBuilder("abc");
+ assertEquals('a', sb.codePointBefore(1));
+ assertEquals('b', sb.codePointBefore(2));
+ assertEquals('c', sb.codePointBefore(3));
+
+ sb = new StringBuilder("\uD800\uDC00");
+ assertEquals(0x10000, sb.codePointBefore(2));
+ assertEquals('\uD800', sb.codePointBefore(1));
+
+ sb = new StringBuilder();
+ sb.append("abc");
+
+ try {
+ sb.codePointBefore(0);
+ fail("No IOOBE on zero index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointBefore(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointBefore(sb.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * 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));
+ assertEquals(1, new StringBuilder("\uDBFF\uDFFF").codePointCount(0, 2));
+
+ assertEquals(3, new StringBuilder("a\uD800\uDC00b").codePointCount(0, 4));
+ assertEquals(4, new StringBuilder("a\uD800\uDC00b\uD800").codePointCount(0, 5));
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("abc");
+ try {
+ sb.codePointCount(-1, 2);
+ fail("No IOOBE for negative begin index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointCount(0, 4);
+ fail("No IOOBE for end index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.codePointCount(3, 2);
+ fail("No IOOBE for begin index larger than end index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+// }
+ }
+
+ /**
+ * java.lang.StringBuilder.insert(int, char)
+ */
+ public void test_insertIC_2() {
+ StringBuilder obj = new StringBuilder();
+ try {
+ obj.insert(-1, '?');
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * java.lang.StringBuilder.length()
+ */
+ public void test_length() {
+ StringBuilder sb = new StringBuilder();
+ assertEquals(0, sb.length());
+ sb.append("0000");
+ assertEquals(4, sb.length());
+ }
+
+ /**
+ * java.lang.StringBuilder.offsetByCodePoints(int, int)'
+ */
+ public void test_offsetByCodePointsII() {
+ int result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 2);
+ assertEquals(3, result);
+
+ result = new StringBuilder("abcd").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 3);
+ assertEquals(4, result);
+
+ result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(3, -1);
+ assertEquals(1, result);
+
+ result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new StringBuilder("\uD800\uDC00bc").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new StringBuilder("a\uDC00bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new StringBuilder("a\uD800bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("abc");
+ try {
+ sb.offsetByCodePoints(-1, 1);
+ fail("No IOOBE for negative index.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(0, 4);
+ fail("No IOOBE for offset that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(3, -4);
+ fail("No IOOBE for offset that's too small.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(3, 1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+
+ try {
+ sb.offsetByCodePoints(4, -1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * java.lang.StringBuilder.reverse()
+ */
+ public void test_reverse() {
+ final String fixture = "0123456789";
+ StringBuilder sb = new StringBuilder(fixture);
+ assertSame(sb, sb.reverse());
+ assertEquals("9876543210", sb.toString());
+
+ sb = new StringBuilder("012345678");
+ assertSame(sb, sb.reverse());
+ assertEquals("876543210", sb.toString());
+
+ sb.setLength(1);
+ assertSame(sb, sb.reverse());
+ assertEquals("8", sb.toString());
+
+ sb.setLength(0);
+ assertSame(sb, sb.reverse());
+ assertEquals("", sb.toString());
+
+ String str;
+ str = "a";
+ reverseTest(str, str, str);
+
+ str = "ab";
+ reverseTest(str, "ba", str);
+
+ str = "abcdef";
+ reverseTest(str, "fedcba", str);
+
+ str = "abcdefg";
+ reverseTest(str, "gfedcba", str);
+
+ str = "\ud800\udc00";
+ reverseTest(str, str, str);
+
+ str = "\udc00\ud800";
+ reverseTest(str, "\ud800\udc00", "\ud800\udc00");
+
+ str = "a\ud800\udc00";
+ reverseTest(str, "\ud800\udc00a", str);
+
+ str = "ab\ud800\udc00";
+ reverseTest(str, "\ud800\udc00ba", str);
+
+ str = "abc\ud800\udc00";
+ reverseTest(str, "\ud800\udc00cba", str);
+
+ str = "\ud800\udc00\udc01\ud801\ud802\udc02";
+ reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01\ud802\udc02");
+
+ str = "\ud800\udc00\ud801\udc01\ud802\udc02";
+ reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00", str);
+
+ str = "\ud800\udc00\udc01\ud801a";
+ reverseTest(str, "a\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01a");
+
+ str = "a\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00a", str);
+
+ str = "\ud800\udc00\udc01\ud801ab";
+ reverseTest(str, "ba\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01ab");
+
+ str = "ab\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00ba", str);
+
+ str = "\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00", str);
+
+ 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+
+ sb = new StringBuilder("abcde");
+ sb.setLength(3);
+ sb.append('g');
+ assertEquals("abcg", sb.toString());
+
+ sb = new StringBuilder("abcde");
+ sb.setLength(2);
+ try {
+ sb.charAt(3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException 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));
+ }
+
+ 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));
+ }
+
+ 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));
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * java.lang.StringBuilder.toString()'
+ */
+ public void test_toString() throws Exception {
+ final String fixture = "0123456789";
+ StringBuilder sb = new StringBuilder(fixture);
+ 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());
+ }
+
+ /**
+ * 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,
+ Serializable deserialized) {
+
+ StringBuilder init = (StringBuilder) initial;
+ StringBuilder desr = (StringBuilder) deserialized;
+
+ assertEquals("toString", init.toString(), desr.toString());
+ }
+ };
+ */
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ // SerializationTest.verifySelf(new StringBuilder("0123456789"),
+ // STRING_BILDER_COMPARATOR);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ 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 Fixture() {
+ super();
+ }
+
+ @Override
+ public String toString() {
+ return "fixture";
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java
new file mode 100644
index 0000000..6bdaa3a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class StringIndexOutOfBoundsExceptionTest extends TestCase {
+
+ /**
+ * java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException()
+ */
+ public void test_Constructor() {
+ StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringTest.java
new file mode 100644
index 0000000..1b3659d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/StringTest.java
@@ -0,0 +1,697 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Constructor;
+import java.nio.charset.Charset;
+import java.util.Arrays;
+import java.util.SortedMap;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for the class {@link String}.
+ */
+public class StringTest extends TestCase {
+
+ private static final Constructor<String> UNSAFE_CONSTRUCTOR;
+
+ static {
+ Constructor<String> uc;
+ try {
+ uc = String.class.getDeclaredConstructor(new Class[] { int.class,
+ int.class, char[].class });
+ uc.setAccessible(true);
+ } catch (Exception e) {
+ uc = null;
+ }
+ UNSAFE_CONSTRUCTOR = uc;
+ }
+
+ private static String newString(int start, int len, char[] data) throws Exception {
+ if (UNSAFE_CONSTRUCTOR == null) {
+ return new String(data, start, len);
+ }
+
+ return UNSAFE_CONSTRUCTOR.newInstance(Integer.valueOf(start), Integer.valueOf(len),
+ data);
+ }
+
+ public void test_contains() {
+ assertTrue("aabc".contains("abc"));
+ assertTrue("abcd".contains("abc"));
+ assertFalse("abcd".contains("cba"));
+ }
+
+ public void test_charAt() {
+ assertTrue("abcd".charAt(0) == 'a');
+ assertTrue("abcd".charAt(3) == 'd');
+ }
+
+ public void test_StartsWith() {
+ assertTrue("abcd".startsWith("abc"));
+ assertFalse("abcd".startsWith("aabc"));
+ }
+
+ public void test_EndsWith() {
+ assertTrue("abcd".endsWith("bcd"));
+ assertFalse("abcd".endsWith("bcde"));
+ }
+
+ public void test_CASE_INSENSITIVE_ORDER() {
+ String s1 = "ABCDEFG";
+ String s2 = "abcdefg";
+
+ assertTrue(String.CASE_INSENSITIVE_ORDER.compare(s1, s2) == 0);
+ }
+
+ public void test_Constructor() {
+ assertEquals("Created incorrect string", "", new String());
+ }
+
+ public void test_Constructor$B() {
+ assertEquals("Failed to create string", "HelloWorld", new String(
+ "HelloWorld".getBytes()));
+ }
+
+ @SuppressWarnings("deprecation")
+ public void test_Constructor$BI() {
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0);
+ assertEquals("Incorrect string returned: " + s, "ABCDE", s);
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1);
+ assertFalse("Did not use nonzero hibyte", s.equals("ABCDE"));
+ }
+
+ public void test_Constructor$BII() {
+ byte[] hwba = "HelloWorld".getBytes();
+ assertEquals("Failed to create string", "HelloWorld", new String(hwba,
+ 0, hwba.length));
+
+ try {
+ new String(new byte[0], 0, Integer.MAX_VALUE);
+ fail("No IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ public void test_Constructor$BIII() {
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 1, 3);
+ assertEquals("Incorrect string returned: " + s, "BCD", s);
+ s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1, 0, 5);
+ assertFalse("Did not use nonzero hibyte", s.equals("ABCDE"));
+ }
+
+ public void test_Constructor$BIILjava_lang_String() throws Exception {
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "8859_1");
+ assertEquals("Incorrect string returned: " + s, "ABCDE", s);
+
+ try {
+ new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "");
+ fail("Should throw UnsupportedEncodingException");
+ } catch (UnsupportedEncodingException e) {
+ //expected
+ }
+ }
+
+ public void test_Constructor$BLjava_lang_String() throws Exception {
+ String s = new String(new byte[] { 65, 66, 67, 68, 69 }, "8859_1");
+ assertEquals("Incorrect string returned: " + s, "ABCDE", s);
+ }
+
+ public void test_Constructor$C() {
+ assertEquals("Failed Constructor test", "World", new String(new char[] {
+ 'W', 'o', 'r', 'l', 'd' }));
+ }
+
+ public void test_Constructor$CII() throws Exception {
+ char[] buf = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
+ String s = new String(buf, 0, buf.length);
+ assertEquals("Incorrect string created", "HelloWorld", s);
+
+ try {
+ new String(new char[0], 0, Integer.MAX_VALUE);
+ fail("No IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_ConstructorLjava_lang_String() {
+ String s = new String("Hello World");
+ assertEquals("Failed to construct correct string", "Hello World", s);
+ }
+
+ public void test_ConstructorLjava_lang_StringBuffer() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("HelloWorld");
+ assertEquals("Created incorrect string", "HelloWorld", new String(sb));
+ }
+
+ public void test_ConstructorLjava_lang_StringBuilder() {
+ StringBuilder sb = new StringBuilder(32);
+ sb.append("HelloWorld");
+ assertEquals("HelloWorld", new String(sb));
+
+ try {
+ new String((StringBuilder) null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_Constructor$III() {
+ assertEquals("HelloWorld", new String(new int[] { 'H', 'e', 'l', 'l',
+ 'o', 'W', 'o', 'r', 'l', 'd' }, 0, 10));
+ assertEquals("Hello", new String(new int[] { 'H', 'e', 'l', 'l', 'o',
+ 'W', 'o', 'r', 'l', 'd' }, 0, 5));
+ assertEquals("World", new String(new int[] { 'H', 'e', 'l', 'l', 'o',
+ 'W', 'o', 'r', 'l', 'd' }, 5, 5));
+ assertEquals("", new String(new int[] { 'H', 'e', 'l', 'l', 'o', 'W',
+ 'o', 'r', 'l', 'd' }, 5, 0));
+
+ assertEquals("\uD800\uDC00", new String(new int[] { 0x010000 }, 0, 1));
+ assertEquals("\uD800\uDC00a\uDBFF\uDFFF", new String(new int[] {
+ 0x010000, 'a', 0x010FFFF }, 0, 3));
+
+ try {
+ new String((int[]) null, 0, 1);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ new String(new int[] { 'a', 'b' }, -1, 2);
+ fail("No IOOBE, negative offset");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ new String(new int[] { 'a', 'b' }, 0, -1);
+ fail("No IOOBE, negative count");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ new String(new int[] { 'a', 'b' }, 0, -1);
+ fail("No IOOBE, negative count");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ new String(new int[] { 'a', 'b' }, 0, 3);
+ fail("No IOOBE, too large");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_contentEqualsLjava_lang_CharSequence() throws Exception {
+ String s = "abc";
+ assertTrue(s.contentEquals((CharSequence) new StringBuffer("abc")));
+ assertFalse(s.contentEquals((CharSequence) new StringBuffer("def")));
+ assertFalse(s.contentEquals((CharSequence) new StringBuffer("ghij")));
+
+ s = newString(1, 3, "_abc_".toCharArray());
+ assertTrue(s.contentEquals((CharSequence) new StringBuffer("abc")));
+ assertFalse(s.contentEquals((CharSequence) new StringBuffer("def")));
+ assertFalse(s.contentEquals((CharSequence) new StringBuffer("ghij")));
+
+ try {
+ s.contentEquals((CharSequence) null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ @SuppressWarnings("nls")
+ public void test_boolean_contentEquals_StringBuffer() throws Exception {
+ String s = "abc";
+ assertTrue(s.contentEquals(new StringBuffer("abc")));
+ assertFalse(s.contentEquals(new StringBuffer("def")));
+ assertFalse(s.contentEquals(new StringBuffer("ghij")));
+
+ s = newString(1, 3, "_abc_".toCharArray());
+ assertTrue(s.contentEquals(new StringBuffer("abc")));
+ assertFalse(s.contentEquals(new StringBuffer("def")));
+ assertFalse(s.contentEquals(new StringBuffer("ghij")));
+
+ try {
+ s.contentEquals((StringBuffer) null);
+ fail("Should throw a NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ @SuppressWarnings("cast")
+ public void test_containsLjava_lang_CharSequence() throws Exception {
+ String s = "abcdefghijklmnopqrstuvwxyz";
+ assertTrue(s.contains((CharSequence) new StringBuffer("abc")));
+ assertTrue(s.contains((CharSequence) new StringBuffer("def")));
+ assertFalse(s.contains((CharSequence) new StringBuffer("ac")));
+
+ s = newString(1, 26, "_abcdefghijklmnopqrstuvwxyz_".toCharArray());
+ assertTrue(s.contains((CharSequence) new StringBuffer("abc")));
+ assertTrue(s.contains((CharSequence) new StringBuffer("def")));
+ assertFalse(s.contains((CharSequence) new StringBuffer("ac")));
+
+ try {
+ s.contentEquals((CharSequence) null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_offsetByCodePoints_II() throws Exception {
+ int result = new String("a\uD800\uDC00b").offsetByCodePoints(0, 2);
+ assertEquals(3, result);
+
+ result = new String("abcd").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new String("a\uD800\uDC00b").offsetByCodePoints(0, 3);
+ assertEquals(4, result);
+
+ result = new String("a\uD800\uDC00b").offsetByCodePoints(3, -1);
+ assertEquals(1, result);
+
+ result = new String("a\uD800\uDC00b").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new String("\uD800\uDC00bc").offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = new String("a\uDC00bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = new String("a\uD800bc").offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
+ .offsetByCodePoints(0, 2);
+ assertEquals(3, result);
+
+ result = newString(2, 4, "__abcd__".toCharArray()).offsetByCodePoints(
+ 3, -1);
+ assertEquals(2, result);
+
+ result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
+ .offsetByCodePoints(0, 3);
+ assertEquals(4, result);
+
+ result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
+ .offsetByCodePoints(3, -1);
+ assertEquals(1, result);
+
+ result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
+ .offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = newString(2, 4, "__\uD800\uDC00bc__".toCharArray())
+ .offsetByCodePoints(3, 0);
+ assertEquals(3, result);
+
+ result = newString(2, 4, "__a\uDC00bc__".toCharArray())
+ .offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ result = newString(2, 4, "__a\uD800bc__".toCharArray())
+ .offsetByCodePoints(3, -1);
+ assertEquals(2, result);
+
+ String s = "abc";
+ try {
+ s.offsetByCodePoints(-1, 1);
+ fail("No IOOBE for negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(0, 4);
+ fail("No IOOBE for offset that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(3, -4);
+ fail("No IOOBE for offset that's too small.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(3, 1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(4, -1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ try {
+ s.offsetByCodePoints(-1, 1);
+ fail("No IOOBE for negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(0, 4);
+ fail("No IOOBE for offset that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(3, -4);
+ fail("No IOOBE for offset that's too small.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(3, 1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.offsetByCodePoints(4, -1);
+ fail("No IOOBE for index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointAtI() throws Exception {
+ String s = "abc";
+ assertEquals('a', s.codePointAt(0));
+ assertEquals('b', s.codePointAt(1));
+ assertEquals('c', s.codePointAt(2));
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ assertEquals('a', s.codePointAt(0));
+ assertEquals('b', s.codePointAt(1));
+ assertEquals('c', s.codePointAt(2));
+
+ s = "\uD800\uDC00";
+ assertEquals(0x10000, s.codePointAt(0));
+ assertEquals('\uDC00', s.codePointAt(1));
+
+ s = newString(2, 2, "__\uD800\uDC00__".toCharArray());
+ assertEquals(0x10000, s.codePointAt(0));
+ assertEquals('\uDC00', s.codePointAt(1));
+
+ s = "abc";
+ try {
+ s.codePointAt(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointAt(s.length());
+ fail("No IOOBE on index equal to length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointAt(s.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ try {
+ s.codePointAt(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointAt(s.length());
+ fail("No IOOBE on index equal to length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointAt(s.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointBeforeI() throws Exception {
+ String s = "abc";
+ assertEquals('a', s.codePointBefore(1));
+ assertEquals('b', s.codePointBefore(2));
+ assertEquals('c', s.codePointBefore(3));
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ assertEquals('a', s.codePointBefore(1));
+ assertEquals('b', s.codePointBefore(2));
+ assertEquals('c', s.codePointBefore(3));
+
+ s = "\uD800\uDC00";
+ assertEquals(0x10000, s.codePointBefore(2));
+ assertEquals('\uD800', s.codePointBefore(1));
+
+ s = newString(2, 2, "__\uD800\uDC00__".toCharArray());
+ assertEquals(0x10000, s.codePointBefore(2));
+ assertEquals('\uD800', s.codePointBefore(1));
+
+ s = "abc";
+ try {
+ s.codePointBefore(0);
+ fail("No IOOBE on zero index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointBefore(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointBefore(s.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ try {
+ s.codePointBefore(0);
+ fail("No IOOBE on zero index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointBefore(-1);
+ fail("No IOOBE on negative index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointBefore(s.length() + 1);
+ fail("No IOOBE on index greater than length.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_codePointCountII() throws Exception {
+ assertEquals(1, "\uD800\uDC00".codePointCount(0, 2));
+ assertEquals(1, "\uD800\uDC01".codePointCount(0, 2));
+ assertEquals(1, "\uD801\uDC01".codePointCount(0, 2));
+ assertEquals(1, "\uDBFF\uDFFF".codePointCount(0, 2));
+
+ assertEquals(3, "a\uD800\uDC00b".codePointCount(0, 4));
+ assertEquals(4, "a\uD800\uDC00b\uD800".codePointCount(0, 5));
+
+ assertEquals(1, newString(2, 2, "__\uD800\uDC00__".toCharArray()).codePointCount(0, 2));
+ assertEquals(1, newString(2, 2, "__\uD800\uDC01__".toCharArray()).codePointCount(0, 2));
+ assertEquals(1, newString(2, 2, "__\uD801\uDC01__".toCharArray()).codePointCount(0, 2));
+ assertEquals(1, newString(2, 2, "__\uDBFF\uDFFF__".toCharArray()).codePointCount(0, 2));
+
+ assertEquals(3, newString(2, 4, "__a\uD800\uDC00b__".toCharArray()).codePointCount(0, 4));
+ assertEquals(4, newString(2, 5, "__a\uD800\uDC00b\uD800__".toCharArray()).codePointCount(0, 5));
+
+ String s = "abc";
+ try {
+ s.codePointCount(-1, 2);
+ fail("No IOOBE for negative begin index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointCount(0, 4);
+ fail("No IOOBE for end index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointCount(3, 2);
+ fail("No IOOBE for begin index larger than end index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ s = newString(2, 3, "__abc__".toCharArray());
+ try {
+ s.codePointCount(-1, 2);
+ fail("No IOOBE for negative begin index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointCount(0, 4);
+ fail("No IOOBE for end index that's too large.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ s.codePointCount(3, 2);
+ fail("No IOOBE for begin index larger than end index.");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ public void test_ConstructorBIIL() throws Exception {
+ // can construct normally
+ new String(new byte[8], 0, 4, Charset.defaultCharset());
+ new String(new byte[8], 8, 0, Charset.defaultCharset());
+ new String(new byte[0], 0, 0, Charset.defaultCharset());
+ // throws exceptions
+ try {
+ new String(new byte[8], 0, 9, Charset.defaultCharset());
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ new String(new byte[8], 9, 0, Charset.defaultCharset());
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ new String(new byte[8], -1, 0, Charset.defaultCharset());
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ new String(new byte[8], 9, -1, Charset.defaultCharset());
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ new String(null, -1, 0, Charset.defaultCharset());
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+ try {
+ new String(null, 0, -1, Charset.defaultCharset());
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+ try {
+ new String(null, 0, 9, Charset.defaultCharset());
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new String(null, 0, 0, Charset.defaultCharset());
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new String(null, -1, 0, (Charset) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new String(new byte[8], -1, 0, (Charset) null);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+ try {
+ new String(new byte[8], 0, 9, (Charset) null);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+ try {
+ new String(new byte[8], 0, 4, (Charset) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_ConstructorBL() throws Exception {
+ new String(new byte[8], Charset.defaultCharset());
+ try {
+ new String(new byte[8], (Charset) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new String(new byte[0], (Charset) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new String(null, Charset.defaultCharset());
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ new String(new byte[0], Charset.defaultCharset());
+ }
+
+ public void test_isEmpty() throws Exception {
+ assertTrue(new String(new byte[0], Charset.defaultCharset()).isEmpty());
+ assertTrue(new String(new byte[8], Charset.defaultCharset()).substring(0, 0).isEmpty());
+ }
+
+ public void test_getBytesLCharset() throws Exception {
+ byte[] emptyBytes = new byte[0];
+ byte[] someBytes = new byte[] { 'T', 'h', 'i', 's', ' ', ' ', 'i', 's', ' ', 't', 'e', 's', 't', ' ', 'b', 'y', 't', 'e', 's' };
+ assertEquals(0, new String(emptyBytes, Charset.defaultCharset()).getBytes(Charset.defaultCharset()).length);
+ try {
+ new String(emptyBytes, Charset.defaultCharset()).getBytes((Charset) null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertTrue(bytesEquals(someBytes, new String(someBytes, Charset.defaultCharset()).getBytes(Charset.defaultCharset())));
+ SortedMap<String, Charset> charsets = Charset.availableCharsets();
+ }
+
+ boolean bytesEquals(byte[] bytes1, byte[] bytes2) {
+ return Arrays.toString(bytes1).equals(Arrays.toString(bytes2));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SystemTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SystemTest.java
new file mode 100644
index 0000000..05a02c3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/SystemTest.java
@@ -0,0 +1,413 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.util.Map;
+import java.util.Properties;
+
+public class SystemTest extends junit.framework.TestCase {
+
+ static boolean flag = false;
+
+ static boolean ranFinalize = false;
+
+ /**
+ * java.lang.System#setIn(java.io.InputStream)
+ */
+ public void test_setInLjava_io_InputStream() {
+ InputStream orgIn = System.in;
+ InputStream in = new ByteArrayInputStream(new byte[0]);
+ System.setIn(in);
+ assertTrue("in not set", System.in == in);
+ System.setIn(orgIn);
+ }
+
+ /**
+ * java.lang.System#setOut(java.io.PrintStream)
+ */
+ public void test_setOutLjava_io_PrintStream() {
+ PrintStream orgOut = System.out;
+ PrintStream out = new PrintStream(new ByteArrayOutputStream());
+ System.setOut(out);
+ assertTrue("out not set", System.out == out);
+ System.setOut(orgOut);
+ }
+
+ /**
+ * java.lang.System#setErr(java.io.PrintStream)
+ */
+ public void test_setErrLjava_io_PrintStream() {
+ PrintStream orgErr = System.err;
+ PrintStream err = new PrintStream(new ByteArrayOutputStream());
+ System.setErr(err);
+ assertTrue("err not set", System.err == err);
+ System.setErr(orgErr);
+ }
+
+ /**
+ * java.lang.System#arraycopy(java.lang.Object, int,
+ *java.lang.Object, int, int)
+ */
+ public void test_arraycopyLjava_lang_ObjectILjava_lang_ObjectII() {
+ // Test for method void java.lang.System.arraycopy(java.lang.Object,
+ // int, java.lang.Object, int, int)
+ Integer a[] = new Integer[20];
+ Integer b[] = new Integer[20];
+ int i = 0;
+ while (i < a.length) {
+ a[i] = new Integer(i);
+ ++i;
+ }
+ System.arraycopy(a, 0, b, 0, a.length);
+ for (i = 0; i < a.length; i++)
+ assertTrue("Copied elements incorrectly", a[i].equals(b[i]));
+
+ /* Non primitive array types don't need to be identical */
+ String[] source1 = new String[] { "element1" };
+ Object[] dest1 = new Object[1];
+ System.arraycopy(source1, 0, dest1, 0, dest1.length);
+ assertTrue("Invalid copy 1", dest1[0] == source1[0]);
+
+ char[][] source = new char[][] { { 'H', 'e', 'l', 'l', 'o' },
+ { 'W', 'o', 'r', 'l', 'd' } };
+ char[][] dest = new char[2][];
+ System.arraycopy(source, 0, dest, 0, dest.length);
+ assertTrue("Invalid copy 2", dest[0] == source[0]
+ && dest[1] == source[1]);
+ }
+
+ /**
+ * java.lang.System#currentTimeMillis()
+ */
+ public void test_currentTimeMillis() {
+ // Test for method long java.lang.System.currentTimeMillis()
+ long firstRead = System.currentTimeMillis();
+ try {
+ Thread.sleep(150);
+ } catch (InterruptedException e) {
+ }
+ long secondRead = System.currentTimeMillis();
+ assertTrue("Incorrect times returned: " + firstRead + ", "
+ + secondRead, firstRead < secondRead);
+ }
+
+ /**
+ * java.lang.System#exit(int)
+ */
+ public void test_exitI() {
+ // Test for method void java.lang.System.exit(int)
+ // Tested in destructive test: Test_System_Exit ???
+ }
+
+ /**
+ * java.lang.System#getProperties()
+ */
+ public void test_getProperties() {
+ // Test for method java.util.Properties java.lang.System.getProperties()
+ Properties p = System.getProperties();
+
+ // Ensure spec'ed properties are non-null. See System.getProperties()
+ // spec.
+ String[] props = { "java.version", "java.vendor", "java.vendor.url",
+ "java.home", "java.vm.specification.version",
+ "java.vm.specification.vendor", "java.vm.specification.name",
+ "java.vm.version", "java.vm.vendor", "java.vm.name",
+ "java.specification.name", "java.specification.vendor",
+ "java.specification.name", "java.class.version",
+ "java.class.path", "java.ext.dirs", "os.name", "os.arch",
+ "os.version", "file.separator", "path.separator",
+ "line.separator", "user.name", "user.home", "user.dir", };
+ for (int i = 0; i < props.length; i++) {
+ assertNotNull(props[i], System.getProperty(props[i]));
+ }
+ }
+
+ /**
+ * java.lang.System#getProperty(java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.lang.System.getProperty(java.lang.String)
+
+ boolean is8859_1 = true;
+ String encoding = System.getProperty("file.encoding");
+ byte[] bytes = new byte[128];
+ char[] chars = new char[128];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = (byte) (i + 128);
+ chars[i] = (char) (i + 128);
+ }
+ String charResult = new String(bytes);
+ byte[] byteResult = new String(chars).getBytes();
+ if (charResult.length() == 128 && byteResult.length == 128) {
+ for (int i = 0; i < bytes.length; i++) {
+ if (charResult.charAt(i) != (char) (i + 128)
+ || byteResult[i] != (byte) (i + 128))
+ is8859_1 = false;
+ }
+ } else
+ is8859_1 = false;
+ String[] possibles = new String[] { "ISO8859_1", "8859_1", "ISO8859-1",
+ "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1978", "ISO-IR-100",
+ "LATIN1", "CSISOLATIN1" };
+ boolean found8859_1 = false;
+ for (int i = 0; i < possibles.length; i++) {
+ if (possibles[i].equals(encoding)) {
+ found8859_1 = true;
+ break;
+ }
+ }
+ assertTrue("Wrong encoding: " + encoding, !is8859_1 || found8859_1);
+ }
+
+ /**
+ * java.lang.System#getProperty(java.lang.String)
+ * Tests that there are no extra path separator in boot class path.
+ * Regression test for HARMONY-3298
+ */
+ public void test_getProperty_bootClassPath() {
+ String bootClassPath = System.getProperty("org.apache.harmony.boot.class.path");
+
+ if (bootClassPath == null) {
+ bootClassPath = System.getProperty("sun.boot.class.path");
+ }
+
+ if (bootClassPath != null
+ && (bootClassPath.indexOf(File.pathSeparator + File.pathSeparator) >= 0)) {
+ fail("Boot class path contains extra path separator: " + bootClassPath);
+ }
+ }
+
+ /**
+ * java.lang.System#getProperty(java.lang.String, java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_StringLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.lang.System.getProperty(java.lang.String, java.lang.String)
+ assertTrue(!System.getProperty("java.version", "99999").equals("99999"));
+ assertEquals("Failed to return correct property value", "bogus", System
+ .getProperty("bogus.prop", "bogus"));
+ }
+
+ /**
+ * java.lang.System#setProperty(java.lang.String, java.lang.String)
+ */
+ public void test_setPropertyLjava_lang_StringLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.lang.System.setProperty(java.lang.String, java.lang.String)
+
+ assertNull("Failed to return null", System.setProperty("testing",
+ "value1"));
+ assertTrue("Failed to return old value", System.setProperty("testing",
+ "value2") == "value1");
+ assertTrue("Failed to find value",
+ System.getProperty("testing") == "value2");
+
+ boolean exception = false;
+ try {
+ System.setProperty("", "default");
+ } catch (IllegalArgumentException e) {
+ exception = true;
+ }
+ assertTrue("Expected IllegalArgumentException", exception);
+ }
+
+ /**
+ * java.lang.System#getSecurityManager()
+ */
+ public void test_getSecurityManager() {
+ // Test for method java.lang.SecurityManager
+ // java.lang.System.getSecurityManager()
+ assertNull("Returned incorrect SecurityManager", System
+ .getSecurityManager());
+ }
+
+ /**
+ * java.lang.System#identityHashCode(java.lang.Object)
+ */
+ public void test_identityHashCodeLjava_lang_Object() {
+ // Test for method int
+ // java.lang.System.identityHashCode(java.lang.Object)
+ Object o = new Object();
+ String s = "Gabba";
+ assertEquals("Nonzero returned for null",
+ 0, System.identityHashCode(null));
+ assertTrue("Nonequal has returned for Object", System
+ .identityHashCode(o) == o.hashCode());
+ assertTrue("Same as usual hash returned for String", System
+ .identityHashCode(s) != s.hashCode());
+ }
+
+ /**
+ * java.lang.System#runFinalization()
+ */
+ public void test_runFinalization() {
+ // Test for method void java.lang.System.runFinalization()
+
+ flag = true;
+ createInstance();
+ int count = 10;
+ // the gc below likely bogosifies the test, but will have to do for
+ // the moment
+ while (!ranFinalize && count-- > 0) {
+ System.gc();
+ System.runFinalization();
+ }
+ assertTrue("Failed to run finalization", ranFinalize);
+ }
+
+ /**
+ * java.lang.System#runFinalizersOnExit(boolean)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_runFinalizersOnExitZ() {
+ // Can we call the method at least?
+ System.runFinalizersOnExit(false);
+ }
+
+ /**
+ * java.lang.System#setProperties(java.util.Properties)
+ */
+ public void test_setPropertiesLjava_util_Properties() {
+ // Test for method void
+ // java.lang.System.setProperties(java.util.Properties)
+
+ Properties orgProps = System.getProperties();
+ java.util.Properties tProps = new java.util.Properties();
+ tProps.put("test.prop", "this is a test property");
+ tProps.put("bogus.prop", "bogus");
+ System.setProperties(tProps);
+ try {
+ assertEquals("Failed to set properties", "this is a test property", System.getProperties()
+ .getProperty("test.prop"));
+ } finally {
+ // restore the original properties
+ System.setProperties(orgProps);
+ }
+ }
+
+ //Regression Test for Harmony-2356
+ public void testEnvUnmodifiable() {
+ Map map = System.getenv();
+ try {
+ map.containsKey(null);
+ fail("Should throw NullPointerExcepiton.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ map.containsKey(new Integer(10));
+ fail("Should throw ClassCastException.");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ try {
+ map.containsValue(null);
+ fail("Should throw NullPointerExcepiton.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ map.containsValue(new Integer(10));
+ fail("Should throw ClassCastException.");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ try {
+ map.get(null);
+ fail("Should throw NullPointerExcepiton.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ map.get(new Integer(10));
+ fail("Should throw ClassCastException.");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ try {
+ map.put(null, "AAA");
+ fail("Should throw UnsupportedOperationExcepiton.");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ map.put("AAA", new Integer(10));
+ fail("Should throw UnsupportedOperationException.");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ map.put("AAA", "BBB");
+ fail("Should throw UnsupportedOperationException.");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ map.clear();
+ fail("Should throw UnsupportedOperationException.");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ map.remove(null);
+ // Android isn't as strict about requiring this exception; no modification takes place anyway
+ // fail("Should throw UnsupportedOperationException.");
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ }
+
+ @Override
+ protected void setUp() {
+ flag = false;
+ ranFinalize = false;
+ }
+
+ protected SystemTest createInstance() {
+ return new SystemTest("FT");
+ }
+
+ @Override
+ protected void finalize() {
+ if (flag)
+ ranFinalize = true;
+ }
+
+ public SystemTest() {
+ }
+
+ public SystemTest(String name) {
+ super(name);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadDeathTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadDeathTest.java
new file mode 100644
index 0000000..1d21dd3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadDeathTest.java
@@ -0,0 +1,30 @@
+/*
+ * 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.tests.java.lang;
+
+public class ThreadDeathTest extends junit.framework.TestCase {
+
+ /**
+ * java.lang.ThreadDeath#ThreadDeath()
+ */
+ public void test_Constructor() {
+ ThreadDeath td = new ThreadDeath();
+ assertNull(td.getCause());
+ assertNull(td.getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadGroupTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadGroupTest.java
new file mode 100644
index 0000000..a437939
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadGroupTest.java
@@ -0,0 +1,795 @@
+/*
+ * 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.tests.java.lang;
+
+import java.util.Vector;
+
+public class ThreadGroupTest extends junit.framework.TestCase {
+
+ private TestThreadDefaultUncaughtExceptionHandler testThreadDefaultUncaughtExceptionHandler;
+ private ThreadGroup rootThreadGroup;
+ private ThreadGroup initialThreadGroup;
+ private Thread.UncaughtExceptionHandler originalThreadDefaultUncaughtExceptionHandler;
+
+ @Override
+ protected void setUp() {
+ initialThreadGroup = Thread.currentThread().getThreadGroup();
+ rootThreadGroup = initialThreadGroup;
+ while (rootThreadGroup.getParent() != null) {
+ rootThreadGroup = rootThreadGroup.getParent();
+ }
+
+ // When running as a CTS test Android will by default treat an uncaught exception as a
+ // fatal application error and kill the test. To avoid this the default
+ // UncaughtExceptionHandler is replaced for the duration of the test (if one exists). It
+ // also allows us to test that ultimately the default handler is called if a ThreadGroup's
+ // UncaughtExceptionHandler doesn't handle an exception.
+ originalThreadDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
+ testThreadDefaultUncaughtExceptionHandler = new TestThreadDefaultUncaughtExceptionHandler();
+ Thread.setDefaultUncaughtExceptionHandler(testThreadDefaultUncaughtExceptionHandler);
+ }
+
+ @Override
+ protected void tearDown() {
+ // Reset the uncaughtExceptionHandler to what it was when the test began.
+ Thread.setDefaultUncaughtExceptionHandler(originalThreadDefaultUncaughtExceptionHandler);
+ }
+
+ // Test for method java.lang.ThreadGroup(java.lang.String)
+ public void test_ConstructorLjava_lang_String() {
+ // Unfortunately we have to use other APIs as well as we test the constructor
+ ThreadGroup initial = initialThreadGroup;
+ final String name = "Test name";
+ ThreadGroup newGroup = new ThreadGroup(name);
+ assertTrue(
+ "Has to be possible to create a subgroup of current group using simple constructor",
+ newGroup.getParent() == initial);
+ assertTrue("Name has to be correct", newGroup.getName().equals(name));
+
+ // cleanup
+ newGroup.destroy();
+ }
+
+ // Test for method java.lang.ThreadGroup(java.lang.ThreadGroup, java.lang.String)
+ public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_String() {
+ // Unfortunately we have to use other APIs as well as we test the constructor
+ ThreadGroup newGroup = null;
+ try {
+ newGroup = new ThreadGroup(null, null);
+ } catch (NullPointerException e) {
+ }
+ assertNull("Can't create a ThreadGroup with a null parent", newGroup);
+
+ newGroup = new ThreadGroup(initialThreadGroup, null);
+ assertTrue("Has to be possible to create a subgroup of current group",
+ newGroup.getParent() == Thread.currentThread().getThreadGroup());
+
+ // Lets start all over
+ newGroup.destroy();
+
+ newGroup = new ThreadGroup(rootThreadGroup, "a name here");
+ assertTrue("Has to be possible to create a subgroup of root group",
+ newGroup.getParent() == rootThreadGroup);
+
+ // Lets start all over
+ newGroup.destroy();
+
+ try {
+ newGroup = new ThreadGroup(newGroup, "a name here");
+ } catch (IllegalThreadStateException e) {
+ newGroup = null;
+ }
+ assertNull("Can't create a subgroup of a destroyed group", newGroup);
+ }
+
+ // Test for method int java.lang.ThreadGroup.activeCount()
+ public void test_activeCount() {
+ ThreadGroup tg = new ThreadGroup("activeCount");
+ Thread t1 = new Thread(tg, new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(5000);
+ } catch (InterruptedException e) {
+ }
+ }
+ });
+ int count = tg.activeCount();
+ assertTrue("wrong active count: " + count, count == 0);
+ t1.start();
+ count = tg.activeCount();
+ assertTrue("wrong active count: " + count, count == 1);
+ t1.interrupt();
+ try {
+ t1.join();
+ } catch (InterruptedException e) {
+ }
+ // cleanup
+ tg.destroy();
+ }
+
+ // Test for method void java.lang.ThreadGroup.destroy()
+ public void test_destroy() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
+ final int DEPTH = 4;
+ final Vector<ThreadGroup> subgroups = buildRandomTreeUnder(testRoot, DEPTH);
+
+ // destroy them all
+ testRoot.destroy();
+
+ for (int i = 0; i < subgroups.size(); i++) {
+ ThreadGroup child = subgroups.elementAt(i);
+ assertEquals("Destroyed child can't have children", 0, child.activeCount());
+ boolean passed = false;
+ try {
+ child.destroy();
+ } catch (IllegalThreadStateException e) {
+ passed = true;
+ }
+ assertTrue("Destroyed child can't be destroyed again", passed);
+ }
+
+ testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
+ testRoot.setDaemon(true);
+
+ ThreadGroup child = new ThreadGroup(testRoot, "daemon child");
+
+ // If we destroy the last daemon's child, the daemon should get destroyed
+ // as well
+ child.destroy();
+
+ boolean passed = false;
+ try {
+ child.destroy();
+ } catch (IllegalThreadStateException e) {
+ passed = true;
+ }
+ assertTrue("Daemon should have been destroyed already", passed);
+
+ passed = false;
+ try {
+ testRoot.destroy();
+ } catch (IllegalThreadStateException e) {
+ passed = true;
+ }
+ assertTrue("Daemon parent should have been destroyed automatically",
+ passed);
+
+ assertTrue(
+ "Destroyed daemon's child should not be in daemon's list anymore",
+ !arrayIncludes(groups(testRoot), child));
+ assertTrue("Destroyed daemon should not be in parent's list anymore",
+ !arrayIncludes(groups(originalCurrent), testRoot));
+
+ testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
+ testRoot.setDaemon(true);
+ Thread noOp = new Thread(testRoot, null, "no-op thread") {
+ @Override
+ public void run() {
+ }
+ };
+ noOp.start();
+
+ // Wait for the no-op thread to run inside daemon ThreadGroup
+ waitForThreadToDieUninterrupted(noOp);
+
+ passed = false;
+ try {
+ child.destroy();
+ } catch (IllegalThreadStateException e) {
+ passed = true;
+ }
+ assertTrue("Daemon group should have been destroyed already when last thread died", passed);
+
+ testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
+ noOp = new Thread(testRoot, null, "no-op thread") {
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException ie) {
+ fail("Should not be interrupted");
+ }
+ }
+ };
+
+ // Has to execute the next lines in an interval < the sleep interval of the no-op thread
+ noOp.start();
+ passed = false;
+ try {
+ testRoot.destroy();
+ } catch (IllegalThreadStateException its) {
+ passed = true;
+ }
+ assertTrue("Can't destroy a ThreadGroup that has threads", passed);
+
+ // But after the thread dies, we have to be able to destroy the thread group
+ waitForThreadToDieUninterrupted(noOp);
+ passed = true;
+ try {
+ testRoot.destroy();
+ } catch (IllegalThreadStateException its) {
+ passed = false;
+ }
+ assertTrue("Should be able to destroy a ThreadGroup that has no threads", passed);
+ }
+
+ // Test for method java.lang.ThreadGroup.destroy()
+ public void test_destroy_subtest0() {
+ ThreadGroup group1 = new ThreadGroup("test_destroy_subtest0");
+ group1.destroy();
+ try {
+ new Thread(group1, "test_destroy_subtest0");
+ fail("should throw IllegalThreadStateException");
+ } catch (IllegalThreadStateException e) {
+ }
+ }
+
+ // Test for method int java.lang.ThreadGroup.getMaxPriority()
+ public void test_getMaxPriority() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
+
+ boolean passed = true;
+ try {
+ testRoot.setMaxPriority(Thread.MIN_PRIORITY);
+ } catch (IllegalArgumentException iae) {
+ passed = false;
+ }
+ assertTrue("Should be able to set priority", passed);
+
+ assertTrue("New value should be the same as we set",
+ testRoot.getMaxPriority() == Thread.MIN_PRIORITY);
+
+ testRoot.destroy();
+ }
+
+ // Test for method java.lang.String java.lang.ThreadGroup.getName()
+ public void test_getName() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ final String name = "Test group";
+ final ThreadGroup testRoot = new ThreadGroup(originalCurrent, name);
+
+ assertTrue("Setting a name&getting does not work", testRoot.getName().equals(name));
+
+ testRoot.destroy();
+ }
+
+ // Test for method java.lang.ThreadGroup java.lang.ThreadGroup.getParent()
+ public void test_getParent() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
+
+ assertTrue("Parent is wrong", testRoot.getParent() == originalCurrent);
+
+ // Create some groups, nested some levels.
+ final int TOTAL_DEPTH = 5;
+ ThreadGroup current = testRoot;
+ Vector<ThreadGroup> groups = new Vector<ThreadGroup>();
+ // To maintain the invariant that a thread in the Vector is parent
+ // of the next one in the collection (and child of the previous one)
+ groups.addElement(testRoot);
+
+ for (int i = 0; i < TOTAL_DEPTH; i++) {
+ current = new ThreadGroup(current, "level " + i);
+ groups.addElement(current);
+ }
+
+ // Now we walk the levels down, checking if parent is ok
+ for (int i = 1; i < groups.size(); i++) {
+ current = groups.elementAt(i);
+ ThreadGroup previous = groups.elementAt(i - 1);
+ assertTrue("Parent is wrong", current.getParent() == previous);
+ }
+
+ testRoot.destroy();
+ }
+
+ // Test for method void java.lang.ThreadGroup.list()
+ public void test_list() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ final ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
+
+ // First save the original System.out
+ java.io.PrintStream originalOut = System.out;
+
+ try {
+ java.io.ByteArrayOutputStream contentsStream = new java.io.ByteArrayOutputStream(100);
+ java.io.PrintStream newOut = new java.io.PrintStream(contentsStream);
+
+ // We have to "redirect" System.out to test the method 'list'
+ System.setOut(newOut);
+
+ originalCurrent.list();
+
+ /*
+ * The output has to look like this:
+ *
+ * java.lang.ThreadGroup[name=main,maxpri=10] Thread[main,5,main]
+ * java.lang.ThreadGroup[name=Test group,maxpri=10]
+ */
+ String contents = new String(contentsStream.toByteArray());
+ boolean passed = (contents.indexOf("ThreadGroup[name=main") != -1) &&
+ (contents.indexOf("Thread[") != -1) &&
+ (contents.indexOf("ThreadGroup[name=Test group") != -1);
+ assertTrue("'list()' does not print expected contents. "
+ + "Result from list: "
+ + contents, passed);
+ // Do proper cleanup
+ testRoot.destroy();
+
+ } finally {
+ // No matter what, we need to restore the original System.out
+ System.setOut(originalOut);
+ }
+ }
+
+ // Test for method boolean java.lang.ThreadGroup.parentOf(java.lang.ThreadGroup)
+ public void test_parentOfLjava_lang_ThreadGroup() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
+ "Test group");
+ final int DEPTH = 4;
+ buildRandomTreeUnder(testRoot, DEPTH);
+
+ final ThreadGroup[] allChildren = allGroups(testRoot);
+ for (ThreadGroup element : allChildren) {
+ assertTrue("Have to be parentOf all children", testRoot.parentOf(element));
+ }
+
+ assertTrue("Have to be parentOf itself", testRoot.parentOf(testRoot));
+
+ testRoot.destroy();
+ assertTrue("Parent can't have test group as subgroup anymore",
+ !arrayIncludes(groups(testRoot.getParent()), testRoot));
+ }
+
+ // Test for method boolean java.lang.ThreadGroup.isDaemon() and
+ // void java.lang.ThreadGroup.setDaemon(boolean)
+ public void test_setDaemon_isDaemon() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
+ "Test group");
+
+ testRoot.setDaemon(true);
+ assertTrue("Setting daemon&getting does not work", testRoot.isDaemon());
+
+ testRoot.setDaemon(false);
+ assertTrue("Setting daemon&getting does not work", !testRoot.isDaemon());
+
+ testRoot.destroy();
+ }
+
+ /*
+ * java.lang.ThreadGroupt#setDaemon(boolean)
+ */
+ public void test_setDaemon_Parent_Child() {
+ ThreadGroup ptg = new ThreadGroup("Parent");
+ ThreadGroup ctg = new ThreadGroup(ptg, "Child");
+
+ ctg.setDaemon(true);
+ assertTrue(ctg.isDaemon());
+
+ ctg.setDaemon(false);
+ assertFalse(ctg.isDaemon());
+
+ ptg.setDaemon(true);
+ assertFalse(ctg.isDaemon());
+
+ ptg.setDaemon(false);
+ assertFalse(ctg.isDaemon());
+ }
+
+ // Test for method void java.lang.ThreadGroup.setMaxPriority(int)
+ public void test_setMaxPriorityI() {
+ final ThreadGroup originalCurrent = initialThreadGroup;
+ ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
+
+ boolean passed;
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ int currentMax = testRoot.getMaxPriority();
+ testRoot.setMaxPriority(Thread.MAX_PRIORITY + 1);
+ passed = testRoot.getMaxPriority() == currentMax;
+ assertTrue(
+ "setMaxPriority: Any value higher than the current one is ignored. Before: "
+ + currentMax + " , after: " + testRoot.getMaxPriority(),
+ passed);
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ currentMax = testRoot.getMaxPriority();
+ testRoot.setMaxPriority(Thread.MIN_PRIORITY - 1);
+ passed = testRoot.getMaxPriority() == Thread.MIN_PRIORITY;
+ assertTrue(
+ "setMaxPriority: Any value smaller than MIN_PRIORITY is adjusted to MIN_PRIORITY. Before: "
+ + currentMax + " , after: " + testRoot.getMaxPriority(), passed);
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ testRoot.destroy();
+ testRoot = new ThreadGroup(originalCurrent, "Test group");
+
+ // Create some groups, nested some levels. Each level will have maxPrio
+ // 1 unit smaller than the parent's. However, there can't be a group
+ // with priority < Thread.MIN_PRIORITY
+ final int TOTAL_DEPTH = testRoot.getMaxPriority() - Thread.MIN_PRIORITY
+ - 2;
+ ThreadGroup current = testRoot;
+ for (int i = 0; i < TOTAL_DEPTH; i++) {
+ current = new ThreadGroup(current, "level " + i);
+ }
+
+ // Now we walk the levels down, changing the maxPrio and later verifying
+ // that the value is indeed 1 unit smaller than the parent's maxPrio.
+ int maxPrio, parentMaxPrio;
+ current = testRoot;
+
+ // To maintain the invariant that when we are to modify a child,
+ // its maxPriority is always 1 unit smaller than its parent's.
+ // We have to set it for the root manually, and the loop does the rest
+ // for all the other sub-levels
+ current.setMaxPriority(current.getParent().getMaxPriority() - 1);
+
+ for (int i = 0; i < TOTAL_DEPTH; i++) {
+ maxPrio = current.getMaxPriority();
+ parentMaxPrio = current.getParent().getMaxPriority();
+
+ ThreadGroup[] children = groups(current);
+ assertEquals("Can only have 1 subgroup", 1, children.length);
+ current = children[0];
+ assertTrue(
+ "Had to be 1 unit smaller than parent's priority in iteration="
+ + i + " checking->" + current,
+ maxPrio == parentMaxPrio - 1);
+ current.setMaxPriority(maxPrio - 1);
+
+ // The next test is sort of redundant, since in next iteration it
+ // will be the parent tGroup, so the test will be done.
+ assertTrue("Had to be possible to change max priority", current
+ .getMaxPriority() == maxPrio - 1);
+ }
+
+ assertTrue(
+ "Priority of leaf child group has to be much smaller than original root group",
+ current.getMaxPriority() == testRoot.getMaxPriority() - TOTAL_DEPTH);
+
+ testRoot.destroy();
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ passed = true;
+ testRoot = new ThreadGroup(originalCurrent, "Test group");
+ try {
+ testRoot.setMaxPriority(Thread.MAX_PRIORITY);
+ } catch (IllegalArgumentException iae) {
+ passed = false;
+ }
+ assertTrue(
+ "Max Priority = Thread.MAX_PRIORITY should be possible if the test is run with default system ThreadGroup as root",
+ passed);
+ testRoot.destroy();
+ }
+
+ /*
+ * Test for method void java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
+ * java.lang.Throwable)
+ * Tests if a Thread tells its ThreadGroup about ThreadDeath.
+ */
+ public void test_uncaughtException_threadDeath() {
+ final boolean[] passed = new boolean[1];
+
+ ThreadGroup testRoot = new ThreadGroup(rootThreadGroup,
+ "Test Forcing a throw of ThreadDeath") {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ if (e instanceof ThreadDeath) {
+ passed[0] = true;
+ }
+ // always forward, any exception
+ super.uncaughtException(t, e);
+ }
+ };
+
+ final ThreadDeath threadDeath = new ThreadDeath();
+ Thread thread = new Thread(testRoot, null, "suicidal thread") {
+ @Override
+ public void run() {
+ throw threadDeath;
+ }
+ };
+ thread.start();
+ waitForThreadToDieUninterrupted(thread);
+ testThreadDefaultUncaughtExceptionHandler.assertWasCalled(thread, threadDeath);
+
+ testRoot.destroy();
+ assertTrue(
+ "Any thread should notify its ThreadGroup about its own death, even if suicide:"
+ + testRoot, passed[0]);
+ }
+
+ /*
+ * Test for method void java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
+ * java.lang.Throwable)
+ * Test if a Thread tells its ThreadGroup about a natural (non-exception) death.
+ */
+ public void test_uncaughtException_naturalDeath() {
+ final boolean[] failed = new boolean[1];
+
+ ThreadGroup testRoot = new ThreadGroup(initialThreadGroup, "Test ThreadDeath") {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ failed[0] = true;
+
+ // always forward any exception
+ super.uncaughtException(t, e);
+ }
+ };
+
+ Thread thread = new Thread(testRoot, null, "no-op thread");
+ thread.start();
+ waitForThreadToDieUninterrupted(thread);
+ testThreadDefaultUncaughtExceptionHandler.assertWasNotCalled();
+ testRoot.destroy();
+ assertFalse("A thread should not call uncaughtException when it dies:"
+ + testRoot, failed[0]);
+ }
+
+ /*
+ * Test for method void java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
+ * java.lang.Throwable)
+ * Test if a Thread tells its ThreadGroup about an Exception
+ */
+ public void test_uncaughtException_runtimeException() {
+ // Our own exception class
+ class TestException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+ }
+
+ final boolean[] passed = new boolean[1];
+
+ ThreadGroup testRoot = new ThreadGroup(initialThreadGroup, "Test other Exception") {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ if (e instanceof TestException) {
+ passed[0] = true;
+ }
+ // always forward any exception
+ super.uncaughtException(t, e);
+ }
+ };
+
+ final TestException testException = new TestException();
+ Thread thread = new Thread(testRoot, null, "RuntimeException thread") {
+ @Override
+ public void run() {
+ throw testException;
+ }
+ };
+ thread.start();
+ waitForThreadToDieUninterrupted(thread);
+ testThreadDefaultUncaughtExceptionHandler.assertWasCalled(thread, testException);
+ testRoot.destroy();
+ assertTrue(
+ "Any thread should notify its ThreadGroup about an uncaught exception:"
+ + testRoot, passed[0]);
+ }
+
+ /*
+ * Test for method void java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
+ * java.lang.Throwable)
+ * Test if a handler doesn't pass on the exception to super.uncaughtException that's ok.
+ */
+ public void test_uncaughtException_exceptionHandledByHandler() {
+ // Our own exception class
+ class TestException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+ }
+
+ ThreadGroup testRoot = new ThreadGroup(initialThreadGroup, "Test other Exception") {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ // Swallow TestException and always forward any other exception
+ if (!(e instanceof TestException)) {
+ super.uncaughtException(t, e);
+ }
+ }
+ };
+
+ final TestException testException = new TestException();
+ Thread thread = new Thread(testRoot, null, "RuntimeException thread") {
+ @Override
+ public void run() {
+ throw testException;
+ }
+ };
+ thread.start();
+ waitForThreadToDieUninterrupted(thread);
+ testThreadDefaultUncaughtExceptionHandler.assertWasNotCalled();
+ testRoot.destroy();
+ }
+
+ /*
+ * Test for method void java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
+ * java.lang.Throwable)
+ * Tests an exception thrown by the handler itself.
+ */
+ public void test_uncaughtException_exceptionInUncaughtException() {
+ // Our own uncaught exception classes
+ class UncaughtException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+ }
+
+ ThreadGroup testRoot = new ThreadGroup(initialThreadGroup,
+ "Test Exception in uncaught exception") {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ // This should be no-op according to the spec
+ throw new UncaughtException();
+ }
+ };
+
+ Thread thread = new Thread(testRoot, null, "no-op thread") {
+ @Override
+ public void run() {
+ throw new RuntimeException();
+ }
+ };
+ thread.start();
+ waitForThreadToDieUninterrupted(thread);
+ testThreadDefaultUncaughtExceptionHandler.assertWasNotCalled();
+ testRoot.destroy();
+ }
+
+ private static ThreadGroup[] allGroups(ThreadGroup parent) {
+ int count = parent.activeGroupCount();
+ ThreadGroup[] all = new ThreadGroup[count];
+ parent.enumerate(all, true);
+ return all;
+ }
+
+ private static void asyncBuildRandomTreeUnder(final ThreadGroup aGroup,
+ final int depth, final Vector<ThreadGroup> allCreated) {
+ if (depth <= 0) {
+ return;
+ }
+
+ final int maxImmediateSubgroups = random(3);
+ for (int i = 0; i < maxImmediateSubgroups; i++) {
+ final int iClone = i;
+ final String name = " Depth = " + depth + ",N = " + iClone
+ + ",Vector size at creation: " + allCreated.size();
+ // Use concurrency to maximize chance of exposing concurrency bugs
+ // in ThreadGroups
+ Thread t = new Thread(aGroup, name) {
+ @Override
+ public void run() {
+ ThreadGroup newGroup = new ThreadGroup(aGroup, name);
+ allCreated.addElement(newGroup);
+ asyncBuildRandomTreeUnder(newGroup, depth - 1, allCreated);
+ }
+ };
+ t.start();
+ }
+
+ }
+
+ private static Vector<ThreadGroup> asyncBuildRandomTreeUnder(final ThreadGroup aGroup,
+ final int depth) {
+ Vector<ThreadGroup> result = new Vector<ThreadGroup>();
+ asyncBuildRandomTreeUnder(aGroup, depth, result);
+ return result;
+
+ }
+
+ private static ThreadGroup[] groups(ThreadGroup parent) {
+ // No API to get the count of immediate children only ?
+ int count = parent.activeGroupCount();
+ ThreadGroup[] all = new ThreadGroup[count];
+ parent.enumerate(all, false);
+ // Now we may have nulls in the array, we must find the actual size
+ int actualSize = 0;
+ for (; actualSize < all.length; actualSize++) {
+ if (all[actualSize] == null) {
+ break;
+ }
+ }
+ ThreadGroup[] result;
+ if (actualSize == all.length) {
+ result = all;
+ } else {
+ result = new ThreadGroup[actualSize];
+ System.arraycopy(all, 0, result, 0, actualSize);
+ }
+
+ return result;
+
+ }
+
+ private static int random(int max) {
+ return 1 + ((new Object()).hashCode() % max);
+ }
+
+ private static Vector<ThreadGroup> buildRandomTreeUnder(ThreadGroup aGroup, int depth) {
+ Vector<ThreadGroup> result = asyncBuildRandomTreeUnder(aGroup, depth);
+ while (true) {
+ int sizeBefore = result.size();
+ try {
+ Thread.sleep(1000);
+ int sizeAfter = result.size();
+ // If no activity for a while, we assume async building may be
+ // done.
+ if (sizeBefore == sizeAfter) {
+ // It can only be done if no more threads. Unfortunately we
+ // are relying on this API to work as well.
+ // If it does not, we may loop forever.
+ if (aGroup.activeCount() == 0) {
+ break;
+ }
+ }
+ } catch (InterruptedException e) {
+ }
+ }
+ return result;
+
+ }
+
+ private static boolean arrayIncludes(Object[] array, Object toTest) {
+ for (Object element : array) {
+ if (element == toTest) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void waitForThreadToDieUninterrupted(Thread thread) {
+ try {
+ thread.join();
+ } catch (InterruptedException ie) {
+ fail("Should not have been interrupted");
+ }
+ }
+
+ private static class TestThreadDefaultUncaughtExceptionHandler
+ implements Thread.UncaughtExceptionHandler {
+
+ private boolean called;
+ private Throwable ex;
+ private Thread thread;
+
+ @Override
+ public void uncaughtException(Thread thread, Throwable ex) {
+ this.called = true;
+ this.thread = thread;
+ this.ex = ex;
+ }
+
+ public void assertWasCalled(Thread thread, Throwable ex) {
+ assertTrue(called);
+ assertSame(this.thread, thread);
+ assertSame(this.ex, ex);
+ }
+
+ public void assertWasNotCalled() {
+ assertFalse(called);
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadLocalTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadLocalTest.java
new file mode 100644
index 0000000..400ff01
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadLocalTest.java
@@ -0,0 +1,150 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class ThreadLocalTest extends TestCase {
+
+ /**
+ * java.lang.ThreadLocal#ThreadLocal()
+ */
+ public void test_Constructor() {
+ new ThreadLocal<Object>();
+ }
+
+ /**
+ * java.lang.ThreadLocal#remove()
+ */
+ public void test_remove() {
+ ThreadLocal<String> tl = new ThreadLocal<String>() {
+ @Override
+ protected String initialValue() {
+ return "initial";
+ }
+ };
+
+ assertEquals("initial", tl.get());
+ tl.set("fixture");
+ assertEquals("fixture", tl.get());
+ tl.remove();
+ assertEquals("initial", tl.get());
+ }
+
+ /**
+ * java.lang.ThreadLocal#get()
+ */
+ public void test_get() {
+ // Test for method java.lang.Object java.lang.ThreadLocal.get()
+ ThreadLocal<Object> l = new ThreadLocal<Object>();
+ assertNull("ThreadLocal's initial value is null", l.get());
+
+ // The ThreadLocal has to run once for each thread that touches the
+ // ThreadLocal
+ final Object INITIAL_VALUE = "'foo'";
+ final ThreadLocal<Object> l1 = new ThreadLocal<Object>() {
+ @Override
+ protected Object initialValue() {
+ return INITIAL_VALUE;
+ }
+ };
+
+ assertTrue("ThreadLocal's initial value should be " + INITIAL_VALUE
+ + " but is " + l1.get(), l1.get() == INITIAL_VALUE);
+
+ // We need this because inner types cannot assign to variables in
+ // container method. But assigning to object slots in the container
+ // method is ok.
+ class ResultSlot {
+ public Object result = null;
+ }
+
+ final ResultSlot THREADVALUE = new ResultSlot();
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ THREADVALUE.result = l1.get();
+ }
+ };
+
+ // Wait for the other Thread assign what it observes as the value of the
+ // variable
+ t.start();
+ try {
+ t.join();
+ } catch (InterruptedException ie) {
+ fail("Interrupted!!");
+ }
+
+ assertTrue("ThreadLocal's initial value in other Thread should be "
+ + INITIAL_VALUE, THREADVALUE.result == INITIAL_VALUE);
+
+ /* Regression test for implementation vulnerability reported
+ * on Harmony dev list.
+ */
+ ThreadLocal<Object> thrVar = new ThreadLocal<Object>() {
+ public int hashCode() {
+ fail("ThreadLocal should not be asked for it's hashCode");
+ return 0; // never reached
+ }
+ };
+ thrVar.get();
+ }
+
+ /**
+ * java.lang.ThreadLocal#set(java.lang.Object)
+ */
+ public void test_setLjava_lang_Object() {
+ // Test for method void java.lang.ThreadLocal.set(java.lang.Object)
+
+ final Object OBJ = new Object();
+ final ThreadLocal<Object> l = new ThreadLocal<Object>();
+ l.set(OBJ);
+ assertTrue("ThreadLocal's initial value is " + OBJ, l.get() == OBJ);
+
+ // We need this because inner types cannot assign to variables in
+ // container method.
+ // But assigning to object slots in the container method is ok.
+ class ResultSlot {
+ public Object result = null;
+ }
+
+ final ResultSlot THREADVALUE = new ResultSlot();
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ THREADVALUE.result = l.get();
+ }
+ };
+
+ // Wait for the other Thread assign what it observes as the value of the
+ // variable
+ t.start();
+ try {
+ t.join();
+ } catch (InterruptedException ie) {
+ fail("Interrupted!!");
+ }
+
+ // ThreadLocal is not inherited, so the other Thread should see it as
+ // null
+ assertNull("ThreadLocal's value in other Thread should be null",
+ THREADVALUE.result);
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadTest.java
new file mode 100644
index 0000000..956e1a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThreadTest.java
@@ -0,0 +1,1011 @@
+/*
+ * 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.tests.java.lang;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.Map;
+
+public class ThreadTest extends junit.framework.TestCase {
+
+ static class SimpleThread implements Runnable {
+ int delay;
+
+ public void run() {
+ try {
+ synchronized (this) {
+ this.notify();
+ this.wait(delay);
+ }
+ } catch (InterruptedException e) {
+ return;
+ }
+
+ }
+
+ public SimpleThread(int d) {
+ if (d >= 0)
+ delay = d;
+ }
+ }
+
+ static class YieldThread implements Runnable {
+ volatile int delay;
+
+ public void run() {
+ int x = 0;
+ while (true) {
+ ++x;
+ }
+ }
+
+ public YieldThread(int d) {
+ if (d >= 0)
+ delay = d;
+ }
+ }
+
+ static class ResSupThread implements Runnable {
+ Thread parent;
+
+ volatile int checkVal = -1;
+
+ public void run() {
+ try {
+ synchronized (this) {
+ this.notify();
+ }
+ while (true) {
+ checkVal++;
+ zz();
+ Thread.sleep(100);
+ }
+ } catch (InterruptedException e) {
+ return;
+ } catch (BogusException e) {
+ try {
+ // Give parent a chance to sleep
+ Thread.sleep(500);
+ } catch (InterruptedException x) {
+ }
+ parent.interrupt();
+ while (!Thread.currentThread().isInterrupted()) {
+ // Don't hog the CPU
+ try {
+ Thread.sleep(50);
+ } catch (InterruptedException x) {
+ // This is what we've been waiting for...don't throw it
+ // away!
+ break;
+ }
+ }
+ }
+ }
+
+ public void zz() throws BogusException {
+ }
+
+ public ResSupThread(Thread t) {
+ parent = t;
+ }
+
+ public synchronized int getCheckVal() {
+ return checkVal;
+ }
+ }
+
+ static class BogusException extends Throwable {
+
+ private static final long serialVersionUID = 1L;
+
+ public BogusException(String s) {
+ super(s);
+ }
+ }
+
+ Thread st, ct, spinner;
+
+ /**
+ * java.lang.Thread#Thread(java.lang.Runnable)
+ */
+ public void test_ConstructorLjava_lang_Runnable() {
+ // Test for method java.lang.Thread(java.lang.Runnable)
+ ct = new Thread(new SimpleThread(10));
+ ct.start();
+ }
+
+ /**
+ * java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_RunnableLjava_lang_String() {
+ // Test for method java.lang.Thread(java.lang.Runnable,
+ // java.lang.String)
+ Thread st1 = new Thread(new SimpleThread(1), "SimpleThread1");
+ assertEquals("Constructed thread with incorrect thread name", "SimpleThread1", st1
+ .getName());
+ st1.start();
+ }
+
+ /**
+ * java.lang.Thread#Thread(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.lang.Thread(java.lang.String)
+ Thread t = new Thread("Testing");
+ assertEquals("Created tread with incorrect name",
+ "Testing", t.getName());
+ t.start();
+ }
+
+ /**
+ * java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable)
+ */
+ public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_Runnable() {
+ // Test for method java.lang.Thread(java.lang.ThreadGroup,
+ // java.lang.Runnable)
+ ThreadGroup tg = new ThreadGroup("Test Group1");
+ st = new Thread(tg, new SimpleThread(1), "SimpleThread2");
+ assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
+ st.start();
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ }
+ tg.destroy();
+ }
+
+ /**
+ * java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_String() {
+ // Test for method java.lang.Thread(java.lang.ThreadGroup,
+ // java.lang.Runnable, java.lang.String)
+ ThreadGroup tg = new ThreadGroup("Test Group2");
+ st = new Thread(tg, new SimpleThread(1), "SimpleThread3");
+ assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
+ && st.getName().equals("SimpleThread3"));
+ st.start();
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ }
+ tg.destroy();
+
+ Runnable r = new Runnable() {
+ public void run() {
+ }
+ };
+
+ ThreadGroup foo = null;
+ try {
+ new Thread(foo = new ThreadGroup("foo"), r, null);
+ // Should not get here
+ fail("Null cannot be accepted as Thread name");
+ } catch (NullPointerException npe) {
+ assertTrue("Null cannot be accepted as Thread name", true);
+ foo.destroy();
+ }
+
+ }
+
+ /**
+ * java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_String() {
+ // Test for method java.lang.Thread(java.lang.ThreadGroup,
+ // java.lang.String)
+ st = new Thread(new SimpleThread(1), "SimpleThread4");
+ assertEquals("Returned incorrect thread name",
+ "SimpleThread4", st.getName());
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#activeCount()
+ */
+ public void test_activeCount() {
+ // Test for method int java.lang.Thread.activeCount()
+ Thread t = new Thread(new SimpleThread(10));
+ int active = 0;
+ synchronized (t) {
+ t.start();
+ active = Thread.activeCount();
+ }
+ assertTrue("Incorrect activeCount for current group: " + active, active > 1);
+ try {
+ t.join();
+ } catch (InterruptedException e) {
+ }
+ }
+
+ /**
+ * java.lang.Thread#checkAccess()
+ */
+ public void test_checkAccess() {
+ // Test for method void java.lang.Thread.checkAccess()
+ ThreadGroup tg = new ThreadGroup("Test Group3");
+ try {
+ st = new Thread(tg, new SimpleThread(1), "SimpleThread5");
+ st.checkAccess();
+ assertTrue("CheckAccess passed", true);
+ } catch (SecurityException e) {
+ fail("CheckAccess failed : " + e.getMessage());
+ }
+ st.start();
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ }
+ tg.destroy();
+ }
+
+ /**
+ * java.lang.Thread#countStackFrames()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_countStackFrames() {
+ /*
+ * Thread.countStackFrames() is unpredictable, so we just test that it
+ * doesn't throw an exception.
+ */
+ Thread.currentThread().countStackFrames();
+ }
+
+ /**
+ * java.lang.Thread#currentThread()
+ */
+ public void test_currentThread() {
+ assertNotNull(Thread.currentThread());
+ }
+
+ public void test_destroy_throwsUnsupportedOperationException() {
+ try {
+ new Thread().destroy();
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
+
+ /**
+ * java.lang.Thread#enumerate(java.lang.Thread[])
+ */
+ public void test_enumerate$Ljava_lang_Thread() {
+ // Test for method int java.lang.Thread.enumerate(java.lang.Thread [])
+ // The test has been updated according to HARMONY-1974 JIRA issue.
+
+ class MyThread extends Thread {
+ MyThread(ThreadGroup tg, String name) {
+ super(tg, name);
+ }
+
+ boolean failed = false;
+ String failMessage = null;
+
+ public void run() {
+ SimpleThread st1 = null;
+ SimpleThread st2 = null;
+ ThreadGroup mytg = null;
+ Thread firstOne = null;
+ Thread secondOne = null;
+ try {
+ int arrayLength = 10;
+ Thread[] tarray = new Thread[arrayLength];
+ st1 = new SimpleThread(-1);
+ st2 = new SimpleThread(-1);
+ mytg = new ThreadGroup("jp");
+ firstOne = new Thread(mytg, st1, "firstOne2");
+ secondOne = new Thread(mytg, st2, "secondOne1");
+ int count = Thread.enumerate(tarray);
+ assertEquals("Incorrect value returned1",
+ 1, count);
+ synchronized (st1) {
+ firstOne.start();
+ try {
+ st1.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ count = Thread.enumerate(tarray);
+ assertEquals("Incorrect value returned2",
+ 2, count);
+ synchronized (st2) {
+ secondOne.start();
+ try {
+ st2.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ count = Thread.enumerate(tarray);
+ assertEquals("Incorrect value returned3",
+ 3, count);
+ } catch (junit.framework.AssertionFailedError e) {
+ failed = true;
+ failMessage = e.getMessage();
+ } finally {
+ synchronized (st1) {
+ firstOne.interrupt();
+ }
+ synchronized (st2) {
+ secondOne.interrupt();
+ }
+ try {
+ firstOne.join();
+ secondOne.join();
+ } catch (InterruptedException e) {
+ }
+ mytg.destroy();
+ }
+ }
+ }
+ ;
+
+ ThreadGroup tg = new ThreadGroup("tg");
+ MyThread t = new MyThread(tg, "top");
+ t.start();
+ try {
+ t.join();
+ } catch (InterruptedException e) {
+ fail("Unexpected interrupt");
+ } finally {
+ tg.destroy();
+ }
+ assertFalse(t.failMessage, t.failed);
+ }
+
+ /**
+ * java.lang.Thread#getContextClassLoader()
+ */
+ public void test_getContextClassLoader() {
+ // Test for method java.lang.ClassLoader
+ // java.lang.Thread.getContextClassLoader()
+ Thread t = new Thread();
+ assertTrue("Incorrect class loader returned",
+ t.getContextClassLoader() == Thread.currentThread()
+ .getContextClassLoader());
+ t.start();
+
+ }
+
+ /**
+ * java.lang.Thread#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.lang.Thread.getName()
+ st = new Thread(new SimpleThread(1), "SimpleThread6");
+ assertEquals("Returned incorrect thread name",
+ "SimpleThread6", st.getName());
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#getPriority()
+ */
+ public void test_getPriority() {
+ // Test for method int java.lang.Thread.getPriority()
+ st = new Thread(new SimpleThread(1));
+ st.setPriority(Thread.MAX_PRIORITY);
+ assertTrue("Returned incorrect thread priority",
+ st.getPriority() == Thread.MAX_PRIORITY);
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#getThreadGroup()
+ */
+ public void test_getThreadGroup() {
+ // Test for method java.lang.ThreadGroup
+ // java.lang.Thread.getThreadGroup()
+ ThreadGroup tg = new ThreadGroup("Test Group4");
+ st = new Thread(tg, new SimpleThread(1), "SimpleThread8");
+ assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
+ st.start();
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ }
+ assertNull("group should be null", st.getThreadGroup());
+ assertNotNull("toString() should not be null", st.toString());
+ tg.destroy();
+
+ final Object lock = new Object();
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ synchronized (lock) {
+ lock.notifyAll();
+ }
+ }
+ };
+ synchronized (lock) {
+ t.start();
+ try {
+ lock.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ int running = 0;
+ while (t.isAlive())
+ running++;
+ ThreadGroup group = t.getThreadGroup();
+ assertNull("ThreadGroup is not null", group);
+ }
+
+ /**
+ * java.lang.Thread#interrupt()
+ */
+ public void test_interrupt() {
+ // Test for method void java.lang.Thread.interrupt()
+ final Object lock = new Object();
+ class ChildThread1 extends Thread {
+ Thread parent;
+
+ boolean sync;
+
+ @Override
+ public void run() {
+ if (sync) {
+ synchronized (lock) {
+ lock.notify();
+ try {
+ lock.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+ parent.interrupt();
+ }
+
+ public ChildThread1(Thread p, String name, boolean sync) {
+ super(name);
+ parent = p;
+ this.sync = sync;
+ }
+ }
+ boolean interrupted = false;
+ try {
+ ct = new ChildThread1(Thread.currentThread(), "Interrupt Test1",
+ false);
+ synchronized (lock) {
+ ct.start();
+ lock.wait();
+ }
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ assertTrue("Failed to Interrupt thread1", interrupted);
+
+ interrupted = false;
+ try {
+ ct = new ChildThread1(Thread.currentThread(), "Interrupt Test2",
+ true);
+ synchronized (lock) {
+ ct.start();
+ lock.wait();
+ lock.notify();
+ }
+ Thread.sleep(20000);
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ assertTrue("Failed to Interrupt thread2", interrupted);
+
+ }
+
+ /**
+ * java.lang.Thread#interrupted()
+ */
+ public void test_interrupted() {
+ assertFalse("Interrupted returned true for non-interrupted thread", Thread
+ .interrupted());
+ Thread.currentThread().interrupt();
+ assertTrue("Interrupted returned true for non-interrupted thread", Thread.interrupted());
+ assertFalse("Failed to clear interrupted flag", Thread.interrupted());
+ }
+
+ /**
+ * java.lang.Thread#isAlive()
+ */
+ public void test_isAlive() {
+ // Test for method boolean java.lang.Thread.isAlive()
+ SimpleThread simple;
+ st = new Thread(simple = new SimpleThread(500));
+ assertFalse("A thread that wasn't started is alive.", st.isAlive());
+ synchronized (simple) {
+ st.start();
+ try {
+ simple.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ assertTrue("Started thread returned false", st.isAlive());
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ fail("Thread did not die");
+ }
+ assertTrue("Stopped thread returned true", !st.isAlive());
+ }
+
+ /**
+ * java.lang.Thread#isDaemon()
+ */
+ public void test_isDaemon() {
+ // Test for method boolean java.lang.Thread.isDaemon()
+ st = new Thread(new SimpleThread(1), "SimpleThread10");
+ assertTrue("Non-Daemon thread returned true", !st.isDaemon());
+ st.setDaemon(true);
+ assertTrue("Daemon thread returned false", st.isDaemon());
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#isInterrupted()
+ */
+ public void test_isInterrupted() {
+ // Test for method boolean java.lang.Thread.isInterrupted()
+ class SpinThread implements Runnable {
+ public volatile boolean done = false;
+
+ public void run() {
+ while (!Thread.currentThread().isInterrupted())
+ ;
+ while (!done)
+ ;
+ }
+ }
+
+ SpinThread spin = new SpinThread();
+ spinner = new Thread(spin);
+ spinner.start();
+ Thread.yield();
+ try {
+ assertTrue("Non-Interrupted thread returned true", !spinner
+ .isInterrupted());
+ spinner.interrupt();
+ assertTrue("Interrupted thread returned false", spinner
+ .isInterrupted());
+ spin.done = true;
+ } finally {
+ spinner.interrupt();
+ spin.done = true;
+ }
+ }
+
+ /**
+ * java.lang.Thread#join()
+ */
+ public void test_join() {
+ // Test for method void java.lang.Thread.join()
+ SimpleThread simple;
+ try {
+ st = new Thread(simple = new SimpleThread(100));
+ // cause isAlive() to be compiled by the JIT, as it must be called
+ // within 100ms below.
+ assertTrue("Thread is alive", !st.isAlive());
+ synchronized (simple) {
+ st.start();
+ simple.wait();
+ }
+ st.join();
+ } catch (InterruptedException e) {
+ fail("Join failed ");
+ }
+ assertTrue("Joined thread is still alive", !st.isAlive());
+ boolean result = true;
+ Thread th = new Thread("test");
+ try {
+ th.join();
+ } catch (InterruptedException e) {
+ result = false;
+ }
+ assertTrue("Hung joining a non-started thread", result);
+ th.start();
+ }
+
+ /**
+ * java.lang.Thread#join(long)
+ */
+ public void test_joinJ() {
+ // Test for method void java.lang.Thread.join(long)
+ SimpleThread simple;
+ try {
+ st = new Thread(simple = new SimpleThread(1000), "SimpleThread12");
+ // cause isAlive() to be compiled by the JIT, as it must be called
+ // within 100ms below.
+ assertTrue("Thread is alive", !st.isAlive());
+ synchronized (simple) {
+ st.start();
+ simple.wait();
+ }
+ st.join(10);
+ } catch (InterruptedException e) {
+ fail("Join failed ");
+ }
+ assertTrue("Join failed to timeout", st.isAlive());
+
+ st.interrupt();
+ try {
+ st = new Thread(simple = new SimpleThread(100), "SimpleThread13");
+ synchronized (simple) {
+ st.start();
+ simple.wait();
+ }
+ st.join(1000);
+ } catch (InterruptedException e) {
+ fail("Join failed : " + e.getMessage());
+ return;
+ }
+ assertTrue("Joined thread is still alive", !st.isAlive());
+
+ final Object lock = new Object();
+ final Thread main = Thread.currentThread();
+ Thread killer = new Thread(new Runnable() {
+ public void run() {
+ try {
+ synchronized (lock) {
+ lock.notify();
+ }
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ return;
+ }
+ main.interrupt();
+ }
+ });
+ boolean result = true;
+ Thread th = new Thread("test");
+ try {
+ synchronized (lock) {
+ killer.start();
+ lock.wait();
+ }
+ th.join(200);
+ } catch (InterruptedException e) {
+ result = false;
+ }
+ killer.interrupt();
+ assertTrue("Hung joining a non-started thread", result);
+ th.start();
+ }
+
+ /**
+ * java.lang.Thread#join(long, int)
+ */
+ public void test_joinJI() throws Exception {
+ // Test for method void java.lang.Thread.join(long, int)
+ SimpleThread simple;
+ st = new Thread(simple = new SimpleThread(1000), "Squawk1");
+ assertTrue("Thread is alive", !st.isAlive());
+ synchronized (simple) {
+ st.start();
+ simple.wait();
+ }
+
+ long firstRead = System.currentTimeMillis();
+ st.join(100, 999999);
+ long secondRead = System.currentTimeMillis();
+ assertTrue("Did not join by appropriate time: " + secondRead + "-"
+ + firstRead + "=" + (secondRead - firstRead), secondRead
+ - firstRead <= 300);
+ assertTrue("Joined thread is not alive", st.isAlive());
+ st.interrupt();
+
+ final Object lock = new Object();
+ final Thread main = Thread.currentThread();
+ Thread killer = new Thread(new Runnable() {
+ public void run() {
+ try {
+ synchronized (lock) {
+ lock.notify();
+ }
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ return;
+ }
+ main.interrupt();
+ }
+ });
+ boolean result = true;
+ Thread th = new Thread("test");
+ try {
+ synchronized (lock) {
+ killer.start();
+ lock.wait();
+ }
+ th.join(200, 20);
+ } catch (InterruptedException e) {
+ result = false;
+ }
+ killer.interrupt();
+ assertTrue("Hung joining a non-started thread", result);
+ th.start();
+ }
+
+ /**
+ * java.lang.Thread#run()
+ */
+ public void test_run() {
+ // Test for method void java.lang.Thread.run()
+ class RunThread implements Runnable {
+ boolean didThreadRun = false;
+
+ public void run() {
+ didThreadRun = true;
+ }
+ }
+ RunThread rt = new RunThread();
+ Thread t = new Thread(rt);
+ try {
+ t.start();
+ int count = 0;
+ while (!rt.didThreadRun && count < 20) {
+ Thread.sleep(100);
+ count++;
+ }
+ assertTrue("Thread did not run", rt.didThreadRun);
+ t.join();
+ } catch (InterruptedException e) {
+ assertTrue("Joined thread was interrupted", true);
+ }
+ assertTrue("Joined thread is still alive", !t.isAlive());
+ }
+
+ /**
+ * java.lang.Thread#setDaemon(boolean)
+ */
+ public void test_setDaemonZ() {
+ // Test for method void java.lang.Thread.setDaemon(boolean)
+ st = new Thread(new SimpleThread(1), "SimpleThread14");
+ st.setDaemon(true);
+ assertTrue("Failed to set thread as daemon thread", st.isDaemon());
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#setName(java.lang.String)
+ */
+ public void test_setNameLjava_lang_String() {
+ // Test for method void java.lang.Thread.setName(java.lang.String)
+ st = new Thread(new SimpleThread(1), "SimpleThread15");
+ st.setName("Bogus Name");
+ assertEquals("Failed to set thread name",
+ "Bogus Name", st.getName());
+ try {
+ st.setName(null);
+ fail("Null should not be accepted as a valid name");
+ } catch (NullPointerException e) {
+ // success
+ assertTrue("Null should not be accepted as a valid name", true);
+ }
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#setPriority(int)
+ */
+ public void test_setPriorityI() {
+ // Test for method void java.lang.Thread.setPriority(int)
+ st = new Thread(new SimpleThread(1));
+ st.setPriority(Thread.MAX_PRIORITY);
+ assertTrue("Failed to set priority",
+ st.getPriority() == Thread.MAX_PRIORITY);
+ st.start();
+ }
+
+ /**
+ * java.lang.Thread#sleep(long)
+ */
+ public void test_sleepJ() {
+ // Test for method void java.lang.Thread.sleep(long)
+
+ // TODO : Test needs enhancing.
+ long stime = 0, ftime = 0;
+ try {
+ stime = System.currentTimeMillis();
+ Thread.sleep(1000);
+ ftime = System.currentTimeMillis();
+ } catch (InterruptedException e) {
+ fail("Unexpected interrupt received");
+ }
+ assertTrue("Failed to sleep long enough", (ftime - stime) >= 800);
+ }
+
+ /**
+ * java.lang.Thread#sleep(long, int)
+ */
+ public void test_sleepJI() {
+ // Test for method void java.lang.Thread.sleep(long, int)
+
+ // TODO : Test needs revisiting.
+ long stime = 0, ftime = 0;
+ try {
+ stime = System.currentTimeMillis();
+ Thread.sleep(1000, 999999);
+ ftime = System.currentTimeMillis();
+ } catch (InterruptedException e) {
+ fail("Unexpected interrupt received");
+ }
+ long result = ftime - stime;
+ assertTrue("Failed to sleep long enough: " + result, result >= 900
+ && result <= 1100);
+ }
+
+ /**
+ * java.lang.Thread#start()
+ */
+ public void test_start() {
+ // Test for method void java.lang.Thread.start()
+ try {
+ ResSupThread t = new ResSupThread(Thread.currentThread());
+ synchronized (t) {
+ ct = new Thread(t, "Interrupt Test4");
+ ct.start();
+ t.wait();
+ }
+ assertTrue("Thread is not running1", ct.isAlive());
+ // Let the child thread get going.
+ int orgval = t.getCheckVal();
+ Thread.sleep(150);
+ assertTrue("Thread is not running2", orgval != t.getCheckVal());
+ ct.interrupt();
+ } catch (InterruptedException e) {
+ fail("Unexpected interrupt occurred");
+ }
+ }
+
+ /**
+ * java.lang.Thread#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.Thread.toString()
+ ThreadGroup tg = new ThreadGroup("Test Group5");
+ st = new Thread(tg, new SimpleThread(1), "SimpleThread17");
+ final String stString = st.toString();
+ final String expected = "Thread[SimpleThread17,5,Test Group5]";
+ assertTrue("Returned incorrect string: " + stString + "\t(expecting :"
+ + expected + ")", stString.equals(expected));
+ st.start();
+ try {
+ st.join();
+ } catch (InterruptedException e) {
+ }
+ tg.destroy();
+ }
+
+ /**
+ * java.lang.Thread#getAllStackTraces()
+ */
+ public void test_getAllStackTraces() {
+ Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
+ assertNotNull(stMap);
+ //TODO add security-based tests
+ }
+
+ /**
+ * java.lang.Thread#getDefaultUncaughtExceptionHandler
+ * java.lang.Thread#setDefaultUncaughtExceptionHandler
+ */
+ public void test_get_setDefaultUncaughtExceptionHandler() {
+ class Handler implements UncaughtExceptionHandler {
+ public void uncaughtException(Thread thread, Throwable ex) {
+ }
+ }
+
+ final Handler handler = new Handler();
+ Thread.setDefaultUncaughtExceptionHandler(handler);
+ assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());
+
+ Thread.setDefaultUncaughtExceptionHandler(null);
+ assertNull(Thread.getDefaultUncaughtExceptionHandler());
+ //TODO add security-based tests
+ }
+
+ /**
+ * java.lang.Thread#getStackTrace()
+ */
+ public void test_getStackTrace() {
+ StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
+
+ assertNotNull(stackTrace);
+
+ stack_trace_loop:
+ {
+ for (int i = 0; i < stackTrace.length; i++) {
+ StackTraceElement e = stackTrace[i];
+ if (getClass().getName().equals(e.getClassName())) {
+ if ("test_getStackTrace".equals(e.getMethodName())) {
+ break stack_trace_loop;
+ }
+ }
+ }
+ fail("class and method not found in stack trace");
+ }
+
+ //TODO add security-based tests
+ }
+
+ /**
+ * java.lang.Thread#getState()
+ */
+ public void test_getState() {
+ Thread.State state = Thread.currentThread().getState();
+ assertNotNull(state);
+ assertEquals(Thread.State.RUNNABLE, state);
+ //TODO add additional state tests
+ }
+
+ /**
+ * java.lang.Thread#getUncaughtExceptionHandler
+ * java.lang.Thread#setUncaughtExceptionHandler
+ */
+ public void test_get_setUncaughtExceptionHandler() {
+ class Handler implements UncaughtExceptionHandler {
+ public void uncaughtException(Thread thread, Throwable ex) {
+ }
+ }
+
+ final Handler handler = new Handler();
+ Thread.currentThread().setUncaughtExceptionHandler(handler);
+ assertSame(handler, Thread.currentThread().getUncaughtExceptionHandler());
+
+ Thread.currentThread().setUncaughtExceptionHandler(null);
+
+ //TODO add security-based tests
+ }
+
+ /**
+ * java.lang.Thread#getId()
+ */
+ public void test_getId() {
+ assertTrue("current thread's ID is not positive", Thread.currentThread().getId() > 0);
+
+ //check all the current threads for positive IDs
+ Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
+ for (Thread thread : stMap.keySet()) {
+ assertTrue("thread's ID is not positive: " + thread.getName(), thread.getId() > 0);
+ }
+ }
+
+
+ @Override
+ protected void tearDown() {
+ try {
+ if (st != null)
+ st.interrupt();
+ } catch (Exception e) {
+ }
+ try {
+ if (spinner != null)
+ spinner.interrupt();
+ } catch (Exception e) {
+ }
+ try {
+ if (ct != null)
+ ct.interrupt();
+ } catch (Exception e) {
+ }
+
+ try {
+ spinner = null;
+ st = null;
+ ct = null;
+ System.runFinalization();
+ } catch (Exception e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThrowableTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThrowableTest.java
new file mode 100644
index 0000000..dbe656f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ThrowableTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.tests.java.lang;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+
+import junit.framework.TestCase;
+
+public class ThrowableTest extends TestCase {
+
+ /**
+ * java.lang.Throwable#Throwable()
+ */
+ public void test_Constructor() {
+ Throwable e = new Throwable();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.Throwable#Throwable(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ Throwable e = new Throwable("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.Throwable#fillInStackTrace()
+ */
+ public void test_fillInStackTrace() {
+ // Test for method java.lang.Throwable
+ // java.lang.Throwable.fillInStackTrace()
+ class Test implements Runnable {
+ public int x;
+
+ public Test(int x) {
+ this.x = x;
+ }
+
+ public void anotherMethod() {
+ if (true)
+ throw new IndexOutOfBoundsException();
+ }
+
+ public void run() {
+ if (x == 0)
+ throw new IndexOutOfBoundsException();
+ try {
+ anotherMethod();
+ } catch (IndexOutOfBoundsException e) {
+ e.fillInStackTrace();
+ throw e;
+ }
+ }
+ }
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bao);
+ try {
+ new Test(0).run();
+ } catch (Throwable e) {
+ e.printStackTrace(ps);
+ }
+ ps.flush();
+ String s = fixStacktrace(new String(bao.toByteArray(), 0, bao.size()));
+
+ bao.reset();
+ try {
+ new Test(1).run();
+ } catch (Throwable e) {
+ e.printStackTrace(ps);
+ }
+ ps.close();
+ String s2 = fixStacktrace(new String(bao.toByteArray(), 0, bao.size()));
+ assertTrue("Invalid stackTrace? length: " + s2.length() + "\n" + s2, s2
+ .length() > 300);
+ assertTrue("Incorrect stackTrace printed: \n" + s2
+ + "\n\nCompared with:\n" + s, s2.equals(s));
+ }
+
+ private String fixStacktrace(String trace) {
+ // remove linenumbers
+ StringBuffer sb = new StringBuffer();
+ int lastIndex = 0;
+ while (lastIndex < trace.length()) {
+ int index = trace.indexOf('\n', lastIndex);
+ if (index == -1)
+ index = trace.length();
+ String line = trace.substring(lastIndex, index);
+ lastIndex = index + 1;
+
+ index = line.indexOf("(");
+ if (index > -1) {
+ line = line.substring(0, index);
+ }
+ // Usually the construction of the exception is removed
+ // however if running with the JIT, it may not be removed
+ if (line.indexOf("java.lang.Throwable") > -1)
+ continue;
+ sb.append(line);
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
+
+ /**
+ * java.lang.Throwable#printStackTrace()
+ */
+ public void test_printStackTrace() {
+ // Test for method void java.lang.Throwable.printStackTrace()
+ Throwable x = new ClassNotFoundException("A Test Message");
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bao);
+ PrintStream err = System.err;
+ System.setErr(ps);
+ x.printStackTrace();
+ System.setErr(err);
+ ps.close();
+ String s = new String(bao.toByteArray(), 0, bao.size());
+ assertTrue("Incorrect stackTrace printed:\n" + s, s != null
+ && s.length() > 400);
+ }
+
+ /**
+ * java.lang.Throwable#printStackTrace(java.io.PrintStream)
+ */
+ public void test_printStackTraceLjava_io_PrintStream() {
+ // Test for method void
+ // java.lang.Throwable.printStackTrace(java.io.PrintStream)
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bao);
+ Throwable x = new java.net.UnknownHostException("A Message");
+ x.printStackTrace(ps);
+ ps.close();
+ String s = new String(bao.toByteArray(), 0, bao.size());
+ assertTrue("Incorrect stackTrace printed:\n" + s, s != null
+ && s.length() > 400);
+ }
+
+ /**
+ * java.lang.Throwable#printStackTrace(java.io.PrintWriter)
+ */
+ public void test_printStackTraceLjava_io_PrintWriter() {
+ // Test for method void
+ // java.lang.Throwable.printStackTrace(java.io.PrintWriter)
+ // SM
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintWriter pw = new PrintWriter(bao);
+ Throwable x = new java.net.UnknownHostException("A Message");
+ x.printStackTrace(pw);
+ pw.close();
+ String s = new String(bao.toByteArray(), 0, bao.size());
+ assertTrue("Incorrect stackTrace printed:\n" + s, s != null
+ && s.length() > 400);
+ }
+
+ /**
+ * java.lang.Throwable#toString()
+ */
+ public void test_toString() {
+ Throwable e = new Throwable("Throw");
+ assertEquals("java.lang.Throwable: Throw", e.toString());
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/TypeNotPresentExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/TypeNotPresentExceptionTest.java
new file mode 100644
index 0000000..3f14e34
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/TypeNotPresentExceptionTest.java
@@ -0,0 +1,54 @@
+/* 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class TypeNotPresentExceptionTest extends TestCase {
+
+ /**
+ * java.lang.TypeNotPresentException.TypeNotPresentException(String, Throwable)
+ */
+ public void test_constructorLjava_lang_StringLjava_lang_Throwable() {
+ TypeNotPresentException e = new TypeNotPresentException(null, null);
+ assertNotNull(e);
+ String m = e.getMessage();
+ assertNotNull(m);
+
+ e = new TypeNotPresentException(getClass().getName(), null);
+ assertNotNull(e);
+ m = e.getMessage();
+ assertNotNull(m);
+
+ NullPointerException npe = new NullPointerException();
+ e = new TypeNotPresentException(getClass().getName(), npe);
+ assertNotNull(e.getMessage());
+ assertSame(npe, e.getCause());
+ }
+
+ /**
+ * java.lang.TypeNotPresentException.typeName()
+ */
+ public void test_typeName() {
+ TypeNotPresentException e = new TypeNotPresentException(null, null);
+ assertNull(e.typeName());
+
+ e = new TypeNotPresentException(getClass().getName(), null);
+ assertEquals(getClass().getName(), e.typeName());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnknownErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnknownErrorTest.java
new file mode 100644
index 0000000..8ec96a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnknownErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class UnknownErrorTest extends TestCase {
+
+ /**
+ * java.lang.UnknownError#UnknownError()
+ */
+ public void test_Constructor() {
+ UnknownError e = new UnknownError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.UnknownError#UnknownError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ UnknownError e = new UnknownError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsatisfiedLinkErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsatisfiedLinkErrorTest.java
new file mode 100644
index 0000000..d6e06db
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsatisfiedLinkErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class UnsatisfiedLinkErrorTest extends TestCase {
+
+ /**
+ * java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError()
+ */
+ public void test_Constructor() {
+ UnsatisfiedLinkError e = new UnsatisfiedLinkError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ UnsatisfiedLinkError e = new UnsatisfiedLinkError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedClassVersionErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedClassVersionErrorTest.java
new file mode 100644
index 0000000..dcf09b8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedClassVersionErrorTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class UnsupportedClassVersionErrorTest extends TestCase {
+ /**
+ * 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.
+ */
+
+ /**
+ * java.lang.UnsupportedClassVersionError#UnsupportedClassVersionError()
+ */
+ public void test_UnsupportedClassVersionError() {
+ UnsupportedClassVersionError error = new UnsupportedClassVersionError();
+ assertNotNull(error);
+ assertNull(error.getMessage());
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedOperationExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedOperationExceptionTest.java
new file mode 100644
index 0000000..73cf5e6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/UnsupportedOperationExceptionTest.java
@@ -0,0 +1,100 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class UnsupportedOperationExceptionTest extends TestCase {
+
+ /**
+ * java.lang.UnsupportedOperationException#UnsupportedOperationException()
+ */
+ public void test_Constructor() {
+ UnsupportedOperationException e = new UnsupportedOperationException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.UnsupportedOperationException#UnsupportedOperationException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ UnsupportedOperationException e = new UnsupportedOperationException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * {@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());
+ }
+
+ /**
+ * {@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());
+ }
+
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new UnsupportedOperationException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new UnsupportedOperationException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VerifyErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VerifyErrorTest.java
new file mode 100644
index 0000000..874ac57
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VerifyErrorTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.lang;
+
+import junit.framework.TestCase;
+
+public class VerifyErrorTest extends TestCase {
+
+ /**
+ * java.lang.VerifyError#VerifyError()
+ */
+ public void test_Constructor() {
+ VerifyError e = new VerifyError();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.VerifyError#VerifyError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ VerifyError e = new VerifyError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VirtualMachineErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VirtualMachineErrorTest.java
new file mode 100644
index 0000000..60ed446
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/VirtualMachineErrorTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.tests.java.lang;
+
+import junit.framework.TestCase;
+
+@SuppressWarnings("serial")
+public class VirtualMachineErrorTest extends TestCase {
+
+ /**
+ * java.lang.VirtualMachineError#VirtualMachineError()
+ */
+ public void test_Constructor() {
+ VirtualMachineError e = new VirtualMachineError() {
+ };
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * java.lang.VirtualMachineError#VirtualMachineError(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ VirtualMachineError e = new VirtualMachineError("fixture") {
+ };
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/PhantomReferenceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/PhantomReferenceTest.java
new file mode 100644
index 0000000..5a80fde
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/PhantomReferenceTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.tests.java.lang.ref;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import libcore.java.lang.ref.FinalizationTester;
+
+//TODO: write a test to verify that the referent's finalize() happens
+// before the PhantomReference is enqueued.
+
+public class PhantomReferenceTest extends junit.framework.TestCase {
+ static Boolean bool;
+ public boolean isCalled = false;
+ protected void doneSuite() {
+ bool = null;
+ }
+
+ /**
+ * java.lang.ref.PhantomReference#get()
+ */
+ public void test_get() {
+ ReferenceQueue rq = new ReferenceQueue();
+ bool = new Boolean(false);
+ PhantomReference pr = new PhantomReference(bool, rq);
+ assertNull("get() should return null.", pr.get());
+ pr.enqueue();
+ assertNull("get() should return null.", pr.get());
+ pr.clear();
+ assertNull("get() should return null.", pr.get());
+ }
+
+ /**
+ * java.lang.Runtime#gc()
+ */
+ public void test_gcInteraction() {
+ class TestPhantomReference<T> extends PhantomReference<T> {
+ public TestPhantomReference(T referent,
+ ReferenceQueue<? super T> q) {
+ super(referent, q);
+ }
+ public boolean enqueue() {
+ // Initiate another GC from inside enqueue() to
+ // see if it causes any problems inside the VM.
+ Runtime.getRuntime().gc();
+ return super.enqueue();
+ }
+ }
+
+ final ReferenceQueue rq = new ReferenceQueue();
+ final PhantomReference[] tprs = new PhantomReference[4];
+
+ class TestThread extends Thread {
+ public void run() {
+ // Create the object in a separate thread to ensure
+ // it will be gc'ed.
+ Object obj = new Object();
+ tprs[0] = new TestPhantomReference(obj, rq);
+ tprs[1] = new TestPhantomReference(obj, rq);
+ tprs[2] = new TestPhantomReference(obj, rq);
+ tprs[3] = new TestPhantomReference(obj, rq);
+ }
+ }
+
+ try {
+ Thread t = new TestThread();
+ t.start();
+ t.join();
+
+ FinalizationTester.induceFinalization();
+
+ assertNull("get() should return null.", tprs[0].get());
+ assertNull("get() should return null.", tprs[1].get());
+ assertNull("get() should return null.", tprs[2].get());
+ assertNull("get() should return null.", tprs[3].get());
+
+ for (int i = 0; i < 4; i++) {
+ Reference r = rq.remove(100L);
+ assertNotNull("Reference should have been enqueued.", r);
+ }
+
+ // These are to make sure that tprs and its elements don't get
+ // optimized out.
+ assertNull("get() should return null.", tprs[0].get());
+ assertNull("get() should return null.", tprs[1].get());
+ assertNull("get() should return null.", tprs[2].get());
+ assertNull("get() should return null.", tprs[3].get());
+ } catch (InterruptedException e) {
+ fail("InterruptedException : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.ref.PhantomReference#PhantomReference(java.lang.Object,
+ * java.lang.ref.ReferenceQueue)
+ */
+ public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
+ ReferenceQueue rq = new ReferenceQueue();
+ bool = new Boolean(true);
+ try {
+ PhantomReference pr = new PhantomReference(bool, rq);
+ // Allow the finalizer to run to potentially enqueue
+ Thread.sleep(1000);
+ assertTrue("Initialization failed.", !pr.isEnqueued());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ // need a reference to bool so the jit does not optimize it away
+ assertTrue("should always pass", bool.booleanValue());
+
+ boolean exception = false;
+ try {
+ new PhantomReference(bool, null);
+ } catch (NullPointerException e) {
+ exception = true;
+ }
+ assertTrue("Should not throw NullPointerException", !exception);
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceQueueTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceQueueTest.java
new file mode 100644
index 0000000..75a5218
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceQueueTest.java
@@ -0,0 +1,254 @@
+/*
+ * 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.tests.java.lang.ref;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
+import libcore.java.lang.ref.FinalizationTester;
+
+public class ReferenceQueueTest extends junit.framework.TestCase {
+ static Boolean b;
+
+ static Integer integer;
+ boolean isThrown = false;
+
+ protected void doneSuite() {
+ b = null;
+ integer = null;
+ }
+
+ public class ChildThread implements Runnable {
+ public ChildThread() {
+ }
+
+ public void run() {
+ try {
+ rq.wait(1000);
+ } catch (Exception e) {
+ }
+ synchronized (rq) {
+ // store in a static so it won't be gc'ed because the jit
+ // optimized it out
+ integer = new Integer(667);
+ SoftReference sr = new SoftReference(integer, rq);
+ sr.enqueue();
+ rq.notify();
+ }
+ }
+ }
+
+ ReferenceQueue rq;
+
+ /**
+ * java.lang.ref.ReferenceQueue#poll()
+ */
+ public void test_poll() {
+ // store in a static so it won't be gc'ed because the jit
+ // optimized it out
+ b = new Boolean(true);
+ Object obj = new Object();
+ String str = "Test";
+
+ SoftReference sr = new SoftReference(b, rq);
+ WeakReference wr = new WeakReference(obj, rq);
+ PhantomReference pr = new PhantomReference(str, rq);
+ assertNull(rq.poll());
+ sr.enqueue();
+ wr.enqueue();
+ pr.enqueue();
+
+ try {
+ assertTrue("Remove failed.", ((Boolean) rq.poll().get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during the test : " + e.getMessage());
+ }
+
+ try {
+ assertEquals("Remove failed.", obj, (rq.poll().get()));
+ } catch (Exception e) {
+ fail("Exception during the test : " + e.getMessage());
+ }
+
+ try {
+ assertNull("Remove failed.", rq.poll().get());
+ } catch (Exception e) {
+ fail("Exception during the test : " + e.getMessage());
+ }
+
+ assertNull(rq.poll());
+
+ sr.enqueue();
+ wr.enqueue();
+
+ FinalizationTester.induceFinalization();
+
+ assertNull(rq.poll());
+ }
+
+ /**
+ * java.lang.ref.ReferenceQueue#remove()
+ */
+ public void test_remove() {
+ // store in a static so it won't be gc'ed because the jit
+ // optimized it out
+ b = new Boolean(true);
+
+ SoftReference sr = new SoftReference(b, rq);
+ sr.enqueue();
+ try {
+ assertTrue("Remove failed.", ((Boolean) rq.remove().get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during the test : " + e.getMessage());
+ }
+
+ assertNull(rq.poll());
+
+ sr.enqueue();
+
+ class RemoveThread extends Thread {
+ public void run() {
+ try {
+ rq.remove();
+ } catch(InterruptedException ie) {
+ isThrown = true;
+ }
+ }
+ }
+ RemoveThread rt = new RemoveThread();
+ rt.start();
+ try {
+ Thread.sleep(100);
+ } catch(InterruptedException ie) {
+
+ }
+ rt.interrupt();
+ try {
+ Thread.sleep(100);
+ } catch(InterruptedException ie) {
+
+ }
+ assertTrue(isThrown);
+ assertNull(rq.poll());
+ }
+
+ /**
+ * java.lang.ref.ReferenceQueue#remove(long)
+ */
+ public void test_removeJ() {
+ try {
+ assertNull("Queue should be empty. (poll)", rq.poll());
+ assertNull("Queue should be empty. (remove(1))",
+ rq.remove((long) 1));
+ Thread ct = new Thread(new ChildThread());
+ ct.start();
+ Reference ret = rq.remove(0L);
+ assertNotNull("Delayed remove failed.", ret);
+ } catch (InterruptedException e) {
+ fail("InterruptedExeException during test : " + e.getMessage());
+ }
+ catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+
+ Object obj = new Object();
+ WeakReference wr = new WeakReference(obj, rq);
+ Boolean b = new Boolean(true);
+ SoftReference sr = new SoftReference(b, rq);
+ String str = "Test";
+ PhantomReference pr = new PhantomReference(str, rq);
+
+ pr.enqueue();
+ wr.enqueue();
+ sr.enqueue();
+
+ try {
+ Reference result = rq.remove(1L);
+ assertNull(result.get());
+ result = rq.remove(1L);
+ assertEquals(obj, result.get());
+ result = rq.remove(1L);
+ assertTrue((Boolean)result.get());
+ } catch (IllegalArgumentException e1) {
+ fail("IllegalArgumentException was thrown.");
+ } catch (InterruptedException e1) {
+ fail("InterruptedException was thrown.");
+ }
+ rq = new ReferenceQueue();
+ isThrown = false;
+ assertNull(rq.poll());
+
+ class RemoveThread extends Thread {
+ public void run() {
+ try {
+ rq.remove(1000L);
+ } catch(InterruptedException ie) {
+ isThrown = true;
+ }
+ }
+ }
+ RemoveThread rt = new RemoveThread();
+ rt.start();
+ try {
+ Thread.sleep(10);
+ } catch(InterruptedException ie) {
+
+ }
+ rt.interrupt();
+ try {
+ Thread.sleep(10);
+ } catch(InterruptedException ie) {
+
+ }
+ assertTrue(isThrown);
+ assertNull(rq.poll());
+
+ try {
+ rq.remove(-1);
+ fail("IllegalArgumentException expected.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ } catch (InterruptedException e) {
+ fail("Unexpected InterruptedException.");
+ }
+ }
+
+ /**
+ * java.lang.ref.ReferenceQueue#ReferenceQueue()
+ */
+ public void test_Constructor() {
+ ReferenceQueue rq = new ReferenceQueue();
+ assertNull(rq.poll());
+ try {
+ rq.remove(100L);
+ } catch (InterruptedException e) {
+ fail("InterruptedException was thrown.");
+ }
+ }
+
+ protected void setUp() {
+ rq = new ReferenceQueue();
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceTest.java
new file mode 100644
index 0000000..031502d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/ReferenceTest.java
@@ -0,0 +1,340 @@
+/*
+ * 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.tests.java.lang.ref;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
+import junit.framework.AssertionFailedError;
+import libcore.java.lang.ref.FinalizationTester;
+
+public class ReferenceTest extends junit.framework.TestCase {
+ Object tmpA, tmpB, tmpC, obj;
+
+ volatile Reference r;
+
+ /*
+ * For test_subclass().
+ */
+ static TestWeakReference twr;
+ static AssertionFailedError error;
+ static boolean testObjectFinalized;
+ static class TestWeakReference<T> extends WeakReference<T> {
+ public volatile boolean clearSeen = false;
+ public volatile boolean enqueueSeen = false;
+
+ public TestWeakReference(T referent) {
+ super(referent);
+ }
+
+ public TestWeakReference(T referent, ReferenceQueue<? super T> q) {
+ super(referent, q);
+ }
+
+ public void clear() {
+ clearSeen = true;
+ if (testObjectFinalized) {
+ error = new AssertionFailedError("Clear should happen " +
+ "before finalization.");
+ throw error;
+ }
+ if (enqueueSeen) {
+ error = new AssertionFailedError("Clear should happen " +
+ "before enqueue.");
+ throw error;
+ }
+ super.clear();
+ }
+
+ public boolean enqueue() {
+ enqueueSeen = true;
+ if (!clearSeen) {
+ error = new AssertionFailedError("Clear should happen " +
+ "before enqueue.");
+ throw error;
+ }
+
+ /* Do this last; it may notify the main test thread,
+ * and anything we'd do after it (e.g., setting clearSeen)
+ * wouldn't be seen.
+ */
+ return super.enqueue();
+ }
+ }
+
+ protected void doneSuite() {
+ tmpA = tmpB = obj = null;
+ }
+
+ /**
+ * java.lang.ref.Reference#clear()
+ */
+ public void test_clear() {
+ tmpA = new Object();
+ tmpB = new Object();
+ tmpC = new Object();
+ SoftReference sr = new SoftReference(tmpA, new ReferenceQueue());
+ WeakReference wr = new WeakReference(tmpB, new ReferenceQueue());
+ PhantomReference pr = new PhantomReference(tmpC, new ReferenceQueue());
+ assertTrue("Start: Object not cleared.", (sr.get() != null)
+ && (wr.get() != null));
+ assertNull("Referent is not null.", pr.get());
+ sr.clear();
+ wr.clear();
+ pr.clear();
+ assertTrue("End: Object cleared.", (sr.get() == null)
+ && (wr.get() == null));
+ assertNull("Referent is not null.", pr.get());
+ // Must reference tmpA and tmpB so the jit does not optimize them away
+ assertTrue("should always pass", tmpA != sr.get() && tmpB != wr.get());
+ }
+
+ /**
+ * java.lang.ref.Reference#enqueue()
+ */
+ public void test_enqueue() {
+ ReferenceQueue rq = new ReferenceQueue();
+ obj = new Object();
+ Reference ref = new SoftReference(obj, rq);
+ assertTrue("Enqueue failed.", (!ref.isEnqueued())
+ && ((ref.enqueue()) && (ref.isEnqueued())));
+ assertTrue("Not properly enqueued.", rq.poll().get() == obj);
+ // This fails...
+ assertTrue("Should remain enqueued.", !ref.isEnqueued());
+ assertTrue("Can not enqueue twice.", (!ref.enqueue())
+ && (rq.poll() == null));
+
+ rq = new ReferenceQueue();
+ obj = new Object();
+
+ ref = new WeakReference(obj, rq);
+ assertTrue("Enqueue failed2.", (!ref.isEnqueued())
+ && ((ref.enqueue()) && (ref.isEnqueued())));
+ assertTrue("Not properly enqueued2.", rq.poll().get() == obj);
+ assertTrue("Should remain enqueued2.", !ref.isEnqueued()); // This
+ // fails.
+ assertTrue("Can not enqueue twice2.", (!ref.enqueue())
+ && (rq.poll() == null));
+
+ ref = new PhantomReference(obj, rq);
+ assertTrue("Enqueue failed3.", (!ref.isEnqueued())
+ && ((ref.enqueue()) && (ref.isEnqueued())));
+ assertNull("Not properly enqueued3.", rq.poll().get());
+ assertTrue("Should remain enqueued3.", !ref.isEnqueued()); // This
+ // fails.
+ assertTrue("Can not enqueue twice3.", (!ref.enqueue())
+ && (rq.poll() == null));
+ }
+
+ public void test_get_WeakReference() throws Exception {
+ // Test the general/overall functionality of Reference.
+ ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
+
+ r = newWeakReference(queue);
+ FinalizationTester.induceFinalization();
+ Reference ref = queue.remove();
+ assertNotNull("Object not enqueued.", ref);
+ assertSame("Unexpected ref1", ref, r);
+ assertNull("Object could not be reclaimed1.", r.get());
+
+ r = newWeakReference(queue);
+ FinalizationTester.induceFinalization();
+
+ // wait for the reference queue thread to enqueue the newly-finalized object
+ Thread.yield();
+ Thread.sleep(200);
+
+ ref = queue.poll();
+ assertNotNull("Object not enqueued.", ref);
+ assertSame("Unexpected ref2", ref, r);
+ assertNull("Object could not be reclaimed.", ref.get());
+ assertNull("Object could not be reclaimed.", r.get());
+ }
+
+ /**
+ * Makes sure that overridden versions of clear() and enqueue()
+ * get called, and that clear/enqueue/finalize happen in the
+ * right order for WeakReferences.
+ *
+ * java.lang.ref.Reference#clear()
+ * java.lang.ref.Reference#enqueue()
+ * java.lang.Object#finalize()
+ */
+ public void test_subclass() {
+ error = null;
+ testObjectFinalized = false;
+ twr = null;
+
+ class TestObject {
+ public TestWeakReference testWeakReference = null;
+
+ public void setTestWeakReference(TestWeakReference twr) {
+ testWeakReference = twr;
+ }
+
+ protected void finalize() {
+ testObjectFinalized = true;
+ }
+ }
+
+ final ReferenceQueue rq = new ReferenceQueue();
+
+ class TestThread extends Thread {
+ public void run() {
+ // Create the object in a separate thread to ensure it will be
+ // gc'ed
+ TestObject testObj = new TestObject();
+ twr = new TestWeakReference(testObj, rq);
+ testObj.setTestWeakReference(twr);
+ testObj = null;
+ }
+ }
+
+ Reference ref;
+
+ try {
+ Thread t = new TestThread();
+ t.start();
+ t.join();
+ FinalizationTester.induceFinalization();
+ ref = rq.remove(5000L); // Give up after five seconds.
+
+ assertNotNull("Object not garbage collected.", ref);
+ assertTrue("Unexpected reference.", ref == twr);
+ assertNull("Object could not be reclaimed.", twr.get());
+ //assertTrue("Overridden clear() should have been called.",
+ // twr.clearSeen);
+ //assertTrue("Overridden enqueue() should have been called.",
+ // twr.enqueueSeen);
+ assertTrue("finalize() should have been called.",
+ testObjectFinalized);
+ } catch (InterruptedException e) {
+ fail("InterruptedException : " + e.getMessage());
+ }
+
+ }
+
+ /**
+ * java.lang.ref.Reference#get()
+ */
+ public void test_get() {
+ WeakReference ref = newWeakReference(null);
+
+ FinalizationTester.induceFinalization();
+ assertNull("get() doesn't return null after gc for WeakReference", ref.get());
+
+ obj = new Object();
+ ref = new WeakReference<Object>(obj, new ReferenceQueue<Object>());
+ ref.clear();
+ assertNull("get() doesn't return null after clear for WeakReference", ref.get());
+ }
+
+ /**
+ * Helper method to prevent live-precise bugs from interfering with analysis
+ * of what is reachable. Do not inline this method; otherwise tests may fail
+ * on VMs that are not live-precise. http://b/4191345
+ */
+ private WeakReference<Object> newWeakReference(ReferenceQueue<Object> queue) {
+ Object o = new Object();
+ WeakReference<Object> ref = new WeakReference<Object>(o, queue);
+ assertSame(o, ref.get());
+ return ref;
+ }
+
+ /**
+ * java.lang.ref.Reference#isEnqueued()
+ */
+ public void test_isEnqueued() {
+ ReferenceQueue rq = new ReferenceQueue();
+ obj = new Object();
+ Reference ref = new SoftReference(obj, rq);
+ assertTrue("Should start off not enqueued.", !ref.isEnqueued());
+ ref.enqueue();
+ assertTrue("Should now be enqueued.", ref.isEnqueued());
+ ref.enqueue();
+ assertTrue("Should still be enqueued.", ref.isEnqueued());
+ rq.poll();
+ // This fails ...
+ assertTrue("Should now be not enqueued.", !ref.isEnqueued());
+ }
+
+ /* Contrives a situation where the only reference to a string
+ * is a WeakReference from an object that is being finalized.
+ * Checks to make sure that the referent of the WeakReference
+ * is still pointing to a valid object.
+ */
+ public void test_finalizeReferenceInteraction() {
+ error = null;
+ testObjectFinalized = false;
+
+ class TestObject {
+ WeakReference<String> stringRef;
+
+ public TestObject(String referent) {
+ stringRef = new WeakReference<String>(referent);
+ }
+
+ protected void finalize() {
+ try {
+ /* If a VM bug has caused the referent to get
+ * freed without the reference getting cleared,
+ * looking it up, assigning it to a local and
+ * doing a GC should cause some sort of exception.
+ */
+ String s = stringRef.get();
+ System.gc();
+ testObjectFinalized = true;
+ } catch (Throwable t) {
+ error = new AssertionFailedError("something threw '" + t +
+ "' in finalize()");
+ }
+ }
+ }
+
+ class TestThread extends Thread {
+ public void run() {
+ // Create the object in a separate thread to ensure it will be
+ // gc'ed
+ TestObject testObj = new TestObject(new String("sup /b/"));
+ }
+ }
+
+ try {
+ Thread t = new TestThread();
+ t.start();
+ t.join();
+ FinalizationTester.induceFinalization();
+ Thread.sleep(1000);
+ if (error != null) {
+ throw error;
+ }
+ assertTrue("finalize() should have been called.",
+ testObjectFinalized);
+ } catch (InterruptedException e) {
+ fail("InterruptedException : " + e.getMessage());
+ }
+ }
+
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/SoftReferenceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/SoftReferenceTest.java
new file mode 100644
index 0000000..f66cbbf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/SoftReferenceTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.tests.java.lang.ref;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.util.Vector;
+import libcore.java.lang.ref.FinalizationTester;
+
+public class SoftReferenceTest extends junit.framework.TestCase {
+ static Boolean bool;
+ SoftReference r;
+
+ protected void doneSuite() {
+ bool = null;
+ }
+
+ /**
+ * java.lang.ref.SoftReference#SoftReference(java.lang.Object,
+ * java.lang.ref.ReferenceQueue)
+ */
+ public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
+ ReferenceQueue rq = new ReferenceQueue();
+ bool = new Boolean(true);
+ try {
+ SoftReference sr = new SoftReference(bool, rq);
+ assertTrue("Initialization failed.", ((Boolean) sr.get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+
+ boolean exception = false;
+ try {
+ new SoftReference(bool, null);
+ } catch (NullPointerException e) {
+ exception = true;
+ }
+ assertTrue("Should not throw NullPointerException", !exception);
+ }
+
+ /**
+ * java.lang.ref.SoftReference#SoftReference(java.lang.Object)
+ */
+ public void test_ConstructorLjava_lang_Object() {
+ bool = new Boolean(true);
+ try {
+ SoftReference sr = new SoftReference(bool);
+ assertTrue("Initialization failed.", ((Boolean) sr.get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.ref.SoftReference#get()
+ */
+ public void test_get() {
+ bool = new Boolean(false);
+ SoftReference sr = new SoftReference(bool);
+ assertTrue("Same object not returned.", bool == sr.get());
+ }
+
+ // SideEffect: Causes OutOfMemoryError to test finalization
+ public void test_get_SoftReference() {
+
+ class TestObject {
+ public boolean finalized;
+ public TestObject() {
+ finalized = false;
+ }
+
+ protected void finalize() {
+ finalized = true;
+ }
+ }
+
+ final ReferenceQueue rq = new ReferenceQueue();
+
+ class TestThread extends Thread {
+ public void run() {
+ Object testObj = new TestObject();
+ r = new SoftReference(testObj, rq);
+ }
+ }
+ Reference ref;
+ try {
+ TestThread t = new TestThread();
+ t.start();
+ t.join();
+ Vector<StringBuffer> v = new Vector<StringBuffer>();
+ try {
+ while(true) {
+ v.add(new StringBuffer(10000));
+ }
+ } catch(OutOfMemoryError ofme) {
+ v = null;
+ }
+ } catch (InterruptedException e) {
+ fail("InterruptedException : " + e.getMessage());
+ }
+
+ assertNull("get() should return null " +
+ "if OutOfMemoryError is thrown.", r.get());
+
+ try {
+ TestThread t = new TestThread();
+ t.start();
+ t.join();
+ FinalizationTester.induceFinalization();
+ ref = rq.poll();
+ assertNotNull("Object not garbage collected.", ref);
+ assertNull("Object is not null.", ref.get());
+ assertNotNull("Object could not be reclaimed.", r.get());
+ } catch (Exception e) {
+ fail("Exception : " + e.getMessage());
+ }
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/WeakReferenceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/WeakReferenceTest.java
new file mode 100644
index 0000000..c881248
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/ref/WeakReferenceTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.tests.java.lang.ref;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+
+public class WeakReferenceTest extends junit.framework.TestCase {
+ static Boolean bool;
+
+ protected void doneSuite() {
+ bool = null;
+ }
+
+ /**
+ * java.lang.ref.WeakReference#WeakReference(java.lang.Object,
+ * java.lang.ref.ReferenceQueue)
+ */
+ public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
+ ReferenceQueue rq = new ReferenceQueue();
+ bool = new Boolean(true);
+ try {
+ // Allow the finalizer to run to potentially enqueue
+ WeakReference wr = new WeakReference(bool, rq);
+ assertTrue("Initialization failed.", ((Boolean) wr.get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ // need a reference to bool so the jit does not optimize it away
+ assertTrue("should always pass", bool.booleanValue());
+
+ boolean exception = false;
+ try {
+ new WeakReference(bool, null);
+ } catch (NullPointerException e) {
+ exception = true;
+ }
+ assertTrue("Should not throw NullPointerException", !exception);
+ }
+
+ /**
+ * java.lang.ref.WeakReference#WeakReference(java.lang.Object)
+ */
+ public void test_ConstructorLjava_lang_Object() {
+ bool = new Boolean(true);
+ try {
+ WeakReference wr = new WeakReference(bool);
+ // Allow the finalizer to run to potentially enqueue
+ Thread.sleep(1000);
+ assertTrue("Initialization failed.", ((Boolean) wr.get())
+ .booleanValue());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ // need a reference to bool so the jit does not optimize it away
+ assertTrue("should always pass", bool.booleanValue());
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/AccessibleObjectTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/AccessibleObjectTest.java
new file mode 100644
index 0000000..60432d7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/AccessibleObjectTest.java
@@ -0,0 +1,215 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Modifier;
+import java.util.HashSet;
+import java.util.Set;
+
+public class AccessibleObjectTest extends junit.framework.TestCase {
+
+ public class TestClass {
+ public Object aField;
+
+ @InheritedRuntime
+ public void annotatedMethod(){}
+ }
+
+ public class SubTestClass extends TestClass{
+ @AnnotationRuntime0
+ @AnnotationRuntime1
+ @AnnotationClass0
+ @AnnotationSource0
+ public void annotatedMethod(){}
+ }
+
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.METHOD})
+ static @interface AnnotationRuntime0 {
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( { ElementType.METHOD})
+ static @interface AnnotationRuntime1 {
+ }
+
+ @Retention(RetentionPolicy.CLASS)
+ @Target( { ElementType.METHOD})
+ static @interface AnnotationClass0 {
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @Target( {ElementType.METHOD})
+ static @interface AnnotationSource0 {
+ }
+
+ @Inherited
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.METHOD})
+ static @interface InheritedRuntime {
+ }
+
+ //used for constructor test
+ private static class MyAccessibleObject extends AccessibleObject{
+ public MyAccessibleObject() {
+ super();
+ }
+ }
+
+ /**
+ * java.lang.reflect.AccessibleObject#AccessibleObject()
+ */
+ public void test_Constructor() {
+ assertNotNull(new MyAccessibleObject());
+ }
+
+ /**
+ * java.lang.reflect.AccessibleObject#isAccessible()
+ */
+ public void test_isAccessible() {
+ // Test for method boolean
+ // java.lang.reflect.AccessibleObject.isAccessible()
+ try {
+ AccessibleObject ao = TestClass.class.getField("aField");
+ ao.setAccessible(true);
+ assertTrue("Returned false to isAccessible", ao.isAccessible());
+ ao.setAccessible(false);
+ assertTrue("Returned true to isAccessible", !ao.isAccessible());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[],
+ * boolean)
+ */
+ public void test_setAccessible$Ljava_lang_reflect_AccessibleObjectZ() {
+ try {
+ AccessibleObject ao = TestClass.class.getField("aField");
+ AccessibleObject[] aoa = new AccessibleObject[] { ao };
+ AccessibleObject.setAccessible(aoa, true);
+ assertTrue("Returned false to isAccessible", ao.isAccessible());
+ AccessibleObject.setAccessible(aoa, false);
+ assertTrue("Returned true to isAccessible", !ao.isAccessible());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.AccessibleObject#setAccessible(boolean)
+ */
+ public void test_setAccessible() throws Exception {
+ AccessibleObject ao = TestClass.class.getField("aField");
+ ao.setAccessible(true);
+ assertTrue("Returned false to isAccessible", ao.isAccessible());
+ ao.setAccessible(false);
+ assertFalse("Returned true to isAccessible", ao.isAccessible());
+ }
+
+ public void test_getAnnotation() throws Exception{
+ AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
+ //test error case
+ boolean npeThrown = false;
+ try {
+ ao.getAnnotation(null);
+ fail("NPE expected");
+ } catch (NullPointerException e) {
+ npeThrown = true;
+ }
+ assertTrue("NPE expected", npeThrown);
+
+ //test inherited on method has no effect
+ InheritedRuntime ir = ao.getAnnotation(InheritedRuntime.class);
+ assertNull("Inherited Annotations should have no effect", ir);
+
+ //test ordinary runtime annotation
+ AnnotationRuntime0 rt0 = ao.getAnnotation(AnnotationRuntime0.class);
+ assertNotNull("AnnotationRuntime0 instance expected", rt0);
+ }
+
+ public void test_getAnnotations() throws Exception {
+ AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
+ Annotation[] annotations = ao.getAnnotations();
+ assertEquals(2, annotations.length);
+
+ Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
+ ignoreOrder.add(annotations[0].annotationType());
+ ignoreOrder.add(annotations[1].annotationType());
+
+ assertTrue("Missing @AnnotationRuntime0",
+ ignoreOrder.contains(AnnotationRuntime0.class));
+ assertTrue("Missing @AnnotationRuntime1",
+ ignoreOrder.contains(AnnotationRuntime1.class));
+ }
+
+ public void test_getDeclaredAnnotations() throws Exception {
+ AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
+ Annotation[] annotations = ao.getDeclaredAnnotations();
+ assertEquals(2, annotations.length);
+
+ Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
+ ignoreOrder.add(annotations[0].annotationType());
+ ignoreOrder.add(annotations[1].annotationType());
+
+ assertTrue("Missing @AnnotationRuntime0",
+ ignoreOrder.contains(AnnotationRuntime0.class));
+ assertTrue("Missing @AnnotationRuntime1",
+ ignoreOrder.contains(AnnotationRuntime1.class));
+ }
+
+ public void test_isAnnotationPresent() throws Exception {
+ AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
+ assertTrue("Missing @AnnotationRuntime0",
+ ao.isAnnotationPresent(AnnotationRuntime0.class));
+ assertFalse("AnnotationSource0 should not be visible at runtime",
+ ao.isAnnotationPresent(AnnotationSource0.class));
+ boolean npeThrown = false;
+ try {
+ ao.isAnnotationPresent(null);
+ fail("NPE expected");
+ } catch (NullPointerException e) {
+ npeThrown = true;
+ }
+ assertTrue("NPE expected", npeThrown);
+ }
+
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ArrayTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ArrayTest.java
new file mode 100644
index 0000000..98dd034
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ArrayTest.java
@@ -0,0 +1,1001 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.reflect.Array;
+
+public class ArrayTest extends junit.framework.TestCase {
+
+ /**
+ * java.lang.reflect.Array#get(java.lang.Object, int)
+ */
+ public void test_getLjava_lang_ObjectI() {
+ // Test for method java.lang.Object
+ // java.lang.reflect.Array.get(java.lang.Object, int)
+
+ int[] x = { 1 };
+ Object ret = null;
+ boolean thrown = false;
+ try {
+ ret = Array.get(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value",
+ 1, ((Integer) ret).intValue());
+ try {
+ ret = Array.get(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.get(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ //same test with non primitive component type
+ Integer[] y = new Integer[]{ 1 };
+ ret = null;
+ thrown = false;
+ try {
+ ret = Array.get(y, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value",
+ 1, ((Integer) ret).intValue());
+ try {
+ ret = Array.get(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.get(y, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getBoolean(java.lang.Object, int)
+ */
+ public void test_getBooleanLjava_lang_ObjectI() {
+ // Test for method boolean
+ // java.lang.reflect.Array.getBoolean(java.lang.Object, int)
+ boolean[] x = { true };
+ boolean ret = false;
+ boolean thrown = false;
+ try {
+ ret = Array.getBoolean(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertTrue("Get returned incorrect value", ret);
+ try {
+ ret = Array.getBoolean(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getBoolean(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getBoolean(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getByte(java.lang.Object, int)
+ */
+ public void test_getByteLjava_lang_ObjectI() {
+ // Test for method byte
+ // java.lang.reflect.Array.getByte(java.lang.Object, int)
+ byte[] x = { 1 };
+ byte ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getByte(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret);
+ try {
+ ret = Array.getByte(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getByte(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getByte(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getChar(java.lang.Object, int)
+ */
+ public void test_getCharLjava_lang_ObjectI() {
+ // Test for method char
+ // java.lang.reflect.Array.getChar(java.lang.Object, int)
+ char[] x = { 1 };
+ char ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getChar(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret);
+ try {
+ ret = Array.getChar(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getChar(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getChar(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getDouble(java.lang.Object, int)
+ */
+ public void test_getDoubleLjava_lang_ObjectI() {
+ // Test for method double
+ // java.lang.reflect.Array.getDouble(java.lang.Object, int)
+ double[] x = { 1 };
+ double ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getDouble(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret, 0.0);
+ try {
+ ret = Array.getDouble(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getDouble(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getDouble(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getFloat(java.lang.Object, int)
+ */
+ public void test_getFloatLjava_lang_ObjectI() {
+ // Test for method float
+ // java.lang.reflect.Array.getFloat(java.lang.Object, int)
+ float[] x = { 1 };
+ float ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getFloat(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret, 0.0);
+ try {
+ ret = Array.getFloat(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getFloat(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getFloat(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getInt(java.lang.Object, int)
+ */
+ public void test_getIntLjava_lang_ObjectI() {
+ // Test for method int java.lang.reflect.Array.getInt(java.lang.Object,
+ // int)
+ int[] x = { 1 };
+ int ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getInt(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret);
+ try {
+ ret = Array.getInt(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getInt(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getInt(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getLength(java.lang.Object)
+ */
+ public void test_getLengthLjava_lang_Object() {
+ // Test for method int
+ // java.lang.reflect.Array.getLength(java.lang.Object)
+ long[] x = { 1 };
+
+ assertEquals("Returned incorrect length", 1, Array.getLength(x));
+ assertEquals("Returned incorrect length", 10000, Array
+ .getLength(new Object[10000]));
+ try {
+ Array.getLength(new Object());
+ } catch (IllegalArgumentException e) {
+ // Correct
+ return;
+ }
+ fail("Failed to throw exception when passed non-array");
+ }
+
+ /**
+ * java.lang.reflect.Array#getLong(java.lang.Object, int)
+ */
+ public void test_getLongLjava_lang_ObjectI() {
+ // Test for method long
+ // java.lang.reflect.Array.getLong(java.lang.Object, int)
+ long[] x = { 1 };
+ long ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getLong(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret);
+ try {
+ ret = Array.getLong(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getLong(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getLong(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#getShort(java.lang.Object, int)
+ */
+ public void test_getShortLjava_lang_ObjectI() {
+ // Test for method short
+ // java.lang.reflect.Array.getShort(java.lang.Object, int)
+ short[] x = { 1 };
+ short ret = 0;
+ boolean thrown = false;
+ try {
+ ret = Array.getShort(x, 0);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ret);
+ try {
+ ret = Array.getShort(new Object(), 0);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getShort(x, 4);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+ thrown = false;
+ try {
+ ret = Array.getShort(null, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#newInstance(java.lang.Class, int[])
+ */
+ public void test_newInstanceLjava_lang_Class$I() {
+ // Test for method java.lang.Object
+ // java.lang.reflect.Array.newInstance(java.lang.Class, int [])
+ int[][] x;
+ int[] y = { 2 };
+
+ x = (int[][]) Array.newInstance(int[].class, y);
+ assertEquals("Failed to instantiate array properly", 2, x.length);
+
+ boolean thrown = false;
+ try {
+ x = (int[][]) Array.newInstance(null, y);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+
+ thrown = false;
+ try {
+ Array.newInstance(int[].class, new int[]{1,-1});
+ } catch (NegativeArraySizeException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Negative array size failed to throw NegativeArraySizeException");
+ }
+
+ thrown = false;
+ try {
+ Array.newInstance(int[].class, new int[]{});
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Zero array size failed to throw IllegalArgumentException");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#newInstance(java.lang.Class, int)
+ */
+ public void test_newInstanceLjava_lang_ClassI() {
+ // Test for method java.lang.Object
+ // java.lang.reflect.Array.newInstance(java.lang.Class, int)
+ int[] x;
+
+ x = (int[]) Array.newInstance(int.class, 100);
+ assertEquals("Failed to instantiate array properly", 100, x.length);
+
+ boolean thrown = false;
+ try {
+ Array.newInstance(null, 100);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+
+ thrown = false;
+ try {
+ Array.newInstance(int[].class, -1);
+ } catch (NegativeArraySizeException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Negative array size failed to throw NegativeArraySizeException");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#set(java.lang.Object, int,
+ * java.lang.Object)
+ */
+ public void test_setLjava_lang_ObjectILjava_lang_Object() {
+ // Test for method void java.lang.reflect.Array.set(java.lang.Object,
+ // int, java.lang.Object)
+ int[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.set(x, 0, new Integer(1));
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, ((Integer) Array.get(x, 0))
+ .intValue());
+ try {
+ Array.set(new Object(), 0, new Object());
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.set(x, 4, new Integer(1));
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ // trying to put null in a primitive array causes
+ // a IllegalArgumentException in 5.0
+ boolean exception = false;
+ try {
+ Array.set(new int[1], 0, null);
+ } catch (IllegalArgumentException e) {
+ exception = true;
+ }
+ assertTrue("expected exception not thrown", exception);
+
+ thrown = false;
+ try {
+ Array.set(null, 0, 2);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setBoolean(java.lang.Object, int, boolean)
+ */
+ public void test_setBooleanLjava_lang_ObjectIZ() {
+ // Test for method void
+ // java.lang.reflect.Array.setBoolean(java.lang.Object, int, boolean)
+ boolean[] x = { false };
+ boolean thrown = false;
+ try {
+ Array.setBoolean(x, 0, true);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertTrue("Failed to set correct value", Array.getBoolean(x, 0));
+ try {
+ Array.setBoolean(new Object(), 0, false);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown){
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setBoolean(x, 4, false);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setBoolean(null, 0, true);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setByte(java.lang.Object, int, byte)
+ */
+ public void test_setByteLjava_lang_ObjectIB() {
+ // Test for method void
+ // java.lang.reflect.Array.setByte(java.lang.Object, int, byte)
+ byte[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setByte(x, 0, (byte) 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getByte(x, 0));
+ try {
+ Array.setByte(new Object(), 0, (byte) 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setByte(x, 4, (byte) 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setByte(null, 0, (byte)0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setChar(java.lang.Object, int, char)
+ */
+ public void test_setCharLjava_lang_ObjectIC() {
+ // Test for method void
+ // java.lang.reflect.Array.setChar(java.lang.Object, int, char)
+ char[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setChar(x, 0, (char) 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getChar(x, 0));
+ try {
+ Array.setChar(new Object(), 0, (char) 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setChar(x, 4, (char) 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setChar(null, 0, (char)0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setDouble(java.lang.Object, int, double)
+ */
+ public void test_setDoubleLjava_lang_ObjectID() {
+ // Test for method void
+ // java.lang.reflect.Array.setDouble(java.lang.Object, int, double)
+ double[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setDouble(x, 0, 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getDouble(x, 0), 0.0);
+ try {
+ Array.setDouble(new Object(), 0, 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setDouble(x, 4, 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setDouble(null, 0, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setFloat(java.lang.Object, int, float)
+ */
+ public void test_setFloatLjava_lang_ObjectIF() {
+ // Test for method void
+ // java.lang.reflect.Array.setFloat(java.lang.Object, int, float)
+ float[] x = { 0.0f };
+ boolean thrown = false;
+ try {
+ Array.setFloat(x, 0, (float) 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getFloat(x, 0), 0.0);
+ try {
+ Array.setFloat(new Object(), 0, (float) 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setFloat(x, 4, (float) 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setFloat(null, 0, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setInt(java.lang.Object, int, int)
+ */
+ public void test_setIntLjava_lang_ObjectII() {
+ // Test for method void java.lang.reflect.Array.setInt(java.lang.Object,
+ // int, int)
+ int[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setInt(x, 0, (int) 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getInt(x, 0));
+ try {
+ Array.setInt(new Object(), 0, (int) 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setInt(x, 4, (int) 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setInt(null, 0, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setLong(java.lang.Object, int, long)
+ */
+ public void test_setLongLjava_lang_ObjectIJ() {
+ // Test for method void
+ // java.lang.reflect.Array.setLong(java.lang.Object, int, long)
+ long[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setLong(x, 0, 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getLong(x, 0));
+ try {
+ Array.setLong(new Object(), 0, 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setLong(x, 4, 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setLong(null, 0, 0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * java.lang.reflect.Array#setShort(java.lang.Object, int, short)
+ */
+ public void test_setShortLjava_lang_ObjectIS() {
+ // Test for method void
+ // java.lang.reflect.Array.setShort(java.lang.Object, int, short)
+ short[] x = { 0 };
+ boolean thrown = false;
+ try {
+ Array.setShort(x, 0, (short) 1);
+ } catch (Exception e) {
+ fail("Exception during get test : " + e.getMessage());
+ }
+ assertEquals("Get returned incorrect value", 1, Array.getShort(x, 0));
+ try {
+ Array.setShort(new Object(), 0, (short) 9);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Passing non-array failed to throw exception");
+ }
+ thrown = false;
+ try {
+ Array.setShort(x, 4, (short) 9);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Invalid index failed to throw exception");
+ }
+
+ thrown = false;
+ try {
+ Array.setShort(null, 0, (short)0);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ thrown = true;
+ }
+ if (!thrown) {
+ fail("Null argument failed to throw NPE");
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/BoundedGenericMethodsTests.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/BoundedGenericMethodsTests.java
new file mode 100644
index 0000000..130aa72
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/BoundedGenericMethodsTests.java
@@ -0,0 +1,128 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+/**
+ * Tests bounded type parameters declared on methods.
+ */
+public class BoundedGenericMethodsTests extends GenericReflectionTestsBase {
+ @SuppressWarnings("unchecked")
+ static class BoundedGenericMethods<S> {
+
+ public <T extends BoundedGenericMethods> void noParamNoReturn() {}
+ public <T extends BoundedGenericMethods> void paramNoReturn(T param) {}
+
+ public <T extends BoundedGenericMethods> T noParamReturn() {
+ return (T) new Object();
+ }
+ public <T extends BoundedGenericMethods> T paramReturn(T t) {
+ return t;
+ }
+ }
+ @SuppressWarnings("unchecked")
+ private static Class<? extends BoundedGenericMethods> clazz = BoundedGenericMethodsTests.BoundedGenericMethods.class;
+
+ /**
+ * Tests whether the type parameter is upper bounded by BoundedGenericMethods.
+ * <T extends BoundedGenericMethods>.
+ *
+ * @param method
+ * the declaring method
+ */
+ private void checkBoundedTypeParameter(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ assertEquals("T", typeParameter.getName());
+ assertEquals(method, typeParameter.getGenericDeclaration());
+
+ Type[] bounds = typeParameter.getBounds();
+ assertLenghtOne(bounds);
+ Type bound = bounds[0];
+ assertEquals(BoundedGenericMethods.class, bound);
+ }
+
+ /**
+ * Tests whether the specified method declares a parameter with the type of
+ * the type parameter.
+ *
+ * @param method
+ * the declaring method
+ */
+ private void parameterType(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ assertLenghtOne(method.getGenericParameterTypes());
+ Type genericParameterType = method.getGenericParameterTypes()[0];
+ assertEquals(typeParameter, genericParameterType);
+ assertTrue(genericParameterType instanceof TypeVariable);
+ TypeVariable<?> typeVariable = (TypeVariable<?>) genericParameterType;
+ assertEquals(method, typeVariable.getGenericDeclaration());
+
+ Type[] paramBounds = typeVariable.getBounds();
+ assertLenghtOne(paramBounds);
+ Type paramBound = paramBounds[0];
+ assertEquals(BoundedGenericMethods.class, paramBound);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void checkReturnType(Method method) {
+ Type genericReturnType = method.getGenericReturnType();
+ assertEquals(getTypeParameter(method), genericReturnType);
+ assertTrue(genericReturnType instanceof TypeVariable);
+
+ TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
+ assertEquals(method, returnTypeVariable.getGenericDeclaration());
+
+ Type[] bounds = returnTypeVariable.getBounds();
+ assertLenghtOne(bounds);
+ Type bound = bounds[0];
+
+ assertEquals(BoundedGenericMethods.class, bound);
+ }
+
+
+
+ /**
+ * Tests that there are is one Type Parameter on the Class itself.
+ */
+ public void testBoundedGenericMethods() {
+ assertLenghtOne(clazz.getTypeParameters());
+ }
+ public void testNoParamNoReturn() throws SecurityException, NoSuchMethodException {
+ Method method = clazz.getMethod("noParamNoReturn");
+ checkBoundedTypeParameter(method);
+ }
+ public void testUnboundedParamNoReturn() throws SecurityException, NoSuchMethodException {
+ Method method = clazz.getMethod("paramNoReturn", BoundedGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ parameterType(method);
+ }
+ public void testNoParamReturn() throws SecurityException, NoSuchMethodException {
+ Method method = clazz.getMethod("noParamReturn");
+ checkBoundedTypeParameter(method);
+ assertLenghtZero(method.getGenericParameterTypes());
+ checkReturnType(method);
+ }
+ public void testUnboundedParamReturn() throws SecurityException, NoSuchMethodException {
+ Method method = clazz.getMethod("paramReturn", BoundedGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ parameterType(method);
+ checkReturnType(method);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ConstructorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ConstructorTest.java
new file mode 100644
index 0000000..ec133aa
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ConstructorTest.java
@@ -0,0 +1,442 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.HashSet;
+import java.util.Set;
+
+public class ConstructorTest extends junit.framework.TestCase {
+
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
+ static @interface ConstructorTestAnnotationRuntime0 {
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
+ static @interface ConstructorTestAnnotationRuntime1 {
+ }
+
+ @Retention(RetentionPolicy.CLASS)
+ @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
+ static @interface ConstructorTestAnnotationClass0 {
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
+ static @interface ConstructorTestAnnotationSource0 {
+ }
+
+ static class ConstructorTestHelper extends Object {
+ int cval;
+
+ @ConstructorTestAnnotationRuntime0
+ @ConstructorTestAnnotationRuntime1
+ @ConstructorTestAnnotationClass0
+ @ConstructorTestAnnotationSource0
+ public ConstructorTestHelper() throws IndexOutOfBoundsException {
+ cval = 99;
+ }
+
+ public ConstructorTestHelper(
+ @ConstructorTestAnnotationRuntime0
+ @ConstructorTestAnnotationRuntime1
+ @ConstructorTestAnnotationClass0
+ @ConstructorTestAnnotationSource0 Object x) {
+ }
+
+ public ConstructorTestHelper(String... x) {
+ }
+
+ private ConstructorTestHelper(int a) {
+ }
+
+ protected ConstructorTestHelper(long a) {
+ }
+
+ public int check() {
+ return cval;
+ }
+ }
+
+ static class GenericConstructorTestHelper<T, S extends T, E extends Exception> {
+ public GenericConstructorTestHelper(T t, S s) {}
+ public GenericConstructorTestHelper() throws E{}
+ }
+
+ static class NoPublicConstructorTestHelper {
+ // This class has no public constructor.
+ }
+
+// Used to test synthetic constructor.
+//
+// static class Outer {
+// private Outer(){}
+// class Inner {
+// {new Outer();}
+// }
+// }
+
+ public void test_getParameterAnnotations() throws Exception {
+ Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class
+ .getConstructor(Object.class);
+ Annotation[][] paramAnnotations = ctor1.getParameterAnnotations();
+ assertEquals("Annotations for wrong number of parameters returned", 1,
+ paramAnnotations.length);
+ assertEquals("Wrong number of annotations returned", 2,
+ paramAnnotations[0].length);
+
+ Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
+ ignoreOrder.add(paramAnnotations[0][0].annotationType());
+ ignoreOrder.add(paramAnnotations[0][1].annotationType());
+
+ assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
+ .contains(ConstructorTestAnnotationRuntime0.class));
+ assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
+ .contains(ConstructorTestAnnotationRuntime1.class));
+ }
+
+
+ public void test_getDeclaredAnnotations() throws Exception {
+ Constructor<ConstructorTestHelper> ctor1 = null;
+ ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]);
+ Annotation[] annotations = ctor1.getDeclaredAnnotations();
+ assertEquals("Wrong number of annotations returned", 2,
+ annotations.length);
+ Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
+ ignoreOrder.add(annotations[0].annotationType());
+ ignoreOrder.add(annotations[1].annotationType());
+
+ assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
+ .contains(ConstructorTestAnnotationRuntime0.class));
+ assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
+ .contains(ConstructorTestAnnotationRuntime1.class));
+ }
+
+ public void test_isVarArgs() throws Exception {
+ Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class
+ .getConstructor(String[].class);
+ assertTrue("Vararg constructor not recognized", varArgCtor.isVarArgs());
+
+ Constructor<ConstructorTestHelper> nonVarArgCtor = ConstructorTestHelper.class
+ .getConstructor(Object.class);
+ assertFalse("Non vararg constructor recognized as vararg constructor",
+ nonVarArgCtor.isVarArgs());
+ }
+
+ public void test_hashCode() throws Exception {
+ Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class
+ .getConstructor();
+ assertEquals(
+ "The constructor's hashCode is not equal to the hashCode of the name of the declaring class",
+ ConstructorTestHelper.class.getName().hashCode(), constructor
+ .hashCode());
+ }
+
+ @SuppressWarnings("unchecked")
+ public void test_toGenericString() throws Exception {
+ Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class
+ .getConstructor(Object.class, Object.class);
+ assertEquals(
+ "Wrong generic string returned",
+ "public org.apache.harmony.tests.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper(T,S)",
+ genericCtor.toGenericString());
+ Constructor<GenericConstructorTestHelper> ctor = GenericConstructorTestHelper.class
+ .getConstructor();
+ assertEquals(
+ "Wrong generic string returned",
+ "public org.apache.harmony.tests.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper() throws E",
+ ctor.toGenericString());
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null;
+ try {
+ ctor1 = ConstructorTestHelper.class.getConstructor(
+ new Class[0]);
+ ctor2 = ConstructorTestHelper.class.getConstructor(Object.class);
+ } catch (Exception e) {
+ fail("Exception during equals test : " + e.getMessage());
+ }
+ assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2));
+ }
+
+ public void test_getDeclaringClass() {
+ boolean val = false;
+ try {
+ Class<? extends ConstructorTestHelper> pclass = new ConstructorTestHelper().getClass();
+ Constructor<? extends ConstructorTestHelper> ctor = pclass.getConstructor(new Class[0]);
+ val = ctor.getDeclaringClass().equals(pclass);
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect declaring class", val);
+ }
+
+ public void test_getExceptionTypes() {
+ // Test for method java.lang.Class []
+ // java.lang.reflect.Constructor.getExceptionTypes()
+ Class[] exceptions = null;
+ Class<? extends IndexOutOfBoundsException> ex = null;
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(new Class[0]);
+ exceptions = ctor.getExceptionTypes();
+ ex = new IndexOutOfBoundsException().getClass();
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ assertEquals("Returned exception list of incorrect length",
+ 1, exceptions.length);
+ assertTrue("Returned incorrect exception", exceptions[0].equals(ex));
+ }
+
+ public void test_getModifiers() {
+ // Test for method int java.lang.reflect.Constructor.getModifiers()
+ int mod = 0;
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(new Class[0]);
+ mod = ctor.getModifiers();
+ assertTrue("Returned incorrect modifers for public ctor",
+ ((mod & Modifier.PUBLIC) == Modifier.PUBLIC)
+ && ((mod & Modifier.PRIVATE) == 0));
+ } catch (NoSuchMethodException e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ try {
+ Class[] cl = { int.class };
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getDeclaredConstructor(cl);
+ mod = ctor.getModifiers();
+ assertTrue("Returned incorrect modifers for private ctor",
+ ((mod & Modifier.PRIVATE) == Modifier.PRIVATE)
+ && ((mod & Modifier.PUBLIC) == 0));
+ } catch (NoSuchMethodException e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ try {
+ Class[] cl = { long.class };
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getDeclaredConstructor(cl);
+ mod = ctor.getModifiers();
+ assertTrue("Returned incorrect modifers for private ctor",
+ ((mod & Modifier.PROTECTED) == Modifier.PROTECTED)
+ && ((mod & Modifier.PUBLIC) == 0));
+ } catch (NoSuchMethodException e) {
+ fail("NoSuchMethodException during test : " + e.getMessage());
+ }
+ }
+
+ public void test_getName() {
+ // Test for method java.lang.String
+ // java.lang.reflect.Constructor.getName()
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(new Class[0]);
+ assertTrue(
+ "Returned incorrect name: " + ctor.getName(),
+ ctor
+ .getName()
+ .equals(
+ "org.apache.harmony.tests.java.lang.reflect.ConstructorTest$ConstructorTestHelper"));
+ } catch (Exception e) {
+ fail("Exception obtaining contructor : " + e.getMessage());
+ }
+ }
+
+ public void test_getParameterTypes() {
+ // Test for method java.lang.Class []
+ // java.lang.reflect.Constructor.getParameterTypes()
+ Class[] types = null;
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(new Class[0]);
+ types = ctor.getParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:"
+ + e.toString());
+ }
+ assertEquals("Incorrect parameter returned", 0, types.length);
+
+ Class[] parms = null;
+ try {
+ parms = new Class[1];
+ parms[0] = new Object().getClass();
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(parms);
+ types = ctor.getParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:"
+ + e.toString());
+ }
+ assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
+ }
+
+ @SuppressWarnings("unchecked")
+ public void test_getGenericParameterTypes() {
+ Type[] types = null;
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
+ .getClass().getConstructor(new Class[0]);
+ types = ctor.getGenericParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:" + e.toString());
+ }
+ assertEquals("Incorrect parameter returned", 0, types.length);
+
+ Class<?>[] parms = null;
+ try {
+ parms = new Class[] {Object.class};
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
+ .getClass().getConstructor(parms);
+ types = ctor.getGenericParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:" + e.toString());
+ }
+ assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
+
+
+ try {
+ Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
+ .getConstructor(Object.class, Object.class);
+ types = constructor.getGenericParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:" + e.toString());
+ }
+
+ assertEquals("Wrong number of parameter types returned", 2,
+ types.length);
+
+ assertEquals("Wrong number of parameter types returned", "T",
+ ((TypeVariable)types[0]).getName());
+ assertEquals("Wrong number of parameter types returned", "S",
+ ((TypeVariable)types[1]).getName());
+ }
+
+ @SuppressWarnings("unchecked")
+ public void test_getGenericExceptionTypes() {
+ Type[] types = null;
+
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
+ .getClass().getConstructor(new Class[0]);
+ types = ctor.getGenericExceptionTypes();
+ } catch (Exception e) {
+ fail("Exception during getGenericExceptionTypes test:" + e.toString());
+ }
+ assertEquals("Wrong number of exception types returned", 1, types.length);
+
+
+ try {
+ Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
+ .getConstructor();
+ types = constructor.getGenericExceptionTypes();
+ } catch (Exception e) {
+ fail("Exception during getGenericExceptionTypes test:"
+ + e.toString());
+ }
+
+ assertEquals("Wrong number of exception types returned", 1,
+ types.length);
+
+ assertEquals("Wrong exception name returned.", "E",
+ ((TypeVariable)types[0]).getName());
+
+ }
+
+
+ public void test_newInstance$Ljava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.lang.reflect.Constructor.newInstance(java.lang.Object [])
+
+ ConstructorTestHelper test = null;
+ try {
+ Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
+ .getConstructor(new Class[0]);
+ test = ctor.newInstance((Object[])null);
+ } catch (Exception e) {
+ fail("Failed to create instance : " + e.getMessage());
+ }
+ assertEquals("improper instance created", 99, test.check());
+ }
+
+ public void test_toString() {
+ // Test for method java.lang.String
+ // java.lang.reflect.Constructor.toString()
+ Class[] parms = null;
+ Constructor<? extends ConstructorTestHelper> ctor = null;
+ try {
+ parms = new Class[1];
+ parms[0] = new Object().getClass();
+ ctor = new ConstructorTestHelper().getClass().getConstructor(parms);
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test:"
+ + e.toString());
+ }
+ assertTrue(
+ "Returned incorrect string representation: " + ctor.toString(),
+ ctor
+ .toString()
+ .equals(
+ "public org.apache.harmony.tests.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)"));
+ }
+
+ public void test_getConstructor() throws Exception {
+ // Passing new Class[0] should be equivalent to (Class[]) null.
+ Class<ConstructorTestHelper> c2 = ConstructorTestHelper.class;
+ assertEquals(c2.getConstructor(new Class[0]), c2.getConstructor((Class[]) null));
+ assertEquals(c2.getDeclaredConstructor(new Class[0]),
+ c2.getDeclaredConstructor((Class[]) null));
+
+ // We can get a non-public constructor via getDeclaredConstructor...
+ Class<NoPublicConstructorTestHelper> c1 = NoPublicConstructorTestHelper.class;
+ c1.getDeclaredConstructor((Class[]) null);
+ // ...but not with getConstructor (which only returns public constructors).
+ try {
+ c1.getConstructor((Class[]) null);
+ fail("Should throw NoSuchMethodException");
+ } catch (NoSuchMethodException ex) {
+ // Expected.
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/FieldTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/FieldTest.java
new file mode 100644
index 0000000..d5ce8c2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/FieldTest.java
@@ -0,0 +1,1639 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import tests.support.Support_Field;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.HashSet;
+import java.util.Set;
+
+public class FieldTest extends junit.framework.TestCase {
+
+ // BEGIN android-note
+ // This test had a couple of bugs in it. Some parts of the code were
+ // unreachable before. Also some tests expected the wrong excpetions
+ // to be thrown. This version has been validated to pass on a standard
+ // JDK 1.5.
+ // END android-note
+
+ public class TestClass {
+ @AnnotationRuntime0
+ @AnnotationRuntime1
+ @AnnotationClass0
+ @AnnotationSource0
+ public int annotatedField;
+ class Inner{}
+ }
+
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.FIELD})
+ static @interface AnnotationRuntime0 {
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( { ElementType.FIELD})
+ static @interface AnnotationRuntime1 {
+ }
+
+ @Retention(RetentionPolicy.CLASS)
+ @Target( { ElementType.FIELD})
+ static @interface AnnotationClass0 {
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @Target( {ElementType.FIELD})
+ static @interface AnnotationSource0 {
+ }
+
+ @Inherited
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target( {ElementType.FIELD})
+ static @interface InheritedRuntime {
+ }
+
+ public class GenericField<S, T extends Number> {
+ S field;
+ T boundedField;
+ int intField;
+ }
+
+
+ static class TestField {
+ public static int pubfield1;
+
+ private static int privfield1 = 123;
+
+ protected int intField = Integer.MAX_VALUE;
+ protected final int intFField = Integer.MAX_VALUE;
+ protected static int intSField = Integer.MAX_VALUE;
+ private final int intPFField = Integer.MAX_VALUE;
+
+ protected short shortField = Short.MAX_VALUE;
+ protected final short shortFField = Short.MAX_VALUE;
+ protected static short shortSField = Short.MAX_VALUE;
+ private final short shortPFField = Short.MAX_VALUE;
+
+ protected boolean booleanField = true;
+ protected static boolean booleanSField = true;
+ protected final boolean booleanFField = true;
+ private final boolean booleanPFField = true;
+
+ protected byte byteField = Byte.MAX_VALUE;
+ protected static byte byteSField = Byte.MAX_VALUE;
+ protected final byte byteFField = Byte.MAX_VALUE;
+ private final byte bytePFField = Byte.MAX_VALUE;
+
+ protected long longField = Long.MAX_VALUE;
+ protected final long longFField = Long.MAX_VALUE;
+ protected static long longSField = Long.MAX_VALUE;
+ private final long longPFField = Long.MAX_VALUE;
+
+ protected double doubleField = Double.MAX_VALUE;
+ protected static double doubleSField = Double.MAX_VALUE;
+ protected static final double doubleSFField = Double.MAX_VALUE;
+ protected final double doubleFField = Double.MAX_VALUE;
+ private final double doublePFField = Double.MAX_VALUE;
+
+ protected float floatField = Float.MAX_VALUE;
+ protected final float floatFField = Float.MAX_VALUE;
+ protected static float floatSField = Float.MAX_VALUE;
+ private final float floatPFField = Float.MAX_VALUE;
+
+ protected char charField = 'T';
+ protected static char charSField = 'T';
+ private final char charPFField = 'T';
+
+ protected final char charFField = 'T';
+
+ private static final int x = 1;
+
+ public volatile transient int y = 0;
+
+ protected static transient volatile int prsttrvol = 99;
+ }
+
+ public class TestFieldSub1 extends TestField {
+ }
+
+ public class TestFieldSub2 extends TestField {
+ }
+
+ static class A {
+ protected short shortField = Short.MAX_VALUE;
+ }
+
+ static enum TestEnum {
+ A, B, C;
+ int field;
+ }
+
+ /**
+ * java.lang.reflect.Field#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.lang.reflect.Field.equals(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ } catch (Exception e) {
+ fail("Exception during getType test : " + e.getMessage());
+ }
+ try {
+ assertTrue("Same Field returned false", f.equals(f));
+ assertTrue("Inherited Field returned false", f.equals(TestField.class
+ .getDeclaredField("shortField")));
+ assertTrue("Identical Field from different class returned true", !f
+ .equals(A.class.getDeclaredField("shortField")));
+ } catch (Exception e) {
+ fail("Exception during getType test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() throws Throwable {
+ // Test for method java.lang.Object
+ // java.lang.reflect.Field.get(java.lang.Object)
+ TestField x = new TestField();
+ Field f = TestField.class.getDeclaredField("doubleField");
+ Double val = (Double) f.get(x);
+
+ assertTrue("Returned incorrect double field value",
+ val.doubleValue() == Double.MAX_VALUE);
+ // Test getting a static field;
+ f = TestField.class.getDeclaredField("doubleSField");
+ f.set(x, new Double(1.0));
+ val = (Double) f.get(x);
+ assertEquals("Returned incorrect double field value", 1.0, val.doubleValue());
+
+ // Try a get on a private field in nested member
+ // temporarily commented because it breaks J9 VM
+ // Regression for HARMONY-1309
+ //f = x.getClass().getDeclaredField("privfield1");
+ //assertEquals(x.privfield1, f.get(x));
+
+ // Try a get using an invalid class.
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.get(new String());
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException exc) {
+ // Correct - Passed an Object that does not declare or inherit f
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("intField");
+ f.get(null);
+ fail("Expected NullPointerException not thrown");
+ } catch (NullPointerException exc) {
+ // Correct - Passed an Object that does not declare or inherit f
+ thrown = true;
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static fields
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleSField");
+ f.get(null);
+ assertTrue("Exception thrown", true);
+ } catch (Exception exc) {
+ fail("No exception expected");
+ }
+ }
+
+ class SupportSubClass extends Support_Field {
+
+ Object getField(char primitiveType, Object o, Field f,
+ Class expected) {
+ Object res = null;
+ try {
+ primitiveType = Character.toUpperCase(primitiveType);
+ switch (primitiveType) {
+ case 'I': // int
+ res = new Integer(f.getInt(o));
+ break;
+ case 'J': // long
+ res = new Long(f.getLong(o));
+ break;
+ case 'Z': // boolean
+ res = new Boolean(f.getBoolean(o));
+ break;
+ case 'S': // short
+ res = new Short(f.getShort(o));
+ break;
+ case 'B': // byte
+ res = new Byte(f.getByte(o));
+ break;
+ case 'C': // char
+ res = new Character(f.getChar(o));
+ break;
+ case 'D': // double
+ res = new Double(f.getDouble(o));
+ break;
+ case 'F': // float
+ res = new Float(f.getFloat(o));
+ break;
+ default:
+ res = f.get(o);
+ }
+ // Since 2011, members are always accessible and throwing is optional
+ assertTrue("expected " + expected + " for " + f.getName(),
+ expected == null || expected == IllegalAccessException.class);
+ } catch (Exception e) {
+ if (expected == null) {
+ fail("unexpected exception " + e);
+ } else {
+ assertTrue("expected exception "
+ + expected.getName() + " and got " + e, e
+ .getClass().equals(expected));
+ }
+ }
+ return res;
+ }
+
+ void setField(char primitiveType, Object o, Field f,
+ Class expected, Object value) {
+ try {
+ primitiveType = Character.toUpperCase(primitiveType);
+ switch (primitiveType) {
+ case 'I': // int
+ f.setInt(o, ((Integer) value).intValue());
+ break;
+ case 'J': // long
+ f.setLong(o, ((Long) value).longValue());
+ break;
+ case 'Z': // boolean
+ f.setBoolean(o, ((Boolean) value).booleanValue());
+ break;
+ case 'S': // short
+ f.setShort(o, ((Short) value).shortValue());
+ break;
+ case 'B': // byte
+ f.setByte(o, ((Byte) value).byteValue());
+ break;
+ case 'C': // char
+ f.setChar(o, ((Character) value).charValue());
+ break;
+ case 'D': // double
+ f.setDouble(o, ((Double) value).doubleValue());
+ break;
+ case 'F': // float
+ f.setFloat(o, ((Float) value).floatValue());
+ break;
+ default:
+ f.set(o, value);
+ }
+ // Since 2011, members are always accessible and throwing is optional
+ assertTrue("expected " + expected + " for " + f.getName() + " = " + value,
+ expected == null || expected == IllegalAccessException.class);
+ } catch (Exception e) {
+ if (expected == null) {
+ e.printStackTrace();
+ fail("unexpected exception " + e + " for field "
+ + f.getName() + ", value " + value);
+ } else {
+ assertTrue("expected exception "
+ + expected.getName() + " and got " + e
+ + " for field " + f.getName() + ", value " + value,
+ e.getClass().equals(expected));
+ }
+ }
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#get(java.lang.Object)
+ * java.lang.reflect.Field#getByte(java.lang.Object)
+ * java.lang.reflect.Field#getBoolean(java.lang.Object)
+ * java.lang.reflect.Field#getShort(java.lang.Object)
+ * java.lang.reflect.Field#getInt(java.lang.Object)
+ * java.lang.reflect.Field#getLong(java.lang.Object)
+ * java.lang.reflect.Field#getFloat(java.lang.Object)
+ * java.lang.reflect.Field#getDouble(java.lang.Object)
+ * java.lang.reflect.Field#getChar(java.lang.Object)
+ * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
+ * java.lang.reflect.Field#setByte(java.lang.Object, byte)
+ * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
+ * java.lang.reflect.Field#setShort(java.lang.Object, short)
+ * java.lang.reflect.Field#setInt(java.lang.Object, int)
+ * java.lang.reflect.Field#setLong(java.lang.Object, long)
+ * java.lang.reflect.Field#setFloat(java.lang.Object, float)
+ * java.lang.reflect.Field#setDouble(java.lang.Object, double)
+ * java.lang.reflect.Field#setChar(java.lang.Object, char)
+ */
+ public void testProtectedFieldAccess() {
+ Class fieldClass = Support_Field.class;
+ String fieldName = null;
+ Field objectField = null;
+ Field booleanField = null;
+ Field byteField = null;
+ Field charField = null;
+ Field shortField = null;
+ Field intField = null;
+ Field longField = null;
+ Field floatField = null;
+ Field doubleField = null;
+ try {
+ fieldName = "objectField";
+ objectField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "booleanField";
+ booleanField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "byteField";
+ byteField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "charField";
+ charField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "shortField";
+ shortField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "intField";
+ intField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "longField";
+ longField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "floatField";
+ floatField = fieldClass.getDeclaredField(fieldName);
+
+ fieldName = "doubleField";
+ doubleField = fieldClass.getDeclaredField(fieldName);
+ } catch (NoSuchFieldException e) {
+ fail("missing field " + fieldName + " in test support class "
+ + fieldClass.getName());
+ }
+
+ // create the various objects that might or might not have an instance
+ // of the field
+ Support_Field parentClass = new Support_Field();
+ SupportSubClass subclass = new SupportSubClass();
+ SupportSubClass otherSubclass = new SupportSubClass();
+ Object plainObject = new Object();
+
+ Class illegalAccessExceptionClass = IllegalAccessException.class;
+ Class illegalArgumentExceptionClass = IllegalArgumentException.class;
+
+ // The test will attempt to use pass an object to set for object, byte,
+ // short, ..., float and double fields
+ // and pass a byte to to setByte for byte, short, ..., float and double
+ // fields and so on.
+ // It will also test if IllegalArgumentException is thrown when the
+ // field does not exist in the given object and that
+ // IllegalAccessException is thrown when trying to access an
+ // inaccessible protected field.
+ // The test will also check that IllegalArgumentException is thrown for
+ // all other attempts.
+
+ // Ordered by widening conversion, except for 'L' at the beg (which
+ // stands for Object).
+ // If the object provided to set can be unwrapped to a primitive, then
+ // the set method can set
+ // primitive fields.
+ char types[] = { 'L', 'B', 'S', 'C', 'I', 'J', 'F', 'D' };
+ Field fields[] = { objectField, byteField, shortField, charField,
+ intField, longField, floatField, doubleField };
+ Object values[] = { new Byte((byte) 1), new Byte((byte) 1),
+ new Short((short) 1), new Character((char) 1), new Integer(1),
+ new Long(1), new Float(1), new Double(1) };
+
+ // test set methods
+ for (int i = 0; i < types.length; i++) {
+ char type = types[i];
+ Object value = values[i];
+ for (int j = i; j < fields.length; j++) {
+ Field field = fields[j];
+ fieldName = field.getName();
+
+ if (field == charField && type != 'C') {
+ // the exception is that bytes and shorts CANNOT be
+ // converted into chars even though chars CAN be
+ // converted into ints, longs, floats and doubles
+ subclass.setField(type, subclass, field,
+ illegalArgumentExceptionClass, value);
+ } else {
+ // setting type into field);
+ subclass.setField(type, subclass, field, null, value);
+ subclass.setField(type, otherSubclass, field, null, value);
+ subclass.setField(type, parentClass, field,
+ illegalAccessExceptionClass, value);
+ subclass.setField(type, plainObject, field,
+ illegalArgumentExceptionClass, value);
+ }
+ }
+ for (int j = 0; j < i; j++) {
+ Field field = fields[j];
+ fieldName = field.getName();
+ // not setting type into field);
+ subclass.setField(type, subclass, field,
+ illegalArgumentExceptionClass, value);
+ }
+ }
+
+ // test setBoolean
+ Boolean booleanValue = Boolean.TRUE;
+ subclass.setField('Z', subclass, booleanField, null, booleanValue);
+ subclass.setField('Z', otherSubclass, booleanField, null, booleanValue);
+ subclass.setField('Z', parentClass, booleanField,
+ illegalAccessExceptionClass, booleanValue);
+ subclass.setField('Z', plainObject, booleanField,
+ illegalArgumentExceptionClass, booleanValue);
+ for (int j = 0; j < fields.length; j++) {
+ Field listedField = fields[j];
+ fieldName = listedField.getName();
+ // not setting boolean into listedField
+ subclass.setField('Z', subclass, listedField,
+ illegalArgumentExceptionClass, booleanValue);
+ }
+ for (int i = 0; i < types.length; i++) {
+ char type = types[i];
+ Object value = values[i];
+ subclass.setField(type, subclass, booleanField,
+ illegalArgumentExceptionClass, value);
+ }
+
+ // We perform the analogous test on the get methods.
+
+ // ordered by widening conversion, except for 'L' at the end (which
+ // stands for Object), to which all primitives can be converted by
+ // wrapping
+ char newTypes[] = new char[] { 'B', 'S', 'C', 'I', 'J', 'F', 'D', 'L' };
+ Field newFields[] = { byteField, shortField, charField, intField,
+ longField, floatField, doubleField, objectField };
+ fields = newFields;
+ types = newTypes;
+ // test get methods
+ for (int i = 0; i < types.length; i++) {
+ char type = types[i];
+ for (int j = 0; j <= i; j++) {
+ Field field = fields[j];
+ fieldName = field.getName();
+ if (type == 'C' && field != charField) {
+ // the exception is that bytes and shorts CANNOT be
+ // converted into chars even though chars CAN be
+ // converted into ints, longs, floats and doubles
+ subclass.getField(type, subclass, field,
+ illegalArgumentExceptionClass);
+ } else {
+ // getting type from field
+ subclass.getField(type, subclass, field, null);
+ subclass.getField(type, otherSubclass, field, null);
+ subclass.getField(type, parentClass, field,
+ illegalAccessExceptionClass);
+ subclass.getField(type, plainObject, field,
+ illegalArgumentExceptionClass);
+ }
+ }
+ for (int j = i + 1; j < fields.length; j++) {
+ Field field = fields[j];
+ fieldName = field.getName();
+ subclass.getField(type, subclass, field,
+ illegalArgumentExceptionClass);
+ }
+ }
+
+ // test getBoolean
+ subclass.getField('Z', subclass, booleanField, null);
+ subclass.getField('Z', otherSubclass, booleanField, null);
+ subclass.getField('Z', parentClass, booleanField,
+ illegalAccessExceptionClass);
+ subclass.getField('Z', plainObject, booleanField,
+ illegalArgumentExceptionClass);
+ for (int j = 0; j < fields.length; j++) {
+ Field listedField = fields[j];
+ fieldName = listedField.getName();
+ // not getting boolean from listedField
+ subclass.getField('Z', subclass, listedField,
+ illegalArgumentExceptionClass);
+ }
+ for (int i = 0; i < types.length - 1; i++) {
+ char type = types[i];
+ subclass.getField(type, subclass, booleanField,
+ illegalArgumentExceptionClass);
+ }
+ Object res = subclass.getField('L', subclass, booleanField, null);
+ assertTrue("unexpected object " + res, res instanceof Boolean);
+ }
+
+ /**
+ * java.lang.reflect.Field#getBoolean(java.lang.Object)
+ */
+ public void test_getBooleanLjava_lang_Object() {
+ TestField x = new TestField();
+ Field f = null;
+ boolean val = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ val = f.getBoolean(x);
+ } catch (Exception e) {
+ fail("Exception during getBoolean test: " + e.toString());
+ }
+ assertTrue("Returned incorrect boolean field value", val);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.getBoolean(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown");
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getBoolean(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanSField");
+ boolean staticValue = f.getBoolean(null);
+ assertTrue("Wrong value returned", staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected");
+ }
+ }
+
+
+ /**
+ * java.lang.reflect.Field#getByte(java.lang.Object)
+ */
+ public void test_getByteLjava_lang_Object() {
+ // Test for method byte
+ // java.lang.reflect.Field.getByte(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ byte val = 0;
+ try {
+ f = TestField.class.getDeclaredField("byteField");
+ val = f.getByte(x);
+ } catch (Exception e) {
+ fail("Exception during getbyte test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect byte field value", val == Byte.MAX_VALUE);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.getByte(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown");
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("byteField");
+ f.getByte(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("byteSField");
+ byte staticValue = f.getByte(null);
+ assertEquals("Wrong value returned", Byte.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getChar(java.lang.Object)
+ */
+ public void test_getCharLjava_lang_Object() {
+ // Test for method char
+ // java.lang.reflect.Field.getChar(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ char val = 0;
+ try {
+ f = TestField.class.getDeclaredField("charField");
+ val = f.getChar(x);
+ } catch (Exception e) {
+ fail("Exception during getCharacter test: " + e.toString());
+ }
+ assertEquals("Returned incorrect char field value", 'T', val);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.getChar(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown");
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("charField");
+ f.getChar(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("charSField");
+ char staticValue = f.getChar(null);
+ assertEquals("Wrong value returned", 'T', staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getDeclaringClass()
+ */
+ public void test_getDeclaringClass() {
+ // Test for method java.lang.Class
+ // java.lang.reflect.Field.getDeclaringClass()
+ Field[] fields;
+
+ try {
+ fields = TestField.class.getFields();
+ assertTrue("Returned incorrect declaring class", fields[0]
+ .getDeclaringClass().equals(TestField.class));
+
+ // Check the case where the field is inherited to be sure the parent
+ // is returned as the declarer
+ fields = TestFieldSub1.class.getFields();
+ assertTrue("Returned incorrect declaring class", fields[0]
+ .getDeclaringClass().equals(TestField.class));
+ } catch (Exception e) {
+ fail("Exception : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getDouble(java.lang.Object)
+ */
+ public void test_getDoubleLjava_lang_Object() {
+ // Test for method double
+ // java.lang.reflect.Field.getDouble(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ double val = 0.0;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ val = f.getDouble(x);
+ } catch (Exception e) {
+ fail("Exception during getDouble test: " + e.toString());
+ }
+ assertTrue("Returned incorrect double field value",
+ val == Double.MAX_VALUE);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getDouble(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown "
+ + ex.getMessage());
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.getDouble(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleSFField");
+ double staticValue = f.getDouble(null);
+ assertEquals("Wrong value returned", Double.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getFloat(java.lang.Object)
+ */
+ public void test_getFloatLjava_lang_Object() {
+ // Test for method float
+ // java.lang.reflect.Field.getFloat(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ float val = 0;
+ try {
+ f = TestField.class.getDeclaredField("floatField");
+ val = f.getFloat(x);
+ } catch (Exception e) {
+ fail("Exception during getFloat test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect float field value",
+ val == Float.MAX_VALUE);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getFloat(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown "
+ + ex.getMessage());
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("floatField");
+ f.getFloat(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("floatSField");
+ float staticValue = f.getFloat(null);
+ assertEquals("Wrong value returned", Float.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getInt(java.lang.Object)
+ */
+ public void test_getIntLjava_lang_Object() {
+ // Test for method int java.lang.reflect.Field.getInt(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ int val = 0;
+ try {
+ f = TestField.class.getDeclaredField("intField");
+ val = f.getInt(x);
+ } catch (Exception e) {
+ fail("Exception during getInt test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect Int field value",
+ val == Integer.MAX_VALUE);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getInt(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown "
+ + ex.getMessage());
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("intField");
+ f.getInt(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("intSField");
+ int staticValue = f.getInt(null);
+ assertEquals("Wrong value returned", Integer.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected " + ex.getMessage());
+ }
+
+ }
+
+ /**
+ * java.lang.reflect.Field#getLong(java.lang.Object)
+ */
+ public void test_getLongLjava_lang_Object() {
+ // Test for method long
+ // java.lang.reflect.Field.getLong(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ long val = 0;
+ try {
+ f = TestField.class.getDeclaredField("longField");
+ val = f.getLong(x);
+ } catch (Exception e) {
+ fail("Exception during getLong test : " + e.getMessage());
+ }
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getLong(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown "
+ + ex.getMessage());
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("longField");
+ f.getLong(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("longSField");
+ long staticValue = f.getLong(null);
+ assertEquals("Wrong value returned", Long.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getModifiers()
+ */
+ public void test_getModifiers() {
+ // Test for method int java.lang.reflect.Field.getModifiers()
+ TestField x = new TestField();
+ Field f = null;
+ try {
+ f = TestField.class.getDeclaredField("prsttrvol");
+ } catch (Exception e) {
+ fail("Exception during getModifiers test: " + e.toString());
+ }
+ int mod = f.getModifiers();
+ int mask = (Modifier.PROTECTED | Modifier.STATIC)
+ | (Modifier.TRANSIENT | Modifier.VOLATILE);
+ int nmask = (Modifier.PUBLIC | Modifier.NATIVE);
+ assertTrue("Returned incorrect field modifiers: ",
+ ((mod & mask) == mask) && ((mod & nmask) == 0));
+ }
+
+ /**
+ * java.lang.reflect.Field#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.lang.reflect.Field.getName()
+ TestField x = new TestField();
+ Field f = null;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ } catch (Exception e) {
+ fail("Exception during getType test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect field name",
+ "shortField", f.getName());
+ }
+
+ /**
+ * java.lang.reflect.Field#getShort(java.lang.Object)
+ */
+ public void test_getShortLjava_lang_Object() {
+ // Test for method short
+ // java.lang.reflect.Field.getShort(java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ short val = 0;
+ ;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ val = f.getShort(x);
+ } catch (Exception e) {
+ fail("Exception during getShort test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect short field value",
+ val == Short.MAX_VALUE);
+
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.getShort(x);
+ fail("IllegalArgumentException expected but not thrown");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("IllegalArgumentException expected but not thrown "
+ + ex.getMessage());
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ f.getShort(null);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ //Test no NPE on static field
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("shortSField");
+ short staticValue = f.getShort(null);
+ assertEquals("Wrong value returned", Short.MAX_VALUE, staticValue);
+ } catch (Exception ex) {
+ fail("No exception expected "+ ex.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Field#getType()
+ */
+ public void test_getType() {
+ // Test for method java.lang.Class java.lang.reflect.Field.getType()
+ TestField x = new TestField();
+ Field f = null;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ } catch (Exception e) {
+ fail("Exception during getType test : " + e.getMessage());
+ }
+ assertTrue("Returned incorrect field type: " + f.getType().toString(),
+ f.getType().equals(short.class));
+ }
+
+ /**
+ * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
+ */
+ public void test_setLjava_lang_ObjectLjava_lang_Object() throws Exception{
+ // Test for method void java.lang.reflect.Field.set(java.lang.Object,
+ // java.lang.Object)
+ TestField x = new TestField();
+ Field f = null;
+ double val = 0.0;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.set(x, new Double(1.0));
+ val = f.getDouble(x);
+ } catch (Exception e) {
+ fail("Exception during set test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect double field value", 1.0, val);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.set(x, new Double(1.0));
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.set(null, true);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("doubleSField");
+ f.set(null, new Double(1.0));
+ val = f.getDouble(x);
+ assertEquals("Returned incorrect double field value", 1.0, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
+ */
+ public void test_setBooleanLjava_lang_ObjectZ() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setBoolean(java.lang.Object, boolean)
+ TestField x = new TestField();
+ Field f = null;
+ boolean val = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setBoolean(x, false);
+ val = f.getBoolean(x);
+ } catch (Exception e) {
+ fail("Exception during setboolean test: " + e.toString());
+ }
+ assertTrue("Returned incorrect float field value", !val);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.setBoolean(x, false);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setBoolean(null, true);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("booleanSField");
+ f.setBoolean(null, false);
+ val = f.getBoolean(x);
+ assertFalse("Returned incorrect boolean field value", val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setByte(java.lang.Object, byte)
+ */
+ public void test_setByteLjava_lang_ObjectB() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setByte(java.lang.Object, byte)
+ TestField x = new TestField();
+ Field f = null;
+ byte val = 0;
+ try {
+ f = TestField.class.getDeclaredField("byteField");
+ f.setByte(x, (byte) 1);
+ val = f.getByte(x);
+ } catch (Exception e) {
+ fail("Exception during setByte test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect float field value", 1, val);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setByte(x, Byte.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("byteField");
+ f.setByte(null, Byte.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("byteSField");
+ f.setByte(null, Byte.MIN_VALUE);
+ val = f.getByte(x);
+ assertEquals("Returned incorrect byte field value", Byte.MIN_VALUE,
+ val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setChar(java.lang.Object, char)
+ */
+ public void test_setCharLjava_lang_ObjectC() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setChar(java.lang.Object, char)
+ TestField x = new TestField();
+ Field f = null;
+ char val = 0;
+ try {
+ f = TestField.class.getDeclaredField("charField");
+ f.setChar(x, (char) 1);
+ val = f.getChar(x);
+ } catch (Exception e) {
+ fail("Exception during setChar test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect float field value", 1, val);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setChar(x, Character.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("charField");
+ f.setChar(null, Character.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("charSField");
+ f.setChar(null, Character.MIN_VALUE);
+ val = f.getChar(x);
+ assertEquals("Returned incorrect char field value",
+ Character.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setDouble(java.lang.Object, double)
+ */
+ public void test_setDoubleLjava_lang_ObjectD() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setDouble(java.lang.Object, double)
+ TestField x = new TestField();
+ Field f = null;
+ double val = 0.0;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.setDouble(x, Double.MIN_VALUE);
+ val = f.getDouble(x);
+ } catch (Exception e) {
+ fail("Exception during setDouble test: " + e.toString());
+ }
+ assertEquals("Returned incorrect double field value", Double.MIN_VALUE,
+ val);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setDouble(x, Double.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("doubleField");
+ f.setDouble(null, Double.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("doubleSField");
+ f.setDouble(null, Double.MIN_VALUE);
+ val = f.getDouble(x);
+ assertEquals("Returned incorrect double field value",
+ Double.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setFloat(java.lang.Object, float)
+ */
+ public void test_setFloatLjava_lang_ObjectF() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setFloat(java.lang.Object, float)
+ TestField x = new TestField();
+ Field f = null;
+ float val = 0.0F;
+ try {
+ f = TestField.class.getDeclaredField("floatField");
+ f.setFloat(x, Float.MIN_VALUE);
+ val = f.getFloat(x);
+ } catch (Exception e) {
+ fail("Exception during setFloat test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect float field value", Float.MIN_VALUE,
+ val, 0.0);
+
+ //test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setFloat(x, Float.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ //Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("floatField");
+ f.setFloat(null, Float.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("floatSField");
+ f.setFloat(null, Float.MIN_VALUE);
+ val = f.getFloat(x);
+ assertEquals("Returned incorrect float field value",
+ Float.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setInt(java.lang.Object, int)
+ */
+ public void test_setIntLjava_lang_ObjectI() throws Exception{
+ // Test for method void java.lang.reflect.Field.setInt(java.lang.Object,
+ // int)
+ TestField x = new TestField();
+ Field f = null;
+ int val = 0;
+ try {
+ f = TestField.class.getDeclaredField("intField");
+ f.setInt(x, Integer.MIN_VALUE);
+ val = f.getInt(x);
+ } catch (Exception e) {
+ fail("Exception during setInteger test: " + e.toString());
+ }
+ assertEquals("Returned incorrect int field value", Integer.MIN_VALUE,
+ val);
+
+ // test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setInt(x, Integer.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ // Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("intField");
+ f.setInt(null, Integer.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("intSField");
+ f.setInt(null, Integer.MIN_VALUE);
+ val = f.getInt(x);
+ assertEquals("Returned incorrect int field value",
+ Integer.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setLong(java.lang.Object, long)
+ */
+ public void test_setLongLjava_lang_ObjectJ() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setLong(java.lang.Object, long)
+ TestField x = new TestField();
+ Field f = null;
+ long val = 0L;
+ try {
+ f = TestField.class.getDeclaredField("longField");
+ f.setLong(x, Long.MIN_VALUE);
+ val = f.getLong(x);
+ } catch (Exception e) {
+ fail("Exception during setLong test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect long field value", Long.MIN_VALUE, val);
+
+ // test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setLong(x, Long.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ // Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("longField");
+ f.setLong(null, Long.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("longSField");
+ f.setLong(null, Long.MIN_VALUE);
+ val = f.getLong(x);
+ assertEquals("Returned incorrect long field value",
+ Long.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#setShort(java.lang.Object, short)
+ */
+ public void test_setShortLjava_lang_ObjectS() throws Exception{
+ // Test for method void
+ // java.lang.reflect.Field.setShort(java.lang.Object, short)
+ TestField x = new TestField();
+ Field f = null;
+ short val = 0;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ f.setShort(x, Short.MIN_VALUE);
+ val = f.getShort(x);
+ } catch (Exception e) {
+ fail("Exception during setShort test : " + e.getMessage());
+ }
+ assertEquals("Returned incorrect short field value", Short.MIN_VALUE,
+ val);
+
+ // test wrong type
+ boolean thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("booleanField");
+ f.setShort(x, Short.MIN_VALUE);
+ fail("Accessed field of invalid type");
+ } catch (IllegalArgumentException ex) {
+ thrown = true;
+ }
+ assertTrue("IllegalArgumentException expected but not thrown", thrown);
+
+ // Test NPE
+ thrown = false;
+ try {
+ f = TestField.class.getDeclaredField("shortField");
+ f.setShort(null, Short.MIN_VALUE);
+ fail("NullPointerException expected but not thrown");
+ } catch (NullPointerException ex) {
+ thrown = true;
+ } catch (Exception ex) {
+ fail("NullPointerException expected but not thrown");
+ }
+ assertTrue("NullPointerException expected but not thrown", thrown);
+
+ // Test setting a static field;
+ f = TestField.class.getDeclaredField("shortSField");
+ f.setShort(null, Short.MIN_VALUE);
+ val = f.getShort(x);
+ assertEquals("Returned incorrect short field value",
+ Short.MIN_VALUE, val);
+ }
+
+ /**
+ * java.lang.reflect.Field#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.reflect.Field.toString()
+ Field f = null;
+
+ try {
+ f = TestField.class.getDeclaredField("x");
+ } catch (Exception e) {
+ fail("Exception getting field : " + e.getMessage());
+ }
+ assertEquals("Field returned incorrect string",
+ "private static final int org.apache.harmony.tests.java.lang.reflect.FieldTest$TestField.x",
+ f.toString());
+ }
+
+ public void test_getDeclaredAnnotations() throws Exception {
+ Field field = TestClass.class.getField("annotatedField");
+ Annotation[] annotations = field.getDeclaredAnnotations();
+ assertEquals(2, annotations.length);
+
+ Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
+ ignoreOrder.add(annotations[0].annotationType());
+ ignoreOrder.add(annotations[1].annotationType());
+
+ assertTrue("Missing @AnnotationRuntime0", ignoreOrder
+ .contains(AnnotationRuntime0.class));
+ assertTrue("Missing @AnnotationRuntime1", ignoreOrder
+ .contains(AnnotationRuntime1.class));
+ }
+
+ public void test_isEnumConstant() throws Exception {
+ Field field = TestEnum.class.getDeclaredField("A");
+ assertTrue("Enum constant not recognized", field.isEnumConstant());
+
+ field = TestEnum.class.getDeclaredField("field");
+ assertFalse("Non enum constant wrongly stated as enum constant", field
+ .isEnumConstant());
+
+ field = TestClass.class.getDeclaredField("annotatedField");
+ assertFalse("Non enum constant wrongly stated as enum constant", field
+ .isEnumConstant());
+ }
+
+ public void test_isSynthetic() throws Exception {
+ Field[] fields = TestClass.Inner.class.getDeclaredFields();
+ assertEquals("Not exactly one field returned", 1, fields.length);
+
+ assertTrue("Enum constant not recognized", fields[0].isSynthetic());
+
+ Field field = TestEnum.class.getDeclaredField("field");
+ assertFalse("Non synthetic field wrongly stated as synthetic", field
+ .isSynthetic());
+
+ field = TestClass.class.getDeclaredField("annotatedField");
+ assertFalse("Non synthetic field wrongly stated as synthetic", field
+ .isSynthetic());
+ }
+
+
+ public void test_getGenericType() throws Exception {
+ Field field = GenericField.class.getDeclaredField("field");
+ Type type = field.getGenericType();
+ @SuppressWarnings("unchecked")
+ TypeVariable typeVar = (TypeVariable) type;
+ assertEquals("Wrong type name returned", "S", typeVar.getName());
+
+ Field boundedField = GenericField.class.getDeclaredField("boundedField");
+ Type boundedType = boundedField.getGenericType();
+ @SuppressWarnings("unchecked")
+ TypeVariable boundedTypeVar = (TypeVariable) boundedType;
+ assertEquals("Wrong type name returned", "T", boundedTypeVar.getName());
+ assertEquals("More than one bound found", 1,
+ boundedTypeVar.getBounds().length);
+ assertEquals("Wrong bound returned", Number.class,
+ boundedTypeVar.getBounds()[0]);
+ }
+
+
+ public void test_toGenericString() throws Exception {
+ Field field = GenericField.class.getDeclaredField("field");
+ assertEquals("Wrong generic string returned",
+ "S org.apache.harmony.tests.java.lang.reflect.FieldTest$GenericField.field",
+ field.toGenericString());
+
+ Field boundedField = GenericField.class
+ .getDeclaredField("boundedField");
+ assertEquals(
+ "Wrong generic string returned",
+ "T org.apache.harmony.tests.java.lang.reflect.FieldTest$GenericField.boundedField",
+ boundedField.toGenericString());
+
+ Field ordinary = GenericField.class.getDeclaredField("intField");
+ assertEquals(
+ "Wrong generic string returned",
+ "int org.apache.harmony.tests.java.lang.reflect.FieldTest$GenericField.intField",
+ ordinary.toGenericString());
+ }
+
+
+ public void test_hashCode() throws Exception {
+ Field field = TestClass.class.getDeclaredField("annotatedField");
+ assertEquals("Wrong hashCode returned", field.getName().hashCode()
+ ^ field.getDeclaringClass().getName().hashCode(), field
+ .hashCode());
+ }
+
+
+ /**
+ * 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() {
+ }
+}
+
+class TestAccess {
+ private static int xxx;
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericArrayTypeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericArrayTypeTest.java
new file mode 100644
index 0000000..4888fd2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericArrayTypeTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+/**
+ * Tests generic reflection on arrays with generic or parameterized component types.
+ */
+public class GenericArrayTypeTest extends GenericReflectionTestsBase {
+
+ static class A<T> {
+ T[] array;
+ }
+ public void testGetGenericComponentType() throws Exception {
+ @SuppressWarnings("unchecked")
+ Class<? extends A> clazz = GenericArrayTypeTest.A.class;
+ Field field = clazz.getDeclaredField("array");
+ Type genericType = field.getGenericType();
+ assertInstanceOf(GenericArrayType.class, genericType);
+ Type componentType = ((GenericArrayType) genericType).getGenericComponentType();
+ assertEquals(getTypeParameter(clazz), componentType);
+ assertInstanceOf(TypeVariable.class, componentType);
+ TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType;
+ assertEquals("T", componentTypeVariable.getName());
+ assertEquals(clazz, componentTypeVariable.getGenericDeclaration());
+ }
+
+ static class B<T> {
+ B<T>[] array;
+ }
+ public void testParameterizedComponentType() throws Exception {
+ @SuppressWarnings("unchecked")
+ Class<? extends B> clazz = GenericArrayTypeTest.B.class;
+ Field field = clazz.getDeclaredField("array");
+ Type genericType = field.getGenericType();
+
+ assertInstanceOf(GenericArrayType.class, genericType);
+ GenericArrayType arrayType = (GenericArrayType) genericType;
+ Type componentType = arrayType.getGenericComponentType();
+ assertInstanceOf(ParameterizedType.class, componentType);
+ ParameterizedType parameteriezdType = (ParameterizedType) componentType;
+ assertEquals(clazz, parameteriezdType.getRawType());
+ assertEquals(clazz.getTypeParameters()[0], parameteriezdType.getActualTypeArguments()[0]);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericMethodsTests.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericMethodsTests.java
new file mode 100644
index 0000000..a209b21
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericMethodsTests.java
@@ -0,0 +1,121 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+
+/**
+ * Tests unbounded type parameters declared on methods.
+ */
+public class GenericMethodsTests extends GenericReflectionTestsBase{
+
+ static class GenericMethods {
+
+ public <T> void noParamNoReturn() {}
+
+ public <T> void paramNoReturn(T param) {}
+
+ @SuppressWarnings("unchecked")
+ public <T> T noParamReturn() { return (T) new Object(); }
+
+ public <T> T paramReturn(T param) {return param;}
+ }
+
+ private static Class<? extends GenericMethods> clazz = GenericMethodsTests.GenericMethods.class;
+
+ /**
+ * Tests that there are no Type Parameters on the Class itself.
+ */
+ public void testGenericMethods() {
+ assertLenghtZero(clazz.getTypeParameters());
+ }
+
+ /**
+ * Tests whether the specified method declares a type parameter T.
+ * @param method the method
+ */
+ private void checkTypeParameter(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ assertEquals("T", typeParameter.getName());
+ assertEquals(method, typeParameter.getGenericDeclaration());
+ }
+
+ /**
+ * Tests whether the specified method declares a parameter with the
+ * type of the type parameter.
+ * @param method the method
+ */
+ private void checkParameterType(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ assertLenghtOne(method.getGenericParameterTypes());
+ Type genericParameterType = method.getGenericParameterTypes()[0];
+ assertEquals(typeParameter, genericParameterType);
+ assertInstanceOf(TypeVariable.class, genericParameterType);
+ assertEquals(method, ((TypeVariable<?>) genericParameterType).getGenericDeclaration());
+ }
+
+ /**
+ * Tests whether the type of the return type is the declared type parameter.
+ * @param method the declaring method
+ */
+ private void checkReturnType(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ Type genericReturnType = method.getGenericReturnType();
+ assertEquals(typeParameter, genericReturnType);
+ assertInstanceOf(TypeVariable.class, genericReturnType);
+ assertEquals(method, ((TypeVariable<?>) genericReturnType).getGenericDeclaration());
+ }
+ public void testNoParamNoReturn() throws Exception {
+ Method method = clazz.getMethod("noParamNoReturn");
+ checkTypeParameter(method);
+ }
+
+ public void testParamNoReturn() throws Exception {
+ Method method = clazz.getMethod("paramNoReturn", Object.class);
+ checkTypeParameter(method);
+ checkParameterType(method);
+ }
+
+ public void testNoParamReturn() throws Exception {
+ Method method = clazz.getMethod("noParamReturn");
+ checkTypeParameter(method);
+ assertLenghtZero(method.getGenericParameterTypes());
+ checkReturnType(method);
+ }
+ public void testParamReturn() throws Exception {
+ Method method = clazz.getMethod("paramReturn", Object.class);
+ checkTypeParameter(method);
+ checkParameterType(method);
+ checkReturnType(method);
+ }
+ public void testIndependencyOfMethodTypeParameters() throws Exception {
+ Method method0 = clazz.getMethod("paramNoReturn", Object.class);
+ TypeVariable<Method> typeParameter0 = method0.getTypeParameters()[0];
+
+ Method method1 = clazz.getMethod("noParamNoReturn");
+ TypeVariable<Method> typeParameter1 = method1.getTypeParameters()[0];
+
+ //Generic method type parameters NAMES are equal
+ assertEquals(typeParameter0.getName(), typeParameter1.getName());
+ //Generic method type PARAMETERS are not equal
+ assertNotEquals(typeParameter0, typeParameter1);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericReflectionTestsBase.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericReflectionTestsBase.java
new file mode 100644
index 0000000..c08fef4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericReflectionTestsBase.java
@@ -0,0 +1,74 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.TypeVariable;
+
+import junit.framework.TestCase;
+
+public class GenericReflectionTestsBase extends TestCase{
+
+ /**
+ * Returns the type parameter of the declaring method.
+ *
+ * @param method
+ * the declaring method
+ * @return the type parameter of the method
+ */
+ public TypeVariable<Method> getTypeParameter(Method method) {
+ TypeVariable<Method>[] typeParameters = method.getTypeParameters();
+ assertLenghtOne(typeParameters);
+ TypeVariable<Method> typeParameter = typeParameters[0];
+ return typeParameter;
+ }
+
+ /**
+ * Returns the type parameter of the declaring class.
+ *
+ * @param method
+ * the declaring method.
+ * @return the type parameter of the method.
+ */
+ @SuppressWarnings("unchecked")
+ public TypeVariable<Class> getTypeParameter(Class<?> clazz) {
+ TypeVariable[] typeParameters = clazz.getTypeParameters();
+ assertLenghtOne(typeParameters);
+ TypeVariable<Class> typeVariable = typeParameters[0];
+ assertEquals(clazz, typeVariable.getGenericDeclaration());
+ assertEquals("T", typeVariable.getName());
+ return typeVariable;
+ }
+
+ public static void assertLenghtOne(Object[] array) {
+ TestCase.assertEquals("Array does NOT contain exactly one element.", 1, array.length);
+ }
+
+ public static void assertLenghtZero(Object[] array) {
+ TestCase.assertEquals("Array has more than zero elements.", 0, array.length);
+ }
+
+ public static void assertInstanceOf(Class<?> expectedClass, Object actual) {
+ TestCase.assertTrue(actual.getClass().getName() + " is not instance of :" + expectedClass.getName(), expectedClass
+ .isInstance(actual));
+ }
+
+ public static void assertNotEquals(Object expected, Object actual) {
+ TestCase.assertFalse(actual.toString() + " has not to be equal to " + expected.toString(), expected.equals(actual));
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericSignatureFormatErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericSignatureFormatErrorTest.java
new file mode 100644
index 0000000..0cad681
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/GenericSignatureFormatErrorTest.java
@@ -0,0 +1,100 @@
+package org.apache.harmony.tests.java.lang.reflect;
+
+import dalvik.annotation.AndroidOnly;
+import dalvik.system.DexFile;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.GenericSignatureFormatError;
+import java.lang.reflect.TypeVariable;
+
+import tests.support.Support_ClassLoader;
+
+public class GenericSignatureFormatErrorTest extends TestCase{
+
+ public void test_Constructor() {
+ assertNotNull(new GenericSignatureFormatError());
+ }
+
+ public void test_readResource() throws Exception {
+ File tf = File.createTempFile("classes", ".dex");
+ // System.out.println("GenericSignatureFormatErrorTest:"
+ // +tf.getAbsolutePath()+", canRead: "+tf.canRead()
+ // +", canWrite: "+tf.canWrite());
+ InputStream is = this.getClass().getResourceAsStream("/resources/dex1.bytes");
+ assertNotNull(is);
+ }
+
+
+ @AndroidOnly("Uses Android specific class dalvik.system.DexFile " +
+ "for loading classes.")
+ // SideEffect: strange issue (exception: 'could not open dex file',
+ // dalvikvm: 'waitpid failed' log msg - only occurs when @SideEffect is removed
+ // and this test is run via running tests.luni.AllTestsLang TestSuite
+ public void test_signatureFormatError() throws Exception {
+ /*
+ * dex1.bytes is a jar file with a classes.dex in it.
+ * the classes.dex was javac'ed, dx'ed and patched
+ * with the following java file:
+ *
+ * package demo;
+ * public class HelloWorld<U> {
+ * public HelloWorld(U t) {}
+ * }
+ *
+ * patch:
+ * the string constant (class generics signature string)
+ * "<U:" was changed to "<<:"
+ *
+ */
+
+ File tf = File.createTempFile("classes", ".dex");
+ // System.out.println("GenericSignatureFormatErrorTest:" +
+ // tf.getAbsolutePath() + ", canRead: " + tf.canRead() +
+ // ", canWrite: "+tf.canWrite());
+ InputStream is = this.getClass().getResourceAsStream("/resources/dex1.bytes");
+ assertNotNull(is);
+ OutputStream fos = new FileOutputStream(tf);
+ copy(is, fos);
+ fos.flush();
+ fos.close();
+
+
+ // class signature string "<U:" was changed to "<<:"
+ //System.out.println("file length:"+tf.length());
+ try {
+ // Was:
+ // DexFile df = new DexFile(tf);
+ // Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader());
+
+ ClassLoader cl = Support_ClassLoader.getInstance(tf.toURL(),
+ getClass().getClassLoader());
+
+ Class clazz = cl.loadClass("demo/HelloWorld");
+ TypeVariable[] tvs = clazz.getTypeParameters();
+ fail("expecting a GenericSignatureFormatError");
+ // for (TypeVariable tv : tvs) {
+ // System.out.println("tv:"+tv.toString());
+ // }
+ } catch (GenericSignatureFormatError gsfe) {
+ // expected
+ }
+ }
+
+ private void copy(InputStream is, OutputStream os) {
+ try {
+ int b;
+ while ((b = is.read()) != -1) {
+ os.write(b);
+ }
+ is.close();
+ } catch (IOException ex) {
+ throw new RuntimeException("io error", ex);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/InvocationTargetExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/InvocationTargetExceptionTest.java
new file mode 100644
index 0000000..3911447
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/InvocationTargetExceptionTest.java
@@ -0,0 +1,305 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayWriter;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+public class InvocationTargetExceptionTest extends junit.framework.TestCase {
+
+ static class TestMethod {
+ public TestMethod() {
+ }
+
+ public void voidMethod() throws IllegalArgumentException {
+ }
+
+ public void parmTest(int x, short y, String s, boolean bool, Object o,
+ long l, byte b, char c, double d, float f) {
+ }
+
+ public int intMethod() {
+ return 1;
+ }
+
+ public static final void printTest(int x, short y, String s,
+ boolean bool, Object o, long l, byte b, char c, double d,
+ float f) {
+ }
+
+ public double doubleMethod() {
+ return 1.0;
+ }
+
+ public short shortMethod() {
+ return (short) 1;
+ }
+
+ public byte byteMethod() {
+ return (byte) 1;
+ }
+
+ public float floatMethod() {
+ return 1.0f;
+ }
+
+ public long longMethod() {
+ return 1l;
+ }
+
+ public char charMethod() {
+ return 'T';
+ }
+
+ public Object objectMethod() {
+ return new Object();
+ }
+
+ private static void prstatic() {
+ }
+
+ public static void pustatic() {
+ }
+
+ public static synchronized void pustatsynch() {
+ }
+
+ public static int invokeStaticTest() {
+ return 1;
+ }
+
+ public int invokeInstanceTest() {
+ return 1;
+ }
+
+ private int privateInvokeTest() {
+ return 1;
+ }
+
+ public int invokeExceptionTest() throws NullPointerException {
+ throw new NullPointerException();
+ }
+
+ public static synchronized native void pustatsynchnat();
+
+ }
+
+ abstract class AbstractTestMethod {
+ public abstract void puabs();
+ }
+
+ class SubInvocationTargetException extends InvocationTargetException {}
+
+ /**
+ * java.lang.reflect.InvocationTargetException#InvocationTargetException()
+ */
+ public void test_Constructor() throws Exception {
+ Constructor<InvocationTargetException> ctor = InvocationTargetException.class
+ .getDeclaredConstructor();
+ assertNotNull("Parameterless constructor does not exist.", ctor);
+ assertTrue("Constructor is not protected", Modifier.isProtected(ctor
+ .getModifiers()));
+ //create an instance of a subtype using this constructor
+ SubInvocationTargetException subException = new SubInvocationTargetException();
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable)
+ */
+ public void test_ConstructorLjava_lang_Throwable() {
+ // Test for method
+ // java.lang.reflect.InvocationTargetException(java.lang.Throwable)
+ try {
+ Method mth = TestMethod.class.getDeclaredMethod(
+ "invokeExceptionTest", new Class[0]);
+ Object[] args = { Object.class };
+ Object ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (InvocationTargetException e) {
+ // Correct behaviour
+ return;
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ }
+ fail("Failed to throw exception");
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_ThrowableLjava_lang_String() {
+ // Test for method
+ // java.lang.reflect.InvocationTargetException(java.lang.Throwable,
+ // java.lang.String)
+ try {
+ Method mth = TestMethod.class.getDeclaredMethod(
+ "invokeExceptionTest", new Class[0]);
+ Object[] args = { Object.class };
+ Object ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (InvocationTargetException e) {
+ // Correct behaviour
+ return;
+ } catch (NoSuchMethodException e) {
+ ;
+ } catch (IllegalAccessException e) {
+ }
+ fail("Failed to throw exception");
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#getTargetException()
+ */
+ public void test_getTargetException() {
+ // Test for method java.lang.Throwable
+ // java.lang.reflect.InvocationTargetException.getTargetException()
+ try {
+ Method mth = TestMethod.class.getDeclaredMethod(
+ "invokeExceptionTest", new Class[0]);
+ Object[] args = { Object.class };
+ Object ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (InvocationTargetException e) {
+ // Correct behaviour
+ assertTrue("Returned incorrect target exception", e
+ .getTargetException() instanceof NullPointerException);
+ return;
+ } catch (Exception e) {
+ fail("Exception during constructor test : " + e.getMessage());
+ }
+ fail("Failed to throw exception");
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#getCause()
+ */
+ public void test_getCause() {
+ // java.lang.reflect.InvocationTargetException.getCause()
+ try {
+ Method mth = TestMethod.class.getDeclaredMethod(
+ "invokeExceptionTest", new Class[0]);
+ Object[] args = {Object.class};
+ Object ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (InvocationTargetException e) {
+ // Correct behaviour
+ assertTrue("Returned incorrect cause",
+ e.getCause() instanceof NullPointerException);
+ return;
+ } catch (Exception e) {
+ fail("Exception during InvocationTargetException test : "
+ + e.getMessage());
+ }
+ fail("Failed to throw exception");
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#printStackTrace()
+ */
+ public void test_printStackTrace() {
+ // Test for method void
+ // java.lang.reflect.InvocationTargetException.printStackTrace()
+ try {
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bao);
+ PrintStream oldErr = System.err;
+ System.setErr(ps);
+ InvocationTargetException ite = new InvocationTargetException(null);
+ ite.printStackTrace();
+ System.setErr(oldErr);
+
+ String s = new String(bao.toByteArray());
+
+ assertTrue("Incorrect Stack trace: " + s, s != null
+ && s.length() > 300);
+ } catch (Exception e) {
+ fail("printStackTrace() caused exception : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintStream)
+ */
+ public void test_printStackTraceLjava_io_PrintStream() {
+ // Test for method void
+ // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintStream)
+ assertTrue("Tested via test_printStackTrace().", true);
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bao);
+ InvocationTargetException ite = new InvocationTargetException(
+ new InvocationTargetException(null));
+ ite.printStackTrace(ps);
+ String s = bao.toString();
+ assertTrue("printStackTrace failed." + s.length(), s != null
+ && s.length() > 400);
+ }
+
+ /**
+ * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintWriter)
+ */
+ public void test_printStackTraceLjava_io_PrintWriter() {
+ // Test for method void
+ // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintWriter)
+ try {
+ PrintWriter pw;
+ InvocationTargetException ite;
+ String s;
+ CharArrayWriter caw = new CharArrayWriter();
+ pw = new PrintWriter(caw);
+ ite = new InvocationTargetException(new InvocationTargetException(
+ null));
+ ite.printStackTrace(pw);
+
+ s = caw.toString();
+ assertTrue("printStackTrace failed." + s.length(), s != null
+ && s.length() > 400);
+ pw.close();
+
+ ByteArrayOutputStream bao = new ByteArrayOutputStream();
+ pw = new PrintWriter(bao);
+ ite = new InvocationTargetException(new InvocationTargetException(
+ null));
+ ite.printStackTrace(pw);
+
+ pw.flush(); // Test will fail if this line removed.
+ s = bao.toString();
+ assertTrue("printStackTrace failed." + s.length(), s != null
+ && s.length() > 400);
+
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTest.java
new file mode 100644
index 0000000..04266d5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTest.java
@@ -0,0 +1,34 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.reflect.MalformedParameterizedTypeException;
+import junit.framework.TestCase;
+
+public class MalformedParameterizedTypeExceptionTest extends TestCase {
+
+ /**
+ * java.lang.reflect.MalformedParameterizedTypeException#
+ * MalformedParameterizedTypeException()
+ */
+ public void testMalformedParameterizedTypeException() {
+ MalformedParameterizedTypeException e = new MalformedParameterizedTypeException();
+ assertNotNull(e);
+ assertNull(e.getMessage());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
new file mode 100644
index 0000000..79ce85e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
@@ -0,0 +1,21 @@
+package org.apache.harmony.tests.java.lang.reflect;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.MalformedParameterizedTypeException;
+import java.lang.reflect.Modifier;
+
+public class MalformedParameterizedTypeExceptionTests extends junit.framework.TestCase {
+
+ /**
+ * java.lang.reflect.MalformedParameterizedTypeException#MalformedParameterizedTypeException()
+ */
+ public void test_Constructor() throws Exception {
+ Constructor<MalformedParameterizedTypeException> ctor = MalformedParameterizedTypeException.class
+ .getDeclaredConstructor();
+ assertNotNull("Parameterless constructor does not exist.", ctor);
+ assertTrue("Constructor is not protected", Modifier.isPublic(ctor
+ .getModifiers()));
+ assertNotNull(ctor.newInstance());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MethodTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MethodTest.java
new file mode 100644
index 0000000..9f4f69e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/MethodTest.java
@@ -0,0 +1,881 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.HashSet;
+import java.util.Set;
+
+public class MethodTest extends junit.framework.TestCase {
+
+ static class TestMethod {
+ public TestMethod() {
+ }
+
+ public void voidMethod() throws IllegalArgumentException {
+ }
+
+ public void parmTest(int x, short y, String s, boolean bool, Object o,
+ long l, byte b, char c, double d, float f) {
+ }
+
+ public int intMethod() {
+ return 1;
+ }
+
+ public static final void printTest(int x, short y, String s,
+ boolean bool, Object o, long l, byte b, char c, double d,
+ float f) {
+ }
+
+ public double doubleMethod() {
+ return 1.0;
+ }
+
+ public short shortMethod() {
+ return (short) 1;
+ }
+
+ public byte byteMethod() {
+ return (byte) 1;
+ }
+
+ public float floatMethod() {
+ return 1.0f;
+ }
+
+ public long longMethod() {
+ return 1l;
+ }
+
+ public char charMethod() {
+ return 'T';
+ }
+
+ public Object objectMethod() {
+ return new Object();
+ }
+
+ private static void prstatic() {
+ }
+
+ public static void pustatic() {
+ }
+
+ public static synchronized void pustatsynch() {
+ }
+
+ public static int invokeStaticTest() {
+ return 1;
+ }
+
+ public int invokeInstanceTest() {
+ return 1;
+ }
+
+ private int privateInvokeTest() {
+ return 1;
+ }
+
+ public int invokeExceptionTest() throws NullPointerException {
+ throw new NullPointerException();
+ }
+
+ public static synchronized native void pustatsynchnat();
+
+ public void publicVoidVarargs(Object... param){}
+ public void publicVoidArray(Object[] param){}
+
+ public void annotatedParameter(@TestAnno @Deprecated int a,
+ @Deprecated int b, int c) {
+ }
+
+ @Deprecated
+ @TestAnno
+ public void annotatedMethod(){}
+
+ public void hashCodeTest(int i){}
+ public void hashCodeTest(String s){}
+
+ public void invokeCastTest1(byte param) {
+ }
+
+ public void invokeCastTest1(short param) {
+ }
+
+ public void invokeCastTest1(int param) {
+ }
+
+ public void invokeCastTest1(long param) {
+ }
+
+ public void invokeCastTest1(float param) {
+ }
+
+ public void invokeCastTest1(double param) {
+ }
+
+ public void invokeCastTest1(char param) {
+ }
+
+ public void invokeCastTest1(boolean param) {
+ }
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target({ElementType.PARAMETER, ElementType.METHOD})
+ public static @interface TestAnno{
+ public static final String DEFAULT_VALUE = "DEFAULT_VALUE";
+
+ String value() default DEFAULT_VALUE;
+ }
+
+ abstract class AbstractTestMethod {
+ public abstract void puabs();
+ }
+
+ class TestMethodSub extends TestMethod {
+ public int invokeInstanceTest() {
+ return 0;
+ }
+ }
+
+ static interface IBrigeTest<T>{
+ T m();
+ }
+
+ static class BrigeTest implements IBrigeTest<String> {
+ public String m(){ return null; }
+ }
+
+ static class ExceptionTest<T extends Exception>{
+ @SuppressWarnings("unused")
+ void exceptionTest() throws T{}
+ }
+
+ static class GenericReturnType<T> {
+ T returnGeneric(){return null;}
+ }
+
+ static class GenericString<T> {
+ public static final String GENERIC =
+ "T org.apache.harmony.tests.java.lang.reflect.MethodTest$GenericString.genericString(T)";
+ T genericString(T t) {
+ return null;
+ }
+ }
+
+ /**
+ * java.lang.reflect.Method#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.lang.reflect.Method.equals(java.lang.Object)
+
+ Method m1 = null, m2 = null;
+ try {
+ m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]);
+ m2 = TestMethodSub.class.getMethod("invokeInstanceTest",
+ new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during equals test : " + e.getMessage());
+ }
+ assertTrue("Overriden method returned equal", !m1.equals(m2));
+ assertTrue("Same method returned not-equal", m1.equals(m1));
+ try {
+ m1 = TestMethod.class.getMethod("invokeStaticTest", new Class[0]);
+ m2 = TestMethodSub.class
+ .getMethod("invokeStaticTest", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during equals test : " + e.getMessage());
+ }
+ assertTrue("Inherited method returned not-equal", m1.equals(m2));
+ }
+
+ /**
+ * java.lang.Class#getMethod(java.lang.String, java.lang.Class[])
+ */
+ public void test_getMethod() throws NoSuchMethodException, SecurityException {
+ // Check that getMethod treats null parameterTypes the same as an empty array.
+ Method m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]);
+ Method m2 = TestMethod.class.getMethod("invokeInstanceTest", (Class[]) null);
+ assertEquals(m1, m2);
+ }
+
+ /**
+ * java.lang.Class#getDeclaredMethod(java.lang.String, java.lang.Class[])
+ */
+ public void test_getDeclaredMethod() throws NoSuchMethodException, SecurityException {
+ // Check that getDeclaredMethod treats null parameterTypes the same as an empty array.
+ Method m1 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", new Class[0]);
+ Method m2 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", (Class[]) null);
+ assertEquals(m1, m2);
+ }
+
+ /**
+ * java.lang.reflect.Method#getDeclaringClass()
+ */
+ public void test_getDeclaringClass() {
+ // Test for method java.lang.Class
+ // java.lang.reflect.Method.getDeclaringClass()
+
+ Method[] mths;
+
+ try {
+ mths = TestMethod.class.getDeclaredMethods();
+ assertTrue("Returned incorrect declaring class: "
+ + mths[0].getDeclaringClass().toString(), mths[0]
+ .getDeclaringClass().equals(TestMethod.class));
+ } catch (Exception e) {
+ fail("Exception during getDeclaringClass test: "
+ + e.toString());
+ }
+ }
+
+ /**
+ * java.lang.reflect.Method#getExceptionTypes()
+ */
+ public void test_getExceptionTypes() {
+ // Test for method java.lang.Class []
+ // java.lang.reflect.Method.getExceptionTypes()
+
+ try {
+ Method mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
+ Class[] ex = mth.getExceptionTypes();
+ assertEquals("Returned incorrect number of exceptions",
+ 1, ex.length);
+ assertTrue("Returned incorrect exception type", ex[0]
+ .equals(IllegalArgumentException.class));
+ mth = TestMethod.class.getMethod("intMethod", new Class[0]);
+ ex = mth.getExceptionTypes();
+ assertEquals("Returned incorrect number of exceptions",
+ 0, ex.length);
+ } catch (Exception e) {
+ fail("Exception during getExceptionTypes: " + e.toString());
+ }
+
+ }
+
+ /**
+ * java.lang.reflect.Method#getModifiers()
+ */
+ public void test_getModifiers() {
+ // Test for method int java.lang.reflect.Method.getModifiers()
+
+ Class cl = TestMethod.class;
+ int mods = 0;
+ Method mth = null;
+ int mask = 0;
+ try {
+ mth = cl.getMethod("pustatic", new Class[0]);
+ mods = mth.getModifiers();
+ } catch (Exception e) {
+ fail("Exception during getModfiers test: " + e.toString());
+ }
+ mask = Modifier.PUBLIC | Modifier.STATIC;
+ assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
+ try {
+ mth = cl.getDeclaredMethod("prstatic", new Class[0]);
+ mods = mth.getModifiers();
+ } catch (Exception e) {
+ fail("Exception during getModfiers test: " + e.toString());
+ }
+ mask = Modifier.PRIVATE | Modifier.STATIC;
+ assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
+ try {
+ mth = cl.getDeclaredMethod("pustatsynch", new Class[0]);
+ mods = mth.getModifiers();
+ } catch (Exception e) {
+ fail("Exception during getModfiers test: " + e.toString());
+ }
+ mask = (Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED;
+ assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
+ try {
+ mth = cl.getDeclaredMethod("pustatsynchnat", new Class[0]);
+ mods = mth.getModifiers();
+ } catch (Exception e) {
+ fail("Exception during getModfiers test: " + e.toString());
+ }
+ mask = ((Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED)
+ | Modifier.NATIVE;
+ assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
+ cl = AbstractTestMethod.class;
+ try {
+ mth = cl.getDeclaredMethod("puabs", new Class[0]);
+ mods = mth.getModifiers();
+ } catch (Exception e) {
+ fail("Exception during getModfiers test: " + e.toString());
+ }
+ mask = Modifier.PUBLIC | Modifier.ABSTRACT;
+ assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
+ }
+
+ /**
+ * java.lang.reflect.Method#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.lang.reflect.Method.getName()
+ Method mth = null;
+ try {
+ mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getMethodName(): " + e.toString());
+ }
+ assertEquals("Returned incorrect method name",
+ "voidMethod", mth.getName());
+ }
+
+ /**
+ * java.lang.reflect.Method#isVarArgs()
+ */
+ public void test_isVarArgs() throws Exception {
+ Method mth = TestMethod.class.getMethod("publicVoidVarargs",
+ Object[].class);
+ assertTrue("Varargs method stated as non vararg.", mth.isVarArgs());
+
+ mth = TestMethod.class.getDeclaredMethod("publicVoidArray",
+ Object[].class);
+ assertFalse("Non varargs method stated as vararg.", mth.isVarArgs());
+ }
+
+ /**
+ * java.lang.reflect.Method#isBridge()
+ */
+ public void test_isBridge() throws Exception {
+ Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
+ assertEquals("Bridge method not generated.", 2, declaredMethods.length);
+ boolean foundBridgeMethod = false;
+ for (Method method : declaredMethods) {
+ if (method.getReturnType().equals(Object.class)) {
+ assertTrue("Bridge method not stated as bridge.", method
+ .isBridge());
+ foundBridgeMethod = true;
+ }
+ }
+ assertTrue("Bridge method not found.", foundBridgeMethod);
+ }
+
+ /**
+ * java.lang.reflect.Method#isSynthetic()
+ */
+ public void test_isSynthetic() throws Exception {
+ Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
+ assertEquals("Synthetic method not generated.", 2,
+ declaredMethods.length);
+ boolean foundSyntheticMethod = false;
+ for (Method method : declaredMethods) {
+ if (method.getReturnType().equals(Object.class)) {
+ assertTrue("Synthetic method not stated as synthetic.", method
+ .isSynthetic());
+ foundSyntheticMethod = true;
+ }
+ }
+ assertTrue("Synthetic method not found.", foundSyntheticMethod);
+ }
+ /**
+ * java.lang.reflect.Method#getParameterAnnotations()
+ */
+ public void test_getParameterAnnotations() throws Exception {
+ Method method = TestMethod.class.getDeclaredMethod(
+ "annotatedParameter", new Class[] {
+ int.class, int.class, int.class});
+ Annotation[][] annotations = method.getParameterAnnotations();
+ assertEquals(3, annotations.length);
+ assertEquals(
+ "Wrong number of annotations returned for first parameter", 2,
+ annotations[0].length);
+ Set<Class<?>> annotationSet = new HashSet<Class<?>>();
+ annotationSet.add(annotations[0][0].annotationType());
+ annotationSet.add(annotations[0][1].annotationType());
+ assertTrue("Missing TestAnno annotation", annotationSet
+ .contains(TestAnno.class));
+ assertTrue("Missing Deprecated annotation", annotationSet
+ .contains(Deprecated.class));
+
+ assertEquals(
+ "Wrong number of annotations returned for second parameter",
+ 1, annotations[1].length);
+ annotationSet = new HashSet<Class<?>>();
+ annotationSet.add(annotations[1][0].annotationType());
+ assertTrue("Missing Deprecated annotation", annotationSet
+ .contains(Deprecated.class));
+ assertEquals(
+ "Wrong number of annotations returned for third parameter", 0,
+ annotations[2].length);
+ }
+
+ /**
+ * java.lang.reflect.Method#getDeclaredAnnotations()
+ */
+ public void test_getDeclaredAnnotations() throws Exception {
+ Method method = TestMethod.class.getDeclaredMethod("annotatedMethod");
+ Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
+ assertEquals(2, declaredAnnotations.length);
+
+ Set<Class<?>> annotationSet = new HashSet<Class<?>>();
+ annotationSet.add(declaredAnnotations[0].annotationType());
+ annotationSet.add(declaredAnnotations[1].annotationType());
+ assertTrue("Missing TestAnno annotation", annotationSet
+ .contains(TestAnno.class));
+ assertTrue("Missing Deprecated annotation", annotationSet
+ .contains(Deprecated.class));
+ }
+
+ /**
+ * java.lang.reflect.Method#getDefaultValue()
+ */
+ public void test_getDefaultValue() throws Exception {
+ Method method = TestAnno.class.getDeclaredMethod("value");
+ assertEquals("Wrong default value returned", TestAnno.DEFAULT_VALUE,
+ method.getDefaultValue());
+ }
+
+ /**
+ * java.lang.reflect.Method#getDefaultValue()
+ */
+ public void test_getGenericExceptionTypes() throws Exception {
+ Method method = ExceptionTest.class.getDeclaredMethod("exceptionTest");
+ Type[] genericExceptionTypes = method.getGenericExceptionTypes();
+ assertEquals(1, genericExceptionTypes.length);
+ assertTrue(genericExceptionTypes[0] instanceof TypeVariable<?>);
+ @SuppressWarnings("unchecked")
+ TypeVariable<Class<ExceptionTest<?>>> tv =
+ (TypeVariable<Class<ExceptionTest<?>>>) genericExceptionTypes[0];
+ assertEquals("T", tv.getName());
+ }
+
+ /**
+ * java.lang.reflect.Method#getGenericReturnType()
+ */
+ public void test_getGenericReturnType() throws Exception {
+ Method method = GenericReturnType.class
+ .getDeclaredMethod("returnGeneric");
+ Type returnType = method.getGenericReturnType();
+ assertNotNull("getGenericReturnType returned null", returnType);
+ assertTrue(returnType instanceof TypeVariable<?>);
+ @SuppressWarnings("unchecked")
+ TypeVariable<Class<ExceptionTest<?>>> tv =
+ (TypeVariable<Class<ExceptionTest<?>>>) returnType;
+ assertEquals("T", tv.getName());
+ }
+
+
+ /**
+ * java.lang.reflect.Method#toGenericString()
+ */
+ public void test_toGenericString() throws Exception {
+ Method method = GenericString.class.getDeclaredMethod("genericString",
+ Object.class);
+ assertEquals("Wrong generic String returned", GenericString.GENERIC,
+ method.toGenericString());
+ }
+
+
+
+
+
+
+ /**
+ * java.lang.reflect.Method#hashCode()
+ */
+ public void test_hashCode() throws Exception {
+ Method mth0 = TestMethod.class.getMethod("hashCodeTest", String.class);
+ Method mth1 = TestMethod.class.getDeclaredMethod("hashCodeTest",
+ int.class);
+ assertEquals("Methods with same name did not return same hashCode.",
+ mth0.hashCode(), mth1.hashCode());
+ }
+
+ /**
+ * java.lang.reflect.Method#getParameterTypes()
+ */
+ public void test_getParameterTypes() {
+ // Test for method java.lang.Class []
+ // java.lang.reflect.Method.getParameterTypes()
+ Class cl = TestMethod.class;
+ Method mth = null;
+ Class[] parms = null;
+ Method[] methods = null;
+ Class[] plist = { int.class, short.class, String.class, boolean.class,
+ Object.class, long.class, byte.class, char.class, double.class,
+ float.class };
+ try {
+ mth = cl.getMethod("voidMethod", new Class[0]);
+ parms = mth.getParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test: "
+ + e.toString());
+ }
+ assertEquals("Returned incorrect parameterTypes", 0, parms.length);
+ try {
+ mth = cl.getMethod("parmTest", plist);
+ parms = mth.getParameterTypes();
+ } catch (Exception e) {
+ fail("Exception during getParameterTypes test: "
+ + e.toString());
+ }
+ assertTrue("Invalid number of parameters returned",
+ plist.length == parms.length);
+ for (int i = 0; i < plist.length; i++)
+ assertTrue("Incorrect parameter returned", plist[i]
+ .equals(parms[i]));
+
+ // Test same method. but this time pull it from the list of methods
+ // rather than asking for it explicitly
+ methods = cl.getDeclaredMethods();
+
+ int i;
+ for (i = 0; i < methods.length; i++)
+ if (methods[i].getName().equals("parmTest")) {
+ mth = methods[i];
+ i = methods.length + 1;
+ }
+ if (i < methods.length) {
+ parms = mth.getParameterTypes();
+ assertTrue("Incorrect number of parameters returned",
+ parms.length == plist.length);
+ for (i = 0; i < plist.length; i++)
+ assertTrue("Incorrect parameter returned", plist[i]
+ .equals(parms[i]));
+ }
+ }
+
+ /**
+ * java.lang.reflect.Method#getReturnType()
+ */
+ public void test_getReturnType() {
+ // Test for method java.lang.Class
+ // java.lang.reflect.Method.getReturnType()
+ Class cl = TestMethod.class;
+ Method mth = null;
+ try {
+ mth = cl.getMethod("charMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted char", mth
+ .getReturnType().equals(char.class));
+ try {
+ mth = cl.getMethod("longMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted long", mth
+ .getReturnType().equals(long.class));
+ try {
+ mth = cl.getMethod("shortMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted short", mth
+ .getReturnType().equals(short.class));
+ try {
+ mth = cl.getMethod("intMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted int: "
+ + mth.getReturnType(), mth.getReturnType().equals(int.class));
+ try {
+ mth = cl.getMethod("doubleMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted double", mth
+ .getReturnType().equals(double.class));
+ try {
+ mth = cl.getMethod("byteMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted byte", mth
+ .getReturnType().equals(byte.class));
+ try {
+ mth = cl.getMethod("byteMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test:" + e.toString());
+ }
+ assertTrue("Gave incorrect returne type, wanted byte", mth
+ .getReturnType().equals(byte.class));
+ try {
+ mth = cl.getMethod("objectMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted Object", mth
+ .getReturnType().equals(Object.class));
+
+ try {
+ mth = cl.getMethod("voidMethod", new Class[0]);
+ } catch (Exception e) {
+ fail("Exception during getReturnType test : " + e.getMessage());
+ }
+ assertTrue("Gave incorrect returne type, wanted void", mth
+ .getReturnType().equals(void.class));
+ }
+
+ /**
+ * java.lang.reflect.Method#invoke(java.lang.Object,
+ * java.lang.Object[])
+ */
+ public void test_invokeLjava_lang_Object$Ljava_lang_Object() throws Exception{
+ // Test for method java.lang.Object
+ // java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object
+ // [])
+ Class cl = TestMethod.class;
+ Class[] dcl = new Class[0];
+
+ // Get and invoke a static method
+ Method mth = cl.getDeclaredMethod("invokeStaticTest", dcl);
+ Object ret = mth.invoke(null, new Object[0]);
+ assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
+ .intValue());
+
+ // Get and invoke an instance method
+ mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
+ ret = mth.invoke(new TestMethod(), new Object[0]);
+ assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
+ .intValue());
+
+ // Get and attempt to invoke a private method
+ mth = cl.getDeclaredMethod("privateInvokeTest", dcl);
+ try {
+ ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (IllegalAccessException e) {
+ // Correct behaviour
+ } catch (Exception e) {
+ fail("Exception during invoke test : " + e.getMessage());
+ }
+ // Generate an IllegalArgumentException
+ mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
+
+ try {
+ Object[] args = { Object.class };
+ ret = mth.invoke(new TestMethod(), args);
+ } catch (IllegalArgumentException e) {
+ // Correct behaviour
+ } catch (Exception e) {
+ fail("Exception during invoke test : " + e.getMessage());
+ }
+
+ // Generate a NullPointerException
+ mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
+
+ try {
+ ret = mth.invoke(null, new Object[0]);
+ } catch (NullPointerException e) {
+ // Correct behaviour
+ } catch (Exception e) {
+ fail("Exception during invoke test : " + e.getMessage());
+ }
+
+ // Generate an InvocationTargetException
+ mth = cl.getDeclaredMethod("invokeExceptionTest", dcl);
+ try {
+ ret = mth.invoke(new TestMethod(), new Object[0]);
+ } catch (InvocationTargetException e) {
+ // Correct behaviour
+ } catch (Exception e) {
+ fail("Exception during invoke test : " + e.getMessage());
+ }
+
+ TestMethod testMethod = new TestMethod();
+ Method methods[] = cl.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().startsWith("invokeCastTest1")) {
+ Class param = methods[i].getParameterTypes()[0];
+
+ try {
+ methods[i].invoke(testMethod, new Object[] { new Byte(
+ (byte) 1) });
+ assertTrue("invalid invoke with Byte: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Float.TYPE
+ || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Byte invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Byte invalid failure: " + methods[i],
+ param == Boolean.TYPE || param == Character.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod, new Object[] { new Short(
+ (short) 1) });
+ assertTrue("invalid invoke with Short: " + methods[i],
+ param == Short.TYPE || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Float.TYPE
+ || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Short invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Short invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Boolean.TYPE
+ || param == Character.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod,
+ new Object[] { new Integer(1) });
+ assertTrue("invalid invoke with Integer: " + methods[i],
+ param == Integer.TYPE || param == Long.TYPE
+ || param == Float.TYPE
+ || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Integer invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Integer invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Boolean.TYPE
+ || param == Character.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod, new Object[] { new Long(1) });
+ assertTrue("invalid invoke with Long: " + methods[i],
+ param == Long.TYPE || param == Float.TYPE
+ || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Long invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Long invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Integer.TYPE
+ || param == Boolean.TYPE
+ || param == Character.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod, new Object[] { new Character(
+ 'a') });
+ assertTrue("invalid invoke with Character: " + methods[i],
+ param == Character.TYPE || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Float.TYPE
+ || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Character invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Character invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Boolean.TYPE);
+ }
+
+ try {
+ methods[i]
+ .invoke(testMethod, new Object[] { new Float(1) });
+ assertTrue("invalid invoke with Float: " + methods[i],
+ param == Float.TYPE || param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Float invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Float invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Boolean.TYPE
+ || param == Character.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod,
+ new Object[] { new Double(1) });
+ assertTrue("invalid invoke with Double: " + methods[i],
+ param == Double.TYPE);
+ } catch (Exception e) {
+ assertTrue("Double invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Double invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Boolean.TYPE
+ || param == Character.TYPE
+ || param == Float.TYPE);
+ }
+
+ try {
+ methods[i].invoke(testMethod, new Object[] { new Boolean(
+ true) });
+ assertTrue("invalid invoke with Boolean: " + methods[i],
+ param == Boolean.TYPE);
+ } catch (Exception e) {
+ assertTrue("Boolean invalid exception: " + e,
+ e instanceof IllegalArgumentException);
+ assertTrue("Boolean invalid failure: " + methods[i],
+ param == Byte.TYPE || param == Short.TYPE
+ || param == Integer.TYPE
+ || param == Long.TYPE
+ || param == Character.TYPE
+ || param == Float.TYPE
+ || param == Double.TYPE);
+ }
+ }
+ }
+ }
+
+ /**
+ * java.lang.reflect.Method#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.lang.reflect.Method.toString()
+ Method mth = null;
+ Class[] parms = { int.class, short.class, String.class, boolean.class,
+ Object.class, long.class, byte.class, char.class, double.class,
+ float.class };
+ try {
+
+ mth = TestMethod.class.getDeclaredMethod("printTest", parms);
+ } catch (Exception e) {
+ fail("Exception during toString test : " + e.getMessage());
+ }
+
+ assertTrue(
+ "Returned incorrect string for method: " + mth.toString(),
+ mth
+ .toString()
+ .equals(
+ "public static final void org.apache.harmony.tests.java.lang.reflect.MethodTest$TestMethod.printTest(int,short,java.lang.String,boolean,java.lang.Object,long,byte,char,double,float)"));
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ModifierTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ModifierTest.java
new file mode 100644
index 0000000..71c207f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ModifierTest.java
@@ -0,0 +1,435 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.reflect.Modifier;
+
+public class ModifierTest extends junit.framework.TestCase {
+
+ private static final int ALL_FLAGS = 0x7FF;
+
+ /**
+ * java.lang.reflect.Modifier#Modifier()
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.reflect.Modifier()
+ new Modifier();
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isAbstract(int)
+ */
+ public void test_isAbstractI() {
+ // Test for method boolean java.lang.reflect.Modifier.isAbstract(int)
+ assertTrue("ABSTRACT returned false", Modifier.isAbstract(ALL_FLAGS));
+ assertTrue("ABSTRACT returned false", Modifier
+ .isAbstract(Modifier.ABSTRACT));
+ assertTrue("Non-ABSTRACT returned true", !Modifier
+ .isAbstract(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isFinal(int)
+ */
+ public void test_isFinalI() {
+ // Test for method boolean java.lang.reflect.Modifier.isFinal(int)
+ assertTrue("FINAL returned false", Modifier.isFinal(ALL_FLAGS));
+ assertTrue("FINAL returned false", Modifier.isFinal(Modifier.FINAL));
+ assertTrue("Non-FINAL returned true", !Modifier
+ .isFinal(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isInterface(int)
+ */
+ public void test_isInterfaceI() {
+ // Test for method boolean java.lang.reflect.Modifier.isInterface(int)
+ assertTrue("INTERFACE returned false", Modifier.isInterface(ALL_FLAGS));
+ assertTrue("INTERFACE returned false", Modifier
+ .isInterface(Modifier.INTERFACE));
+ assertTrue("Non-INTERFACE returned true", !Modifier
+ .isInterface(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isNative(int)
+ */
+ public void test_isNativeI() {
+ // Test for method boolean java.lang.reflect.Modifier.isNative(int)
+ assertTrue("NATIVE returned false", Modifier.isNative(ALL_FLAGS));
+ assertTrue("NATIVE returned false", Modifier.isNative(Modifier.NATIVE));
+ assertTrue("Non-NATIVE returned true", !Modifier
+ .isNative(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isPrivate(int)
+ */
+ public void test_isPrivateI() {
+ // Test for method boolean java.lang.reflect.Modifier.isPrivate(int)
+ assertTrue("PRIVATE returned false", Modifier.isPrivate(ALL_FLAGS));
+ assertTrue("PRIVATE returned false", Modifier
+ .isPrivate(Modifier.PRIVATE));
+ assertTrue("Non-PRIVATE returned true", !Modifier
+ .isPrivate(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isProtected(int)
+ */
+ public void test_isProtectedI() {
+ // Test for method boolean java.lang.reflect.Modifier.isProtected(int)
+ assertTrue("PROTECTED returned false", Modifier.isProtected(ALL_FLAGS));
+ assertTrue("PROTECTED returned false", Modifier
+ .isProtected(Modifier.PROTECTED));
+ assertTrue("Non-PROTECTED returned true", !Modifier
+ .isProtected(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isPublic(int)
+ */
+ public void test_isPublicI() {
+ // Test for method boolean java.lang.reflect.Modifier.isPublic(int)
+ assertTrue("PUBLIC returned false", Modifier.isPublic(ALL_FLAGS));
+ assertTrue("PUBLIC returned false", Modifier.isPublic(Modifier.PUBLIC));
+ assertTrue("Non-PUBLIC returned true", !Modifier
+ .isPublic(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isStatic(int)
+ */
+ public void test_isStaticI() {
+ // Test for method boolean java.lang.reflect.Modifier.isStatic(int)
+ assertTrue("STATIC returned false", Modifier.isStatic(ALL_FLAGS));
+ assertTrue("STATIC returned false", Modifier.isStatic(Modifier.STATIC));
+ assertTrue("Non-STATIC returned true", !Modifier
+ .isStatic(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isStrict(int)
+ */
+ public void test_isStrictI() {
+ // Test for method boolean java.lang.reflect.Modifier.isStrict(int)
+ assertTrue("STRICT returned false", Modifier.isStrict(Modifier.STRICT));
+ assertTrue("Non-STRICT returned true", !Modifier
+ .isStrict(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isSynchronized(int)
+ */
+ public void test_isSynchronizedI() {
+ // Test for method boolean
+ // java.lang.reflect.Modifier.isSynchronized(int)
+ assertTrue("Synchronized returned false", Modifier
+ .isSynchronized(ALL_FLAGS));
+ assertTrue("Non-Synchronized returned true", !Modifier
+ .isSynchronized(Modifier.VOLATILE));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isTransient(int)
+ */
+ public void test_isTransientI() {
+ // Test for method boolean java.lang.reflect.Modifier.isTransient(int)
+ assertTrue("Transient returned false", Modifier.isTransient(ALL_FLAGS));
+ assertTrue("Transient returned false", Modifier
+ .isTransient(Modifier.TRANSIENT));
+ assertTrue("Non-Transient returned true", !Modifier
+ .isTransient(Modifier.VOLATILE));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#isVolatile(int)
+ */
+ public void test_isVolatileI() {
+ // Test for method boolean java.lang.reflect.Modifier.isVolatile(int)
+ assertTrue("Volatile returned false", Modifier.isVolatile(ALL_FLAGS));
+ assertTrue("Volatile returned false", Modifier
+ .isVolatile(Modifier.VOLATILE));
+ assertTrue("Non-Volatile returned true", !Modifier
+ .isVolatile(Modifier.TRANSIENT));
+ }
+
+ /**
+ * java.lang.reflect.Modifier#toString(int)
+ */
+ public void test_toStringI() {
+ // Test for method java.lang.String
+ // java.lang.reflect.Modifier.toString(int)
+ assertTrue("Returned incorrect string value: "
+ + Modifier.toString(java.lang.reflect.Modifier.PUBLIC
+ + java.lang.reflect.Modifier.ABSTRACT), Modifier
+ .toString(
+ java.lang.reflect.Modifier.PUBLIC
+ + java.lang.reflect.Modifier.ABSTRACT).equals(
+ "public abstract"));
+
+ int i = 0xFFF;
+ String modification = "public protected private abstract static final transient "
+ + "volatile synchronized native strictfp interface";
+ assertTrue("Returned incorrect string value", Modifier.toString(i)
+ .equals(modification));
+ }
+
+ public void test_Constants_Value() {
+ assertEquals(1024, Modifier.ABSTRACT);
+ assertEquals(16, Modifier.FINAL);
+ assertEquals(512, Modifier.INTERFACE);
+ assertEquals(256, Modifier.NATIVE);
+ assertEquals(2, Modifier.PRIVATE);
+ assertEquals(4, Modifier.PROTECTED);
+ assertEquals(1, Modifier.PUBLIC);
+ assertEquals(8, Modifier.STATIC);
+ assertEquals(2048, Modifier.STRICT);
+ assertEquals(32, Modifier.SYNCHRONIZED);
+ assertEquals(128, Modifier.TRANSIENT);
+ assertEquals(64, Modifier.VOLATILE);
+ }
+
+ abstract class AbstractClazz {
+ }
+
+ final class FinalClazz {
+ }
+
+ static class StaticClazz {
+ }
+
+ interface InterfaceClazz {
+ }
+
+ public class PublicClazz {
+ }
+
+ protected class ProtectedClazz {
+ }
+
+ private class PrivateClazz {
+ }
+
+ public abstract class PublicAbstractClazz {
+ }
+
+ protected abstract class ProtectedAbstractClazz {
+ }
+
+ private abstract class PrivateAbstractClazz {
+ }
+
+ public final class PublicFinalClazz {
+ }
+
+ protected final class ProtectedFinalClazz {
+ }
+
+ private final class PrivateFinalClazz {
+ }
+
+ public static class PublicStaticClazz {
+ }
+
+ protected static class ProtectedStaticClazz {
+ }
+
+ private static class PrivateStaticClazz {
+ }
+
+ public interface PublicInterface {
+ }
+
+ protected interface ProtectedInterface {
+ }
+
+ private interface PrivateInterface {
+ }
+
+ static abstract class StaticAbstractClazz {
+ }
+
+ public static abstract class PublicStaticAbstractClazz {
+ }
+
+ protected static abstract class ProtectedStaticAbstractClazz {
+ }
+
+ private static abstract class PrivateStaticAbstractClazz {
+ }
+
+ static final class StaticFinalClazz {
+ }
+
+ public static final class PublicStaticFinalClazz {
+ }
+
+ protected static final class ProtectedStaticFinalClazz {
+ }
+
+ private static final class PrivateStaticFinalClazz {
+ }
+
+ static interface StaticInterface {
+ }
+
+ public static interface PublicStaticInterface {
+ }
+
+ protected static interface ProtectedStaticInterface {
+ }
+
+ private static interface PrivateStaticInterface {
+ }
+
+ static abstract interface StaticAbstractInterface {
+ }
+
+ public static abstract interface PublicStaticAbstractInterface {
+ }
+
+ protected static abstract interface ProtectedStaticAbstractInterface {
+ }
+
+ private static abstract interface PrivateStaticAbstractInterface {
+ }
+
+ public void test_Class_Modifier() {
+ assertEquals(Modifier.ABSTRACT, AbstractClazz.class.getModifiers());
+ assertEquals(Modifier.FINAL, FinalClazz.class.getModifiers());
+ assertEquals(Modifier.STATIC, StaticClazz.class.getModifiers());
+ assertEquals(Modifier.INTERFACE + Modifier.STATIC + Modifier.ABSTRACT,
+ InterfaceClazz.class.getModifiers());
+
+ assertEquals(Modifier.PUBLIC, PublicClazz.class.getModifiers());
+ assertEquals(Modifier.PROTECTED, ProtectedClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE, PrivateClazz.class.getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.ABSTRACT,
+ PublicAbstractClazz.class.getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.ABSTRACT,
+ ProtectedAbstractClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.ABSTRACT,
+ PrivateAbstractClazz.class.getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.FINAL, PublicFinalClazz.class
+ .getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.FINAL,
+ ProtectedFinalClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.FINAL, PrivateFinalClazz.class
+ .getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.STATIC, PublicStaticClazz.class
+ .getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.STATIC,
+ ProtectedStaticClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.STATIC,
+ PrivateStaticClazz.class.getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PublicInterface.class.getModifiers());
+ assertEquals(Modifier.STATIC + Modifier.FINAL, StaticFinalClazz.class
+ .getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PrivateInterface.class.getModifiers());
+
+ assertEquals(Modifier.STATIC + Modifier.ABSTRACT,
+ StaticAbstractClazz.class.getModifiers());
+ assertEquals(Modifier.PUBLIC + Modifier.STATIC + Modifier.ABSTRACT,
+ PublicStaticAbstractClazz.class.getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.STATIC + Modifier.ABSTRACT,
+ ProtectedStaticAbstractClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.STATIC + Modifier.ABSTRACT,
+ PrivateStaticAbstractClazz.class.getModifiers());
+
+ assertEquals(Modifier.STATIC + Modifier.FINAL, StaticFinalClazz.class
+ .getModifiers());
+ assertEquals(Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL,
+ PublicStaticFinalClazz.class.getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.STATIC + Modifier.FINAL,
+ ProtectedStaticFinalClazz.class.getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.STATIC + Modifier.FINAL,
+ PrivateStaticFinalClazz.class.getModifiers());
+
+ assertEquals(Modifier.INTERFACE + Modifier.STATIC + Modifier.ABSTRACT,
+ StaticInterface.class.getModifiers());
+ assertEquals(Modifier.PUBLIC + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PublicStaticInterface.class.getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, ProtectedStaticInterface.class
+ .getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PrivateStaticInterface.class
+ .getModifiers());
+
+ assertEquals(Modifier.INTERFACE + Modifier.STATIC + Modifier.ABSTRACT,
+ StaticAbstractInterface.class.getModifiers());
+ assertEquals(Modifier.PUBLIC + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PublicStaticAbstractInterface.class
+ .getModifiers());
+ assertEquals(Modifier.PROTECTED + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, ProtectedStaticAbstractInterface.class
+ .getModifiers());
+ assertEquals(Modifier.PRIVATE + Modifier.INTERFACE + Modifier.STATIC
+ + Modifier.ABSTRACT, PrivateStaticAbstractInterface.class
+ .getModifiers());
+ }
+
+ static abstract class MethodClass {
+
+ public abstract void publicAbstractMethod();
+
+ public static void publicStaticMethod() {
+ }
+
+ public final void publicFinalMethod() {
+ }
+
+ public static final void publicStaticFinalMethod() {
+ }
+ }
+
+ public void test_Method_Modifier() throws Exception {
+ assertEquals(Modifier.PUBLIC + Modifier.ABSTRACT, MethodClass.class
+ .getMethod("publicAbstractMethod", new Class[0]).getModifiers());
+ assertEquals(Modifier.PUBLIC + Modifier.STATIC, MethodClass.class
+ .getMethod("publicStaticMethod", new Class[0]).getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.FINAL, MethodClass.class
+ .getMethod("publicFinalMethod", new Class[0]).getModifiers());
+
+ assertEquals(Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL,
+ MethodClass.class.getMethod("publicStaticFinalMethod",
+ new Class[0]).getModifiers());
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ParameterizedTypeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ParameterizedTypeTest.java
new file mode 100644
index 0000000..3b2614e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ParameterizedTypeTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+/**
+ * Tests parameterized types and their properties.
+ */
+public class ParameterizedTypeTest extends GenericReflectionTestsBase {
+
+ static class A<T>{}
+ static class B extends A<String>{}
+
+ public void testStringParameterizedSuperClass() {
+ Class<? extends B> clazz = B.class;
+ Type genericSuperclass = clazz.getGenericSuperclass();
+ assertInstanceOf(ParameterizedType.class, genericSuperclass);
+ ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
+ assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
+ assertEquals(A.class, parameterizedType.getRawType());
+
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ assertLenghtOne(actualTypeArguments);
+ assertEquals(String.class, actualTypeArguments[0]);
+ }
+
+ static class C<T>{}
+ static class D<T> extends C<T>{}
+
+ public void testTypeParameterizedSuperClass() {
+ Class<? extends D> clazz = D.class;
+ Type genericSuperclass = clazz.getGenericSuperclass();
+ assertInstanceOf(ParameterizedType.class, genericSuperclass);
+ ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
+ assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
+ assertEquals(C.class, parameterizedType.getRawType());
+
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ assertLenghtOne(actualTypeArguments);
+ assertEquals(getTypeParameter(D.class), actualTypeArguments[0]);
+ }
+
+ static class E<T>{}
+ static class F<T>{
+ E<T> e;
+ }
+
+ public void testParameterizedMemeber() throws Exception{
+ Class<? extends F> clazz = F.class;
+ Field field = clazz.getDeclaredField("e");
+ assertInstanceOf(ParameterizedType.class, field.getGenericType());
+ ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
+ assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
+ assertEquals(E.class, parameterizedType.getRawType());
+
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ assertLenghtOne(actualTypeArguments);
+ assertEquals(getTypeParameter(clazz), actualTypeArguments[0]);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ProxyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ProxyTest.java
new file mode 100644
index 0000000..86383bd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ProxyTest.java
@@ -0,0 +1,334 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import tests.support.Support_Proxy_I1;
+import tests.support.Support_Proxy_I2;
+import tests.support.Support_Proxy_ParentException;
+import tests.support.Support_Proxy_SubException;
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.security.AllPermission;
+import java.security.ProtectionDomain;
+import java.util.ArrayList;
+
+public class ProxyTest extends junit.framework.TestCase {
+
+ /*
+ * When multiple interfaces define the same method, the list of thrown
+ * exceptions are those which can be mapped to another exception in the
+ * other method:
+ *
+ * String foo(String s) throws SubException, LinkageError;
+ *
+ * UndeclaredThrowableException wrappers any checked exception which is not
+ * in the merged list. So ParentException would be wrapped, BUT LinkageError
+ * would not be since its not an Error/RuntimeException.
+ *
+ * interface I1 { String foo(String s) throws ParentException, LinkageError; }
+ * interface I2 { String foo(String s) throws SubException, Error; }
+ */
+
+ interface Broken1 {
+ public float method(float _number0, float _number1);
+ }
+
+ class Broken1Invoke implements InvocationHandler {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return args[1];
+ }
+ }
+
+ class ProxyCoonstructorTest extends Proxy {
+ protected ProxyCoonstructorTest(InvocationHandler h) {
+ super(h);
+ }
+ }
+
+ /**
+ * java.lang.reflect.Proxy#getProxyClass(java.lang.ClassLoader,
+ * java.lang.Class[])
+ */
+ public void test_getProxyClassLjava_lang_ClassLoader$Ljava_lang_Class() {
+ Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class });
+
+ assertTrue("Did not create a Proxy subclass ",
+ proxy.getSuperclass() == Proxy.class);
+ assertTrue("Does not believe its a Proxy class ", Proxy
+ .isProxyClass(proxy));
+
+ assertTrue("Does not believe it's a Proxy class ", Proxy
+ .isProxyClass(Proxy.getProxyClass(null,
+ new Class[] { Comparable.class })));
+
+ try {
+ Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
+ (Class<?>[]) null);
+ fail("NPE expected");
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
+ new Class<?>[] {Support_Proxy_I1.class, null});
+ fail("NPE expected");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * java.lang.reflect.Proxy#Proxy(java.lang.reflect.InvocationHandler)
+ */
+ public void test_ProxyLjava_lang_reflect_InvocationHandler() {
+ assertNotNull(new ProxyCoonstructorTest(new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return null;
+ }
+ }));
+ }
+
+
+
+ /**
+ * java.lang.reflect.Proxy#newProxyInstance(java.lang.ClassLoader,
+ * java.lang.Class[], java.lang.reflect.InvocationHandler)
+ */
+ public void test_newProxyInstanceLjava_lang_ClassLoader$Ljava_lang_ClassLjava_lang_reflect_InvocationHandler()
+ throws Exception {
+ Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class,
+ Support_Proxy_I2.class }, new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ if (method.getName().equals("equals"))
+ return new Boolean(proxy == args[0]);
+ if (method.getName().equals("array"))
+ return new int[] { (int) ((long[]) args[0])[1], -1 };
+ if (method.getName().equals("string")) {
+ if ("".equals(args[0]))
+ throw new Support_Proxy_SubException();
+ if ("clone".equals(args[0]))
+ throw new Support_Proxy_ParentException();
+ if ("error".equals(args[0]))
+ throw new ArrayStoreException();
+ if ("any".equals(args[0]))
+ throw new IllegalAccessException();
+ }
+ return null;
+ }
+ });
+
+ Support_Proxy_I1 proxy = (Support_Proxy_I1) p;
+ assertTrue("Failed identity test ", proxy.equals(proxy));
+ assertTrue("Failed not equals test ", !proxy.equals(""));
+ int[] result = (int[]) proxy.array(new long[] { 100L, -200L });
+ assertEquals("Failed primitive type conversion test ", -200, result[0]);
+
+ try {
+ proxy.string("");
+ fail("Problem converting exception");
+ } catch (Support_Proxy_SubException e) {
+ }
+
+ try {
+ proxy.string("clone");
+ fail("Problem converting exception");
+ } catch (UndeclaredThrowableException e) {
+ assertSame(Support_Proxy_ParentException.class, e.getCause().getClass());
+ }
+
+ try {
+ proxy.string("error");
+ fail("Problem converting exception");
+ } catch (ArrayStoreException e) {
+ }
+
+ try {
+ proxy.string("any");
+ fail("Problem converting exception");
+ } catch (UndeclaredThrowableException e) {
+ assertSame(IllegalAccessException.class, e.getCause().getClass());
+ }
+
+ Broken1 proxyObject = (Broken1) Proxy.newProxyInstance(Broken1.class
+ .getClassLoader(), new Class[] { Broken1.class },
+ new Broken1Invoke());
+
+ float brokenResult = proxyObject.method(2.1f, 5.8f);
+ assertTrue("Invalid invoke result", brokenResult == 5.8f);
+ }
+
+ /**
+ * java.lang.reflect.Proxy#isProxyClass(java.lang.Class)
+ */
+ public void test_isProxyClassLjava_lang_Class() {
+ Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class });
+
+ class Fake extends Proxy {
+ Fake() {
+ super(null);
+ }
+ }
+
+ Proxy fake = new Proxy(new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return null;
+ }
+ }) {
+ };
+
+ assertTrue("Does not believe its a Proxy class ", Proxy
+ .isProxyClass(proxy));
+ assertTrue("Proxy subclasses do not count ", !Proxy
+ .isProxyClass(Fake.class));
+ assertTrue("Is not a runtime generated Proxy class ", !Proxy
+ .isProxyClass(fake.getClass()));
+ try{
+ Proxy.isProxyClass(null);
+ fail("NPE was not thrown");
+ } catch (NullPointerException expected){
+ }
+ }
+
+ /**
+ * java.lang.reflect.Proxy#getInvocationHandler(java.lang.Object)
+ */
+ public void test_getInvocationHandlerLjava_lang_Object() {
+ InvocationHandler handler = new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return null;
+ }
+ };
+
+ Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
+ .getClassLoader(), new Class[] { Support_Proxy_I1.class },
+ handler);
+
+ assertTrue("Did not return invocation handler ", Proxy
+ .getInvocationHandler(p) == handler);
+ try {
+ Proxy.getInvocationHandler("");
+ fail("Did not detect non proxy object");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ //Regression Test for HARMONY-2355
+ public void test_newProxyInstance_withCompatibleReturnTypes() {
+ Object o = Proxy
+ .newProxyInstance(this.getClass().getClassLoader(),
+ new Class[] { ITestReturnObject.class,
+ ITestReturnString.class },
+ new TestProxyHandler(new TestProxyImpl()));
+ assertNotNull(o);
+ }
+
+ public void test_newProxyInstance_withNonCompatibleReturnTypes() {
+ try {
+ Proxy.newProxyInstance(this.getClass().getClassLoader(),
+ new Class[] { ITestReturnInteger.class,
+ ITestReturnString.class }, new TestProxyHandler(
+ new TestProxyImpl()));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void test_ProxyClass_withParentAndSubInThrowList() throws SecurityException, NoSuchMethodException {
+ TestParentIntf myImpl = new MyImplWithParentAndSubInThrowList();
+ Class<?> c = Proxy.getProxyClass(myImpl.getClass().getClassLoader(), myImpl.getClass().getInterfaces());
+ Method m = c.getMethod("test", (Class<?>[]) null);
+ Class<?>[] exceptions = m.getExceptionTypes();
+ ArrayList<Class> exps = new ArrayList<Class>();
+ for (Class<?> exp : exceptions) {
+ exps.add(exp);
+ }
+ assertTrue(exps.contains(Exception.class));
+ }
+
+ public static interface ITestReturnObject {
+ Object f();
+ }
+
+ public static interface ITestReturnString {
+ String f();
+ }
+
+ public static interface ITestReturnInteger {
+ Integer f();
+ }
+
+ public static class TestProxyImpl implements ITestReturnObject,
+ ITestReturnString {
+ public String f() {
+ // do nothing
+ return null;
+ }
+ }
+
+ public static class TestProxyHandler implements InvocationHandler {
+ private Object proxied;
+
+ public TestProxyHandler(Object object) {
+ proxied = object;
+ }
+
+ public Object invoke(Object object, Method method, Object[] args)
+ throws Throwable {
+ // do nothing
+ return method.invoke(proxied, args);
+ }
+
+ }
+
+ class MyImplWithParentAndSubInThrowList implements TestSubIntf {
+ public void test() throws Exception {
+ throw new Exception();
+ }
+ }
+
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
+
+interface PkgIntf {
+}
+
+interface TestParentIntf {
+ //IOException is a subclass of Exception
+ public void test() throws IOException, Exception;
+}
+
+interface TestSubIntf extends TestParentIntf {
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/TypeVariableTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/TypeVariableTest.java
new file mode 100644
index 0000000..d1c7ea9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/TypeVariableTest.java
@@ -0,0 +1,150 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+import java.io.Serializable;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+/**
+ * Tests type variables and their properties.
+ */
+public class TypeVariableTest extends GenericReflectionTestsBase {
+
+ static class A<T>{}
+ public void testSimpleTypeVariableOnClass(){
+ Class<? extends A> clazz = A.class;
+ TypeVariable[] typeParameters = clazz.getTypeParameters();
+ assertLenghtOne(typeParameters);
+ TypeVariable<Class> typeVariable = typeParameters[0];
+ assertEquals(clazz, typeVariable.getGenericDeclaration());
+ assertEquals("T", typeVariable.getName());
+ Type[] bounds = typeVariable.getBounds();
+ assertLenghtOne(bounds);
+ assertEquals(Object.class, bounds[0]);
+ }
+
+ static class B{
+ <T> void b(){};
+ }
+ public void testSimpleTypeVariableOnMethod() throws Exception{
+ Class<? extends B> clazz = B.class;
+ Method method = clazz.getDeclaredMethod("b");
+ TypeVariable<Method>[] typeParameters = method.getTypeParameters();
+ assertLenghtOne(typeParameters);
+ TypeVariable<Method> typeVariable = typeParameters[0];
+ assertEquals(method, typeVariable.getGenericDeclaration());
+ assertEquals("T", typeVariable.getName());
+ Type[] bounds = typeVariable.getBounds();
+ assertLenghtOne(bounds);
+ assertEquals(Object.class, bounds[0]);
+ }
+
+ static class C {
+ <T>C(){}
+ }
+ public void testSimpleTypeVariableOnConstructor() throws Exception{
+ Class<? extends C> clazz = C.class;
+ Constructor<?> constructor = clazz.getDeclaredConstructor();
+ TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
+ assertLenghtOne(typeParameters);
+ TypeVariable<?> typeVariable = typeParameters[0];
+ assertEquals(constructor, typeVariable.getGenericDeclaration());
+ assertEquals("T", typeVariable.getName());
+ Type[] bounds = typeVariable.getBounds();
+ assertLenghtOne(bounds);
+ assertEquals(Object.class, bounds[0]);
+ }
+
+ static class D<Q,R,S>{}
+ public void testMultipleTypeVariablesOnClass() throws Exception {
+ Class<? extends D> clazz = D.class;
+ TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
+ assertEquals(3, typeParameters.length);
+ assertEquals("Q", typeParameters[0].getName());
+ assertEquals(clazz, typeParameters[0].getGenericDeclaration());
+
+ assertEquals("R", typeParameters[1].getName());
+ assertEquals(clazz, typeParameters[1].getGenericDeclaration());
+
+ assertEquals("S", typeParameters[2].getName());
+ assertEquals(clazz, typeParameters[2].getGenericDeclaration());
+
+ }
+
+ static class E {
+ <Q,R,S> void e(){}
+ }
+ public void testMultipleTypeVariablesOnMethod() throws Exception {
+ Class<? extends E> clazz = E.class;
+ Method method = clazz.getDeclaredMethod("e");
+
+ TypeVariable<?>[] typeParameters = method.getTypeParameters();
+ assertEquals(3, typeParameters.length);
+ assertEquals("Q", typeParameters[0].getName());
+ assertEquals(method, typeParameters[0].getGenericDeclaration());
+
+ assertEquals("R", typeParameters[1].getName());
+ assertEquals(method, typeParameters[1].getGenericDeclaration());
+
+ assertEquals("S", typeParameters[2].getName());
+ assertEquals(method, typeParameters[2].getGenericDeclaration());
+ }
+
+ static class F {
+ <Q,R,S> F(){}
+ }
+ public void testMultipleTypeVariablesOnConstructor() throws Exception {
+ Class<? extends F> clazz = F.class;
+ Constructor<?> constructor = clazz.getDeclaredConstructor();
+
+ TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
+ assertEquals(3, typeParameters.length);
+ assertEquals("Q", typeParameters[0].getName());
+ assertEquals(constructor, typeParameters[0].getGenericDeclaration());
+
+ assertEquals("R", typeParameters[1].getName());
+ assertEquals(constructor, typeParameters[1].getGenericDeclaration());
+
+ assertEquals("S", typeParameters[2].getName());
+ assertEquals(constructor, typeParameters[2].getGenericDeclaration());
+ }
+
+ static class G <T extends Number>{}
+
+ public void testSingleBound() throws Exception {
+ Class<? extends G> clazz = G.class;
+ TypeVariable[] typeParameters = clazz.getTypeParameters();
+ TypeVariable<Class> typeVariable = typeParameters[0];
+ Type[] bounds = typeVariable.getBounds();
+ assertLenghtOne(bounds);
+ assertEquals(Number.class, bounds[0]);
+ }
+
+ static class H <T extends Number & Serializable >{}
+ public void testMultipleBound() throws Exception {
+ Class<? extends H> clazz = H.class;
+ TypeVariable[] typeParameters = clazz.getTypeParameters();
+ TypeVariable<Class> typeVariable = typeParameters[0];
+ Type[] bounds = typeVariable.getBounds();
+ assertEquals(2, bounds.length);
+ assertEquals(Number.class, bounds[0]);
+ assertEquals(Serializable.class, bounds[1]);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTest.java
new file mode 100644
index 0000000..9f3679e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.tests.java.lang.reflect;
+
+import java.lang.reflect.UndeclaredThrowableException;
+
+import junit.framework.TestCase;
+
+public class UndeclaredThrowableExceptionTest extends TestCase {
+
+ /**
+ * {@link java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable)}
+ */
+ public void test_UndeclaredThrowableException_LThrowable() {
+ UndeclaredThrowableException e = new UndeclaredThrowableException(
+ (Exception) null);
+ assertNotNull(e);
+ assertNull(e.getCause());
+
+ }
+
+ /**
+ * {@link java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable, java.lang.String)}
+ */
+ public void test_UndeclaredThrowableException_LThrowable_LString() {
+ UndeclaredThrowableException e = new UndeclaredThrowableException(null,
+ "SomeMsg");
+ assertNotNull(e);
+ assertNull(e.getCause());
+ assertEquals("Wrong message", "SomeMsg", e.getMessage());
+ }
+
+ /**
+ * {@link java.lang.reflect.UndeclaredThrowableException#getUndeclaredThrowable()}
+ */
+ public void test_getUndeclaredThrowable() {
+ UndeclaredThrowableException e = new UndeclaredThrowableException(null);
+ assertNotNull(e);
+ assertNull(e.getUndeclaredThrowable());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTests.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTests.java
new file mode 100644
index 0000000..2112ed7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/UndeclaredThrowableExceptionTests.java
@@ -0,0 +1,53 @@
+package org.apache.harmony.tests.java.lang.reflect;
+
+import junit.framework.TestCase;
+
+import java.io.EOFException;
+import java.lang.reflect.UndeclaredThrowableException;
+
+public class UndeclaredThrowableExceptionTests extends TestCase {
+
+ private static EOFException throwable = new EOFException();
+ private static String msg = "TEST_MSG";
+ /**
+ * java.lang.reflect.UndeclaredThrowableException#getCause()
+ */
+ public void test_getCause() throws Exception {
+ UndeclaredThrowableException ute = new UndeclaredThrowableException(
+ throwable);
+ assertSame("Wrong cause returned", throwable, ute.getCause());
+ }
+
+ /**
+ * java.lang.reflect.UndeclaredThrowableException#getUndeclaredThrowable()
+ */
+ public void test_getUndeclaredThrowable() throws Exception {
+ UndeclaredThrowableException ute = new UndeclaredThrowableException(
+ throwable);
+ assertSame("Wrong undeclared throwable returned", throwable, ute
+ .getUndeclaredThrowable());
+ }
+
+ /**
+ * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable)
+ */
+ public void test_Constructor_Throwable() throws Exception {
+ UndeclaredThrowableException e = new UndeclaredThrowableException(
+ throwable);
+ assertEquals("Wrong cause returned", throwable, e.getCause());
+ assertEquals("Wrong throwable returned", throwable, e
+ .getUndeclaredThrowable());
+ }
+
+ /**
+ * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable, java.lang.String)
+ */
+ public void test_Constructor_Throwable_String() throws Exception {
+ UndeclaredThrowableException e = new UndeclaredThrowableException(
+ throwable, msg);
+ assertEquals("Wrong cause returned", throwable, e.getCause());
+ assertEquals("Wrong throwable returned", throwable, e
+ .getUndeclaredThrowable());
+ assertEquals("Wrong message returned", msg, e.getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/WildcardTypeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/WildcardTypeTest.java
new file mode 100644
index 0000000..e29fd47
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/WildcardTypeTest.java
@@ -0,0 +1,151 @@
+/*
+ * 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 org.apache.harmony.tests.java.lang.reflect;
+
+
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+
+/**
+ * Tests bounded type parameters declared on methods and bounded wildcards.
+ */
+public class WildcardTypeTest extends GenericReflectionTestsBase {
+ @SuppressWarnings({"unchecked", "hiding"})
+ static class BoundedWildcardsGenericMethods<T> {
+
+ public <T extends BoundedWildcardsGenericMethods> void lowerBoundedParamNoReturn( BoundedWildcardsGenericMethods<? super T> param) {}
+
+ public <T extends BoundedWildcardsGenericMethods> void upperBoundedParamNoReturn( BoundedWildcardsGenericMethods<? extends T> param) {}
+
+ public <T extends BoundedWildcardsGenericMethods> T lowerBoundedParamReturn(BoundedWildcardsGenericMethods<? super T> param) { return (T) new Object(); }
+
+ public <T extends BoundedWildcardsGenericMethods> T upperBoundedParamReturn(BoundedWildcardsGenericMethods<? extends T> param) { return (T) new Object();}
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<? extends BoundedWildcardsGenericMethods> clazz = BoundedWildcardsGenericMethods.class;
+
+ /**
+ * Tests that there are is one Type Parameter on the Class itself.
+ */
+ public void testBoundedGenericMethods() {
+ assertLenghtOne(clazz.getTypeParameters());
+ }
+
+ /**
+ * Tests whether the type parameter is bounded by BoundedGenericMethods like:
+ * <T extends BoundedGenericMethods>.
+ * @param method the declaring method
+ */
+ private void checkBoundedTypeParameter(Method method) {
+ TypeVariable<Method> typeParameter = getTypeParameter(method);
+ assertEquals("T", typeParameter.getName());
+ assertEquals(method, typeParameter.getGenericDeclaration());
+
+ Type[] bounds = typeParameter.getBounds();
+ assertLenghtOne(bounds);
+ Type bound = bounds[0];
+ assertEquals(BoundedWildcardsGenericMethods.class, bound);
+ }
+
+ private void checkLowerBoundedParameter(Method method) {
+ Type genericParameterType = method.getGenericParameterTypes()[0];
+ assertInstanceOf(ParameterizedType.class, genericParameterType);
+
+ ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
+
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ assertLenghtOne(actualTypeArguments);
+ assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
+
+ WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
+
+ Type[] lowerBounds = wildcardType.getLowerBounds();
+ assertLenghtOne(lowerBounds);
+ Type lowerBound = lowerBounds[0];
+ assertEquals(getTypeParameter(method), lowerBound);
+
+ Type[] upperBounds = wildcardType.getUpperBounds();
+ assertEquals(Object.class, upperBounds[0]);
+ }
+
+ private void checkUpperBoundedParameter(Method method) {
+ assertLenghtOne(method.getGenericParameterTypes());
+ Type genericParameterType = method.getGenericParameterTypes()[0];
+ assertInstanceOf(ParameterizedType.class, genericParameterType);
+
+ ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ assertLenghtOne(actualTypeArguments);
+ assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
+
+ WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
+ assertLenghtZero(wildcardType.getLowerBounds());
+
+ Type[] upperBounds = wildcardType.getUpperBounds();
+ assertLenghtOne(upperBounds);
+ Type upperBound = upperBounds[0];
+ assertEquals(getTypeParameter(method), upperBound);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void checkReturnType(Method method) {
+ Type genericReturnType = method.getGenericReturnType();
+ assertEquals(getTypeParameter(method), genericReturnType);
+ assertTrue(genericReturnType instanceof TypeVariable);
+
+ TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
+ assertEquals(method, returnTypeVariable.getGenericDeclaration());
+
+ Type[] bounds = returnTypeVariable.getBounds();
+ assertLenghtOne(bounds);
+ Type bound = bounds[0];
+
+ assertEquals(BoundedWildcardsGenericMethods.class, bound);
+ }
+
+ public void testUpperBoundedParamNoReturn() throws Exception {
+ Method method = clazz.getMethod("upperBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ checkUpperBoundedParameter(method);
+ }
+
+ public void testLowerBoundedParamReturn() throws Exception {
+ Method method = clazz.getMethod("lowerBoundedParamReturn", BoundedWildcardsGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ checkLowerBoundedParameter(method);
+ checkReturnType(method);
+ }
+
+ public void testUpperBoundedParamReturn() throws Exception {
+ Method method = clazz.getMethod("upperBoundedParamReturn", BoundedWildcardsGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ checkUpperBoundedParameter(method);
+ checkReturnType(method);
+ }
+
+ public void testLowerBoundedParamNoReturn() throws Exception {
+ Method method = clazz.getMethod("lowerBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
+ checkBoundedTypeParameter(method);
+ assertLenghtOne(method.getGenericParameterTypes());
+ checkLowerBoundedParameter(method);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalTest.java
index 4fd27bf..20e9237 100644
--- a/harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package tests.api.java.math;
+package org.apache.harmony.tests.java.math;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
diff --git a/harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerTest.java
index 28995cb..337e7c4 100644
--- a/harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package tests.api.java.math;
+package org.apache.harmony.tests.java.math;
import java.math.BigInteger;
import java.util.Random;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/MathContextTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/MathContextTest.java
new file mode 100644
index 0000000..d9942d3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/MathContextTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.tests.java.math;
+
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.math.RoundingMode;
+
+public class MathContextTest extends junit.framework.TestCase {
+
+ /**
+ * java.math.MathContext#MathContext(...)
+ */
+ public void test_MathContextConstruction() {
+ String a = "-12380945E+61";
+ BigDecimal aNumber = new BigDecimal(a);
+ MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
+ MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
+ MathContext mcInt6 = new MathContext(6);
+ MathContext mcInt134 = new MathContext(134);
+
+ // getPrecision()
+ assertEquals("MathContext.getPrecision() returns incorrect value",
+ 6, mcIntRm6hd.getPrecision() );
+ assertEquals("MathContext.getPrecision() returns incorrect value",
+ 134, mcInt134.getPrecision() );
+
+ // getRoundingMode()
+ assertEquals("MathContext.getRoundingMode() returns incorrect value",
+ RoundingMode.HALF_UP,
+ mcInt6.getRoundingMode());
+ assertEquals("MathContext.getRoundingMode() returns incorrect value",
+ RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode() );
+
+ // toString()
+ assertEquals("MathContext.toString() returning incorrect value",
+ "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString() );
+ assertEquals("MathContext.toString() returning incorrect value",
+ "precision=6 roundingMode=HALF_UP", mcInt6.toString() );
+
+ // equals(.)
+ assertEquals("Equal MathContexts are not equal ",
+ mcIntRm6hd, mcStr6hd );
+ assertFalse("Different MathContexts are reported as equal ",
+ mcInt6.equals(mcStr6hd) );
+ assertFalse("Different MathContexts are reported as equal ",
+ mcInt6.equals(mcInt134) );
+
+ // hashCode(.)
+ assertEquals("Equal MathContexts have different hashcodes ",
+ mcIntRm6hd.hashCode(), mcStr6hd.hashCode() );
+ assertFalse("Different MathContexts have equal hashcodes ",
+ mcInt6.hashCode() == mcStr6hd.hashCode() );
+ assertFalse("Different MathContexts have equal hashcodes ",
+ mcInt6.hashCode() == mcInt134.hashCode() );
+
+ // other:
+ BigDecimal res = aNumber.abs(mcInt6);
+ assertEquals("MathContext Constructor with int precision failed",
+ new BigDecimal("1.23809E+68"),
+ res);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/OldBigIntegerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/OldBigIntegerTest.java
new file mode 100644
index 0000000..7d1f1b4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/OldBigIntegerTest.java
@@ -0,0 +1,372 @@
+/*
+ * 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.tests.java.math;
+
+import java.math.BigInteger;
+import java.util.Random;
+
+public class OldBigIntegerTest extends junit.framework.TestCase {
+
+ BigInteger minusOne = new BigInteger("-1", 10);
+
+ BigInteger two = new BigInteger("2", 10);
+
+ BigInteger aZillion = new BigInteger("100000000000000000000000000000000000000000000000000", 10);
+
+ Random rand = new Random();
+
+ BigInteger bi;
+
+ BigInteger bi2;
+
+ BigInteger bi3;
+
+ /**
+ * java.math.BigInteger#BigInteger(int, java.util.Random)
+ */
+ public void test_ConstructorILjava_util_Random() {
+ // regression test for HARMONY-1047
+ try {
+ new BigInteger(128, (Random) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ bi = new BigInteger(70, rand);
+ bi2 = new BigInteger(70, rand);
+ assertTrue("Random number is negative", bi.compareTo(BigInteger.ZERO) >= 0);
+ assertTrue("Random number is too big", bi.compareTo(two.pow(70)) < 0);
+ assertTrue(
+ "Two random numbers in a row are the same (might not be a bug but it very likely is)",
+ !bi.equals(bi2));
+ assertTrue("Not zero", new BigInteger(0, rand).equals(BigInteger.ZERO));
+
+ try {
+ new BigInteger(-1, (Random)null);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // PASSED
+ }
+ }
+
+ /**
+ * java.math.BigInteger#BigInteger(int, int, java.util.Random)
+ */
+ // BIGNUM returns no Primes smaller than 16 bits.
+ public void test_ConstructorIILjava_util_Random() {
+ BigInteger bi1 = new BigInteger(10, 5, rand);
+ BigInteger bi2 = new BigInteger(10, 5, rand);
+ assertTrue(bi1 + " is negative", bi1.compareTo(BigInteger.ZERO) >= 0);
+ assertTrue(bi1 + " is too big", bi1.compareTo(new BigInteger("1024", 10)) < 0);
+ assertTrue(bi2 + " is negative", bi2.compareTo(BigInteger.ZERO) >= 0);
+ assertTrue(bi2 + " is too big", bi2.compareTo(new BigInteger("1024", 10)) < 0);
+
+ Random rand = new Random();
+ BigInteger bi;
+ int certainty[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
+ Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -2, -1 };
+ for (int i = 2; i <= 20; i++) {
+ for (int c = 0; c < certainty.length; c++) {
+ bi = new BigInteger(i, c, rand); // Create BigInteger
+ assertEquals(i, bi.bitLength());
+ }
+ }
+
+ try {
+ new BigInteger(1, 80, (Random)null);
+ fail("ArithmeticException expected");
+ } catch (ArithmeticException expected) {
+ }
+
+ try {
+ new BigInteger(-1, (Random)null);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+// public void test_SpecialPrimes() {
+// System.out.println("test_SpecialPrimes");
+// final BigInteger TWO = BigInteger.valueOf(2);
+// BigInteger p, q;
+// for (;;) {
+// p = new BigInteger(1024, 23, new Random());
+// q = p.subtract(BigInteger.ONE).divide(TWO);
+// if (q.isProbablePrime(20)) {
+// System.out.println(q);
+// System.out.println(p);
+// break;
+// }
+// System.out.print(".");
+// }
+// fail("isProbablePrime failed for: " + bi);
+// }
+
+ /**
+ * java.math.BigInteger#isProbablePrime(int)
+ */
+ public void test_isProbablePrimeI() {
+ int fails = 0;
+ bi = new BigInteger(20, 20, rand);
+ if (!bi.isProbablePrime(17)) {
+ fails++;
+ }
+ bi = new BigInteger("4", 10);
+ if (bi.isProbablePrime(17)) {
+ fail("isProbablePrime failed for: " + bi);
+ }
+ bi = BigInteger.valueOf(17L * 13L);
+ if (bi.isProbablePrime(17)) {
+ fail("isProbablePrime failed for: " + bi);
+ }
+ for (long a = 2; a < 1000; a++) {
+ if (isPrime(a)) {
+ assertTrue("false negative on prime number <1000", BigInteger
+ .valueOf(a).isProbablePrime(5));
+ } else if (BigInteger.valueOf(a).isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + a);
+ fails++;
+ }
+ }
+ for (int a = 0; a < 1000; a++) {
+ bi = BigInteger.valueOf(rand.nextInt(1000000)).multiply(
+ BigInteger.valueOf(rand.nextInt(1000000)));
+ if (bi.isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + bi);
+ fails++;
+ }
+ }
+ for (int a = 0; a < 200; a++) {
+ bi = new BigInteger(70, rand).multiply(new BigInteger(70, rand));
+ if (bi.isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + bi);
+ fails++;
+ }
+ }
+ assertTrue("Too many false positives - may indicate a problem",
+ fails <= 1);
+
+ //
+ // And now some tests on real big integers:
+ //
+ bi = new BigInteger("153890972191202256150310830154922163807316525358455215516067727076235016932726922093888770552128767458882963869421440585369743", 10);
+ if (!bi.isProbablePrime(80)) {
+ fail("isProbablePrime failed for: " + bi);
+ }
+ bi = new BigInteger("2090575416269141767246491983797422123741252476560371649798066134123893524014911825188890458270426076468664046568752890122415061377308817346303546688282957897504000216241497550243010257911214329646877810655164658470278901030511157372440751259674247310396158238588463284702737181653", 10);
+ if (!bi.isProbablePrime(80)) {
+ fail("isProbablePrime failed for: " + bi);
+ }
+ //
+ for (int bitLength = 100; bitLength <= 600; bitLength += 100) {
+ BigInteger a = BigInteger.probablePrime(bitLength, rand);
+ BigInteger b = BigInteger.probablePrime(bitLength, rand);
+ BigInteger c = a.multiply(b);
+ assertFalse("isProbablePrime failed for product of two large primes" +
+ a + " * " + b + " = " + c +
+ " (bitLength = " + bitLength + ")",
+ c.isProbablePrime(80) );
+ }
+ }
+
+ /**
+ * java.math.BigInteger#nextProbablePrime()
+ */
+ public void test_nextProbablePrime() {
+ largePrimesProduct(
+ new BigInteger("2537895984043447429238717358455377929009126353874925049325287329295635198252046158619999217453233889378619619008359011789"),
+ new BigInteger("1711501451602688337873833423534849678524059393231999670806585630179374689152366029939952735718718709436427337762082614710093"),
+ "4343612660706993434504106787562106084038357258130862545477481433639575850237346784798851102536616749334772541987502120552264920040629526028540204698334741815536099373917351194423681128374184971846099257056996626343051832131340568120612204287123"
+ );
+
+ largePrimesProduct(
+ new BigInteger("4617974730611208463200675282934641082129817404749925308887287017217158545765190433369842932770197341032031682222405074564586462802072184047198214312142847809259437477387527466762251087500170588962277514858557309036550499896961735701485020851"),
+ new BigInteger("4313158964405728158057980867015758419530142215799386331265837224051830838583266274443105715022196238165196727467066901495701708590167750818040112544031694506528759169669442493029999154074962566165293254671176670719518898684698255068313216294333"),
+ "19918059106734861363335842730108905466210762564765297409619920041621379008685530738918145604092111306972524565803236031571858280032420140331838737621152630780261815015157696362550138161774466814661069892975003440654998880587960037013294137372709096788892473385003457361736563927256562678181177287998121131179907762285048659075843995525830945659905573174849006768920618442371027575308854641789533211132313916836205357976988977849024687805212304038260207820679964201211309384057458137851"
+ );
+ }
+
+ static void largePrimesProduct(BigInteger a, BigInteger b, String c) {
+ BigInteger wp = a.multiply(b);
+ assertFalse("isProbablePrime failed for product of two large primes" +
+ a + " * " + b + " = " + c,
+ wp.isProbablePrime(80) );
+ BigInteger wpMinusOne = wp.subtract(BigInteger.ONE);
+ BigInteger next = wpMinusOne.nextProbablePrime();
+// System.out.println(c);
+// System.out.println(next);
+ assertTrue("nextProbablePrime returns wrong number: " + next +
+ "instead of expected: " + c,
+ next.toString().equals(c) );
+ }
+
+ /**
+ * java.math.BigInteger#probablePrime(int, java.util.Random)
+ */
+ public void test_probablePrime() {
+ for (int bitLength = 50; bitLength <= 1050; bitLength += 100) {
+ BigInteger a = BigInteger.probablePrime(bitLength, rand);
+ assertTrue("isProbablePrime(probablePrime()) failed for: " + bi,
+ a.isProbablePrime(80));
+// System.out.println(a);
+// BigInteger prime = a.nextProbablePrime();
+// System.out.print("Next Probable Prime is ");
+// System.out.println(prime);
+ }
+ }
+
+// BEGIN android-added
+// public void testModPowPerformance() {
+// Random rnd = new Random();
+// for (int i = 0; i < 10; i++) {
+// BigInteger a = new BigInteger(512, rnd);
+// BigInteger m = new BigInteger(1024, rnd);
+// BigInteger p = new BigInteger(256, rnd);
+// BigInteger mp = a.modPow(p, m);
+// System.out.println(mp);
+// }
+// }
+
+// shows factor 20 speed up (BIGNUM to Harmony Java):
+// public void testNextProbablePrime() {
+// Random rnd = new Random();
+// rnd.setSeed(0);
+// for (int i = 1; i <= 32; i += 1) {
+// BigInteger a = new BigInteger(i, rnd);
+// System.out.println(a);
+// BigInteger prime = a.nextProbablePrime();
+// System.out.print("Next Probable Prime is ");
+// System.out.println(prime);
+// }
+// for (int i = 1; i <= 32; i += 4) {
+// BigInteger a = new BigInteger(32 * i, rnd);
+// System.out.println(a);
+// BigInteger prime = a.nextProbablePrime();
+// System.out.print("Next Probable Prime is ");
+// System.out.println(prime);
+// }
+// }
+
+// shows factor 20 speed up (BIGNUM to Harmony Java):
+// shows that certainty 80 is "practically aquivalent" to certainty 100
+// public void testPrimeGenPerformance() {
+// Random rnd = new Random();
+// rnd.setSeed(0);
+// for (int i = 1; i <= 32; i +=8 ) {
+// BigInteger a = new BigInteger(32 * i, 80, rnd);
+// System.out.println(a);
+// System.out.println("Now testing it again:");
+// if (a.isProbablePrime(100)) {
+// System.out.println("************************ PASSED! **************************");
+// } else {
+// System.out.println("************************ FAILED!!! **************************");
+// System.out.println("************************ FAILED!!! **************************");
+// System.out.println("************************ FAILED!!! **************************");
+// System.out.println("************************ FAILED!!! **************************");
+// System.out.println("************************ FAILED!!! **************************");
+// System.out.println("************************ FAILED!!! **************************");
+// }
+// }
+// }
+// END android-added
+
+
+
+ /**
+ * java.math.BigInteger#add(java.math.BigInteger)
+ */
+ public void test_addLjava_math_BigInteger() {
+ assertTrue("Incorrect sum--wanted a zillion", aZillion.add(aZillion)
+ .add(aZillion.negate()).equals(aZillion));
+ assertTrue("0+0", BigInteger.ZERO.add(BigInteger.ZERO).equals(BigInteger.ZERO));
+ assertTrue("0+1", BigInteger.ZERO.add(BigInteger.ONE).equals(BigInteger.ONE));
+ assertTrue("1+0", BigInteger.ONE.add(BigInteger.ZERO).equals(BigInteger.ONE));
+ assertTrue("1+1", BigInteger.ONE.add(BigInteger.ONE).equals(two));
+ assertTrue("0+(-1)", BigInteger.ZERO.add(minusOne).equals(minusOne));
+ assertTrue("(-1)+0", minusOne.add(BigInteger.ZERO).equals(minusOne));
+ assertTrue("(-1)+(-1)", minusOne.add(minusOne).equals(new BigInteger("-2", 10)));
+ assertTrue("1+(-1)", BigInteger.ONE.add(minusOne).equals(BigInteger.ZERO));
+ assertTrue("(-1)+1", minusOne.add(BigInteger.ONE).equals(BigInteger.ZERO));
+
+ for (int i = 0; i < 200; i++) {
+ BigInteger midbit = BigInteger.ZERO.setBit(i);
+ assertTrue("add fails to carry on bit " + i, midbit.add(midbit)
+ .equals(BigInteger.ZERO.setBit(i + 1)));
+ }
+ BigInteger bi2p3 = bi2.add(bi3);
+ BigInteger bi3p2 = bi3.add(bi2);
+ assertTrue("bi2p3=bi3p2", bi2p3.equals(bi3p2));
+
+
+ // BESSER UEBERGREIFENDE TESTS MACHEN IN FORM VON STRESS TEST.
+ // add large positive + small positive
+ BigInteger sum = aZillion;
+ BigInteger increment = BigInteger.ONE;
+ for (int i = 0; i < 20; i++) {
+
+ }
+
+ // add large positive + small negative
+
+ // add large negative + small positive
+
+ // add large negative + small negative
+ }
+
+ public void testClone() {
+ // Regression test for HARMONY-1770
+ MyBigInteger myBigInteger = new MyBigInteger("12345");
+ myBigInteger = (MyBigInteger) myBigInteger.clone();
+ }
+
+ static class MyBigInteger extends BigInteger implements Cloneable {
+ public MyBigInteger(String val) {
+ super(val);
+ }
+ public Object clone() {
+ try {
+ return super.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e); // android-changed
+ }
+ }
+ }
+
+ @Override
+ protected void setUp() {
+ bi2 = new BigInteger("4576829475724387584378543764555", 16);
+ bi3 = new BigInteger("43987298363278574365732645872643587624387563245", 16);
+ }
+
+ private boolean isPrime(long b) {
+ if (b == 2) {
+ return true;
+ }
+ // check for div by 2
+ if ((b & 1L) == 0) {
+ return false;
+ }
+ long maxlen = ((long) Math.sqrt(b)) + 2;
+ for (long x = 3; x < maxlen; x += 2) {
+ if (b % x == 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/RoundingModeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/RoundingModeTest.java
new file mode 100644
index 0000000..4004ca3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/RoundingModeTest.java
@@ -0,0 +1,49 @@
+/*
+ * 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.tests.java.math;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public class RoundingModeTest extends junit.framework.TestCase {
+
+ /**
+ * java.math.RoundingMode#valueOf(int)
+ */
+ 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);
+ assertEquals("valueOf failed for ROUND_FLOOR", RoundingMode.valueOf(BigDecimal.ROUND_FLOOR), RoundingMode.FLOOR);
+ assertEquals("valueOf failed for ROUND_HALF_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_DOWN), RoundingMode.HALF_DOWN);
+ assertEquals("valueOf failed for ROUND_HALF_EVEN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_EVEN), RoundingMode.HALF_EVEN);
+ assertEquals("valueOf failed for ROUND_HALF_UP", RoundingMode.valueOf(BigDecimal.ROUND_HALF_UP), RoundingMode.HALF_UP);
+ assertEquals("valueOf failed for ROUND_UNNECESSARY", RoundingMode.valueOf(BigDecimal.ROUND_UNNECESSARY), RoundingMode.UNNECESSARY);
+ assertEquals("valueOf failed for ROUND_UP", RoundingMode.valueOf(BigDecimal.ROUND_UP), RoundingMode.UP);
+ try {
+ RoundingMode.valueOf(13);
+ fail("IllegalArgumentException expected for RoundingMode(13)");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ RoundingMode.valueOf(-1);
+ fail("IllegalArgumentException expected for RoundingMode(-1)");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/BindExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/BindExceptionTest.java
new file mode 100644
index 0000000..799211e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/BindExceptionTest.java
@@ -0,0 +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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.tests.java.net;
+
+import java.net.BindException;
+
+public class BindExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.BindException#BindException()
+ */
+ public void test_Constructor() {
+ // Test for method java.net.BindException()
+ try {
+ throw new BindException();
+ } catch (BindException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during BindException test" + e.toString());
+ }
+ fail("Failed to generate exception");
+ }
+
+ /**
+ * java.net.BindException#BindException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.net.BindException(java.lang.String)
+ try {
+ throw new BindException("Some error message");
+ } catch (BindException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during BindException test : " + e.getMessage());
+ }
+ fail("Failed to generate exception");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java
new file mode 100644
index 0000000..d0290ec
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.ConnectException;
+
+public class ConnectExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.ConnectException#ConnectException()
+ * java.net.ConnectException#ConnectException(java.lang.String)
+ */
+ public void test_Constructor() {
+ assertNull("Wrong message", new ConnectException().getMessage());
+ assertEquals("Wrong message", "message", new ConnectException("message").getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieHandlerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieHandlerTest.java
new file mode 100644
index 0000000..3cefc85
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieHandlerTest.java
@@ -0,0 +1,62 @@
+/* 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.CookieHandler;
+import java.net.NetPermission;
+import java.net.URI;
+import java.security.Permission;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+public class CookieHandlerTest extends TestCase {
+
+ /**
+ * java.net.CookieHandler#getDefault()
+ */
+ public void test_GetDefault() {
+ assertNull(CookieHandler.getDefault());
+ }
+
+ /**
+ * java.net.CookieHandler#setDefault(CookieHandler)
+ */
+ public void test_SetDefault_java_net_cookieHandler() {
+ MockCookieHandler rc1 = new MockCookieHandler();
+ MockCookieHandler rc2 = new MockCookieHandler();
+ CookieHandler.setDefault(rc1);
+ assertSame(CookieHandler.getDefault(), rc1);
+ CookieHandler.setDefault(rc2);
+ assertSame(CookieHandler.getDefault(), rc2);
+ CookieHandler.setDefault(null);
+ assertNull(CookieHandler.getDefault());
+ }
+
+ class MockCookieHandler extends CookieHandler {
+
+ public Map get(URI uri, Map requestHeaders) throws IOException {
+ return null;
+ }
+
+ public void put(URI uri, Map responseHeaders) throws IOException {
+ // empty
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieManagerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieManagerTest.java
new file mode 100644
index 0000000..d0c4ee1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieManagerTest.java
@@ -0,0 +1,303 @@
+/* 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.tests.java.net;
+
+import junit.framework.TestCase;
+import java.io.IOException;
+import java.net.CookieManager;
+import java.net.CookiePolicy;
+import java.net.CookieStore;
+import java.net.HttpCookie;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class CookieManagerTest extends TestCase {
+
+ private static void checkValidParams4Get(URI uri,
+ Map<String, List<String>> map) throws IOException {
+ CookieManager manager = new CookieManager();
+ try {
+ manager.get(uri, map);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ private static void checkValidParams4Put(URI uri,
+ Map<String, List<String>> map) throws IOException {
+ CookieManager manager = new CookieManager();
+ try {
+ manager.put(uri, map);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * {@link java.net.CookieManager#get(java.net.URI, java.util.Map)} &
+ * {@link java.net.CookieManager#put(java.net.URI, java.util.Map)}
+ * IllegalArgumentException
+ * @since 1.6
+ */
+ public void test_Put_Get_LURI_LMap_exception() throws IOException,
+ URISyntaxException {
+ // get
+ checkValidParams4Get(new URI(""), null);
+ checkValidParams4Get(new URI("http://www.test.com"), null);
+ checkValidParams4Get(null, null);
+ checkValidParams4Get(null, new HashMap<String, List<String>>());
+
+ // put
+ checkValidParams4Put(new URI(""), null);
+ checkValidParams4Put(new URI("http://www.test.com"), null);
+ checkValidParams4Put(null, null);
+ checkValidParams4Put(null, new HashMap<String, List<String>>());
+ }
+
+ private static Map<String, List<String>> addCookie(String[][] cookies) {
+ Map<String, List<String>> responseHeaders = new LinkedHashMap<String, List<String>>();
+ for (int i = 0; i < cookies.length; i++) {
+ List<String> fields = new ArrayList<String>();
+ for (int j = 1; j < cookies[i].length; j += 2) {
+ fields.add(cookies[i][j]);
+ }
+ responseHeaders.put(cookies[i][0], fields);
+ }
+ return responseHeaders;
+ }
+
+ private static CookieManager store(String[][] cookies,
+ Map<String, List<String>> responseHeaders, CookiePolicy policy)
+ throws IOException, URISyntaxException {
+ CookieManager manager = new CookieManager(null, policy);
+ // Put all cookies into manager
+ for (int i = 0; i < cookies.length; i++) {
+ for (int j = 2; j < cookies[i].length; j += 2) {
+ URI uri = new URI(cookies[i][j]);
+ manager.put(uri, responseHeaders);
+ }
+ }
+ return manager;
+ }
+
+ /**
+ * Unlike the RI, we flatten all matching cookies into a single Cookie header
+ * instead of sending down multiple cookie headers. Also, when no cookies match
+ * a given URI, we leave the requestHeaders unmodified.
+ *
+ * @since 1.6
+ */
+ public void test_Put_Get_LURI_LMap() throws IOException, URISyntaxException {
+ // cookie-key | (content, URI)...
+ String[][] cookies = {
+ { "Set-cookie",
+ "Set-cookie:PREF=test;path=/;domain=.b.c;", "http://a.b.c/",
+ "Set-cookie:PREF1=test2;path=/;domain=.beg.com;", "http://a.b.c/" },
+
+ { "Set-cookie2",
+ "Set-cookie2:NAME1=VALUE1;path=/te;domain=.b.c;", "http://a.b.c/test" },
+
+ { "Set-cookie",
+ "Set-cookie2:NAME=VALUE;path=/;domain=.beg.com;", "http://a.beg.com/test",
+ "Set-cookie2:NAME1=VALUE1;path=/;domain=.beg.com;", "http://a.beg.com/test" },
+
+ { "Set-cookie2",
+ "Set-cookie3:NAME=VALUE;path=/;domain=.test.org;", "http://a.test.org/test" },
+
+ { null,
+ "Set-cookie3:NAME=VALUE;path=/te;domain=.test.org;", "http://a.test.org/test" },
+
+ { "Set-cookie2",
+ "lala", "http://a.test.org/test" }
+
+ };
+
+ // requires path of cookie is the prefix of uri
+ // domain of cookie must match that of uri
+ Map<String, List<String>> responseHeaders = addCookie(new String[][] {
+ cookies[0], cookies[1] });
+ CookieManager manager = store(
+ new String[][] { cookies[0], cookies[1] }, responseHeaders,
+ null);
+
+ HashMap<String, List<String>> dummyMap = new HashMap<String, List<String>>();
+ Map<String, List<String>> map = manager.get(new URI("http://a.b.c/"),
+ dummyMap);
+
+ assertEquals(1, map.size());
+ List<String> list = map.get("Cookie");
+ assertEquals(1, list.size());
+
+ // requires path of cookie is the prefix of uri
+ map = manager.get(new URI("http://a.b.c/te"), dummyMap);
+ list = map.get("Cookie");
+ assertEquals(1, list.size());
+ assertTrue(list.get(0).contains("PREF=test"));
+ // Cookies from "/test" should *not* match the URI "/te".
+ assertFalse(list.get(0).contains("NAME=VALUE"));
+
+ // If all cookies are of version 1, then $version=1 will be added
+ // ,no matter the value cookie-key
+ responseHeaders = addCookie(new String[][] { cookies[2] });
+ manager = store(new String[][] { cookies[2] }, responseHeaders, null);
+ map = manager.get(new URI("http://a.beg.com/test"), dummyMap);
+ list = map.get("Cookie");
+ assertEquals(1, list.size());
+ assertTrue(list.get(0).startsWith("$Version=\"1\""));
+
+ // cookie-key will not have effect on determining cookie version
+ responseHeaders = addCookie(new String[][] { cookies[3] });
+ manager = store(new String[][] { cookies[3] }, responseHeaders, null);
+ map = manager.get(new URI("http://a.test.org/"), responseHeaders);
+ list = map.get("Cookie");
+ assertEquals(1, list.size());
+ assertEquals("Set-cookie3:NAME=VALUE", list.get(0));
+
+ // When key is null, no cookie can be stored/retrieved, even if policy =
+ // ACCEPT_ALL
+ responseHeaders = addCookie(new String[][] { cookies[4] });
+ manager = store(new String[][] { cookies[4] }, responseHeaders,
+ CookiePolicy.ACCEPT_ALL);
+ map = manager.get(new URI("http://a.test.org/"), responseHeaders);
+ list = map.get("Cookie");
+ assertNull(list);
+
+ // All cookies will be rejected if policy == ACCEPT_NONE
+ responseHeaders = addCookie(new String[][] { cookies[3] });
+ manager = store(new String[][] { cookies[3] }, responseHeaders,
+ CookiePolicy.ACCEPT_NONE);
+ map = manager.get(new URI("http://a.test.org/"), responseHeaders);
+ list = map.get("Cookie");
+ assertNull(list);
+
+ responseHeaders = addCookie(new String[][] { cookies[5] });
+ manager = store(new String[][] { cookies[5] }, responseHeaders,
+ CookiePolicy.ACCEPT_ALL);
+ list = map.get("Cookie");
+ assertNull(list);
+
+ try {
+ map.put(null, null);
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * {@link java.net.CookieManager#CookieManager()}
+ * @since 1.6
+ */
+ public void test_CookieManager() {
+ CookieManager cookieManager = new CookieManager();
+ assertNotNull(cookieManager);
+ assertNotNull(cookieManager.getCookieStore());
+ }
+
+ /**
+ * {@link java.net.CookieManager#CookieManager(java.net.CookieStore, java.net.CookiePolicy)}
+ * @since 1.6
+ */
+ public void testCookieManager_LCookieStore_LCookiePolicy() {
+ class DummyStore implements CookieStore {
+ public String getName() {
+ return "A dummy store";
+ }
+
+ public void add(URI uri, HttpCookie cookie) {
+ // expected
+ }
+
+ public List<HttpCookie> get(URI uri) {
+ return null;
+ }
+
+ public List<HttpCookie> getCookies() {
+ return null;
+ }
+
+ public List<URI> getURIs() {
+ return null;
+ }
+
+ public boolean remove(URI uri, HttpCookie cookie) {
+ return false;
+ }
+
+ public boolean removeAll() {
+ return false;
+ }
+ }
+ CookieStore store = new DummyStore();
+ CookieManager cookieManager = new CookieManager(store,
+ CookiePolicy.ACCEPT_ALL);
+ assertEquals("A dummy store", ((DummyStore) cookieManager
+ .getCookieStore()).getName());
+ assertSame(store, cookieManager.getCookieStore());
+ }
+
+ /**
+ * {@link java.net.CookieManager#setCookiePolicy(java.net.CookiePolicy)}
+ * @since 1.6
+ */
+ public void test_SetCookiePolicy_LCookiePolicy() throws URISyntaxException,
+ IOException {
+
+ // Policy = ACCEPT_NONE
+ CookieManager manager = new CookieManager();
+ manager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);
+ Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>();
+ URI uri = new URI("http://a.b.c");
+ manager.put(uri, responseHeaders);
+ Map<String, List<String>> map = manager.get(uri,
+ new HashMap<String, List<String>>());
+
+ assertEquals(0, map.size());
+
+ // Policy = ACCEPT_ALL
+ manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
+ responseHeaders = new TreeMap<String, List<String>>();
+ ArrayList<String> list = new ArrayList<String>();
+ list.add("test=null");
+ responseHeaders.put("Set-cookie", list);
+ uri = new URI("http://b.c.d");
+ manager.put(uri, responseHeaders);
+ map = manager.get(uri, new HashMap<String, List<String>>());
+ assertEquals(1, map.size());
+ }
+
+ /**
+ * {@link java.net.CookieManager#getCookieStore()}
+ * @since 1.6
+ */
+ public void test_GetCookieStore() {
+ CookieManager cookieManager = new CookieManager();
+ CookieStore store = cookieManager.getCookieStore();
+ assertNotNull(store);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookiePolicyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookiePolicyTest.java
new file mode 100644
index 0000000..61eff1e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookiePolicyTest.java
@@ -0,0 +1,112 @@
+/* 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.tests.java.net;
+
+import java.net.CookiePolicy;
+import java.net.HttpCookie;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import junit.framework.TestCase;
+
+public class CookiePolicyTest extends TestCase {
+
+ /**
+ * java.net.CookiePolicy#shouldAccept(java.net.URI,
+ *java.net.HttpCookie).
+ * @since 1.6
+ */
+ public void test_ShouldAccept_LURI_LHttpCookie() throws URISyntaxException {
+ HttpCookie cookie = new HttpCookie("Harmony_6", "ongoing");
+ URI uri = new URI("");
+ try {
+ CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(null, cookie);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // Policy: ACCEPT_ALL, always returns true
+ boolean accept = CookiePolicy.ACCEPT_ALL.shouldAccept(null, cookie);
+ assertTrue(accept);
+
+ accept = CookiePolicy.ACCEPT_ALL.shouldAccept(null, null);
+ assertTrue(accept);
+
+ accept = CookiePolicy.ACCEPT_ALL.shouldAccept(uri, null);
+ assertTrue(accept);
+
+ // Policy: ACCEPT_NONE, always returns false
+ accept = CookiePolicy.ACCEPT_NONE.shouldAccept(null, cookie);
+ assertFalse(accept);
+
+ accept = CookiePolicy.ACCEPT_NONE.shouldAccept(null, null);
+ assertFalse(accept);
+
+ accept = CookiePolicy.ACCEPT_NONE.shouldAccept(uri, null);
+ assertFalse(accept);
+
+ // Policy: ACCEPT_ORIGINAL_SERVER
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
+ assertFalse(accept);
+
+ cookie.setDomain(".b.c");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "schema://a.b.c"), cookie);
+ assertTrue(accept);
+
+ cookie.setDomain(".b.c");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "s://a.b.c.d"), cookie);
+ assertFalse(accept);
+
+ cookie.setDomain("b.c");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "s://a.b.c.d"), cookie);
+ assertFalse(accept);
+
+ cookie.setDomain("a.b.c.d");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "s://a.b.c.d"), cookie);
+ assertTrue(accept);
+
+ cookie.setDomain(".");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "s://a.b.c.d"), cookie);
+ assertFalse(accept);
+
+ cookie.setDomain("");
+ accept = CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(new URI(
+ "s://a.b.c.d"), cookie);
+ assertFalse(accept);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieStoreTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieStoreTest.java
new file mode 100644
index 0000000..72be761
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/CookieStoreTest.java
@@ -0,0 +1,401 @@
+/* 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.tests.java.net;
+
+import junit.framework.TestCase;
+import java.net.CookieManager;
+import java.net.CookieStore;
+import java.net.HttpCookie;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.RandomAccess;
+
+public class CookieStoreTest extends TestCase {
+
+ private CookieManager cookieManager;
+
+ private CookieStore cookieStore;
+
+ /**
+ * java.net.CookieStore#add(URI, HttpCookie)
+ * @since 1.6
+ */
+ public void test_add_LURI_LHttpCookie() throws URISyntaxException {
+ URI uri = new URI("http://harmony.test.unit.org");
+ HttpCookie cookie = new HttpCookie("name1", "value1");
+ cookie.setDiscard(true);
+
+ // This needn't throw. We should use the cookie's domain, if set.
+ // If no domain is set, this cookie will languish in the store until
+ // it expires.
+ cookieStore.add(null, cookie);
+
+ try {
+ cookieStore.add(uri, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ cookieStore.add(null, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ cookieStore.add(uri, cookie);
+ List<HttpCookie> list = cookieStore.get(uri);
+ assertEquals(1, list.size());
+ assertTrue(list.contains(cookie));
+
+ HttpCookie cookie2 = new HttpCookie(" NaME1 ", " TESTVALUE1 ");
+ cookieStore.add(uri, cookie2);
+ list = cookieStore.get(uri);
+ assertEquals(1, list.size());
+ assertEquals(" TESTVALUE1 ", list.get(0).getValue());
+ assertTrue(list.contains(cookie2));
+
+ // domain and path attributes works
+ HttpCookie anotherCookie = new HttpCookie("name1", "value1");
+ anotherCookie.setDomain("domain");
+ anotherCookie.setPath("Path");
+ cookieStore.add(uri, anotherCookie);
+ list = cookieStore.get(uri);
+ assertEquals(2, list.size());
+ assertNull(list.get(0).getDomain());
+ assertEquals("domain", list.get(1).getDomain());
+ assertEquals("Path", list.get(1).getPath());
+
+ URI uri2 = new URI("http://.test.unit.org");
+ HttpCookie cookie3 = new HttpCookie("NaME2", "VALUE2");
+ cookieStore.add(uri2, cookie3);
+ list = cookieStore.get(uri2);
+ assertEquals(1, list.size());
+ assertEquals("VALUE2", list.get(0).getValue());
+ list = cookieStore.getCookies();
+ assertEquals(3, list.size());
+
+ // expired cookie won't be selected.
+ HttpCookie cookie4 = new HttpCookie("cookie4", "value4");
+ cookie4.setMaxAge(-2);
+ assertTrue(cookie4.hasExpired());
+ cookieStore.add(uri2, cookie4);
+ list = cookieStore.getCookies();
+ assertEquals(3, list.size());
+ assertFalse(cookieStore.remove(uri2, cookie4));
+
+ cookie4.setMaxAge(3000);
+ cookie4.setDomain("domain");
+ cookie4.setPath("path");
+ cookieStore.add(uri2, cookie4);
+ list = cookieStore.get(uri2);
+ assertEquals(2, list.size());
+
+ cookieStore.add(uri, cookie4);
+ list = cookieStore.get(uri);
+ assertEquals(3, list.size());
+ list = cookieStore.get(uri2);
+ assertEquals(2, list.size());
+ list = cookieStore.getCookies();
+ assertEquals(4, list.size());
+
+ URI baduri = new URI("bad_url");
+ HttpCookie cookie6 = new HttpCookie("cookie5", "value5");
+ cookieStore.add(baduri, cookie6);
+ list = cookieStore.get(baduri);
+ assertTrue(list.contains(cookie6));
+ }
+
+ /**
+ * java.net.CookieStore#get(URI)
+ * @since 1.6
+ */
+ public void test_get_LURI() throws URISyntaxException {
+ try {
+ cookieStore.get(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ URI uri1 = new URI("http://get.uri1.test.org");
+ List<HttpCookie> list = cookieStore.get(uri1);
+ assertTrue(list.isEmpty());
+
+ HttpCookie cookie1 = new HttpCookie("cookie_name1", "cookie_value1");
+ HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
+ cookieStore.add(uri1, cookie1);
+ cookieStore.add(uri1, cookie2);
+ URI uri2 = new URI("http://get.uri2.test.org");
+ HttpCookie cookie3 = new HttpCookie("cookie_name3", "cookie_value3");
+ cookieStore.add(uri2, cookie3);
+ list = cookieStore.get(uri1);
+ assertEquals(2, list.size());
+ list = cookieStore.get(uri2);
+ assertEquals(1, list.size());
+
+ // domain-match cookies also be selected.
+ HttpCookie cookie4 = new HttpCookie("cookie_name4", "cookie_value4");
+ cookie4.setDomain(".uri1.test.org");
+ cookieStore.add(uri2, cookie4);
+ list = cookieStore.get(uri1);
+ assertEquals(3, list.size());
+
+ cookieStore.add(uri1, cookie4);
+ list = cookieStore.get(uri1);
+ assertEquals(3, list.size());
+ list = cookieStore.get(uri2);
+ assertEquals(2, list.size());
+
+ // expired cookie won't be selected.
+ HttpCookie cookie5 = new HttpCookie("cookie_name5", "cookie_value5");
+ cookie5.setMaxAge(-333);
+ assertTrue(cookie5.hasExpired());
+ cookieStore.add(uri1, cookie5);
+ list = cookieStore.get(uri1);
+ assertEquals(3, list.size());
+ assertFalse(cookieStore.remove(uri1, cookie5));
+ list = cookieStore.getCookies();
+ assertEquals(4, list.size());
+
+ cookie4.setMaxAge(-123);
+ list = cookieStore.get(uri1);
+ assertEquals(2, list.size());
+ list = cookieStore.getCookies();
+ assertEquals(3, list.size());
+ // expired cookies are also deleted even if it domain-matches the URI
+ HttpCookie cookie6 = new HttpCookie("cookie_name6", "cookie_value6");
+ cookie6.setMaxAge(-2);
+ cookie6.setDomain(".uri1.test.org");
+ cookieStore.add(uri2, cookie6);
+ list = cookieStore.get(uri1);
+ assertEquals(2, list.size());
+ assertFalse(cookieStore.remove(null, cookie6));
+
+ URI uri3 = new URI("http://get.uri3.test.org");
+ assertTrue(cookieStore.get(uri3).isEmpty());
+ URI baduri = new URI("invalid_uri");
+ assertTrue(cookieStore.get(baduri).isEmpty());
+ }
+
+ /**
+ * java.net.CookieStore#getCookies()
+ * @since 1.6
+ */
+ public void test_getCookies() throws URISyntaxException {
+ List<HttpCookie> list = cookieStore.getCookies();
+ assertTrue(list.isEmpty());
+ assertTrue(list instanceof RandomAccess);
+
+ HttpCookie cookie1 = new HttpCookie("cookie_name", "cookie_value");
+ URI uri1 = new URI("http://getcookies1.test.org");
+ cookieStore.add(uri1, cookie1);
+ list = cookieStore.getCookies();
+ assertTrue(list.contains(cookie1));
+
+ HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
+ URI uri2 = new URI("http://getcookies2.test.org");
+ cookieStore.add(uri2, cookie2);
+ list = cookieStore.getCookies();
+ assertEquals(2, list.size());
+ assertTrue(list.contains(cookie1));
+ assertTrue(list.contains(cookie2));
+
+ // duplicated cookie won't be selected.
+ cookieStore.add(uri2, cookie1);
+ list = cookieStore.getCookies();
+ assertEquals(2, list.size());
+ // expired cookie won't be selected.
+ HttpCookie cookie3 = new HttpCookie("cookie_name3", "cookie_value3");
+ cookie3.setMaxAge(-1357);
+ cookieStore.add(uri1, cookie3);
+ list = cookieStore.getCookies();
+ assertEquals(2, list.size());
+
+ try {
+ list.add(new HttpCookie("readOnlyName", "readOnlyValue"));
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ list.remove(new HttpCookie("readOnlyName", "readOnlyValue"));
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.CookieStore#getURIs()
+ * @since 1.6
+ */
+ public void test_getURIs() throws URISyntaxException {
+ List<URI> list = cookieStore.getURIs();
+ assertTrue(list.isEmpty());
+
+ URI uri1 = new URI("http://geturis1.test.com");
+ HttpCookie cookie1 = new HttpCookie("cookie_name1", "cookie_value1");
+ cookieStore.add(uri1, cookie1);
+ list = cookieStore.getURIs();
+ assertEquals("geturis1.test.com", list.get(0).getHost());
+
+ HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
+ cookieStore.add(uri1, cookie2);
+ list = cookieStore.getURIs();
+ assertEquals(1, list.size());
+
+ URI uri2 = new URI("http://geturis2.test.com");
+ cookieStore.add(uri2, cookie2);
+ list = cookieStore.getURIs();
+ assertEquals(2, list.size());
+ assertTrue(list.contains(uri1));
+ assertTrue(list.contains(uri2));
+ }
+
+ /**
+ * java.net.CookieStore#remove(URI, HttpCookie)
+ * @since 1.6
+ */
+ public void test_remove_LURI_LHttpCookie() throws URISyntaxException {
+ URI uri1 = new URI("http://remove1.test.com");
+ HttpCookie cookie1 = new HttpCookie("cookie_name1", "cookie_value1");
+ try {
+ cookieStore.remove(uri1, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertFalse(cookieStore.remove(uri1, cookie1));
+ assertFalse(cookieStore.remove(null, cookie1));
+
+ cookieStore.add(uri1, cookie1);
+ URI uri2 = new URI("http://remove2.test.com");
+ HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
+ cookieStore.add(uri2, cookie2);
+ assertTrue(cookieStore.remove(uri1, cookie1));
+ assertFalse(cookieStore.remove(uri1, cookie1));
+ assertEquals(2, cookieStore.getURIs().size());
+ assertEquals(1, cookieStore.getCookies().size());
+ assertTrue(cookieStore.remove(uri2, cookie2));
+ assertFalse(cookieStore.remove(uri2, cookie2));
+ assertEquals(2, cookieStore.getURIs().size());
+ assertEquals(0, cookieStore.getCookies().size());
+
+ assertTrue(cookieStore.removeAll());
+ cookieStore.add(uri1, cookie1);
+ cookieStore.add(uri2, cookie2);
+ HttpCookie cookie3 = new HttpCookie("cookie_name3", "cookie_value3");
+ assertFalse(cookieStore.remove(null, cookie3));
+ // No guarantees on behavior if we call remove with a different
+ // uri from the one originally associated with the cookie.
+ assertFalse(cookieStore.remove(null, cookie1));
+ assertTrue(cookieStore.remove(uri1, cookie1));
+ assertFalse(cookieStore.remove(uri1, cookie1));
+
+ assertEquals(2, cookieStore.getURIs().size());
+ assertEquals(1, cookieStore.getCookies().size());
+ assertTrue(cookieStore.remove(uri2, cookie2));
+ assertFalse(cookieStore.remove(uri2, cookie2));
+ assertEquals(2, cookieStore.getURIs().size());
+ assertEquals(0, cookieStore.getCookies().size());
+
+ cookieStore.removeAll();
+ // expired cookies can also be deleted.
+ cookie2.setMaxAge(-34857);
+ cookieStore.add(uri2, cookie2);
+ assertTrue(cookieStore.remove(uri2, cookie2));
+ assertFalse(cookieStore.remove(uri2, cookie2));
+ assertEquals(0, cookieStore.getCookies().size());
+
+ cookie2.setMaxAge(34857);
+ cookieStore.add(uri1, cookie1);
+ cookieStore.add(uri2, cookie1);
+ cookieStore.add(uri2, cookie2);
+ assertTrue(cookieStore.remove(uri1, cookie1));
+ assertFalse(cookieStore.remove(uri1, cookie1));
+ assertTrue(cookieStore.get(uri2).contains(cookie1));
+ assertTrue(cookieStore.get(uri2).contains(cookie2));
+ assertEquals(0, cookieStore.get(uri1).size());
+ cookieStore.remove(uri2, cookie2);
+
+ cookieStore.removeAll();
+ cookieStore.add(uri2, cookie2);
+ cookieStore.add(uri1, cookie1);
+ assertEquals(2, cookieStore.getCookies().size());
+ assertFalse(cookieStore.remove(uri2, cookie1));
+ assertTrue(cookieStore.remove(uri1, cookie1));
+ assertEquals(2, cookieStore.getURIs().size());
+ assertEquals(1, cookieStore.getCookies().size());
+ assertTrue(cookieStore.getCookies().contains(cookie2));
+
+ cookieStore.removeAll();
+ URI uri3 = new URI("http://remove3.test.com");
+ URI uri4 = new URI("http://test.com");
+ HttpCookie cookie4 = new HttpCookie("cookie_name4", "cookie_value4");
+ cookie4.setDomain(".test.com");
+ cookie2.setMaxAge(-34857);
+ cookie3.setMaxAge(-22);
+ cookie4.setMaxAge(-45);
+ cookieStore.add(uri1, cookie1);
+ cookieStore.add(uri2, cookie2);
+ cookieStore.add(uri3, cookie3);
+ cookieStore.add(uri4, cookie4);
+ assertEquals(0, cookieStore.get(uri2).size());
+ assertFalse(cookieStore.remove(uri2, cookie2));
+ assertTrue(cookieStore.remove(uri3, cookie3));
+ assertFalse(cookieStore.remove(uri4, cookie4));
+ }
+
+ /**
+ * java.net.CookieStore#test_removeAll()
+ * @since 1.6
+ */
+ public void test_removeAll() throws URISyntaxException {
+ assertFalse(cookieStore.removeAll());
+
+ URI uri1 = new URI("http://removeAll1.test.com");
+ HttpCookie cookie1 = new HttpCookie("cookie_name1", "cookie_value1");
+ cookieStore.add(uri1, cookie1);
+ URI uri2 = new URI("http://removeAll2.test.com");
+ HttpCookie cookie2 = new HttpCookie("cookie_name2", "cookie_value2");
+ cookieStore.add(uri2, cookie2);
+
+ assertTrue(cookieStore.removeAll());
+ assertTrue(cookieStore.getURIs().isEmpty());
+ assertTrue(cookieStore.getCookies().isEmpty());
+
+ assertFalse(cookieStore.removeAll());
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ cookieManager = new CookieManager();
+ cookieStore = cookieManager.getCookieStore();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ cookieManager = null;
+ cookieStore = null;
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramPacketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramPacketTest.java
new file mode 100644
index 0000000..2730b85
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramPacketTest.java
@@ -0,0 +1,338 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+import tests.support.Support_Configuration;
+
+public class DatagramPacketTest extends junit.framework.TestCase {
+
+ volatile boolean started = false;
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int)
+ */
+ public void test_Constructor$BI() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ assertEquals("Created incorrect packet", "Hello", new String(dp
+ .getData(), 0, dp.getData().length));
+ assertEquals("Wrong length", 5, dp.getLength());
+
+ // Regression for HARMONY-890
+ dp = new DatagramPacket(new byte[942], 4);
+ assertEquals(-1, dp.getPort());
+ try {
+ dp.getSocketAddress();
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int, int)
+ */
+ public void test_Constructor$BII() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 2, 3);
+ assertEquals("Created incorrect packet", "Hello", new String(dp
+ .getData(), 0, dp.getData().length));
+ assertEquals("Wrong length", 3, dp.getLength());
+ assertEquals("Wrong offset", 2, dp.getOffset());
+ }
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int, int,
+ *java.net.InetAddress, int)
+ */
+ public void test_Constructor$BIILjava_net_InetAddressI() throws IOException {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 2, 3,
+ InetAddress.getLocalHost(), 0);
+ assertEquals("Wrong host", InetAddress.getLocalHost(), dp.getAddress());
+ assertEquals("Wrong port", 0, dp.getPort());
+ assertEquals("Wrong length", 3, dp.getLength());
+ assertEquals("Wrong offset", 2, dp.getOffset());
+ }
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int,
+ *java.net.InetAddress, int)
+ */
+ public void test_Constructor$BILjava_net_InetAddressI() throws IOException {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5,
+ InetAddress.getLocalHost(), 0);
+ assertEquals("Wrong address", InetAddress.getLocalHost(), dp
+ .getAddress());
+ assertEquals("Wrong port", 0, dp.getPort());
+ assertEquals("Wrong length", 5, dp.getLength());
+ }
+
+ /**
+ * java.net.DatagramPacket#getAddress()
+ */
+ public void test_getAddress() throws IOException {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5,
+ InetAddress.getLocalHost(), 0);
+ assertEquals("Incorrect address returned", InetAddress.getLocalHost(),
+ dp.getAddress());
+ }
+
+ /**
+ * java.net.DatagramPacket#getData()
+ */
+ public void test_getData() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ assertEquals("Incorrect length returned", "Hello", new String(dp
+ .getData(), 0, dp.getData().length));
+ }
+
+ /**
+ * java.net.DatagramPacket#getLength()
+ */
+ public void test_getLength() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ assertEquals("Incorrect length returned", 5, dp.getLength());
+ }
+
+ /**
+ * java.net.DatagramPacket#getOffset()
+ */
+ public void test_getOffset() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 3, 2);
+ assertEquals("Incorrect length returned", 3, dp.getOffset());
+ }
+
+ /**
+ * java.net.DatagramPacket#getPort()
+ */
+ public void test_getPort() throws IOException {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5,
+ InetAddress.getLocalHost(), 1000);
+ assertEquals("Incorrect port returned", 1000, dp.getPort());
+
+ final InetAddress localhost = InetAddress.getLocalHost();
+ DatagramSocket socket = new DatagramSocket(0, localhost);
+ final int port = socket.getLocalPort();
+
+ socket.setSoTimeout(3000);
+ DatagramPacket packet = new DatagramPacket(new byte[] { 1, 2, 3, 4, 5,
+ 6 }, 6, localhost, port);
+ socket.send(packet);
+ socket.receive(packet);
+ socket.close();
+ assertTrue("datagram received wrong port: " + packet.getPort(), packet
+ .getPort() == port);
+ }
+
+ /**
+ * java.net.DatagramPacket#setAddress(java.net.InetAddress)
+ */
+ public void test_setAddressLjava_net_InetAddress() throws IOException {
+ InetAddress ia = InetAddress.getByName("127.0.0.1");
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5,
+ InetAddress.getLocalHost(), 0);
+ dp.setAddress(ia);
+ assertEquals("Incorrect address returned", ia, dp.getAddress());
+ }
+
+ /**
+ * java.net.DatagramPacket#setData(byte[], int, int)
+ */
+ public void test_setData$BII() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ dp.setData("Wagga Wagga".getBytes(), 2, 3);
+ assertEquals("Incorrect data set", "Wagga Wagga", new String(dp
+ .getData()));
+ }
+
+ /**
+ * java.net.DatagramPacket#setData(byte[])
+ */
+ public void test_setData$B() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ dp.setData("Ralph".getBytes());
+ assertEquals("Incorrect data set", "Ralph", new String(dp.getData(), 0,
+ dp.getData().length));
+ }
+
+ /**
+ * java.net.DatagramPacket#setLength(int)
+ */
+ public void test_setLengthI() {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5);
+ dp.setLength(1);
+ assertEquals("Failed to set packet length", 1, dp.getLength());
+ }
+
+ /**
+ * java.net.DatagramPacket#setPort(int)
+ */
+ public void test_setPortI() throws Exception {
+ DatagramPacket dp = new DatagramPacket("Hello".getBytes(), 5,
+ InetAddress.getLocalHost(), 1000);
+ dp.setPort(2000);
+ assertEquals("Port not set", 2000, dp.getPort());
+ }
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int,
+ *java.net.SocketAddress)
+ */
+ public void test_Constructor$BILjava_net_SocketAddress() throws IOException {
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ // Unsupported SocketAddress subclass
+ byte buf[] = new byte[1];
+ try {
+ new DatagramPacket(buf, 1, new UnsupportedSocketAddress());
+ fail("No exception when constructing using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // Case were we try to pass in null
+ try {
+ new DatagramPacket(buf, 1, null);
+ fail("No exception when constructing address using null");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // Now validate we can construct
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 2067);
+ DatagramPacket thePacket = new DatagramPacket(buf, 1, theAddress);
+ assertEquals("Socket address not set correctly (1)", theAddress,
+ thePacket.getSocketAddress());
+ assertEquals("Socket address not set correctly (2)", theAddress,
+ new InetSocketAddress(thePacket.getAddress(), thePacket
+ .getPort()));
+ }
+
+ /**
+ * java.net.DatagramPacket#DatagramPacket(byte[], int, int,
+ *java.net.SocketAddress)
+ */
+ public void test_Constructor$BIILjava_net_SocketAddress()
+ throws IOException {
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ // Unsupported SocketAddress subclass
+ byte buf[] = new byte[2];
+ try {
+ new DatagramPacket(buf, 1, 1, new UnsupportedSocketAddress());
+ fail("No exception when constructing using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // Case were we try to pass in null
+ try {
+ new DatagramPacket(buf, 1, 1, null);
+ fail("No exception when constructing address using null");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // now validate we can construct
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 2067);
+ DatagramPacket thePacket = new DatagramPacket(buf, 1, 1, theAddress);
+ assertEquals("Socket address not set correctly (1)", theAddress,
+ thePacket.getSocketAddress());
+ assertEquals("Socket address not set correctly (2)", theAddress,
+ new InetSocketAddress(thePacket.getAddress(), thePacket
+ .getPort()));
+ assertEquals("Offset not set correctly", 1, thePacket.getOffset());
+ }
+
+ /**
+ * java.net.DatagramPacket#getSocketAddress()
+ */
+ public void test_getSocketAddress() throws IOException {
+ byte buf[] = new byte[1];
+ DatagramPacket thePacket = new DatagramPacket(buf, 1);
+
+ // Validate get returns the value we set
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ thePacket = new DatagramPacket(buf, 1);
+ thePacket.setSocketAddress(theAddress);
+ assertEquals("Socket address not set correctly (1)", theAddress,
+ thePacket.getSocketAddress());
+ }
+
+ /**
+ * java.net.DatagramPacket#setSocketAddress(java.net.SocketAddress)
+ */
+ public void test_setSocketAddressLjava_net_SocketAddress()
+ throws IOException {
+
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ // Unsupported SocketAddress subclass
+ byte buf[] = new byte[1];
+ DatagramPacket thePacket = new DatagramPacket(buf, 1);
+ try {
+ thePacket.setSocketAddress(new UnsupportedSocketAddress());
+ fail("No exception when setting address using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // Case were we try to pass in null
+ thePacket = new DatagramPacket(buf, 1);
+ try {
+ thePacket.setSocketAddress(null);
+ fail("No exception when setting address using null");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+
+ // Now validate we can set it correctly
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 2049);
+ thePacket = new DatagramPacket(buf, 1);
+ thePacket.setSocketAddress(theAddress);
+ assertEquals("Socket address not set correctly (1)", theAddress,
+ thePacket.getSocketAddress());
+ assertEquals("Socket address not set correctly (2)", theAddress,
+ new InetSocketAddress(thePacket.getAddress(), thePacket
+ .getPort()));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketImplTest.java
new file mode 100644
index 0000000..e94a963
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketImplTest.java
@@ -0,0 +1,152 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocketImpl;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.SocketAddress;
+import java.net.SocketException;
+
+public class DatagramSocketImplTest extends junit.framework.TestCase {
+ /**
+ * java.net.DatagramSocketImpl#DatagramSocketImpl()
+ */
+ public void test_Constructor() throws Exception {
+ // regression test for Harmony-1117
+ MockDatagramSocketImpl impl = new MockDatagramSocketImpl();
+ assertNull(impl.getFileDescriptor());
+ }
+
+
+ public void test_connect() throws Exception {
+ MockDatagramSocketImpl impl = new MockDatagramSocketImpl();
+ InetAddress localhost = InetAddress.getByName("localhost"); //$NON-NLS-1$
+ // connect do nothing, so will not throw exception
+ impl.test_connect(localhost, 0);
+ impl.test_connect(localhost, -1);
+ impl.test_connect(null, -1);
+ // disconnect
+ impl.test_disconnect();
+ }
+}
+
+class MockDatagramSocketImpl extends DatagramSocketImpl {
+
+ @Override
+ public FileDescriptor getFileDescriptor() {
+ return super.getFileDescriptor();
+ }
+
+ @Override
+ protected void bind(int port, InetAddress addr) throws SocketException {
+ // empty
+ }
+
+ @Override
+ protected void close() {
+ // empty
+ }
+
+ @Override
+ protected void create() throws SocketException {
+ // empty
+ }
+
+ public Object getOption(int optID) throws SocketException {
+ return null;
+ }
+
+ @Override
+ protected byte getTTL() throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected int getTimeToLive() throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected void join(InetAddress addr) throws IOException {
+ // empty
+ }
+
+ @Override
+ protected void joinGroup(SocketAddress addr, NetworkInterface netInterface)
+ throws IOException {
+ // empty
+ }
+
+ @Override
+ protected void leave(InetAddress addr) throws IOException {
+ // empty
+ }
+
+ @Override
+ protected void leaveGroup(SocketAddress addr, NetworkInterface netInterface)
+ throws IOException {
+ // empty
+ }
+
+ @Override
+ protected int peek(InetAddress sender) throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected int peekData(DatagramPacket pack) throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected void receive(DatagramPacket pack) throws IOException {
+ // empty
+ }
+
+ @Override
+ protected void send(DatagramPacket pack) throws IOException {
+ // empty
+
+ }
+
+ public void setOption(int optID, Object val) throws SocketException {
+ // empty
+ }
+
+ @Override
+ protected void setTTL(byte ttl) throws IOException {
+ // empty
+ }
+
+ @Override
+ protected void setTimeToLive(int ttl) throws IOException {
+ // empty
+ }
+
+ public void test_connect(InetAddress inetAddr, int port) throws SocketException {
+ super.connect(inetAddr, port);
+ }
+
+ public void test_disconnect() {
+ super.disconnect();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java
new file mode 100644
index 0000000..e585b14
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java
@@ -0,0 +1,940 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.BindException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.DatagramSocketImpl;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.UnknownHostException;
+import java.nio.channels.DatagramChannel;
+
+public class DatagramSocketTest extends junit.framework.TestCase {
+
+ static final class DatagramServer extends Thread {
+
+ volatile boolean running = true;
+
+ private final boolean echo;
+ private final byte[] rbuf;
+ private final DatagramPacket rdp;
+ final DatagramSocket serverSocket;
+
+ public DatagramServer(InetAddress address, boolean echo)
+ throws IOException {
+ this.echo = echo;
+ rbuf = new byte[512];
+ rbuf[0] = -1;
+ rdp = new DatagramPacket(rbuf, rbuf.length);
+ serverSocket = new DatagramSocket(0, address);
+ serverSocket.setSoTimeout(2000);
+ }
+
+ public DatagramServer(InetAddress address) throws IOException {
+ this(address, true /* echo */);
+ }
+
+ public void run() {
+ try {
+ while (running) {
+ try {
+ serverSocket.receive(rdp);
+ if (echo) {
+ serverSocket.send(rdp);
+ }
+ } catch (InterruptedIOException e) {
+ }
+ }
+ } catch (IOException e) {
+ fail();
+ } finally {
+ serverSocket.close();
+ }
+ }
+
+ public int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ public void stopServer() {
+ running = false;
+ }
+ }
+
+ /**
+ * java.net.DatagramSocket#DatagramSocket()
+ */
+ public void test_Constructor() throws SocketException {
+ new DatagramSocket();
+ }
+
+ /**
+ * java.net.DatagramSocket#DatagramSocket(int)
+ */
+ public void test_ConstructorI() throws SocketException {
+ DatagramSocket ds = new DatagramSocket(0);
+ ds.close();
+ }
+
+ /**
+ * java.net.DatagramSocket#DatagramSocket(int, java.net.InetAddress)
+ */
+ public void test_ConstructorILjava_net_InetAddress() throws IOException {
+ DatagramSocket ds = new DatagramSocket(0, InetAddress.getLocalHost());
+ assertTrue("Created socket with incorrect port", ds.getLocalPort() != 0);
+ assertEquals("Created socket with incorrect address", InetAddress
+ .getLocalHost(), ds.getLocalAddress());
+ }
+
+ /**
+ * java.net.DatagramSocket#close()
+ */
+ public void test_close() throws UnknownHostException, SocketException {
+ DatagramSocket ds = new DatagramSocket(0);
+ DatagramPacket dp = new DatagramPacket("Test String".getBytes(), 11,
+ InetAddress.getLocalHost(), 0);
+ ds.close();
+ try {
+ ds.send(dp);
+ fail("Data sent after close");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ public void test_connectLjava_net_InetAddressI() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ InetAddress inetAddress = InetAddress.getLocalHost();
+ ds.connect(inetAddress, 0);
+ assertEquals("Incorrect InetAddress", inetAddress, ds.getInetAddress());
+ assertEquals("Incorrect Port", 0, ds.getPort());
+ ds.disconnect();
+
+ ds = new java.net.DatagramSocket();
+ inetAddress = InetAddress.getByName("FE80:0000:0000:0000:020D:60FF:FE0F:A776%4");
+ ds.connect(inetAddress, 0);
+ assertEquals(inetAddress, ds.getInetAddress());
+ ds.disconnect();
+ }
+
+ public void testConnect_connectToSelf() throws Exception {
+ // Create a connected datagram socket to test
+ // PlainDatagramSocketImpl.peek()
+ InetAddress localHost = InetAddress.getLocalHost();
+ final DatagramSocket ds = new DatagramSocket(0);
+ ds.connect(localHost, ds.getLocalPort());
+ DatagramPacket send = new DatagramPacket(new byte[10], 10, localHost,
+ ds.getLocalPort());
+ ds.send(send);
+
+ DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+ ds.setSoTimeout(2000);
+ ds.receive(receive);
+ ds.close();
+
+ assertEquals(10, receive.getLength());
+ assertEquals(localHost, receive.getAddress());
+ }
+
+ private static void assertPacketDataEquals(DatagramPacket p1, DatagramPacket p2)
+ throws Exception {
+ assertEquals(p1.getLength(), p2.getLength());
+ final byte[] p1Bytes = p1.getData();
+ final byte[] p2Bytes = p2.getData();
+
+ for (int i = 0; i < p1.getLength(); ++i) {
+ if (p1Bytes[p1.getOffset() + i] != p2Bytes[p2.getOffset() + i]) {
+ String expected = new String(p1Bytes, p1.getOffset(), p1.getLength(),
+ "UTF-8");
+ String actual = new String(p2Bytes, p2.getOffset(), p2.getLength(),
+ "UTF-8");
+ fail("expected: " + expected + ", actual: " + actual);
+ }
+ }
+ }
+
+ public void testConnect_echoServer() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ server.start();
+
+ ds.connect(Inet6Address.LOOPBACK, server.getPort());
+
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+
+ ds.send(send);
+ ds.setSoTimeout(2000);
+ ds.receive(receive);
+ ds.close();
+
+ assertEquals(sendBytes.length, receive.getLength());
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ }
+
+ // Validate that once connected we cannot send to another address.
+ public void testConnect_throwsOnAddressMismatch() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+
+ DatagramServer s1 = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramServer s2 = new DatagramServer(Inet6Address.LOOPBACK);
+ try {
+ ds.connect(Inet6Address.LOOPBACK, s1.getPort());
+ ds.send(new DatagramPacket(new byte[10], 10, Inet6Address.LOOPBACK, s2.getPort()));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ } finally {
+ ds.close();
+ s1.stopServer();
+ s2.stopServer();
+ }
+ }
+
+ // Validate that we can connect, then disconnect, then connect then
+ // send/recv.
+ public void testConnect_connectDisconnectConnectThenSendRecv() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ final DatagramServer broken = new DatagramServer(Inet6Address.LOOPBACK, false);
+ server.start();
+ broken.start();
+
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, broken.getPort());
+ ds.disconnect();
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
+
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+ ds.send(send);
+ ds.setSoTimeout(2000);
+ ds.receive(receive);
+ ds.close();
+
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ broken.stopServer();
+ }
+
+ // Validate that we can connect/disconnect then send/recv to any address
+ public void testConnect_connectDisconnectThenSendRecv() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ server.start();
+
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
+ ds.disconnect();
+
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length,
+ Inet6Address.LOOPBACK, serverPortNumber);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+ ds.send(send);
+ ds.setSoTimeout(2000);
+ ds.receive(receive);
+ ds.close();
+
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ }
+
+ public void testConnect_connectTwice() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ final DatagramServer broken = new DatagramServer(Inet6Address.LOOPBACK);
+ server.start();
+ broken.start();
+
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, broken.getPort());
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
+ ds.disconnect();
+
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length,
+ Inet6Address.LOOPBACK, serverPortNumber);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+ ds.send(send);
+ ds.setSoTimeout(2000);
+ ds.receive(receive);
+ ds.close();
+
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ broken.stopServer();
+ }
+
+ public void testConnect_zeroAddress() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ byte[] addressBytes = { 0, 0, 0, 0 };
+ InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
+ ds.connect(inetAddress, 0);
+
+ ds = new java.net.DatagramSocket();
+ byte[] addressTestBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0 };
+ inetAddress = InetAddress.getByAddress(addressTestBytes);
+ ds.connect(inetAddress, 0);
+ }
+
+ public void test_disconnect() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ InetAddress inetAddress = InetAddress.getLocalHost();
+ ds.connect(inetAddress, 0);
+ ds.disconnect();
+ assertNull("Incorrect InetAddress", ds.getInetAddress());
+ assertEquals("Incorrect Port", -1, ds.getPort());
+
+ ds = new DatagramSocket();
+ inetAddress = InetAddress.getByName("FE80:0000:0000:0000:020D:60FF:FE0F:A776%4");
+ ds.connect(inetAddress, 0);
+ ds.disconnect();
+ assertNull("Incorrect InetAddress", ds.getInetAddress());
+ assertEquals("Incorrect Port", -1, ds.getPort());
+ }
+
+ public void test_getLocalAddress() throws Exception {
+ // Test for method java.net.InetAddress
+ // java.net.DatagramSocket.getLocalAddress()
+ InetAddress local = InetAddress.getLocalHost();
+ DatagramSocket ds = new java.net.DatagramSocket(0, local);
+ assertEquals(InetAddress.getByName(InetAddress.getLocalHost().getHostName()), ds.getLocalAddress());
+
+ // now check behavior when the ANY address is returned
+ DatagramSocket s = new DatagramSocket(0);
+ assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(), s.getLocalAddress() instanceof Inet6Address);
+ s.close();
+ }
+
+ public void test_getLocalPort() throws SocketException {
+ DatagramSocket ds = new DatagramSocket();
+ assertTrue("Returned incorrect port", ds.getLocalPort() != 0);
+ }
+
+ public void test_getPort() throws IOException {
+ DatagramSocket theSocket = new DatagramSocket();
+ assertEquals("Expected -1 for remote port as not connected", -1,
+ theSocket.getPort());
+
+ // Now connect the socket and validate that we get the right port
+ int portNumber = 49152; // any valid port, even if it is unreachable
+ theSocket.connect(InetAddress.getLocalHost(), portNumber);
+ assertEquals("getPort returned wrong value", portNumber, theSocket
+ .getPort());
+ }
+
+ public void test_getReceiveBufferSize() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ ds.setReceiveBufferSize(130);
+ assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
+ ds.close();
+ try {
+ ds.getReceiveBufferSize();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_getSendBufferSize() throws Exception {
+ final DatagramSocket ds = new java.net.DatagramSocket(0);
+ ds.setSendBufferSize(134);
+ assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
+ ds.close();
+ try {
+ ds.getSendBufferSize();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_getSoTimeout() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ ds.setSoTimeout(100);
+ assertEquals("Returned incorrect timeout", 100, ds.getSoTimeout());
+ }
+
+ static final class TestDatagramSocketImpl extends DatagramSocketImpl {
+ // This field exists solely to force initialization of this class
+ // inside a test method.
+ public static final Object ACCESS = new Object();
+
+ @Override
+ protected void create() throws SocketException {
+ }
+
+ @Override
+ protected void bind(int arg0, InetAddress arg1)
+ throws SocketException {
+ }
+
+ @Override
+ protected void send(DatagramPacket arg0) throws IOException {
+ }
+
+ @Override
+ protected int peek(InetAddress arg0) throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected int peekData(DatagramPacket arg0) throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected void receive(DatagramPacket arg0) throws IOException {
+ }
+
+ @Override
+ protected void setTTL(byte arg0) throws IOException {
+ }
+
+ @Override
+ protected byte getTTL() throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected void setTimeToLive(int arg0) throws IOException {
+ }
+
+ @Override
+ protected int getTimeToLive() throws IOException {
+ return 0;
+ }
+
+ @Override
+ protected void join(InetAddress arg0) throws IOException {
+ }
+
+ @Override
+ protected void joinGroup(SocketAddress addr, NetworkInterface netInterface) throws IOException {
+
+ }
+
+ @Override
+ protected void leave(InetAddress arg0) throws IOException {
+ }
+
+ @Override
+ protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1)
+ throws IOException {
+ }
+
+ @Override
+ protected void close() {
+ }
+
+ public void setOption(int arg0, Object arg1) throws SocketException {
+ }
+
+ public Object getOption(int arg0) throws SocketException {
+ return null;
+ }
+ }
+
+ static final class TestDatagramSocket extends DatagramSocket {
+ // This field exists solely to force initialization of this class
+ // inside a test method.
+ public static final Object ACCESS = new Object();
+
+ public TestDatagramSocket(DatagramSocketImpl impl) {
+ super(impl);
+ }
+ }
+
+
+ public void testArchivedHarmonyRegressions() throws Exception {
+ // Regression for HARMONY-1118
+ assertNotNull(TestDatagramSocketImpl.ACCESS);
+ assertNotNull(TestDatagramSocket.ACCESS);
+
+ // Regression test for Harmony-2938
+ InetAddress i = InetAddress.getByName("127.0.0.1");
+ DatagramSocket d = new DatagramSocket(0, i);
+ try {
+ d.send(new DatagramPacket(new byte[] { 1 }, 1));
+ fail();
+ } catch (NullPointerException expected) {
+ } finally {
+ d.close();
+ }
+
+ // Regression test for Harmony-6413
+ InetSocketAddress addr = InetSocketAddress.createUnresolved(
+ "localhost", 0);
+ try {
+ new DatagramPacket(new byte[272], 3, addr);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_sendLjava_net_DatagramPacket_nullDestination() throws IOException {
+ DatagramSocket datagramSocket = new DatagramSocket(0);
+ byte[] data = { 65 };
+ DatagramPacket sendPacket = new DatagramPacket(data, data.length, null, 25000);
+ try {
+ datagramSocket.send(sendPacket);
+ fail();
+ } catch (NullPointerException expected) {
+ // Expected
+ } finally {
+ datagramSocket.close();
+ }
+
+ }
+
+ public void test_setSendBufferSizeI() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+ ds.setSendBufferSize(134);
+ assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
+ ds.close();
+ try {
+ ds.setSendBufferSize(1);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_setReceiveBufferSizeI() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
+ ds.setReceiveBufferSize(130);
+ assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
+
+ try {
+ ds.setReceiveBufferSize(0);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ ds.setReceiveBufferSize(-1);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ ds.close();
+
+ try {
+ ds.setReceiveBufferSize(1);
+ fail("SocketException was not thrown.");
+ } catch (SocketException e) {
+ //expected
+ }
+ }
+
+
+ public void test_ConstructorLjava_net_DatagramSocketImpl() {
+ class SimpleTestDatagramSocket extends DatagramSocket {
+ public SimpleTestDatagramSocket(DatagramSocketImpl impl) {
+ super(impl);
+ }
+ }
+
+ try {
+ new SimpleTestDatagramSocket(null);
+ fail("exception expected");
+ } catch (NullPointerException ex) {
+ // expected
+ }
+ }
+
+ public void test_ConstructorLjava_net_SocketAddress() throws Exception {
+ class UnsupportedSocketAddress extends SocketAddress {
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ DatagramSocket ds = new DatagramSocket(new InetSocketAddress(
+ InetAddress.getLocalHost(), 0));
+ assertTrue(ds.getBroadcast());
+ assertTrue("Created socket with incorrect port", ds.getLocalPort() != 0);
+ assertEquals("Created socket with incorrect address", InetAddress
+ .getLocalHost(), ds.getLocalAddress());
+
+ try {
+ ds = new java.net.DatagramSocket(new UnsupportedSocketAddress());
+ fail("No exception when constructing datagramSocket with unsupported SocketAddress type");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // regression for HARMONY-894
+ ds = new DatagramSocket(null);
+ assertTrue(ds.getBroadcast());
+ }
+
+
+ public void test_bindLjava_net_SocketAddress_null() throws Exception {
+ // validate if we pass in null that it picks an address for us.
+ DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
+ theSocket.bind(null);
+ assertNotNull(theSocket.getLocalSocketAddress());
+ theSocket.close();
+ }
+
+ public void test_bindLjava_net_SocketAddress_address_in_use() throws Exception {
+ DatagramSocket socket1 = new DatagramSocket(0);
+ try {
+ new DatagramSocket(socket1.getLocalPort());
+ fail();
+ } catch (SocketException expected) {
+ }
+ socket1.close();
+ }
+
+ public void test_bindLjava_net_SocketAddress_unsupported_address_type() throws Exception {
+ class mySocketAddress extends SocketAddress {
+ public mySocketAddress() {
+ }
+ }
+
+ // unsupported SocketAddress subclass
+ DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
+ try {
+ theSocket.bind(new mySocketAddress());
+ fail("No exception when binding using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException expected) {
+ }
+ theSocket.close();
+ }
+
+ public void test_isBound() throws Exception {
+ DatagramSocket theSocket = new DatagramSocket(0);
+ assertTrue(theSocket.isBound());
+ theSocket.close();
+
+ theSocket = new DatagramSocket(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ assertTrue(theSocket.isBound());
+ theSocket.close();
+
+ theSocket = new DatagramSocket(null);
+ assertFalse(theSocket.isBound());
+ theSocket.close();
+
+ // connect causes implicit bind
+ theSocket = new DatagramSocket(null);
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ assertTrue(theSocket.isBound());
+ theSocket.close();
+
+ // now test when we bind explicitely
+ InetSocketAddress theLocalAddress = new InetSocketAddress(Inet6Address.LOOPBACK, 0);
+ theSocket = new DatagramSocket(null);
+ assertFalse(theSocket.isBound());
+ theSocket.bind(theLocalAddress);
+ assertTrue(theSocket.isBound());
+ theSocket.close();
+ assertTrue(theSocket.isBound());
+ }
+
+ public void test_isConnected() throws Exception {
+ DatagramServer ds = new DatagramServer(Inet6Address.LOOPBACK);
+
+ // base test
+ DatagramSocket theSocket = new DatagramSocket(0);
+ assertFalse(theSocket.isConnected());
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
+ assertTrue(theSocket.isConnected());
+
+ // reconnect the socket and make sure we get the right answer
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
+ assertTrue(theSocket.isConnected());
+
+ // now disconnect the socket and make sure we get the right answer
+ theSocket.disconnect();
+ assertFalse(theSocket.isConnected());
+ theSocket.close();
+
+ // now check behavior when socket is closed when connected
+ theSocket = new DatagramSocket(0);
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
+ theSocket.close();
+ assertTrue(theSocket.isConnected());
+ }
+
+ public void test_getRemoteSocketAddress() throws Exception {
+ DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramSocket s = new DatagramSocket(0);
+ s.connect(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()));
+
+ assertEquals(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()),
+ s.getRemoteSocketAddress());
+ s.close();
+
+ // now create one that is not connected and validate that we get the
+ // right answer
+ DatagramSocket theSocket = new DatagramSocket(null);
+ theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ assertNull(theSocket.getRemoteSocketAddress());
+
+ // now connect and validate we get the right answer
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()));
+ assertEquals(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()),
+ theSocket.getRemoteSocketAddress());
+ theSocket.close();
+ }
+
+ public void test_getLocalSocketAddress_late_bind() throws Exception {
+ // An unbound socket should return null as its local address.
+ DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
+ assertNull(theSocket.getLocalSocketAddress());
+
+ // now bind the socket and make sure we get the right answer
+ InetSocketAddress localAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket.bind(localAddress);
+ assertEquals(localAddress.getAddress(), theSocket.getLocalAddress());
+ assertTrue(theSocket.getLocalPort() > 0);
+ theSocket.close();
+ }
+
+ public void test_getLocalSocketAddress_unbound() throws Exception {
+ InetSocketAddress localAddress1 = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ DatagramSocket s = new DatagramSocket(localAddress1);
+ assertEquals(localAddress1.getAddress(), s.getLocalAddress());
+ s.close();
+
+ InetSocketAddress remoteAddress = (InetSocketAddress) s.getRemoteSocketAddress();
+ assertNull(remoteAddress);
+ }
+
+ public void test_getLocalSocketAddress_ANY() throws Exception {
+ DatagramSocket s = new DatagramSocket(0);
+ try {
+ assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
+ ((InetSocketAddress) s.getLocalSocketAddress()).getAddress() instanceof Inet6Address);
+ } finally {
+ s.close();
+ }
+ }
+
+ public void test_setReuseAddressZ() throws Exception {
+ // test case were we set it to false
+ DatagramSocket theSocket1 = null;
+ DatagramSocket theSocket2 = null;
+ try {
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket1 = new DatagramSocket(null);
+ theSocket2 = new DatagramSocket(null);
+ theSocket1.setReuseAddress(false);
+ theSocket2.setReuseAddress(false);
+ theSocket1.bind(theAddress);
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
+ fail();
+ } catch (BindException expected) {
+ }
+ if (theSocket1 != null) {
+ theSocket1.close();
+ }
+ if (theSocket2 != null) {
+ theSocket2.close();
+ }
+
+ // test case were we set it to true
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket1 = new DatagramSocket(null);
+ theSocket2 = new DatagramSocket(null);
+ theSocket1.setReuseAddress(true);
+ theSocket2.setReuseAddress(true);
+ theSocket1.bind(theAddress);
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
+
+ if (theSocket1 != null) {
+ theSocket1.close();
+ }
+ if (theSocket2 != null) {
+ theSocket2.close();
+ }
+
+ // test the default case which we expect to be the same on all
+ // platforms
+ try {
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket1 = new DatagramSocket(null);
+ theSocket2 = new DatagramSocket(null);
+ theSocket1.bind(theAddress);
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
+ fail("No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
+ } catch (BindException expected) {
+ }
+ if (theSocket1 != null) {
+ theSocket1.close();
+ }
+ if (theSocket2 != null) {
+ theSocket2.close();
+ }
+
+ try {
+ theSocket1.setReuseAddress(true);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_getReuseAddress() throws Exception {
+ DatagramSocket theSocket = new DatagramSocket();
+ theSocket.setReuseAddress(true);
+ assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
+ theSocket.setReuseAddress(false);
+ assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
+ theSocket.close();
+ try {
+ theSocket.getReuseAddress();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_setBroadcastZ() throws Exception {
+ DatagramSocket theSocket = new DatagramSocket(0);
+ theSocket.setBroadcast(false);
+ byte theBytes[] = { -1, -1, -1, -1 };
+
+ // validate we cannot connect to the broadcast address when
+ // setBroadcast is false
+ try {
+ theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), 0));
+ fail();
+ } catch (Exception expected) {
+ }
+
+ // now validate that we can connect to the broadcast address when
+ // setBroadcast is true
+ theSocket.setBroadcast(true);
+ theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), 0));
+
+ theSocket.close();
+ try {
+ theSocket.setBroadcast(false);
+ fail();
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_getBroadcast() throws Exception {
+ DatagramSocket theSocket = new DatagramSocket();
+ theSocket.setBroadcast(true);
+ assertTrue("getBroadcast false when it should be true", theSocket.getBroadcast());
+ theSocket.setBroadcast(false);
+ assertFalse("getBroadcast true when it should be False", theSocket.getBroadcast());
+ }
+
+ public void test_setTrafficClassI() throws Exception {
+ int IPTOS_LOWCOST = 0x2;
+ int IPTOS_THROUGHPUT = 0x8;
+ DatagramSocket theSocket = new DatagramSocket(0);
+
+ // validate that value set must be between 0 and 255
+ try {
+ theSocket.setTrafficClass(256);
+ fail("No exception when traffic class set to 256");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ theSocket.setTrafficClass(-1);
+ fail("No exception when traffic class set to -1");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // now validate that we can set it to some good values
+ theSocket.setTrafficClass(IPTOS_LOWCOST);
+ theSocket.setTrafficClass(IPTOS_THROUGHPUT);
+ }
+
+
+ public void test_isClosed() throws Exception {
+ DatagramSocket theSocket = new DatagramSocket();
+ // validate isClosed returns expected values
+ assertFalse(theSocket.isClosed());
+ theSocket.close();
+ assertTrue(theSocket.isClosed());
+
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ theSocket = new DatagramSocket(theAddress);
+ assertFalse(theSocket.isClosed());
+ theSocket.close();
+ assertTrue(theSocket.isClosed());
+ }
+
+ public void test_getChannel() throws Exception {
+ assertNull(new DatagramSocket().getChannel());
+
+ DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramSocket ds = new DatagramSocket(0);
+ assertNull(ds.getChannel());
+ ds.disconnect();
+ ds.close();
+ server.stopServer();
+
+ DatagramChannel channel = DatagramChannel.open();
+ DatagramSocket socket = channel.socket();
+ assertEquals(channel, socket.getChannel());
+ socket.close();
+ }
+
+ public void testReceiveOversizePacket() throws Exception {
+ DatagramSocket ds = new DatagramSocket(0);
+ DatagramSocket sds = new DatagramSocket(0);
+
+ DatagramPacket rdp = new DatagramPacket("0123456789".getBytes("UTF-8"),
+ 5, Inet6Address.LOOPBACK, ds.getLocalPort());
+ sds.send(rdp);
+ sds.close();
+
+ byte[] recvBuffer = new byte[5];
+ DatagramPacket receive = new DatagramPacket(recvBuffer, recvBuffer.length);
+ ds.receive(receive);
+ ds.close();
+ assertEquals(new String("01234"), new String(recvBuffer, 0, recvBuffer.length, "UTF-8"));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/HttpCookieTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/HttpCookieTest.java
new file mode 100644
index 0000000..d1cf18f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/HttpCookieTest.java
@@ -0,0 +1,978 @@
+/*
+ * 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.tests.java.net;
+
+import junit.framework.TestCase;
+import java.net.HttpCookie;
+import java.util.List;
+import java.util.Locale;
+
+public class HttpCookieTest extends TestCase {
+ private Locale locale;
+
+ /**
+ * java.net.HttpCookie(String, String).
+ * @since 1.6
+ */
+ public void test_HttpCookie_LString_LString() {
+ assertNotNull(new HttpCookie("harmony_6", "test,sem"));
+ assertNotNull(new HttpCookie("harmony_6", null));
+ assertNotNull(new HttpCookie("harmony ", null));
+ assertEquals("harmony", new HttpCookie("harmony ", null).getName());
+
+ constructHttpCookie("", null);
+
+ String value = "value";
+ constructHttpCookie("", value);
+
+ constructHttpCookie("harmony,", value);
+ constructHttpCookie("harmony;", value);
+ constructHttpCookie("$harmony", value);
+ constructHttpCookie("n\tame", value);
+ constructHttpCookie("n\rame", value);
+ constructHttpCookie("n\r\name", value);
+ constructHttpCookie("Comment", value);
+ constructHttpCookie("CommentURL", value);
+ constructHttpCookie("Domain", value);
+ constructHttpCookie("Discard", value);
+ constructHttpCookie("Max-Age", value);
+ constructHttpCookie(" Path ", value);
+ constructHttpCookie("Port ", value);
+ constructHttpCookie("SeCure", value);
+ constructHttpCookie("VErsion", value);
+ constructHttpCookie("expires", value);
+ constructHttpCookie("na\u0085me", value);
+ constructHttpCookie("\u2028me", value);
+ constructHttpCookie("na\u2029me", value);
+
+ try {
+ new HttpCookie(null, value);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new HttpCookie("\u007f", value);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ HttpCookie cookie = new HttpCookie("harmony!", null);
+ assertEquals("harmony!", cookie.getName());
+
+ cookie = new HttpCookie("harmon$y", null);
+ assertEquals("harmon$y", cookie.getName());
+
+ }
+
+ private static void constructHttpCookie(String name, String value) {
+ try {
+ new HttpCookie(name, value);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.HttpCookie#domainMatches(String, String).
+ * @since 1.6
+ */
+ public void test_DomainMatches() {
+
+ /*
+ * Rule 1: A host isn't in a domain (RFC 2965 sec. 3.3.2) if: The value
+ * for the Domain attribute contains no embedded dots, and the value is
+ * not .local.
+ */
+ boolean match = HttpCookie.domainMatches("hostname", "hostname");
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(".com", "test.com");
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(".com.", "test.com");
+ assertFalse(match);
+
+ // During comparison, host name is transformed to effective host name
+ // first.
+ match = HttpCookie.domainMatches(".local", "hostname");
+ assertTrue(match);
+
+ /*
+ * Rule 3: The request-host is a HDN (not IP address) and has the form
+ * HD, where D is the value of the Domain attribute, and H is a string
+ * that contains one or more dots.
+ */
+ match = HttpCookie.domainMatches(".c.d", "a.b.c.d");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches("c.d", "a.b.c.d");
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(".foo.com", "y.x.foo.com");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches(".foo.com", "x.foo.com");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches(".local", "hostname.local");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches(".ajax.com", "a.ajax.com");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches(".ajax.com", "a.AJAX.com");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches("...", "test...");
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(".ajax.com", "b.a.AJAX.com");
+ assertTrue(match);
+
+ match = HttpCookie.domainMatches(".a", "b.a");
+ assertFalse(match);
+
+ // when either parameter is null
+ match = HttpCookie.domainMatches(".ajax.com", null);
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(null, null);
+ assertFalse(match);
+
+ match = HttpCookie.domainMatches(null, "b.a.AJAX.com");
+ assertFalse(match);
+ }
+
+ /**
+ * java.net.HttpCookie#getVersion(), setVersion(int).
+ * @since 1.6
+ */
+ public void test_Get_SetVersion() {
+ HttpCookie cookie = new HttpCookie("name", "value");
+ assertEquals(1, cookie.getVersion());
+ cookie.setVersion(0);
+ assertEquals(0, cookie.getVersion());
+ cookie.setVersion(1);
+ assertEquals(1, cookie.getVersion());
+
+ try {
+ cookie.setVersion(-1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ cookie.setVersion(2);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.HttpCookie#getValue(), setValue(String)
+ * @since 1.6
+ */
+ public void test_Get_SetValue() {
+ HttpCookie cookie = new HttpCookie("name", "value");
+ assertEquals("value", cookie.getValue());
+ cookie.setValue("newValue");
+ assertEquals("newValue", cookie.getValue());
+
+ cookie.setValue(null);
+ assertNull(cookie.getValue());
+
+ cookie.setValue("na\u64DEme");
+ assertEquals("na\u64DEme", cookie.getValue());
+ cookie.setVersion(0);
+ cookie.setValue("{(new value, 11)}");
+ assertEquals("{(new value, 11)}", cookie.getValue());
+ }
+
+ /**
+ * java.net.HttpCookie#getName()
+ * @since 1.6
+ */
+ public void test_GetName() {
+ HttpCookie cookie = new HttpCookie("testName", "value");
+ assertEquals("testName", cookie.getName());
+ }
+
+ /**
+ * java.net.HttpCookie#getSecure(), setSecure(boolean)
+ * @since 1.6
+ */
+ public void test_Get_SetSecure() {
+ HttpCookie cookie = new HttpCookie("testName", "value");
+ assertFalse(cookie.getSecure());
+ cookie.setVersion(0);
+ assertFalse(cookie.getSecure());
+
+ cookie.setSecure(true);
+ assertTrue(cookie.getSecure());
+ cookie.setSecure(false);
+ cookie.setVersion(1);
+ assertFalse(cookie.getSecure());
+ }
+
+ /**
+ * java.net.HttpCookie#getPath(), setPath(String)
+ * @since 1.6
+ */
+ public void test_Get_SetPath() {
+ HttpCookie cookie = new HttpCookie("name", "test new value");
+ assertNull(cookie.getPath());
+
+ cookie.setPath("{}() test,; 43!@");
+ assertEquals("{}() test,; 43!@", cookie.getPath());
+
+ cookie.setPath(" test");
+ assertEquals(" test", cookie.getPath());
+
+ cookie.setPath("\u63DF\u64DE");
+ cookie.setDomain("test");
+ assertEquals("\u63DF\u64DE", cookie.getPath());
+ }
+
+ /**
+ * java.net.HttpCookie#getMaxAge(), setMaxAge(long)
+ * @since 1.6
+ */
+ public void test_Get_SetMaxAge() {
+ HttpCookie cookie = new HttpCookie("name", "test new value");
+ assertEquals(-1, cookie.getMaxAge());
+
+ cookie.setMaxAge(Long.MAX_VALUE);
+ assertEquals(Long.MAX_VALUE, cookie.getMaxAge());
+
+ cookie.setMaxAge(Long.MIN_VALUE);
+ cookie.setDiscard(false);
+ assertEquals(Long.MIN_VALUE, cookie.getMaxAge());
+ }
+
+ /**
+ * java.net.HttpCookie#getDomain(), setDomain(String)
+ * @since 1.6
+ */
+ public void test_Get_SetDomain() {
+ HttpCookie cookie = new HttpCookie("name", "test new value");
+ assertNull(cookie.getDomain());
+
+ cookie.setDomain("a.b.d.c.com.");
+ assertEquals("a.b.d.c.com.", cookie.getDomain());
+
+ cookie.setDomain(" a.b.d.c.com. ");
+ assertEquals(" a.b.d.c.com. ", cookie.getDomain());
+
+ cookie.setPath("temp/subTemp");
+ cookie.setDomain("xy.foo.bar.de.edu");
+ assertEquals("xy.foo.bar.de.edu", cookie.getDomain());
+ }
+
+ /**
+ * java.net.HttpCookie#getPortlist(), setPortlist(String)
+ * @since 1.6
+ */
+ public void test_Get_SetPortlist() {
+ HttpCookie cookie = new HttpCookie("cookieName", "cookieName value");
+ assertNull(cookie.getPortlist());
+
+ cookie.setPortlist("80,23,20");
+ assertEquals("80,23,20", cookie.getPortlist());
+ cookie.setPortlist("abcdefg1234567");
+ cookie.setValue("cookie value again");
+ assertEquals("abcdefg1234567", cookie.getPortlist());
+ }
+
+ /**
+ * java.net.HttpCookie#getDiscard(), setDiscard(boolean)
+ * @since 1.6
+ */
+ public void test_Get_SetDiscard() {
+ HttpCookie cookie = new HttpCookie("cookie'sName",
+ "cookie's Test value");
+ assertFalse(cookie.getDiscard());
+
+ cookie.setDiscard(true);
+ assertTrue(cookie.getDiscard());
+ cookie.setDiscard(false);
+ cookie.setMaxAge(-1);
+ assertFalse(cookie.getDiscard());
+ }
+
+ /**
+ * java.net.HttpCookie#getCommentURL(), setCommentURL(String)
+ * @since 1.6
+ */
+ public void test_Get_SetCommentURL() {
+ HttpCookie cookie = new HttpCookie("cookie'\"sName",
+ "cookie's Test value");
+ assertNull(cookie.getCommentURL());
+
+ cookie.setCommentURL("http://www.test.com");
+ assertEquals("http://www.test.com", cookie.getCommentURL());
+
+ cookie.setCommentURL("schema://harmony.test.org");
+ cookie.setComment("just a comment");
+ assertEquals("schema://harmony.test.org", cookie.getCommentURL());
+ }
+
+ /**
+ * java.net.HttpCookie#getComment(), setComment(String)
+ * @since 1.6
+ */
+ public void test_Get_SetComment() {
+ HttpCookie cookie = new HttpCookie("cookie'\"sName?",
+ "cookie's Test??!@# value");
+ assertNull(cookie.getComment());
+
+ cookie.setComment("");
+ assertEquals("", cookie.getComment());
+
+ cookie.setComment("cookie''s @#$!&*()");
+ cookie.setVersion(0);
+ assertEquals("cookie''s @#$!&*()", cookie.getComment());
+ }
+
+ /**
+ * java.net.HttpCookie#hasExpired()
+ * @since 1.6
+ */
+ public void test_HasExpired() {
+ HttpCookie cookie = new HttpCookie("cookie'\"sName123456",
+ "cookie's Test?()!@# value");
+ assertFalse(cookie.hasExpired());
+
+ cookie.setMaxAge(0);
+ assertTrue(cookie.hasExpired());
+
+ cookie.setMaxAge(Long.MAX_VALUE);
+ cookie.setVersion(0);
+ assertFalse(cookie.hasExpired());
+
+ cookie.setMaxAge(Long.MIN_VALUE);
+ cookie.setDiscard(false);
+ assertTrue(cookie.hasExpired());
+
+ cookie.setDiscard(true);
+ cookie.setMaxAge(-1);
+ assertFalse(cookie.hasExpired());
+ }
+
+ /**
+ * java.net.HttpCookie#equals()
+ * @since 1.6
+ */
+ public void test_Equals() {
+ Object obj = new Object();
+ HttpCookie cookie = new HttpCookie("test", "testValue");
+ HttpCookie cookie2 = new HttpCookie("TesT", "TEstValue");
+
+ assertFalse(cookie.equals(obj));
+ assertFalse(cookie.equals(null));
+ assertTrue(cookie2.equals(cookie));
+ assertTrue(cookie.equals(cookie2));
+ assertTrue(cookie.equals(cookie));
+
+ cookie.setDomain(" test");
+ cookie2.setDomain("test");
+ assertFalse(cookie.equals(cookie2));
+ cookie.setDomain("TEST");
+ assertTrue(cookie.equals(cookie2));
+
+ cookie.setPath("temp\\e");
+ assertFalse(cookie.equals(cookie2));
+ cookie2.setPath("temp\\E");
+ assertFalse(cookie.equals(cookie2));
+
+ cookie.setDiscard(true);
+ cookie.setMaxAge(-1234);
+ cookie2.setPath("temp\\e");
+ assertTrue(cookie.equals(cookie2));
+ }
+
+ /**
+ * java.net.HttpCookie#clone()
+ * @since 1.6
+ */
+ public void test_Clone() {
+ HttpCookie cookie = new HttpCookie("test", "testValue");
+ cookie.setMaxAge(33l);
+ cookie.setComment("test comment");
+ HttpCookie cloneCookie = (HttpCookie) cookie.clone();
+ assertNotSame(cloneCookie, cookie);
+ assertEquals("test", cloneCookie.getName());
+ assertEquals(33l, cloneCookie.getMaxAge());
+ assertEquals("test comment", cloneCookie.getComment());
+ }
+
+ /**
+ * java.net.HttpCookie#toString()
+ * @since 1.6
+ */
+ public void test_ToString() {
+ HttpCookie cookie = new HttpCookie("test", "testValue");
+ cookie.setComment("ABCd");
+ cookie.setCommentURL("\u63DF");
+ cookie.setDomain(".B.com");
+ cookie.setDiscard(true);
+ cookie.setMaxAge(Integer.MAX_VALUE);
+ cookie.setPath("temp/22RuTh");
+ cookie.setPortlist("80.562Ab");
+ cookie.setSecure(true);
+ cookie.setVersion(1);
+
+ assertEquals(
+ "test=\"testValue\";$Path=\"temp/22RuTh\";$Domain=\".b.com\";$Port=\"80.562Ab\"",
+ cookie.toString());
+
+ cookie.setPath(null);
+ assertEquals(
+ "test=\"testValue\";$Domain=\".b.com\";$Port=\"80.562Ab\"",
+ cookie.toString());
+ cookie.setComment(null);
+ assertEquals(
+ "test=\"testValue\";$Domain=\".b.com\";$Port=\"80.562Ab\"",
+ cookie.toString());
+ cookie.setPortlist(null);
+ assertEquals("test=\"testValue\";$Domain=\".b.com\"", cookie.toString());
+ cookie.setDomain(null);
+ assertEquals("test=\"testValue\"", cookie.toString());
+
+ cookie.setVersion(0);
+ cookie.setPortlist("80,8000");
+ assertEquals("test=testValue", cookie.toString());
+ }
+
+ /**
+ * java.net.HttpCookie#hashCode()
+ * @since 1.6
+ */
+ public void test_HashCode() {
+ HttpCookie cookie = new HttpCookie("nAmW_1", "value_1");
+ assertEquals(-1052814577, cookie.hashCode());
+
+ cookie.setDomain("a.b.c.de");
+ assertEquals(1222695220, cookie.hashCode());
+
+ cookie.setPath("3kmxiq;1");
+ assertEquals(-675006347, cookie.hashCode());
+ cookie.setPath("3KmxiQ;1");
+ assertEquals(989616181, cookie.hashCode());
+
+ cookie.setValue("Vw0,22_789");
+ assertEquals(989616181, cookie.hashCode());
+ cookie.setComment("comment");
+ assertEquals(989616181, cookie.hashCode());
+
+ cookie.setDomain("");
+ assertEquals(-1285893616, cookie.hashCode());
+ }
+
+ /**
+ * java.net.HttpCookie#parse(String) for exception cases
+ * @since 1.6
+ */
+ public void test_Parse_exception() {
+ try {
+ HttpCookie.parse(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ /*
+ * Please note that Netscape draft specification does not fully conform
+ * to the HTTP header format. Netscape draft does not specify whether
+ * multiple cookies may be sent in one header. Hence, comma character
+ * may be present in unquoted cookie value or unquoted parameter value.
+ * Refer to <a
+ * href="http://jakarta.apache.org/commons/httpclient/apidocs/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.html#parse(java.lang.String,%20int,%20java.lang.String,%20boolean,%20java.lang.String)">
+ * http://jakarta.apache.org/commons/httpclient/apidocs/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.html#parse(java.lang.String,%20int,%20java.lang.String,%20boolean,%20java.lang.String)
+ * </a>
+ */
+ // violates the cookie specification's syntax
+ checkInvalidCookie("invalid cookie name");
+ checkInvalidCookie("Set-Cookie2:");
+ checkInvalidCookie("name");
+ checkInvalidCookie("$name=");
+ checkInvalidCookie("Set-Cookie2:$name=");
+ checkInvalidCookie("Set-Cookie:$");
+ checkInvalidCookie("Set-Cookie");
+
+ // cookie name contains llegal characters
+ checkInvalidCookie("Set-Cookie:n,ame=");
+ checkInvalidCookie("Set-Cookie2:n\name=");
+ checkInvalidCookie("Set-Cookie2:n,ame=");
+ checkInvalidCookie("Set-Cookie2:n\tame=");
+ checkInvalidCookie("Set-Cookie2:n\rame=");
+ checkInvalidCookie("Set-Cookie2:n\r\name=");
+ checkInvalidCookie("Set-Cookie2:na\u0085me=");
+ checkInvalidCookie("Set-Cookie2:na\u2028me=");
+ checkInvalidCookie("Set-Cookie2:na\u2029me=");
+ checkInvalidCookie("Set-Cookie2:=");
+ checkInvalidCookie("Set-Cookie2:name=tes,t");
+
+ // 'CommentURL' is one of the tokens reserved, case-insensitive
+ checkInvalidCookie("Set-Cookie2:COmmentURL=\"lala\"");
+
+ // check value
+ checkInvalidCookie("Set-Cookie2:val,ue");
+ checkInvalidCookie("Set-Cookie2:name=test;comMent=sent,ence");
+ checkInvalidCookie("Set-Cookie2:name=test;comMentUrL=u,rl");
+ checkInvalidCookie("Set-Cookie2:name=test;Discard=fa,lse");
+ checkInvalidCookie("Set-Cookie2:name=test;Disc,ard");
+ checkInvalidCookie("Set-Cookie2:name=test;Domain=u,rl");
+ checkInvalidCookie("Set-Cookie2:name=test;Path=pa,th");
+ checkInvalidCookie("Set-Cookie2:name=test;Secure=se,cure");
+ checkInvalidCookie("Set-Cookie2:name=test;se,cure");
+ checkInvalidCookie("Set-Cookie2:name=test;Max-Age=se,cure");
+ checkInvalidCookie("Set-Cookie2:name=test;Max-Age=");
+ checkInvalidCookie("Set-Cookie2:name=test;Max-Age=max-age");
+ checkInvalidCookie("Set-Cookie2:name=test;Max-Age=1000.0");
+ }
+
+ /**
+ * java.net.HttpCookie#parse(String) for locales other than
+ * Locale.ENGLISH.
+ * @since 1.6
+ */
+ public void test_Parse_locale() {
+ Locale.setDefault(Locale.FRENCH);
+ List<HttpCookie> list = HttpCookie
+ .parse("Set-Cookie:name=test;expires=Thu, 30-Oct-2008 19:14:07 GMT;");
+ HttpCookie cookie = list.get(0);
+ assertTrue(cookie.hasExpired());
+
+ Locale.setDefault(Locale.GERMAN);
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;expires=Sun, 30-Oct-2005 19:14:07 GMT;");
+ cookie = list.get(0);
+ assertTrue(cookie.hasExpired());
+
+ Locale.setDefault(Locale.KOREA);
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;max-age=1234;expires=Sun, 30-Oct-2005 19:14:07 GMT;");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals(1234, cookie.getMaxAge());
+ assertFalse(cookie.hasExpired());
+
+ Locale.setDefault(Locale.TAIWAN);
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;max-age=-12345;");
+ cookie = list.get(0);
+ assertEquals(-12345, cookie.getMaxAge());
+ assertTrue(cookie.hasExpired());
+
+ // Locale does not affect version 1 cookie.
+ Locale.setDefault(Locale.ITALIAN);
+ list = HttpCookie.parse("Set-Cookie2:name=test;max-age=1000");
+ cookie = list.get(0);
+ assertEquals(1000, cookie.getMaxAge());
+ assertFalse(cookie.hasExpired());
+ }
+
+ /**
+ * java.net.HttpCookie#parse(String) for normal cases
+ * @since 1.6
+ */
+ public void test_Parse() {
+ List<HttpCookie> list = HttpCookie.parse("test=\"null\"");
+ HttpCookie cookie = list.get(0);
+ // when two '"' presents, the parser ignores it.
+ assertEquals("null", cookie.getValue());
+ assertNull(cookie.getComment());
+ assertNull(cookie.getCommentURL());
+ assertFalse(cookie.getDiscard());
+ assertNull(cookie.getDomain());
+ assertEquals(-1, cookie.getMaxAge());
+ assertNull(cookie.getPath());
+ assertNull(cookie.getPortlist());
+ assertFalse(cookie.getSecure());
+ // default version is 0
+ assertEquals(0, cookie.getVersion());
+
+ list = HttpCookie.parse("Set-cookie2:name=\"tes,t\"");
+ cookie = list.get(0);
+ // when two '"' presents, the parser ignores it.
+ assertEquals("tes,t", cookie.getValue());
+
+ // If cookie header = Set-Cookie2, version = 1
+ list = HttpCookie
+ .parse("Set-cookie2:test=null\";;Port=abde,82;Path=/temp;;;Discard;commentURl=http://harmonytest.org;Max-age=-10;");
+ cookie = list.get(0);
+ assertEquals("null\"", cookie.getValue());
+ assertEquals(1, cookie.getVersion());
+ assertEquals("/temp", cookie.getPath());
+ assertTrue(cookie.getDiscard());
+ assertEquals("http://harmonytest.org", cookie.getCommentURL());
+ assertEquals(-10l, cookie.getMaxAge());
+ assertTrue(cookie.hasExpired());
+ assertEquals("abde,82", cookie.getPortlist());
+ // Version 0 cookie
+ list = HttpCookie
+ .parse("Set-Cookie:name=tes,t;Comment=version1-cookie;Discard=false;commentURL=vers\nion1-cookie-url;Domain=x.y;");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals("tes,t", cookie.getValue());
+ assertEquals("name", cookie.getName());
+ assertEquals("version1-cookie", cookie.getComment());
+ assertEquals("vers\nion1-cookie-url", cookie.getCommentURL());
+ assertEquals("x.y", cookie.getDomain());
+ assertTrue(cookie.getDiscard());
+
+ // Check value
+ checkValidValue("Set-Cookie:", "val,ue");
+ checkValidValue("Set-Cookie:", "val\nue");
+ checkValidValue("Set-Cookie:", "value=value");
+ checkValidValue("Set-Cookie2:", "val\nue");
+ checkValidValue("Set-Cookie2:", "val\u2029ue");
+ checkValidValue("Set-Cookie2:", "value=value");
+
+ // Check comment
+ // In RFC 2965 '=' is mandatory, but this is not the case in RI.
+ list = HttpCookie.parse("Set-Cookie:name=tes,t;Comment;");
+ cookie = list.get(0);
+ assertNull(cookie.getComment());
+
+ list = HttpCookie
+ .parse("Set-Cookie:name=tes,t;Comment=sentence;Comment=anotherSentence");
+ cookie = list.get(0);
+ assertEquals("sentence", cookie.getComment());
+
+ // Check CommentURL
+ list = HttpCookie
+ .parse("Set-Cookie:name=tes,t;Commenturl;commentuRL=(la,la)");
+ cookie = list.get(0);
+ assertEquals("(la,la)", cookie.getCommentURL());
+
+ // Check Domain
+ list = HttpCookie.parse("Set-Cookie:name=test;Domain=a_domain");
+ cookie = list.get(0);
+ assertEquals("a_domain", cookie.getDomain());
+
+ // Check Path
+ list = HttpCookie.parse("Set-Cookie:name=test;PaTh=pa$th");
+ cookie = list.get(0);
+ assertEquals("pa$th", cookie.getPath());
+
+ // Check Max-Age
+ list = HttpCookie.parse("Set-Cookie:name=test;Max-Age=1000");
+ cookie = list.get(0);
+ assertEquals(1000, cookie.getMaxAge());
+
+ list = HttpCookie.parse("Set-Cookie:name=test;Max-Age=-1000");
+ cookie = list.get(0);
+ assertEquals(-1000, cookie.getMaxAge());
+
+ // TODO: Uncomment when Long.parseLong() accepts numbers with a leading +
+ // list = HttpCookie.parse("Set-Cookie:name=test;max-age=+12345;");
+ // cookie = list.get(0);
+ // assertEquals(12345, cookie.getMaxAge());
+
+ list = HttpCookie.parse("Set-Cookie:name=test;max-age=0;");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getMaxAge());
+
+ // Check portlist
+ list = HttpCookie.parse("Set-Cookie:name=tes,t;port");
+ cookie = list.get(0);
+ assertEquals("", cookie.getPortlist());
+
+ list = HttpCookie.parse("Set-Cookie:name=tes,t;port=");
+ cookie = list.get(0);
+ assertEquals("", cookie.getPortlist());
+
+ list = HttpCookie.parse("Set-Cookie:name=tes,t;port=123 345");
+ cookie = list.get(0);
+ assertEquals("123 345", cookie.getPortlist());
+
+ list = HttpCookie.parse("Set-Cookie:name=tes,t;port=123,345");
+ cookie = list.get(0);
+ assertEquals("123,345", cookie.getPortlist());
+
+ // Check Secure
+ list = HttpCookie.parse("Set-Cookie:name=test;secure");
+ cookie = list.get(0);
+ assertTrue(cookie.getSecure());
+
+ list = HttpCookie.parse("Set-Cookie:name=test;secure=fa");
+ cookie = list.get(0);
+ assertTrue(cookie.getSecure());
+ assertFalse(cookie.hasExpired());
+
+ list = HttpCookie.parse("Set-Cookie2:name=test;secure=false");
+ cookie = list.get(0);
+ assertTrue(cookie.getSecure());
+
+ // Check expire
+ list = HttpCookie.parse("Set-Cookie:name=test;expires=2006-10-23");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getMaxAge());
+ assertTrue(cookie.hasExpired());
+
+ // Also recognize invalid date
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;expires=Sun, 29-Feb-1999 19:14:07 GMT");
+ cookie = list.get(0);
+ assertTrue(cookie.getMaxAge() < 0);
+ assertTrue(cookie.hasExpired());
+
+ // Parse multiple cookies
+ list = HttpCookie
+ .parse("Set-Cookie2:name=test;,Set-Cookie2:name2=test2;comment=c234;");
+ cookie = list.get(0);
+ assertEquals("name", cookie.getName());
+ assertEquals(1, cookie.getVersion());
+ assertEquals("test", cookie.getValue());
+ cookie = list.get(1);
+ assertEquals(1, cookie.getVersion());
+ // From the second cookie, the "set-cookie2" header does not take effect
+ assertEquals("Set-Cookie2:name2", cookie.getName());
+ assertEquals("c234", cookie.getComment());
+
+ list = HttpCookie.parse("Set-Cookie2:name=test,name2=test2");
+ assertEquals(1, list.get(0).getVersion());
+ assertEquals(1, list.get(1).getVersion());
+
+ // Must begin with "set-cookie2" header
+ list = HttpCookie.parse("name=test,Set-Cookie2:name2=test2");
+ cookie = list.get(0);
+ assertEquals(1, list.size());
+
+ HttpCookie c = HttpCookie.parse(
+ "Set-cookie:NAME2=VALUE2;path=/t;domain=.b.c;version=1").get(0);
+ assertEquals(1, c.getVersion());
+
+ c = HttpCookie.parse(
+ "Set-cookie2:NAME2=VALUE2;path=/t;domain=.b.c;version=0")
+ .get(0);
+ assertEquals(1, c.getVersion());
+
+ list = HttpCookie.parse("Set-cookie:null=;Domain=null;Port=null");
+ cookie = list.get(0);
+
+ assertNotNull(cookie.getValue());
+ assertNotNull(cookie.getName());
+ assertNotNull(cookie.getDomain());
+ assertNotNull(cookie.getPortlist());
+
+ try {
+ list = HttpCookie
+ .parse("Set-Cookie:a name=tes,t;Commenturl;commentuRL=(la,la);path=hello");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException expected) {
+ }
+
+
+ list = HttpCookie
+ .parse("Set-Cookie:name=tes,t;Commenturl;commentuRL=(la,la);commentuRL=hello");
+ cookie = list.get(0);
+ assertEquals("(la,la)", cookie.getCommentURL());
+
+ list = HttpCookie
+ .parse("Set-Cookie:name=tes,t;Commenturl;commentuRL=(la,la); path =hello");
+ cookie = list.get(0);
+ assertEquals("(la,la)", cookie.getCommentURL());
+ assertEquals("hello", cookie.getPath());
+
+ try {
+ list = HttpCookie
+ .parse("a Set-Cookie:name=tes,t;Commenturl;commentuRL=(la,la);path=hello");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_Parse_httpOnly() {
+ // Default is !httpOnly.
+ List<HttpCookie> list = HttpCookie.parse("Set-Cookie: SID=31d4d96e407aad42");
+ HttpCookie cookie = list.get(0);
+
+ // Well formed, simple.
+ list = HttpCookie.parse("Set-Cookie: SID=31d4d96e407aad42; HttpOnly");
+ cookie = list.get(0);
+
+ // Well formed, other attributes present.
+ list = HttpCookie.parse("Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
+ cookie = list.get(0);
+ assertTrue(cookie.getSecure());
+ assertEquals("/", cookie.getPath());
+
+ // Mangled spacing, casing and attributes that have an (ignored) value.
+ list = HttpCookie.parse("Set-Cookie:SID=31d4d96e407aad42;Path=/;secure=false;httponly=false");
+ cookie = list.get(0);
+ assertTrue(cookie.getSecure());
+ assertEquals("/", cookie.getPath());
+ }
+
+ /**
+ * java.net.HttpCookie#parse(String) for version conflict cases
+ * @since 1.6
+ */
+ public void test_Parse_versionConflict() {
+ // If attribute expires presents, cookie will be recognized as version
+ // 0. No matter header is Set-cookie or Set-cookie2
+ List<HttpCookie> list = HttpCookie
+ .parse("Set-Cookie2:name=;expires=;discard");
+ HttpCookie cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertTrue(cookie.getDiscard());
+
+ list = HttpCookie.parse("Set-Cookie: name=value;port=80");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals("80", cookie.getPortlist());
+
+ // In Set-Cookie header, max-age does not take effect when expires
+ // exists.
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;expires=Tue, 27-Jan-1998 19:14:07 GMT;Max-Age=1000");
+ cookie = list.get(0);
+ assertTrue(cookie.getMaxAge() < 0);
+ assertTrue(cookie.hasExpired());
+ assertFalse(cookie.getDiscard());
+ // Reverse sequence. max-age takes effect and decides the result of
+ // hasExpired() method.
+ list = HttpCookie
+ .parse("Set-Cookie:name=value;max-age=1000;expires=Tue, 17-Jan-1998 19:14:07 GMT;version=1");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals(1000, cookie.getMaxAge());
+ assertFalse(cookie.hasExpired());
+
+ // expires decides the version. Not take Set-cookie header, version into
+ // consideration if expires exists.
+ list = HttpCookie
+ .parse("Set-Cookie2:name=value;max-age=1000;version=1;expires=Tue, 17-Jan-1998 19:07:14 GMT;");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals(1000, cookie.getMaxAge());
+ assertFalse(cookie.hasExpired());
+
+ // expires does not cover other version 1 attributes.
+ list = HttpCookie
+ .parse("Set-Cookie2: name=value;expires=Sun, 27-Jan-2018 19:14:07 GMT;comment=mycomment;port=80,8080");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals("80,8080", cookie.getPortlist());
+ assertEquals("mycomment", cookie.getComment());
+
+ // When expires does not exist, version takes effect.
+ list = HttpCookie.parse("Set-Cookie:name=test;Version=1");
+ cookie = list.get(0);
+ assertEquals(1, cookie.getVersion());
+ assertEquals(-1, cookie.getMaxAge());
+ list = HttpCookie.parse("Set-Cookie:name=test;vERsion=0;Version=1;versioN=0;vErsIon=1");
+ cookie = list.get(0);
+ assertEquals(1, cookie.getVersion());
+
+ // When expires does not exist, max-age takes effect.
+ list = HttpCookie.parse("Set-Cookie:name=test;Max-Age=11");
+ cookie = list.get(0);
+ assertEquals(1, cookie.getVersion());
+ assertEquals(11, cookie.getMaxAge());
+ // other version 1 attributes does not take effect
+ list = HttpCookie
+ .parse("Set-Cookie:name=test;comment=mycomment;commentURL=url;discard;domain=a.b.com;path=temp;port=79;secure");
+ cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ }
+
+ /**
+ * java.net.HttpCookie#parse(String) on multiple threads
+ * Regression test for HARMONY-6307
+ * @since 1.6
+ */
+ class ParseThread extends Thread {
+ public AssertionError error = null;
+
+ public void run() {
+ try {
+ for (int i = 0; i < 200; i++) {
+ List<HttpCookie> list = HttpCookie.parse("Set-cookie:PREF=test;path=/;domain=.b.c;");
+ assertEquals(1, list.size());
+ HttpCookie cookie = list.get(0);
+ assertEquals(0, cookie.getVersion());
+ assertEquals(".b.c", cookie.getDomain());
+ }
+ } catch (AssertionError e) {
+ error = e;
+ }
+ }
+ }
+
+ public void test_Parse_multipleThreads() throws InterruptedException {
+ ParseThread[] threads = new ParseThread[10];
+ // create threads
+ for (int i = 0; i < threads.length; i++) {
+ threads[i] = new ParseThread();
+ }
+
+ // start threads
+ for (ParseThread thread : threads) {
+ thread.start();
+ }
+
+ // wait for threads to finish
+ for (ParseThread thread : threads) {
+ thread.join();
+ }
+
+ for (ParseThread thread : threads) {
+ if (thread.error != null) {
+ fail("Assertion thrown in thread " + thread + ": " + thread.error);
+ }
+ }
+ }
+
+ private void checkValidValue(String header, String value) {
+ List<HttpCookie> list = HttpCookie
+ .parse(header + "name=" + value + ";");
+ HttpCookie cookie = list.get(0);
+ assertEquals(value, cookie.getValue());
+ }
+
+ private void checkInvalidCookie(String header) {
+ try {
+ HttpCookie.parse(header);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ // version 0 cookie only takes effect on Locale.ENGLISH
+ locale = Locale.getDefault();
+ Locale.setDefault(Locale.ENGLISH);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ Locale.setDefault(locale);
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/IDNTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/IDNTest.java
new file mode 100644
index 0000000..dfd4d66
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/IDNTest.java
@@ -0,0 +1,156 @@
+/* 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.tests.java.net;
+
+import java.net.IDN;
+
+import junit.framework.TestCase;
+
+public class IDNTest extends TestCase {
+
+ /**
+ * {@link java.net.IDN#toASCII(String)}
+ * @since 1.6
+ */
+ public void test_ToASCII_LString() {
+ try {
+ IDN.toASCII(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ IDN.toASCII("www.m\uE400kitorppa.edu");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ IDN.toASCII("www.\u672C\uFE73\uFFFF.jp");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ assertEquals("www.xn--gwtq9nb2a.jp", IDN
+ .toASCII("www.\u65E5\u672C\u5E73.jp"));
+ assertEquals(
+ "www.xn--vckk7bxa0eza9ezc9d.com",
+ IDN
+ .toASCII("www.\u30CF\u30F3\u30C9\u30DC\u30FC\u30EB\u30B5\u30E0\u30BA.com"));
+ assertEquals("www.xn--frgbolaget-q5a.nu", IDN
+ .toASCII("www.f\u00E4rgbolaget.nu"));
+ assertEquals("www.xn--bcher-kva.de", IDN.toASCII("www.b\u00FCcher.de"));
+ assertEquals("www.xn--brndendekrlighed-vobh.com", IDN
+ .toASCII("www.br\u00E6ndendek\u00E6rlighed.com"));
+ assertEquals("www.xn--rksmrgs-5wao1o.se", IDN
+ .toASCII("www.r\u00E4ksm\u00F6rg\u00E5s.se"));
+ assertEquals("www.xn--9d0bm53a3xbzui.com", IDN
+ .toASCII("www.\uC608\uBE44\uAD50\uC0AC.com"));
+ assertEquals("xn--lck1c3crb1723bpq4a.com", IDN
+ .toASCII("\u7406\u5BB9\u30CA\u30AB\u30E0\u30E9.com"));
+ assertEquals("xn--l8je6s7a45b.org", IDN
+ .toASCII("\u3042\u30FC\u308B\u3044\u3093.org"));
+ assertEquals("www.xn--frjestadsbk-l8a.net", IDN
+ .toASCII("www.f\u00E4rjestadsbk.net"));
+ assertEquals("www.xn--mkitorppa-v2a.edu", IDN
+ .toASCII("www.m\u00E4kitorppa.edu"));
+ }
+
+ /**
+ * {@link java.net.IDN#toASCII(String, int)}
+ * @since 1.6
+ */
+ public void test_ToASCII_LString_I() {
+ try {
+ IDN.toASCII("www.br\u00E6ndendek\u00E6rlighed.com",
+ IDN.USE_STD3_ASCII_RULES);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ IDN.toASCII("www.r\u00E4ksm\u00F6rg\u00E5s.se",
+ IDN.USE_STD3_ASCII_RULES);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ IDN.toASCII("www.f\u00E4rjestadsbk.net", IDN.ALLOW_UNASSIGNED
+ | IDN.USE_STD3_ASCII_RULES);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ assertEquals("www.xn--gwtq9nb2a.jp", IDN.toASCII(
+ "www.\u65E5\u672C\u5E73.jp", 0));
+ assertEquals(
+ "www.xn--vckk7bxa0eza9ezc9d.com",
+ IDN
+ .toASCII(
+ "www.\u30CF\u30F3\u30C9\u30DC\u30FC\u30EB\u30B5\u30E0\u30BA.com",
+ 0));
+ assertEquals("www.xn--frgbolaget-q5a.nu", IDN.toASCII(
+ "www.f\u00E4rgbolaget.nu", IDN.ALLOW_UNASSIGNED));
+ assertEquals("www.xn--bcher-kva.de", IDN.toASCII("www.b\u00FCcher.de",
+ IDN.ALLOW_UNASSIGNED));
+ assertEquals("www.google.com", IDN.toASCII("www.google\u002Ecom",
+ IDN.USE_STD3_ASCII_RULES));
+ }
+
+ /**
+ * {@link java.net.IDN#toUnicode(String)}
+ * @since 1.6
+ */
+ public void test_ToUnicode_LString() {
+ try {
+ IDN.toUnicode(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ assertEquals("", IDN.toUnicode(""));
+ assertEquals("www.bcher.de", IDN.toUnicode("www.bcher.de"));
+ assertEquals("www.b\u00FCcher.de", IDN.toUnicode("www.b\u00FCcher.de"));
+ assertEquals("www.\u65E5\u672C\u5E73.jp", IDN
+ .toUnicode("www.\u65E5\u672C\u5E73.jp"));
+ assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode("www\uFF0Exn--gwtq9nb2a\uFF61jp"));
+ assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode("www.xn--gwtq9nb2a.jp"));
+ }
+
+ /**
+ * {@link java.net.IDN#toUnicode(String, int)}
+ * @since 1.6
+ */
+ public void test_ToUnicode_LString_I() {
+ assertEquals("", IDN.toUnicode("", IDN.ALLOW_UNASSIGNED));
+ assertEquals("www.f\u00E4rgbolaget.nu", IDN.toUnicode(
+ "www.f\u00E4rgbolaget.nu", IDN.USE_STD3_ASCII_RULES));
+ assertEquals("www.r\u00E4ksm\u00F6rg\u00E5s.nu", IDN.toUnicode(
+ "www.r\u00E4ksm\u00F6rg\u00E5s\u3002nu",
+ IDN.USE_STD3_ASCII_RULES));
+ // RI bug. It cannot parse "www.xn--gwtq9nb2a.jp" when
+ // USE_STD3_ASCII_RULES is set.
+ assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode(
+ "www\uFF0Exn--gwtq9nb2a\uFF61jp", IDN.USE_STD3_ASCII_RULES));
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet4AddressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet4AddressTest.java
new file mode 100644
index 0000000..94df634
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet4AddressTest.java
@@ -0,0 +1,346 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.Serializable;
+import java.net.Inet4Address;
+import java.net.InetAddress;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class Inet4AddressTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.Inet4Address#isMulticastAddress()
+ */
+ public void test_isMulticastAddress() throws Exception {
+
+ // Create 2 IP v4 addresses and call "isMulticastAddress()"
+ // result should return true if the first 4 bits of the
+ // address are: 1110, false otherwise
+ // Make 1 address with 1110, and 1 without
+ String addrName = "";
+ addrName = "224.0.0.0"; // a multicast addr 1110 = 224-239
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("Multicast address " + addrName + " not detected.", addr
+ .isMulticastAddress());
+
+ addrName = "239.255.255.255"; // a multicast addr 1110 = 224-239
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Multicast address " + addrName + " not detected.", addr
+ .isMulticastAddress());
+
+ addrName = "42.42.42.42"; // a non-multicast address
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Non multicast address " + addrName
+ + " reporting as a multicast address.", !addr
+ .isMulticastAddress());
+
+ }
+
+ public void test_isAnyLocalAddress() throws Exception {
+ assertTrue(InetAddress.getByName("0.0.0.0").isAnyLocalAddress());
+ assertFalse(InetAddress.getByName("127.0.0.1").isAnyLocalAddress());
+ }
+
+ public void test_isLoopbackAddress() throws Exception {
+ // Create some IP V4 addresses and test if they are local...
+
+ String addrName = "";
+
+ addrName = "127.0.0.0"; // a loopback address should be 127.d.d.d
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("Loopback address " + addrName + " not detected.", addr
+ .isLoopbackAddress());
+
+ addrName = "127.42.42.42"; // a loopback address should be
+ // 127.d.d.d
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Loopback address " + addrName + " not detected.", addr
+ .isLoopbackAddress());
+
+ addrName = "42.42.42.42"; // a loopback address should be
+ // 127.d.d.d
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Address incorrectly " + addrName
+ + " detected as a loopback address.", !addr
+ .isLoopbackAddress());
+ }
+
+ /**
+ * java.net.Inet4Address#isLinkLocalAddress()
+ */
+ public void test_isLinkLocalAddress() throws Exception {
+
+ String addrName = "";
+ // There are no link local addresses for IPv4
+ // We'll test one to ensure we get "false"
+
+ addrName = "42.42.42.42";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 address " + addrName
+ + " incorrectly reporting as a link local address.", !addr
+ .isLinkLocalAddress());
+ }
+
+ /**
+ * java.net.Inet4Address#isSiteLocalAddress()
+ */
+ public void test_isSiteLocalAddress() throws Exception {
+ String addrName = "";
+ // There are no site local addresses for IPv4
+ // We'll test one to ensure we get "false"
+
+ addrName = "42.42.42.42";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 address " + addrName
+ + " incorrectly reporting as a site local address.", !addr
+ .isSiteLocalAddress());
+ }
+
+ /**
+ * java.net.Inet4Address#isMCGlobal()
+ */
+ public void test_isMCGlobal() throws Exception {
+
+ // Create an IPv4 mulitcast address. It should return
+ // false for globabl mutlicast. There are no valid IPv4
+ // global multicast addresses
+
+ String addrName = "";
+ addrName = "224.0.0.0"; // a multicast addr 1110
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " incorrectly identified as a global multicast address.",
+ !addr.isMCGlobal());
+
+ addrName = "224.0.0.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " incorrectly identified as a global multicast address.",
+ !addr.isMCGlobal());
+
+ addrName = "224.0.1.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 global multicast address " + addrName
+ + " not identified as a global multicast address.", addr
+ .isMCGlobal());
+
+ addrName = "238.255.255.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 global multicast address " + addrName
+ + " not identified as a global multicast address.", addr
+ .isMCGlobal());
+
+ addrName = "239.0.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 reserved multicast address " + addrName
+ + " incorrectly identified as a global multicast address.",
+ !addr.isMCGlobal());
+
+ addrName = "239.191.255.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 reserved multicast address " + addrName
+ + " incorrectly identified as a global multicast address.",
+ !addr.isMCGlobal());
+ }
+
+ /**
+ * java.net.Inet4Address#isMCNodeLocal()
+ */
+ public void test_isMCNodeLocal() throws Exception {
+ // Create an IPv4 mulitcast address. It should return
+ // false for node-local mutlicast. There are no valid IPv4
+ // node-local multicast addresses
+
+ String addrName = "";
+ addrName = "224.42.42.42"; // a multicast addr 1110 = 224
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 multicast address "
+ + addrName
+ + " incorrectly identified as a node-local multicast address.",
+ !addr.isMCNodeLocal());
+
+ addrName = "239.0.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 reserved multicast address "
+ + addrName
+ + " incorrectly identified as a node-local multicast address.",
+ !addr.isMCNodeLocal());
+ }
+
+ /**
+ * java.net.Inet4Address#isMCLinkLocal()
+ */
+ public void test_isMCLinkLocal() throws Exception {
+ // Create an IPv4 mulitcast address. It should return
+ // false for link-local mutlicast. There are no valid IPv4
+ // link-local multicast addresses
+
+ String addrName = "";
+ addrName = "224.0.0.0"; // a multicast addr 1110
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " not identified as a link-local multicast address.",
+ addr.isMCLinkLocal());
+
+ addrName = "224.0.0.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " not identified as a link-local multicast address.",
+ addr.isMCLinkLocal());
+
+ addrName = "224.0.1.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 global multicast address "
+ + addrName
+ + " incorrectly identified as a link-local multicast address.",
+ !addr.isMCLinkLocal());
+
+ addrName = "239.0.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 reserved multicast address "
+ + addrName
+ + " incorrectly identified as a link-local multicast address.",
+ !addr.isMCLinkLocal());
+ }
+
+ /**
+ * java.net.Inet4Address#isMCSiteLocal()
+ */
+ public void test_isMCSiteLocal() throws Exception {
+ // Create an IPv4 mulitcast address. It should return
+ // false for site-local mutlicast. There are no valid IPv4
+ // site-local multicast addresses
+
+ String addrName = "";
+ addrName = "240.0.0.0"; // a multicast addr 1110 = 224
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 multicast address "
+ + addrName
+ + " incorrectly identified as a site-local multicast address.",
+ !addr.isMCSiteLocal());
+
+ addrName = "239.0.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 reserved multicast address "
+ + addrName
+ + " incorrectly identified as a site-local multicast address.",
+ !addr.isMCSiteLocal());
+
+ addrName = "239.255.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 site-local multicast address " + addrName
+ + " not identified as a site-local multicast address.",
+ addr.isMCSiteLocal());
+
+ addrName = "239.255.255.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 site-local multicast address " + addrName
+ + " not identified as a site-local multicast address.",
+ addr.isMCSiteLocal());
+
+ addrName = "239.255.2.2"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 site-local multicast address " + addrName
+ + " not identified as a site-local multicast address.",
+ addr.isMCSiteLocal());
+ }
+
+ /**
+ * java.net.Inet4Address#isMCOrgLocal()
+ */
+ public void test_isMCOrgLocal() throws Exception {
+ // Create an IPv4 mulitcast address. It should return
+ // false for organization-local mutlicast. There are no valid IPv4
+ // organization-local multicast addresses
+
+ String addrName = "";
+
+ addrName = "239.191.255.255"; // a multicast addr 1110
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 reserved multicast address "
+ + addrName
+ + " incorrectly identified as a org-local multicast address.",
+ !addr.isMCOrgLocal());
+
+ addrName = "239.252.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv4 site-local multicast address "
+ + addrName
+ + " incorrectly identified as a org-local multicast address.",
+ !addr.isMCOrgLocal());
+
+ addrName = "239.192.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 org-local multicast address " + addrName
+ + " not identified as a org-local multicast address.", addr
+ .isMCOrgLocal());
+
+ addrName = "239.195.255.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 org-local multicast address " + addrName
+ + " not identified as a org-local multicast address.", addr
+ .isMCOrgLocal());
+ }
+
+ // comparator for Inet4Address objects
+ private static final SerializableAssert COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ Inet4Address initAddr = (Inet4Address) initial;
+ Inet4Address desrAddr = (Inet4Address) deserialized;
+
+ byte[] iaAddresss = initAddr.getAddress();
+ byte[] deIAAddresss = desrAddr.getAddress();
+ for (int i = 0; i < iaAddresss.length; i++) {
+ assertEquals(iaAddresss[i], deIAAddresss[i]);
+ }
+ assertEquals(4, deIAAddresss.length);
+ assertEquals(initAddr.getHostName(), desrAddr.getHostName());
+ }
+ };
+
+ /**
+ * serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(Inet4Address.getByName("localhost"),
+ COMPARATOR);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, Inet4Address
+ .getByName("localhost"), COMPARATOR);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet6AddressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet6AddressTest.java
new file mode 100644
index 0000000..77b8405
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/Inet6AddressTest.java
@@ -0,0 +1,916 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.Serializable;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.UnknownHostException;
+import java.util.Locale;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class Inet6AddressTest extends junit.framework.TestCase {
+ public void test_isMulticastAddress() throws Exception {
+
+ String addrName = "";
+ InetAddress addr = null;
+
+ // IP V6 regular multicast and non-multicast tests
+ //
+ // Create 2 IP v6 addresses and call "isMulticastAddress()"
+ // A prefix of "11111111" means that the address is multicast
+ // The first one will be one with the prefix the second without
+
+ addrName = "FFFF::42:42"; // 11111111 = FFFF
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Multicast address " + addrName + " not detected.", addr
+ .isMulticastAddress());
+
+ addrName = "42::42:42"; // an non-multicast address
+ addr = InetAddress.getByName(addrName);
+ assertTrue("Non multicast address " + addrName
+ + " reporting as a multicast address.", !addr
+ .isMulticastAddress());
+
+ // IPv4-compatible IPv6 address tests
+ //
+ // Now create 2 IP v6 addresses that are IP v4 compatable
+ // to IP v6 addresses. The address prefix for a multicast ip v4
+ // address is 1110 for the last 16 bits ::d.d.d.d
+ // We expect these to be false
+
+ addrName = "::224.42.42.42"; // an ipv4 multicast addr 1110 = 224
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 compatable address " + addrName
+ + " reported incorrectly as multicast.", !addr
+ .isMulticastAddress());
+
+ addrName = "::42.42.42.42"; // an ipv4 non-multicast address
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 compatable address " + addrName
+ + " reported incorrectly as multicast.", !addr
+ .isMulticastAddress());
+
+ // IPv4-mapped IPv6 address tests
+ //
+ // Now create 2 IP v6 addresses that are IP v4 compatable
+ // to IP v6 addresses. The address prefix for a multicast ip v4
+ // address is 1110 for the last 16 bits ::FFFF:d.d.d.d
+
+ addrName = "::FFFF:224.42.42.42"; // an ipv4 multicast addr 1110 =
+ // 224
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-mapped IPv6 multicast address " + addrName
+ + " not detected.", addr.isMulticastAddress());
+
+ addrName = "::FFFF:42.42.42.42"; // an ipv4 non-multicast address
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-mapped IPv6 non-multicast address " + addrName
+ + " reporting as a multicast address.", !addr
+ .isMulticastAddress());
+ }
+
+ public void test_isAnyLocalAddress() throws Exception {
+
+ String addrName = "";
+ InetAddress addr = null;
+
+ // test to ensure that the unspecified address returns tru
+ addrName = "::0"; // The unspecified address
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "The unspecified (also known as wildcard and any local address) "
+ + addrName + " not detected.", addr
+ .isAnyLocalAddress());
+
+ addrName = "::"; // another form of the unspecified address
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "The unspecified (also known as wildcard and any local address) "
+ + addrName + " not detected.", addr
+ .isAnyLocalAddress());
+
+ addrName = "::1"; // The loopback address
+ addr = InetAddress.getByName(addrName);
+ assertTrue("The addresses " + addrName
+ + " incorrectly reporting an the unspecified address.",
+ !addr.isAnyLocalAddress());
+ }
+
+ public void test_isLoopbackAddress() throws Exception {
+
+ String addrName = "";
+ // IP V6 regular address tests for loopback
+ // The loopback address for IPv6 is ::1
+
+ addrName = "::1";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 loopback address " + addrName + " not detected.",
+ addr.isLoopbackAddress());
+
+ addrName = "::2";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address incorrectly " + addrName
+ + " detected as a loopback address.", !addr
+ .isLoopbackAddress());
+
+ // a loopback address should be 127.d.d.d
+ addrName = "42:42::42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address incorrectly " + addrName
+ + " detected as a loopback address.", !addr
+ .isLoopbackAddress());
+
+ // IPv4-compatible IPv6 address tests
+ //
+ // Now create 2 IP v6 addresses that are IP v4 compatable
+ // to IP v6 addresses. The address prefix for a multicast ip v4
+ // address is 1110 for the last 16 bits ::d.d.d.d
+ // We expect these to be false, as they are not IPv4 addresses
+
+ // a loopback address should be 127.d.d.d
+ addrName = "::127.0.0.0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 address " + addrName
+ + " detected incorrectly as a loopback.", !addr
+ .isLoopbackAddress());
+
+ addrName = "::127.42.42.42"; // a loopback address should be
+ // 127.d.d.d
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 address " + addrName
+ + " detected incorrectly as a loopback.", !addr
+ .isLoopbackAddress());
+
+ // a loopback address should be 127.d.d.d
+ addrName = "::42.42.42.42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 address " + addrName
+ + " detected incorrectly as a loopback.", !addr
+ .isLoopbackAddress());
+
+ // IPv4-mapped IPv6 address tests
+ //
+ // Now create 2 IP v6 addresses that are IP v4 compatable
+ // to IP v6 addresses. The address prefix for a multicast ip v4
+ // address is 1110 for the last 16 bits ::FFFF:d.d.d.d
+
+ // a loopback address should be 127.d.d.d
+ addrName = "::FFFF:127.0.0.0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 loopback address " + addrName
+ + " not detected.", addr.isLoopbackAddress());
+
+ // a loopback address should be 127.d.d.d
+ addrName = "::FFFF:127.42.42.42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 loopback address " + addrName
+ + " not detected.", addr.isLoopbackAddress());
+
+ // a loopback address should be 127.d.d.d
+ addrName = "::FFFF:42.42.42.42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4-compatible IPv6 address incorrectly " + addrName
+ + " detected as a loopback address.", !addr
+ .isLoopbackAddress());
+ }
+
+ public void test_isLinkLocalAddress() throws Exception {
+
+ String addrName = "";
+ // IP V6 regular address tests for link local addresses
+ //
+ // Link local addresses are FE80:: -
+ // FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
+
+ addrName = "FE80::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 link local address " + addrName + " not detected.",
+ addr.isLinkLocalAddress());
+
+ addrName = "FEBF::FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 link local address " + addrName + " not detected.",
+ addr.isLinkLocalAddress());
+
+ addrName = "FEC0::1";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address " + addrName
+ + " detected incorrectly as a link local address.", !addr
+ .isLinkLocalAddress());
+
+ addrName = "FD80::1:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address " + addrName
+ + " detected incorrectly as a link local address.", !addr
+ .isLinkLocalAddress());
+
+ addrName = "FE7F::FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address " + addrName
+ + " detected incorrectly as a link local address.", !addr
+ .isLinkLocalAddress());
+ }
+
+ public void test_isSiteLocalAddress() throws Exception {
+ String addrName = "";
+
+ // IP V6 regular address tests for link local addresses
+ //
+ // Link local addresses are FEC0::0 through to
+ // FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
+
+ addrName = "FEC0::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 site local address " + addrName + " not detected.",
+ addr.isSiteLocalAddress());
+
+ addrName = "FEFF::FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 site local address " + addrName + " not detected.",
+ addr.isSiteLocalAddress());
+
+ addrName = "FEBF::FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address " + addrName
+ + " detected incorrectly as a site local address.", !addr
+ .isSiteLocalAddress());
+
+ addrName = "FFC0::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 address " + addrName
+ + " detected incorrectly as a site local address.", !addr
+ .isSiteLocalAddress());
+ }
+
+ public void test_isMCGlobal() throws Exception {
+ String addrName = "";
+ // IP V6 regular address tests for Mulitcase Global addresses
+ //
+ // Multicast global addresses are FFxE:/112 where x is
+ // a set of flags, and the addition 112 bits make up
+ // the global address space
+
+ addrName = "FF0E::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 global mutlicast address " + addrName
+ + " not detected.", addr.isMCGlobal());
+
+ addrName = "FF0E:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 global multicast address " + addrName
+ + " not detected.", addr.isMCGlobal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFFE::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 global mutlicast address " + addrName
+ + " not detected.", addr.isMCGlobal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFFE:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 global multicast address " + addrName
+ + " not detected.", addr.isMCGlobal());
+
+ // a sample MC organizational address
+ addrName = "FF08:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast organizational " + addrName
+ + " incorrectly indicated as a global address.", !addr
+ .isMCGlobal());
+
+ // a sample MC site address
+ addrName = "FF05:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast site address " + addrName
+ + " incorrectly indicated as a global address.", !addr
+ .isMCGlobal());
+
+ // a sample MC link address
+ addrName = "FF02:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast link address " + addrName
+ + " incorrectly indicated as a global address.", !addr
+ .isMCGlobal());
+
+ // a sample MC Node
+ addrName = "FF01:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast node address " + addrName
+ + " incorrectly indicated as a global address.", !addr
+ .isMCGlobal());
+
+ // IPv4-mapped IPv6 address tests
+ addrName = "::FFFF:224.0.1.0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 global multicast address " + addrName
+ + " not identified as a global multicast address.", addr
+ .isMCGlobal());
+
+ addrName = "::FFFF:238.255.255.255";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 global multicast address " + addrName
+ + " not identified as a global multicast address.", addr
+ .isMCGlobal());
+ }
+
+ public void test_isMCNodeLocal() throws Exception {
+ String addrName = "";
+ // IP V6 regular address tests for Mulitcase node local addresses
+ //
+ // Multicast node local addresses are FFx1:/112 where x is
+ // a set of flags, and the addition 112 bits make up
+ // the global address space
+
+ addrName = "FF01::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 node-local mutlicast address " + addrName
+ + " not detected.", addr.isMCNodeLocal());
+
+ addrName = "FF01:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 node-local multicast address " + addrName
+ + " not detected.", addr.isMCNodeLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF1::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 node-local mutlicast address " + addrName
+ + " not detected.", addr.isMCNodeLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF1:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 node-local multicast address " + addrName
+ + " not detected.", addr.isMCNodeLocal());
+
+ // a sample MC organizational address
+ addrName = "FF08:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast organizational address " + addrName
+ + " incorrectly indicated as a node-local address.", !addr
+ .isMCNodeLocal());
+
+ // a sample MC site address
+ addrName = "FF05:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast site address " + addrName
+ + " incorrectly indicated as a node-local address.", !addr
+ .isMCNodeLocal());
+
+ // a sample MC link address
+ addrName = "FF02:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast link address " + addrName
+ + " incorrectly indicated as a node-local address.", !addr
+ .isMCNodeLocal());
+
+ // a sample MC global address
+ addrName = "FF0E:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 mulitcast node address " + addrName
+ + " incorrectly indicated as a node-local address.", !addr
+ .isMCNodeLocal());
+ }
+
+ public void test_isMCLinkLocal() throws Exception {
+ String addrName = "";
+ // IP V6 regular address tests for Mulitcase link local addresses
+ //
+ // Multicast link local addresses are FFx2:/112 where x is
+ // a set of flags, and the addition 112 bits make up
+ // the global address space
+
+ addrName = "FF02::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 link local multicast address " + addrName
+ + " not detected.", addr.isMCLinkLocal());
+
+ addrName = "FF02:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 link local multicast address " + addrName
+ + " not detected.", addr.isMCLinkLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF2::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 link local multicast address " + addrName
+ + " not detected.", addr.isMCLinkLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF2:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 link local multicast address " + addrName
+ + " not detected.", addr.isMCLinkLocal());
+
+ // a sample MC organizational address
+ addrName = "FF08:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 organization multicast address "
+ + addrName
+ + " incorrectly indicated as a link-local mulitcast address.",
+ !addr.isMCLinkLocal());
+
+ // a sample MC site address
+ addrName = "FF05:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 site-local mulitcast address "
+ + addrName
+ + " incorrectly indicated as a link-local mulitcast address.",
+ !addr.isMCLinkLocal());
+
+ // a sample MC global address
+ addrName = "FF0E:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 global multicast address "
+ + addrName
+ + " incorrectly indicated as a link-local mulitcast address.",
+ !addr.isMCLinkLocal());
+
+ // a sample MC Node
+ addrName = "FF01:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 mulitcast node address "
+ + addrName
+ + " incorrectly indicated as a link-local mulitcast address.",
+ !addr.isMCLinkLocal());
+
+ // Ipv4-mapped IPv6 addresses
+
+ addrName = "::FFFF:224.0.0.0"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " not identified as a link-local multicast address.",
+ addr.isMCLinkLocal());
+
+ addrName = "::FFFF:224.0.0.255"; // a multicast addr 1110
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 link-local multicast address " + addrName
+ + " not identified as a link-local multicast address.",
+ addr.isMCLinkLocal());
+ }
+
+ public void test_isMCSiteLocal() throws Exception {
+ String addrName = "";
+ // IP V6 regular address tests for Multicast site-local addresses
+ //
+ // Multicast global addresses are FFx5:/112 where x is
+ // a set of flags, and the addition 112 bits make up
+ // the global address space
+
+ addrName = "FF05::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 site-local mutlicast address " + addrName
+ + " not detected.", addr.isMCSiteLocal());
+
+ addrName = "FF05:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 site-local multicast address " + addrName
+ + " not detected.", addr.isMCSiteLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF5::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 site-local mutlicast address " + addrName
+ + " not detected.", addr.isMCSiteLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF5:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 site-local multicast address " + addrName
+ + " not detected.", addr.isMCSiteLocal());
+
+ // a sample MC organizational address
+ addrName = "FF08:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 organization multicast address "
+ + addrName
+ + " incorrectly indicated as a site-local mulitcast address.",
+ !addr.isMCSiteLocal());
+
+ // a sample MC global address
+ addrName = "FF0E:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 global mulitcast address "
+ + addrName
+ + " incorrectly indicated as a site-local mulitcast address.",
+ !addr.isMCSiteLocal());
+
+ // a sample MC link address
+ addrName = "FF02:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 link-local multicast address "
+ + addrName
+ + " incorrectly indicated as a site-local mulitcast address.",
+ !addr.isMCSiteLocal());
+
+ // a sample MC Node
+ addrName = "FF01:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 mulitcast node address "
+ + addrName
+ + " incorrectly indicated as a site-local mulitcast address.",
+ !addr.isMCSiteLocal());
+
+ // IPv4-mapped IPv6 addresses
+ addrName = "::FFFF:239.255.0.0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 site-local multicast address " + addrName
+ + " not identified as a site-local multicast address.",
+ addr.isMCSiteLocal());
+
+ addrName = "::FFFF:239.255.255.255";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 site-local multicast address " + addrName
+ + " not identified as a site-local multicast address.",
+ addr.isMCSiteLocal());
+ }
+
+ public void test_isMCOrgLocal() throws Exception {
+ String addrName = "";
+ // IP V6 regular address tests for Mulitcase organization-local
+ // addresses
+ //
+ // Multicast global addresses are FFxE:/112 where x is
+ // a set of flags, and the addition 112 bits make up
+ // the global address space
+
+ addrName = "FF08::0";
+ InetAddress addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 organization-local mutlicast address " + addrName
+ + " not detected.", addr.isMCOrgLocal());
+
+ addrName = "FF08:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 organization-local multicast address " + addrName
+ + " not detected.", addr.isMCOrgLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF8::0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 organization-local mutlicast address " + addrName
+ + " not detected.", addr.isMCOrgLocal());
+
+ // a currently invalid address as the prefix FFxE
+ // is only valid for x = {1,0} as the rest are reserved
+ addrName = "FFF8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv6 organization-local multicast address " + addrName
+ + " not detected.", addr.isMCOrgLocal());
+
+ // a sample MC global address
+ addrName = "FF0E:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 global multicast address "
+ + addrName
+ + " incorrectly indicated as an organization-local mulitcast address.",
+ !addr.isMCOrgLocal());
+
+ // a sample MC site address
+ addrName = "FF05:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 site-local mulitcast address "
+ + addrName
+ + " incorrectly indicated as an organization-local mulitcast address.",
+ !addr.isMCOrgLocal());
+
+ // a sample MC link address
+ addrName = "FF02:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 link-local multicast address "
+ + addrName
+ + " incorrectly indicated as an organization-local mulitcast address.",
+ !addr.isMCOrgLocal());
+
+ // a sample MC Node
+ addrName = "FF01:42:42:42:42:42:42:42";
+ addr = InetAddress.getByName(addrName);
+ assertTrue(
+ "IPv6 mulitcast node address "
+ + addrName
+ + " incorrectly indicated as an organization-local mulitcast address.",
+ !addr.isMCOrgLocal());
+
+ // IPv4-mapped IPv6 addresses
+
+ addrName = "::FFFF:239.192.0.0";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 org-local multicast address " + addrName
+ + " not identified as a org-local multicast address.", addr
+ .isMCOrgLocal());
+
+ addrName = "::FFFF:239.195.255.255";
+ addr = InetAddress.getByName(addrName);
+ assertTrue("IPv4 org-local multicast address " + addrName
+ + " not identified as a org-local multicast address.", addr
+ .isMCOrgLocal());
+ }
+
+ public void test_isIPv4CompatibleAddress() throws Exception {
+ String addrName = "";
+ Inet6Address addr = null;
+
+ // Tests a number of addresses to see if they are compatable with
+ // IPv6 addresses
+
+ addrName = "FFFF::42:42"; // 11111111 = FFFF
+ addr = (Inet6Address) InetAddress.getByName(addrName);
+ assertTrue("A non-compatable IPv6 address " + addrName
+ + " incorrectly identified as a IPv4 compatable address.",
+ !addr.isIPv4CompatibleAddress());
+
+ // IPv4-compatible IPv6 address tests
+ //
+ // Now create 2 IP v6 addresses that are IP v4 compatable
+ // to IP v6 addresses.
+
+ addrName = "::0.0.0.0";
+ addr = (Inet6Address) InetAddress.getByName(addrName);
+ assertTrue("IPv4 compatable address " + addrName
+ + " not detected correctly.", addr
+ .isIPv4CompatibleAddress());
+
+ addrName = "::255.255.255.255"; // an ipv4 non-multicast address
+ addr = (Inet6Address) InetAddress.getByName(addrName);
+ assertTrue("IPv4 compatable address " + addrName
+ + " not detected correctly.", addr
+ .isIPv4CompatibleAddress());
+ }
+
+ public void test_getByNameLjava_lang_String() throws Exception {
+ // ones to add "::255.255.255.255", "::FFFF:0.0.0.0",
+ // "0.0.0.0.0.0::255.255.255.255", "F:F:F:F:F:F:F:F",
+ // "[F:F:F:F:F:F:F:F]"
+ String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
+ "::1", "0", /* jdk1.5 accepts 0 as valid */
+ "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
+ "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
+ "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0" };
+
+ String invalidIPAddresses[] = { "FFFF:FFFF" };
+
+ for (int i = 0; i < validIPAddresses.length; i++) {
+
+ InetAddress.getByName(validIPAddresses[i]);
+
+ //exercise positive cache
+ InetAddress.getByName(validIPAddresses[i]);
+
+ if (!validIPAddresses[i].equals("0")) {
+ String tempIPAddress = "[" + validIPAddresses[i] + "]";
+ InetAddress.getByName(tempIPAddress);
+ }
+ }
+
+ for (int i = 0; i < invalidIPAddresses.length; i++) {
+ try {
+ InetAddress.getByName(invalidIPAddresses[i]);
+ fail("Invalid IP address incorrectly recognized as valid: "
+ + invalidIPAddresses[i]);
+ } catch (Exception e) {
+ }
+
+ //exercise negative cache
+ try {
+ InetAddress.getByName(invalidIPAddresses[i]);
+ fail("Invalid IP address incorrectly recognized as valid: "
+ + invalidIPAddresses[i]);
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ public void test_getByAddressLString$BI() throws UnknownHostException {
+ try {
+ Inet6Address.getByAddress("123", null, 0);
+ fail("should throw UnknownHostException");
+ } catch (UnknownHostException uhe) {
+ // expected
+ }
+ byte[] addr1 = { (byte) 127, 0, 0, 1 };
+ try {
+ Inet6Address.getByAddress("123", addr1, 0);
+ fail("should throw UnknownHostException");
+ } catch (UnknownHostException uhe) {
+ // expected
+ }
+
+ byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
+ 0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
+ (byte) 0xB2 };
+
+ // should not throw any exception
+ Inet6Address.getByAddress("123", addr2, 3);
+ Inet6Address.getByAddress("123", addr2, 0);
+ Inet6Address.getByAddress("123", addr2, -1);
+ }
+
+ public void test_getByAddressLString$BLNetworkInterface()
+ throws UnknownHostException {
+ NetworkInterface nif = null;
+ try {
+ Inet6Address.getByAddress("123", null, nif);
+ fail("should throw UnknownHostException");
+ } catch (UnknownHostException uhe) {
+ // expected
+ }
+ byte[] addr1 = { (byte) 127, 0, 0, 1 };
+ try {
+ Inet6Address.getByAddress("123", addr1, nif);
+ fail("should throw UnknownHostException");
+ } catch (UnknownHostException uhe) {
+ // expected
+ }
+ byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
+ 0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte)
+
+ 0x7C, (byte) 0xB2 };
+ // should not throw any exception
+ Inet6Address.getByAddress("123", addr2, nif);
+ }
+
+ public void test_getHostAddress_() throws Exception {
+ byte[] ipAddress = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+ InetAddress ia = InetAddress.getByAddress(ipAddress);
+ assertEquals("::1", ia.getHostAddress().toLowerCase(Locale.US));
+
+ ipAddress = new byte[] { -2, -128, 0, 0, 0, 0, 0, 0, 2, 17, 37, -1, -2, -8, 124, -79 };
+ ia = InetAddress.getByAddress(ipAddress);
+ assertEquals("fe80::211:25ff:fef8:7cb1", ia.getHostAddress().toLowerCase(Locale.US));
+ }
+
+ public void test_getScopeID() throws UnknownHostException {
+ Inet6Address v6ia;
+ byte[] addr = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x11,
+ 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
+ (byte) 0xB2 };
+
+ v6ia = Inet6Address.getByAddress("123", addr, 3);
+ assertEquals(3, v6ia.getScopeId());
+
+ v6ia = Inet6Address.getByAddress("123", addr, 0);
+ assertEquals(0, v6ia.getScopeId());
+
+ v6ia = Inet6Address.getByAddress("123", addr, -1);
+ assertEquals(0, v6ia.getScopeId());
+ }
+
+ public void test_getScopedInterface() throws UnknownHostException {
+ byte[] addr = { (byte) 0xFE, (byte) 0x80, (byte) 0x09, (byte) 0xb5,
+ (byte) 0x6b, (byte) 0xa4, 0, 0, 0, 0, 0, 0, (byte) 0x09,
+ (byte) 0xb5, (byte) 0x6b, (byte) 0xa4 };
+ Inet6Address v6Addr;
+ v6Addr = Inet6Address.getByAddress("123", addr, null);
+ assertNull(v6Addr.getScopedInterface());
+ }
+
+ public void test_hashCode() throws UnknownHostException {
+ byte[] addr = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x11,
+ 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
+ (byte) 0xB2 };
+ Inet6Address address1, address2;
+
+ address1 = Inet6Address.getByAddress("123", addr, 0);
+ address2 = Inet6Address.getByAddress("1234", addr, 0);
+ assertEquals(address1.hashCode(), address2.hashCode());
+ }
+
+ int bytesToInt(byte bytes[], int start) {
+
+ int byteMask = 255;
+ int value = ((bytes[start + 3] & byteMask))
+ | ((bytes[start + 2] & byteMask) << 8)
+ | ((bytes[start + 1] & byteMask) << 16)
+ | ((bytes[start] & byteMask) << 24);
+ return value;
+
+ }
+
+ String byteArrayToHexString(byte bytes[], boolean leadingZeros) {
+
+ String fullString = "";
+ int times = bytes.length / 4;
+ int intArray[] = new int[times];
+ for (int i = 0; i < times; i++) {
+ intArray[i] = bytesToInt(bytes, i * 4);
+ }
+
+ return intArrayToHexString(intArray, leadingZeros);
+ }
+
+ void intToBytes(int value, byte bytes[], int start) {
+
+ int byteMask = 255;
+ bytes[start + 3] = (byte) (value & byteMask);
+ bytes[start + 2] = (byte) ((value >> 8) & byteMask);
+ bytes[start + 1] = (byte) ((value >> 16) & byteMask);
+ bytes[start] = (byte) ((value >> 24) & byteMask);
+ }
+
+ String intArrayToHexString(int ints[], boolean leadingZeros) {
+
+ String fullString = "";
+ String tempString;
+ int intsLength = ints.length;
+ for (int i = 0; i < intsLength; i++) {
+ tempString = Integer.toHexString(ints[i]);
+ while (tempString.length() < 4 && leadingZeros) {
+ tempString = "0" + tempString;
+ }
+ if (i + 1 < intsLength) {
+ tempString += ":";
+ }
+ fullString += tempString;
+ }
+
+ return fullString.toUpperCase();
+ }
+
+ // comparator for Inet6Address objects
+ private static final SerializableAssert COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ Inet6Address initAddr = (Inet6Address) initial;
+ Inet6Address desrAddr = (Inet6Address) deserialized;
+
+ byte[] iaAddresss = initAddr.getAddress();
+ byte[] deIAAddresss = desrAddr.getAddress();
+ for (int i = 0; i < iaAddresss.length; i++) {
+ assertEquals(iaAddresss[i], deIAAddresss[i]);
+ }
+ assertEquals(initAddr.getScopeId(), desrAddr.getScopeId());
+ assertEquals(initAddr.getScopedInterface(), desrAddr
+ .getScopedInterface());
+ }
+ };
+
+ /**
+ * Tests serialization/deserialization compatibility with ourselves.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+ SerializationTest.verifySelf(InetAddress.getByAddress(localv6),
+ COMPARATOR);
+ }
+
+ /**
+ * Tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+ Object[] addresses = { InetAddress.getByAddress(localv6),
+ // Regression for Harmony-1039: ser-form has
+ // null interface name
+ InetAddress.getByAddress(localv6) };
+
+ SerializationTest.verifyGolden(this, addresses, COMPARATOR);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressTest.java
new file mode 100644
index 0000000..42f88c1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressTest.java
@@ -0,0 +1,443 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.DatagramSocket;
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+
+public class InetAddressTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.InetAddress#getByName(String)
+ */
+ public void test_getByName_exceptionContainsUsefulMessage() {
+ // Related to HARMONY-5784
+ try {
+ InetAddress.getByName("1.2.3.4hello");
+ fail();
+ } catch (UnknownHostException e) {
+ assertTrue(e.getMessage().contains("1.2.3.4hello"));
+ }
+ }
+
+ public void test_equalsLjava_lang_Object() throws Exception {
+ InetAddress ia1 = InetAddress.getByName("localhost");
+ InetAddress ia2 = InetAddress.getByName("::1");
+ assertEquals(ia2, ia1);
+ }
+
+ /**
+ * java.net.InetAddress#getAddress()
+ */
+ public void test_getAddress() throws UnknownHostException {
+ // Test for method byte [] java.net.InetAddress.getAddress()
+ try {
+ InetAddress ia = InetAddress.getByName("127.0.0.1");
+ byte[] caddr = new byte[] { 127, 0, 0, 1 };
+ byte[] addr = ia.getAddress();
+ for (int i = 0; i < addr.length; i++)
+ assertTrue("Incorrect address returned", caddr[i] == addr[i]);
+ } catch (java.net.UnknownHostException e) {
+ }
+
+ byte[] origBytes = new byte[] { 0, 1, 2, 3 };
+ InetAddress address = InetAddress.getByAddress(origBytes);
+ origBytes[0] = -1;
+ byte[] newBytes = address.getAddress();
+ assertSame((byte) 0, newBytes[0]);
+ }
+
+ /**
+ * java.net.InetAddress#getAllByName(java.lang.String)
+ */
+ @SuppressWarnings("nls")
+ public void test_getAllByNameLjava_lang_String() throws Exception {
+ // Test for method java.net.InetAddress []
+ // java.net.InetAddress.getAllByName(java.lang.String)
+ InetAddress[] all = InetAddress.getAllByName("localhost");
+ assertNotNull(all);
+ // Number of aliases depends on individual test machine
+ assertTrue(all.length >= 1);
+ for (InetAddress alias : all) {
+ // Check that each alias has the same hostname. Intentionally not
+ // checking for exact string match.
+ assertTrue(alias.getHostName().startsWith("localhost"));
+ }// end for all aliases
+
+ //Regression for HARMONY-56
+ InetAddress[] ias = InetAddress.getAllByName(null);
+ assertEquals(2, ias.length);
+ for (InetAddress ia : ias) {
+ assertTrue(ia.isLoopbackAddress());
+ }
+ ias = InetAddress.getAllByName("");
+ assertEquals(2, ias.length);
+ for (InetAddress ia : ias) {
+ assertTrue(ia.isLoopbackAddress());
+ }
+
+ // Check that getting addresses by dotted string distinguish
+ // IPv4 and IPv6 subtypes.
+ InetAddress[] list = InetAddress.getAllByName("192.168.0.1");
+ for (InetAddress addr : list) {
+ assertFalse("Expected subclass returned",
+ addr.getClass().equals(InetAddress.class));
+ }
+ }
+
+ /**
+ * java.net.InetAddress#getByName(java.lang.String)
+ */
+ public void test_getByNameLjava_lang_String() throws Exception {
+ // Test for method java.net.InetAddress
+ // java.net.InetAddress.getByName(java.lang.String)
+ InetAddress ia2 = InetAddress.getByName("127.0.0.1");
+
+ // TODO : Test to ensure all the address formats are recognized
+ InetAddress i = InetAddress.getByName("1.2.3");
+ assertEquals("1.2.0.3", i.getHostAddress());
+ i = InetAddress.getByName("1.2");
+ assertEquals("1.0.0.2", i.getHostAddress());
+ i = InetAddress.getByName(String.valueOf(0xffffffffL));
+ assertEquals("255.255.255.255", i.getHostAddress());
+ }
+
+ /**
+ * java.net.InetAddress#getHostAddress()
+ */
+ public void test_getHostAddress() throws Exception {
+ assertEquals("1.2.3.4", InetAddress.getByName("1.2.3.4").getHostAddress());
+ assertEquals("::1", InetAddress.getByName("::1").getHostAddress());
+ }
+
+ /**
+ * java.net.InetAddress#getLocalHost()
+ */
+ public void test_getLocalHost() throws Exception {
+ // Test for method java.net.InetAddress
+ // java.net.InetAddress.getLocalHost()
+
+ // We don't know the host name or ip of the machine
+ // running the test, so we can't build our own address
+ DatagramSocket dg = new DatagramSocket(0, InetAddress
+ .getLocalHost());
+ assertTrue("Incorrect host returned", InetAddress.getLocalHost()
+ .equals(dg.getLocalAddress()));
+ dg.close();
+ }
+
+ /**
+ * java.net.InetAddress#getLocalHost()
+ */
+ public void test_getLocalHost_extended() throws Exception {
+ // Bogus, but we don't know the host name or ip of the machine
+ // running the test, so we can't build our own address
+ DatagramSocket dg = new DatagramSocket(0, InetAddress.getLocalHost());
+ assertEquals("Incorrect host returned", InetAddress.getLocalHost(), dg.getLocalAddress());
+ dg.close();
+ }
+
+ /**
+ * java.net.InetAddress#isMulticastAddress()
+ */
+ public void test_isMulticastAddress() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertTrue(ia2.isMulticastAddress());
+ ia2 = InetAddress.getByName("localhost");
+ assertFalse(ia2.isMulticastAddress());
+ }
+
+ /**
+ * java.net.InetAddress#isAnyLocalAddress()
+ */
+ public void test_isAnyLocalAddress() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertFalse(ia2.isAnyLocalAddress());
+ ia2 = InetAddress.getByName("localhost");
+ assertFalse(ia2.isAnyLocalAddress());
+ }
+
+ /**
+ * java.net.InetAddress#isLinkLocalAddress()
+ */
+ public void test_isLinkLocalAddress() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertFalse(ia2.isLinkLocalAddress());
+ ia2 = InetAddress.getByName("localhost");
+ assertFalse(ia2.isLinkLocalAddress());
+ }
+
+ /**
+ * java.net.InetAddress#isLoopbackAddress()
+ */
+ public void test_isLoopbackAddress() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertFalse(ia2.isLoopbackAddress());
+ ia2 = InetAddress.getByName("localhost");
+ assertTrue(ia2.isLoopbackAddress());
+ ia2 = InetAddress.getByName("127.0.0.2");
+ assertTrue(ia2.isLoopbackAddress());
+ }
+
+ /**
+ * java.net.InetAddress#isLoopbackAddress()
+ */
+ public void test_isSiteLocalAddress() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertFalse(ia2.isSiteLocalAddress());
+ ia2 = InetAddress.getByName("localhost");
+ assertFalse(ia2.isSiteLocalAddress());
+ ia2 = InetAddress.getByName("127.0.0.2");
+ assertFalse(ia2.isSiteLocalAddress());
+ ia2 = InetAddress.getByName("243.243.45.3");
+ assertFalse(ia2.isSiteLocalAddress());
+ ia2 = InetAddress.getByName("10.0.0.2");
+ assertTrue(ia2.isSiteLocalAddress());
+ }
+
+ /**
+ * java.net.InetAddress#isMCGlobal()/isMCLinkLocal/isMCNodeLocal/isMCOrgLocal/isMCSiteLocal
+ */
+ public void test_isMCVerify() throws UnknownHostException {
+ InetAddress ia2 = InetAddress.getByName("239.255.255.255");
+ assertFalse(ia2.isMCGlobal());
+ assertFalse(ia2.isMCLinkLocal());
+ assertFalse(ia2.isMCNodeLocal());
+ assertFalse(ia2.isMCOrgLocal());
+ assertTrue(ia2.isMCSiteLocal());
+ ia2 = InetAddress.getByName("243.243.45.3");
+ assertFalse(ia2.isMCGlobal());
+ assertFalse(ia2.isMCLinkLocal());
+ assertFalse(ia2.isMCNodeLocal());
+ assertFalse(ia2.isMCOrgLocal());
+ assertFalse(ia2.isMCSiteLocal());
+ ia2 = InetAddress.getByName("250.255.255.254");
+ assertFalse(ia2.isMCGlobal());
+ assertFalse(ia2.isMCLinkLocal());
+ assertFalse(ia2.isMCNodeLocal());
+ assertFalse(ia2.isMCOrgLocal());
+ assertFalse(ia2.isMCSiteLocal());
+ ia2 = InetAddress.getByName("10.0.0.2");
+ assertFalse(ia2.isMCGlobal());
+ assertFalse(ia2.isMCLinkLocal());
+ assertFalse(ia2.isMCNodeLocal());
+ assertFalse(ia2.isMCOrgLocal());
+ assertFalse(ia2.isMCSiteLocal());
+ }
+
+ /**
+ * java.net.InetAddress#toString()
+ */
+ public void test_toString() throws Exception {
+ // Test for method java.lang.String java.net.InetAddress.toString()
+ InetAddress ia2 = InetAddress.getByName("127.0.0.1");
+ assertEquals("/127.0.0.1", ia2.toString());
+ // Regression for HARMONY-84
+ InetAddress addr2 = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
+ assertEquals("Assert 1: wrong string from address", "/127.0.0.1", addr2.toString());
+ }
+
+ /**
+ * java.net.InetAddress#getByAddress(java.lang.String, byte[])
+ */
+ public void test_getByAddressLjava_lang_String$B() {
+ // Check an IPv4 address with an IPv6 hostname
+ byte ipAddress[] = { 127, 0, 0, 1 };
+ String addressStr = "::1";
+ try {
+ InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress);
+ addr = InetAddress.getByAddress(ipAddress);
+ } catch (UnknownHostException e) {
+ fail("Unexpected problem creating IP Address "
+ + ipAddress.length);
+ }
+
+ byte ipAddress2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0,
+ 1 };
+ addressStr = "::1";
+ try {
+ InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress2);
+ addr = InetAddress.getByAddress(ipAddress);
+ } catch (UnknownHostException e) {
+ fail("Unexpected problem creating IP Address "
+ + ipAddress.length);
+ }
+ }
+
+ /**
+ * java.net.InetAddress#getCanonicalHostName()
+ */
+ public void test_getCanonicalHostName() throws Exception {
+ InetAddress theAddress = null;
+ theAddress = InetAddress.getLocalHost();
+ assertTrue("getCanonicalHostName returned a zero length string ",
+ theAddress.getCanonicalHostName().length() != 0);
+ assertTrue("getCanonicalHostName returned an empty string ",
+ !theAddress.equals(""));
+ }
+
+ /**
+ * java.net.InetAddress#isReachableI
+ */
+ public void test_isReachableI() throws Exception {
+ InetAddress ia = Inet4Address.getByName("127.0.0.1");
+ assertTrue(ia.isReachable(10000));
+ ia = Inet4Address.getByName("127.0.0.1");
+ try {
+ ia.isReachable(-1);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // correct
+ }
+ }
+
+ /**
+ * java.net.InetAddress#isReachableLjava_net_NetworkInterfaceII
+ */
+ public void test_isReachableLjava_net_NetworkInterfaceII() throws Exception {
+ // tests local address
+ InetAddress ia = Inet4Address.getByName("127.0.0.1");
+ assertTrue(ia.isReachable(null, 0, 10000));
+ ia = Inet4Address.getByName("127.0.0.1");
+ try {
+ ia.isReachable(null, -1, 10000);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // correct
+ }
+ try {
+ ia.isReachable(null, 0, -1);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // correct
+ }
+ try {
+ ia.isReachable(null, -1, -1);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // correct
+ }
+ // tests nowhere
+ ia = Inet4Address.getByName("1.1.1.1");
+ assertFalse(ia.isReachable(1000));
+ assertFalse(ia.isReachable(null, 0, 1000));
+
+ // Regression test for HARMONY-1842.
+ ia = InetAddress.getByName("localhost"); //$NON-NLS-1$
+ Enumeration<NetworkInterface> nif = NetworkInterface.getNetworkInterfaces();
+ NetworkInterface netif;
+ while (nif.hasMoreElements()) {
+ netif = nif.nextElement();
+ ia.isReachable(netif, 10, 1000);
+ }
+ }
+
+ // comparator for InetAddress objects
+ private static final SerializableAssert COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ InetAddress initAddr = (InetAddress) initial;
+ InetAddress desrAddr = (InetAddress) deserialized;
+
+ byte[] iaAddresss = initAddr.getAddress();
+ byte[] deIAAddresss = desrAddr.getAddress();
+ for (int i = 0; i < iaAddresss.length; i++) {
+ assertEquals(iaAddresss[i], deIAAddresss[i]);
+ }
+ assertEquals(initAddr.getHostName(), desrAddr.getHostName());
+ }
+ };
+
+ // Regression Test for Harmony-2290
+ public void test_isReachableLjava_net_NetworkInterfaceII_loopbackInterface() throws IOException {
+ final int TTL = 20;
+ final int TIME_OUT = 3000;
+
+ NetworkInterface loopbackInterface = null;
+ ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
+ Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
+ .getNetworkInterfaces();
+ while (networkInterfaces.hasMoreElements()) {
+ NetworkInterface networkInterface = networkInterfaces.nextElement();
+ Enumeration<InetAddress> addresses = networkInterface
+ .getInetAddresses();
+ while (addresses.hasMoreElements()) {
+ InetAddress address = addresses.nextElement();
+ if (address.isLoopbackAddress()) {
+ loopbackInterface = networkInterface;
+ } else {
+ localAddresses.add(address);
+ }
+ }
+ }
+
+ //loopbackInterface can reach local address
+ if (null != loopbackInterface) {
+ for (InetAddress destAddress : localAddresses) {
+ assertTrue(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
+ }
+ }
+
+ //loopback Interface cannot reach outside address
+ InetAddress destAddress = InetAddress.getByName("www.google.com");
+ assertFalse(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
+ }
+
+ /**
+ * serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(InetAddress.getByName("localhost"),
+ COMPARATOR);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ InetAddress.getByName("localhost"), COMPARATOR);
+ }
+
+ /**
+ * java.net.InetAddress#getByAddress(byte[])
+ */
+ public void test_getByAddress() {
+ // Regression for HARMONY-61
+ try {
+ InetAddress.getByAddress(null);
+ fail("Assert 0: UnknownHostException must be thrown");
+ } catch (UnknownHostException e) {
+ // Expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressThreadTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressThreadTest.java
new file mode 100644
index 0000000..840f28e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetAddressThreadTest.java
@@ -0,0 +1,175 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.InetAddress;
+
+import tests.support.Support_Configuration;
+
+public class InetAddressThreadTest extends junit.framework.TestCase {
+
+ private static boolean someoneDone[] = new boolean[2];
+
+ protected static boolean threadedTestSucceeded;
+
+ protected static String threadedTestErrorString;
+
+ /**
+ * This class is used to test inet_ntoa, gethostbyaddr and gethostbyname
+ * functions in the VM to make sure they're threadsafe. getByName will cause
+ * the gethostbyname function to be called. getHostName will cause the
+ * gethostbyaddr to be called. getHostAddress will cause inet_ntoa to be
+ * called.
+ */
+ static class threadsafeTestThread extends Thread {
+ private String lookupName;
+
+ private InetAddress testAddress;
+
+ private int testType;
+
+ /*
+ * REP_NUM can be adjusted if desired. Since this error is
+ * non-deterministic it may not always occur. Setting REP_NUM higher,
+ * increases the chances of an error being detected, but causes the test
+ * to take longer. Because the Java threads spend a lot of time
+ * performing operations other than running the native code that may not
+ * be threadsafe, it is quite likely that several thousand iterations
+ * will elapse before the first error is detected.
+ */
+ private static final int REP_NUM = 20000;
+
+ public threadsafeTestThread(String name, String lookupName,
+ InetAddress testAddress, int type) {
+ super(name);
+ this.lookupName = lookupName;
+ this.testAddress = testAddress;
+ testType = type;
+ }
+
+ public void run() {
+ try {
+ String correctName = testAddress.getHostName();
+ String correctAddress = testAddress.getHostAddress();
+ long startTime = System.currentTimeMillis();
+
+ synchronized (someoneDone) {
+ }
+
+ for (int i = 0; i < REP_NUM; i++) {
+ if (someoneDone[testType]) {
+ break;
+ } else if ((i % 25) == 0
+ && System.currentTimeMillis() - startTime > 240000) {
+ System.out
+ .println("Exiting due to time limitation after "
+ + i + " iterations");
+ break;
+ }
+
+ InetAddress ia = InetAddress.getByName(lookupName);
+ String hostName = ia.getHostName();
+ String hostAddress = ia.getHostAddress();
+
+ // Intentionally not looking for exact name match so that
+ // the test works across different platforms that may or
+ // may not include a domain suffix on the hostname
+ if (!hostName.startsWith(correctName)) {
+ threadedTestSucceeded = false;
+ threadedTestErrorString = (testType == 0 ? "gethostbyname"
+ : "gethostbyaddr")
+ + ": getHostName() returned "
+ + hostName
+ + " instead of " + correctName;
+ break;
+ }
+ // IP addresses should match exactly
+ if (!correctAddress.equals(hostAddress)) {
+ threadedTestSucceeded = false;
+ threadedTestErrorString = (testType == 0 ? "gethostbyname"
+ : "gethostbyaddr")
+ + ": getHostName() returned "
+ + hostAddress
+ + " instead of " + correctAddress;
+ break;
+ }
+
+ }
+ someoneDone[testType] = true;
+ } catch (Exception e) {
+ threadedTestSucceeded = false;
+ threadedTestErrorString = e.toString();
+ }
+ }
+ }
+
+ /**
+ * java.net.InetAddress#getHostName()
+ */
+ public void test_getHostName() throws Exception {
+ // Test for method java.lang.String java.net.InetAddress.getHostName()
+
+ // Make sure there is no caching
+ String originalPropertyValue = System
+ .getProperty("networkaddress.cache.ttl");
+ System.setProperty("networkaddress.cache.ttl", "0");
+
+ // Test for threadsafety
+ try {
+ InetAddress lookup1 = InetAddress.getByName("localhost");
+ assertEquals("127.0.0.1", lookup1.getHostAddress());
+ InetAddress lookup2 = InetAddress.getByName("localhost");
+ assertEquals("127.0.0.1", lookup2.getHostAddress());
+ threadsafeTestThread thread1 = new threadsafeTestThread("1",
+ lookup1.getHostName(), lookup1, 0);
+ threadsafeTestThread thread2 = new threadsafeTestThread("2",
+ lookup2.getHostName(), lookup2, 0);
+ threadsafeTestThread thread3 = new threadsafeTestThread("3",
+ lookup1.getHostAddress(), lookup1, 1);
+ threadsafeTestThread thread4 = new threadsafeTestThread("4",
+ lookup2.getHostAddress(), lookup2, 1);
+
+ // initialize the flags
+ threadedTestSucceeded = true;
+ synchronized (someoneDone) {
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+ }
+ thread1.join();
+ thread2.join();
+ thread3.join();
+ thread4.join();
+ /* FIXME: comment the assertion below because it is platform/configuration dependent
+ * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
+ * for details
+ */
+// assertTrue(threadedTestErrorString, threadedTestSucceeded);
+ } finally {
+ // restore the old value of the property
+ if (originalPropertyValue == null)
+ // setting the property to -1 has the same effect as having the
+ // property be null
+ System.setProperty("networkaddress.cache.ttl", "-1");
+ else
+ System.setProperty("networkaddress.cache.ttl",
+ originalPropertyValue);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetSocketAddressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetSocketAddressTest.java
new file mode 100644
index 0000000..916ee3e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InetSocketAddressTest.java
@@ -0,0 +1,131 @@
+/* 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.tests.java.net;
+
+import java.io.Serializable;
+import java.net.InetSocketAddress;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class InetSocketAddressTest extends TestCase {
+
+ /**
+ * java.net.InetSocketAddress#InetSocketAddress(String, int)
+ */
+ public void test_ConstructorLjava_lang_StringI() throws Exception {
+ // regression test for Harmony-1042
+ InetSocketAddress address = new InetSocketAddress("127.0.0.1", 0);
+ assertEquals("/127.0.0.1:0", address.toString());
+ String localhostName = address.getHostName();
+ assertNotNull(localhostName);
+ assertEquals(localhostName + "/127.0.0.1:0", address.toString());
+ }
+
+ /**
+ * java.net.InetSocketAddress#createUnresolved(String, int)
+ */
+ public void test_createUnresolvedLjava_lang_StringI() {
+ HostPortPair[] legalHostPortPairs = { new HostPortPair("127.0.0.1", 1234),
+ new HostPortPair("192.168.0.1", 10000), new HostPortPair("127.0.0", 0),
+ new HostPortPair("127.0.0", 65535),
+ new HostPortPair("strange host", 65535) };
+ for (int i = 0; i < legalHostPortPairs.length; i++) {
+ InetSocketAddress isa = InetSocketAddress.createUnresolved(
+ legalHostPortPairs[i].host, legalHostPortPairs[i].port);
+ assertTrue(isa.isUnresolved());
+ assertNull(isa.getAddress());
+ assertEquals(isa.getHostName(), legalHostPortPairs[i].host);
+ assertEquals(isa.getPort(), legalHostPortPairs[i].port);
+ }
+ }
+
+ /**
+ * java.net.InetSocketAddress#createUnresolved(String, int)
+ */
+ public void test_createUnresolvedLjava_lang_StringI_IllegalArgumentException() {
+ HostPortPair[] illegalHostPortPairs = { new HostPortPair(null, 1),
+ new HostPortPair("host", -1), new HostPortPair("host", 65536) };
+ for (int i = 0; i < illegalHostPortPairs.length; i++) {
+ try {
+ InetSocketAddress.createUnresolved(
+ illegalHostPortPairs[i].host,
+ illegalHostPortPairs[i].port);
+ fail("should throw IllegalArgumentException, host = "
+ + illegalHostPortPairs[i].host + ",port = "
+ + illegalHostPortPairs[i].port);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+ }
+
+ /*
+ * inner class for createUnresolved test convenience.
+ */
+ class HostPortPair {
+ String host;
+
+ int port;
+
+ public HostPortPair(String host, int port) {
+ this.host = host;
+ this.port = port;
+ }
+ }
+
+ ;
+
+ // comparator for InetSocketAddress objects
+ private static final SerializableAssert COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ InetSocketAddress init = (InetSocketAddress) initial;
+ InetSocketAddress desr = (InetSocketAddress) deserialized;
+
+ assertEquals("HostName", init.getHostName(), desr.getHostName());
+ assertEquals("Port", init.getPort(), desr.getPort());
+ assertEquals("Address", init.getAddress(), desr.getAddress());
+ }
+ };
+
+ /**
+ * serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ Object[] testCases = {
+ InetSocketAddress.createUnresolved("badhost", 1000), // unresolved
+ new InetSocketAddress("Localhost", 1000) };
+
+ SerializationTest.verifySelf(testCases, COMPARATOR);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ Object[] testCases = {
+ InetSocketAddress.createUnresolved("badhost", 1000), // unresolved
+ new InetSocketAddress("Localhost", 1000) };
+
+ SerializationTest.verifyGolden(this, testCases, COMPARATOR);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InterfaceAddressTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InterfaceAddressTest.java
new file mode 100644
index 0000000..c4c2b90
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/InterfaceAddressTest.java
@@ -0,0 +1,164 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InterfaceAddress;
+import java.net.NetworkInterface;
+import java.util.Enumeration;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+public class InterfaceAddressTest extends TestCase {
+ private InterfaceAddress interfaceAddr;
+
+ private InterfaceAddress anotherInterfaceAddr;
+
+ /**
+ * java.net.InterfaceAddress.hashCode()
+ * @since 1.6
+ */
+ public void test_hashCode() {
+ // RI may fail on this when both broadcast addresses are null
+ if (interfaceAddr != null) {
+ assertEquals(anotherInterfaceAddr, interfaceAddr);
+ assertEquals(anotherInterfaceAddr.hashCode(), interfaceAddr
+ .hashCode());
+ }
+ }
+
+ /**
+ * java.net.InterfaceAddress.equals(Object)
+ * @since 1.6
+ */
+ public void test_equals_LObject() {
+ // RI may fail on this when both broadcast addresses are null
+ if (interfaceAddr != null) {
+ assertFalse(interfaceAddr.equals(null));
+ assertFalse(interfaceAddr.equals(new Object()));
+
+ assertTrue(interfaceAddr.equals(anotherInterfaceAddr));
+ assertNotSame(anotherInterfaceAddr, interfaceAddr);
+ }
+ }
+
+ /**
+ * java.net.InterfaceAddress.toString()
+ * @since 1.6
+ */
+ public void test_toString() {
+ if (interfaceAddr != null) {
+ assertNotNull(interfaceAddr.toString());
+ assertEquals(anotherInterfaceAddr.toString(), interfaceAddr
+ .toString());
+ assertTrue(interfaceAddr.toString().contains("/"));
+ assertTrue(interfaceAddr.toString().contains("["));
+ assertTrue(interfaceAddr.toString().contains("]"));
+ }
+ }
+
+ /**
+ * java.net.InterfaceAddress.getAddress()
+ * @since 1.6
+ */
+ public void test_getAddress() {
+ if (interfaceAddr != null) {
+ InetAddress addr1 = interfaceAddr.getAddress();
+ assertNotNull(addr1);
+ InetAddress addr2 = anotherInterfaceAddr.getAddress();
+ assertNotNull(addr2);
+ assertEquals(addr2, addr1);
+ }
+ }
+
+ /**
+ * java.net.InterfaceAddress.getBroadcast()
+ * @since 1.6
+ */
+ public void test_getBroadcast() {
+ if (interfaceAddr != null) {
+ InetAddress addr = interfaceAddr.getAddress();
+ InetAddress addr1 = interfaceAddr.getBroadcast();
+ InetAddress addr2 = anotherInterfaceAddr.getBroadcast();
+ if (addr instanceof Inet4Address) {
+ assertEquals(addr2, addr1);
+ } else if (addr instanceof Inet6Address) {
+ assertNull(addr1);
+ assertNull(addr2);
+ }
+ }
+ }
+
+ /**
+ * java.net.InterfaceAddress.getNetworkPrefixLength()
+ * @since 1.6
+ */
+ public void test_getNetworkPrefixLength() {
+ if (interfaceAddr != null) {
+ short prefix1 = interfaceAddr.getNetworkPrefixLength();
+ short prefix2 = anotherInterfaceAddr.getNetworkPrefixLength();
+ assertEquals(prefix2, prefix1);
+ }
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ Enumeration<NetworkInterface> netifs = NetworkInterface
+ .getNetworkInterfaces();
+ NetworkInterface theInterface = null;
+ if (netifs != null) {
+ while (netifs.hasMoreElements()) {
+ theInterface = netifs.nextElement();
+ if (theInterface != null) {
+ List<InterfaceAddress> addrs = theInterface
+ .getInterfaceAddresses();
+ if (!(addrs == null || addrs.isEmpty())) {
+ interfaceAddr = addrs.get(0);
+ break;
+ }
+ }
+ }
+ }
+
+ // get another InterfaceAddress object if the interfaceAddr exists. It
+ // equals to interfaceAddr, but is not the same one.
+ if (theInterface != null && interfaceAddr != null) {
+ Enumeration<InetAddress> addresses = theInterface
+ .getInetAddresses();
+ if (addresses != null && addresses.hasMoreElements()) {
+ NetworkInterface anotherNetworkInter = NetworkInterface
+ .getByInetAddress(addresses.nextElement());
+ anotherInterfaceAddr = anotherNetworkInter
+ .getInterfaceAddresses().get(0);
+ }
+ }
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ interfaceAddr = null;
+ anotherInterfaceAddr = null;
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/JarURLConnectionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/JarURLConnectionTest.java
new file mode 100644
index 0000000..c938785
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/JarURLConnectionTest.java
@@ -0,0 +1,312 @@
+/*
+ * 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.tests.java.net;
+
+import tests.support.resource.Support_Resources;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.JarURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+public class JarURLConnectionTest extends junit.framework.TestCase {
+
+ private JarURLConnection juc;
+
+ private URL copyAndOpenResourceStream(String jarFile, String inFile)
+ throws MalformedURLException {
+
+ File resources = Support_Resources.createTempFolder();
+
+ Support_Resources.copyFile(resources, "net", jarFile);
+ File file = new File(resources.toString() + "/net/" + jarFile);
+
+ return new URL("jar:file:" + file.getPath() + "!/" + inFile);
+ }
+
+
+ /**
+ * java.net.JarURLConnection#getAttributes()
+ */
+ public void test_getAttributes() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "swt.dll");
+
+ juc = (JarURLConnection) u.openConnection();
+ java.util.jar.Attributes a = juc.getJarEntry().getAttributes();
+ assertEquals("Returned incorrect Attributes", "SHA MD5", a
+ .get(new java.util.jar.Attributes.Name("Digest-Algorithms")));
+ }
+
+ /**
+ * @throws Exception
+ * java.net.JarURLConnection#getEntryName()
+ */
+ public void test_getEntryName() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ juc = (JarURLConnection) u.openConnection();
+ assertEquals("Returned incorrect entryName", "plus.bmp", juc
+ .getEntryName());
+ u = copyAndOpenResourceStream("lf.jar", "");
+ juc = (JarURLConnection) u.openConnection();
+ assertNull("Returned incorrect entryName", juc.getEntryName());
+// Regression test for harmony-3053
+ URL url = copyAndOpenResourceStream("lf.jar", "foo.jar!/Bugs/HelloWorld.class");
+ assertEquals("foo.jar!/Bugs/HelloWorld.class", ((JarURLConnection) url.openConnection()).getEntryName());
+ }
+
+ /**
+ * java.net.JarURLConnection#getJarEntry()
+ */
+ public void test_getJarEntry() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ juc = (JarURLConnection) u.openConnection();
+ assertEquals("Returned incorrect JarEntry", "plus.bmp", juc
+ .getJarEntry().getName());
+ u = copyAndOpenResourceStream("lf.jar", "");
+ juc = (JarURLConnection) u.openConnection();
+ assertNull("Returned incorrect JarEntry", juc.getJarEntry());
+ }
+
+ /**
+ * java.net.JarURLConnection#getJarFile()
+ */
+ public void test_getJarFile() throws MalformedURLException, IOException {
+ URL url = copyAndOpenResourceStream("lf.jar", "missing");
+
+ JarURLConnection connection = null;
+ connection = (JarURLConnection) url.openConnection();
+ try {
+ connection.connect();
+ fail("Did not throw exception on connect");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ connection.getJarFile();
+ fail("Did not throw exception after connect");
+ } catch (IOException e) {
+ // expected
+ }
+
+ File resources = Support_Resources.createTempFolder();
+
+ Support_Resources.copyFile(resources, null, "hyts_att.jar");
+ File file = new File(resources.toString() + "/hyts_att.jar");
+ URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/");
+ JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
+ ZipFile jf1 = con1.getJarFile();
+ JarURLConnection con2 = (JarURLConnection) fUrl1.openConnection();
+ ZipFile jf2 = con2.getJarFile();
+ assertTrue("file: JarFiles not the same", jf1 == jf2);
+ jf1.close();
+ assertTrue("File should exist", file.exists());
+ con1 = (JarURLConnection) fUrl1.openConnection();
+ jf1 = con1.getJarFile();
+ con2 = (JarURLConnection) fUrl1.openConnection();
+ jf2 = con2.getJarFile();
+ assertTrue("http: JarFiles not the same", jf1 == jf2);
+ jf1.close();
+ }
+
+ /**
+ * java.net.JarURLConnection.getJarFile()
+ * <p/>
+ * Regression test for HARMONY-29
+ */
+ public void test_getJarFile29() throws Exception {
+ File jarFile = File.createTempFile("1+2 3", "test.jar");
+ jarFile.deleteOnExit();
+ JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile));
+ out.putNextEntry(new ZipEntry("test"));
+ out.closeEntry();
+ out.close();
+
+ JarURLConnection conn = (JarURLConnection) new URL("jar:file:"
+ + jarFile.getAbsolutePath().replaceAll(" ", "%20") + "!/")
+ .openConnection();
+ conn.getJarFile().entries();
+ }
+
+ //Regression for HARMONY-3436
+ public void test_setUseCaches() throws Exception {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "hyts_att.jar");
+ File file = new File(resources.toString() + "/hyts_att.jar");
+ URL url = new URL("jar:file:" + file.getPath() + "!/HasAttributes.txt");
+
+ JarURLConnection connection = (JarURLConnection) url.openConnection();
+ connection.setUseCaches(false);
+ InputStream in = connection.getInputStream();
+ JarFile jarFile1 = connection.getJarFile();
+ JarEntry jarEntry1 = connection.getJarEntry();
+ byte[] data = new byte[1024];
+ while (in.read(data) >= 0)
+ ;
+ in.close();
+ JarFile jarFile2 = connection.getJarFile();
+ JarEntry jarEntry2 = connection.getJarEntry();
+ assertSame(jarFile1, jarFile2);
+ assertSame(jarEntry1, jarEntry2);
+
+ try {
+ connection.getInputStream();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.JarURLConnection#getJarFileURL()
+ */
+ public void test_getJarFileURL() throws Exception {
+ // Regression test for harmony-3053
+ URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
+ assertEquals("file:///bar.jar", ((JarURLConnection) url.openConnection()).getJarFileURL().toString());
+ }
+
+ /**
+ * java.net.JarURLConnection#getMainAttributes()
+ */
+ public void test_getMainAttributes() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "swt.dll");
+ juc = (JarURLConnection) u.openConnection();
+ java.util.jar.Attributes a = juc.getMainAttributes();
+ assertEquals("Returned incorrect Attributes", "1.0", a
+ .get(java.util.jar.Attributes.Name.MANIFEST_VERSION));
+ }
+
+ /**
+ * java.net.JarURLConnection#getInputStream()
+ */
+ public void test_getInputStream_DeleteJarFileUsingURLConnection()
+ throws Exception {
+ File file = File.createTempFile("JarUrlConnectionTest", "jar");
+ FileOutputStream jarFile = new FileOutputStream(file);
+ JarOutputStream out = new JarOutputStream(new BufferedOutputStream(
+ jarFile));
+ JarEntry jarEntry = new JarEntry("entry.txt");
+ out.putNextEntry(jarEntry);
+ out.write(new byte[] { 'a', 'b', 'c' });
+ out.close();
+
+ URL url = new URL("jar:file:" + file.getAbsolutePath() + "!/entry.txt");
+ URLConnection conn = url.openConnection();
+ conn.setUseCaches(false);
+ InputStream is = conn.getInputStream();
+ is.close();
+ assertTrue(file.delete());
+ }
+
+ /**
+ * java.net.JarURLConnection#getManifest()
+ */
+ public void test_getManifest() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ juc = (JarURLConnection) u.openConnection();
+ Manifest mf = juc.getManifest();
+ assertNotNull(mf);
+ // equal but not same manifest
+ assertEquals(mf, juc.getManifest());
+ assertNotSame(mf, juc.getManifest());
+ // same main attributes
+ assertEquals(juc.getMainAttributes(), mf.getMainAttributes());
+ }
+
+ /**
+ * java.net.JarURLConnection#getCertificates()
+ */
+ public void test_getCertificates() throws Exception {
+ URL u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ juc = (JarURLConnection) u.openConnection();
+ // read incomplete, shall return null
+ assertNull(juc.getCertificates());
+ assertEquals("Returned incorrect JarEntry", "plus.bmp", juc
+ .getJarEntry().getName());
+ // read them all
+ InputStream is = juc.getInputStream();
+ byte[] buf = new byte[80];
+ while (is.read(buf) > 0) ;
+ // still return null for this type of file
+ assertNull(juc.getCertificates());
+
+ URL fileURL = copyAndOpenResourceStream("lf.jar", "");
+ juc = (JarURLConnection) fileURL.openConnection();
+ is = juc.getJarFileURL().openStream();
+ while (is.read(buf) > 0) ;
+ // null for this jar file
+ assertNull(juc.getCertificates());
+ }
+
+ /**
+ * java.net.JarURLConnection#getContentLength()
+ * Regression test for HARMONY-3665
+ */
+ public void test_getContentLength() throws Exception {
+ // check length for jar file itself
+ URL u = copyAndOpenResourceStream("lf.jar", "");
+ assertEquals("Returned incorrect size for jar file", 33095,
+ u.openConnection().getContentLength());
+
+ // check length for jar entry
+ u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ assertEquals("Returned incorrect size for the entry", 190,
+ u.openConnection().getContentLength());
+ }
+
+ /**
+ * java.net.JarURLConnection#getContentType()
+ * Regression test for HARMONY-3665
+ */
+ public void test_getContentType() throws Exception {
+ // check type for jar file itself
+ URL u = copyAndOpenResourceStream("lf.jar", "");
+ assertEquals("Returned incorrect type for jar file", "x-java/jar",
+ u.openConnection().getContentType());
+
+ // check type for jar entry with known type
+ u = copyAndOpenResourceStream("lf.jar", "plus.bmp");
+ assertEquals("Returned incorrect type for the entry with known type",
+ "image/x-ms-bmp", u.openConnection().getContentType());
+
+ // check type for jar entry with unknown type
+ u = copyAndOpenResourceStream("lf.jar", "Manifest.mf");
+ assertEquals("Returned incorrect type for the entry with known type",
+ "content/unknown", u.openConnection().getContentType());
+ }
+
+ public void test_getURLEncodedEntry() throws IOException {
+ URL url = copyAndOpenResourceStream("url-test.jar", "test%20folder%20for%20url%20test/test");
+ if (url != null) {
+ // Force existence check
+ InputStream is = url.openStream();
+ is.close();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MalformedURLExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MalformedURLExceptionTest.java
new file mode 100644
index 0000000..d5c2287
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MalformedURLExceptionTest.java
@@ -0,0 +1,72 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+public class MalformedURLExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.MalformedURLException#MalformedURLException()
+ */
+ public void test_Constructor() {
+ // Test for method java.net.MalformedURLException()
+ boolean passed;
+ passed = false;
+ try {
+ new URL("notAProtocol://www.ibm.com");
+ } catch (MalformedURLException e) {
+ // correct
+ passed = true;
+ }
+
+ assertTrue("Failed to throw correct exception", passed);
+ }
+
+ /**
+ * java.net.MalformedURLException#MalformedURLException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.net.MalformedURLException(java.lang.String)
+ final String myString = "Gawsh!";
+ try {
+ if (true)
+ throw new MalformedURLException(myString);
+ } catch (MalformedURLException e) {
+ assertTrue("Incorrect exception text", e.toString().indexOf(
+ myString) >= 0);
+ return;
+ }
+ fail("Exception not thrown");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java
new file mode 100644
index 0000000..828dc99
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java
@@ -0,0 +1,929 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.BindException;
+import java.net.DatagramPacket;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MulticastSocket;
+import java.net.NetworkInterface;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+public class MulticastSocketTest extends junit.framework.TestCase {
+
+ private static InetAddress lookup(String s) {
+ try {
+ return InetAddress.getByName(s);
+ } catch (IOException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ // These IP addresses aren't inherently "good" or "bad"; they're just used like that.
+ // We use the "good" addresses for our actual group, and the "bad" addresses are for
+ // a group that we won't actually set up.
+
+ private static InetAddress GOOD_IPv4 = lookup("224.0.0.3");
+ private static InetAddress BAD_IPv4 = lookup("224.0.0.4");
+
+ private static InetAddress GOOD_IPv6 = lookup("ff05::7:7");
+ private static InetAddress BAD_IPv6 = lookup("ff05::7:8");
+
+ private NetworkInterface loopbackInterface;
+ private NetworkInterface ipv4NetworkInterface;
+ private NetworkInterface ipv6NetworkInterface;
+ private boolean supportsMulticast;
+
+ @Override
+ protected void setUp() throws Exception {
+ // The loopback interface isn't actually useful for sending/receiving multicast messages
+ // but it can be used as a dummy for tests where that does not matter.
+ loopbackInterface = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
+ assertNotNull(loopbackInterface);
+ assertTrue(loopbackInterface.isLoopback());
+ assertFalse(loopbackInterface.supportsMulticast());
+
+ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ assertNotNull(interfaces);
+
+ // Determine if the device is marked to support multicast or not. If this propery is not
+ // set we assume the device has an interface capable of supporting multicast.
+ supportsMulticast = Boolean.valueOf(
+ System.getProperty("android.cts.device.multicast", "true"));
+ if (!supportsMulticast) {
+ return;
+ }
+
+ while (interfaces.hasMoreElements()
+ && (ipv4NetworkInterface == null || ipv6NetworkInterface == null)) {
+ NetworkInterface nextInterface = interfaces.nextElement();
+ if (willWorkForMulticast(nextInterface)) {
+ Enumeration<InetAddress> addresses = nextInterface.getInetAddresses();
+ while (addresses.hasMoreElements()) {
+ final InetAddress nextAddress = addresses.nextElement();
+ if (nextAddress instanceof Inet6Address && ipv6NetworkInterface == null) {
+ ipv6NetworkInterface = nextInterface;
+ } else if (nextAddress instanceof Inet4Address && ipv4NetworkInterface == null) {
+ ipv4NetworkInterface = nextInterface;
+ }
+ }
+ }
+ }
+ assertTrue("Test environment must have at least one interface capable of multicast for IPv4"
+ + " and IPv6",
+ ipv4NetworkInterface != null && ipv6NetworkInterface != null);
+ }
+
+ public void test_Constructor() throws IOException {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Regression test for 497.
+ MulticastSocket s = new MulticastSocket();
+ // Regression test for Harmony-1162.
+ assertTrue(s.getReuseAddress());
+
+ s.close();
+ }
+
+ public void test_ConstructorI() throws IOException {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket orig = new MulticastSocket();
+ int port = orig.getLocalPort();
+ orig.close();
+
+ MulticastSocket dup = new MulticastSocket(port);
+ // Regression test for Harmony-1162.
+ assertTrue(dup.getReuseAddress());
+ dup.close();
+ }
+
+ public void test_getInterface() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Validate that we get the expected response when one was not set.
+ MulticastSocket mss = new MulticastSocket(0);
+ // We expect an ANY address in this case.
+ assertTrue(mss.getInterface().isAnyLocalAddress());
+
+ // Validate that we get the expected response when we set via setInterface.
+ Enumeration addresses = ipv4NetworkInterface.getInetAddresses();
+ if (addresses.hasMoreElements()) {
+ InetAddress firstAddress = (InetAddress) addresses.nextElement();
+ mss.setInterface(firstAddress);
+ assertEquals("getNetworkInterface did not return interface set by setInterface",
+ firstAddress, mss.getInterface());
+
+ mss.close();
+ mss = new MulticastSocket(0);
+ mss.setNetworkInterface(ipv4NetworkInterface);
+ assertEquals("getInterface did not return interface set by setNetworkInterface",
+ ipv4NetworkInterface, NetworkInterface.getByInetAddress(mss.getInterface()));
+ }
+
+ mss.close();
+ }
+
+ public void test_getNetworkInterface() throws IOException {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Validate that we get the expected response when one was not set.
+ MulticastSocket mss = new MulticastSocket(0);
+ NetworkInterface theInterface = mss.getNetworkInterface();
+ assertTrue(
+ "network interface returned wrong network interface when not set:" + theInterface,
+ theInterface.getInetAddresses().hasMoreElements());
+ InetAddress firstAddress = theInterface.getInetAddresses().nextElement();
+ // Validate we the first address in the network interface is the ANY address.
+ assertTrue(firstAddress.isAnyLocalAddress());
+
+ mss.setNetworkInterface(ipv4NetworkInterface);
+ assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
+ ipv4NetworkInterface, mss.getNetworkInterface());
+
+ mss.setNetworkInterface(loopbackInterface);
+ assertEquals(
+ "getNetworkInterface did not return network interface set by second"
+ + " setNetworkInterface call",
+ loopbackInterface, mss.getNetworkInterface());
+ mss.close();
+
+ if (ipv6NetworkInterface != null) {
+ mss = new MulticastSocket(0);
+ mss.setNetworkInterface(ipv6NetworkInterface);
+ assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
+ ipv6NetworkInterface, mss.getNetworkInterface());
+ mss.close();
+ }
+
+ // Validate that we get the expected response when we set via setInterface.
+ mss = new MulticastSocket(0);
+ Enumeration addresses = ipv4NetworkInterface.getInetAddresses();
+ if (addresses.hasMoreElements()) {
+ firstAddress = (InetAddress) addresses.nextElement();
+ mss.setInterface(firstAddress);
+ assertEquals("getNetworkInterface did not return interface set by setInterface",
+ ipv4NetworkInterface, mss.getNetworkInterface());
+ }
+ mss.close();
+ }
+
+ public void test_getTimeToLive() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket();
+ mss.setTimeToLive(120);
+ assertEquals("Returned incorrect 1st TTL", 120, mss.getTimeToLive());
+ mss.setTimeToLive(220);
+ assertEquals("Returned incorrect 2nd TTL", 220, mss.getTimeToLive());
+ mss.close();
+ }
+
+ public void test_getTTL() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket();
+ mss.setTTL((byte) 120);
+ assertEquals("Returned incorrect TTL", 120, mss.getTTL());
+ mss.close();
+ }
+
+ public void test_joinGroupLjava_net_InetAddress_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_InetAddress(GOOD_IPv4);
+ }
+
+ public void test_joinGroupLjava_net_InetAddress_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_InetAddress(GOOD_IPv6);
+ }
+
+ private void test_joinGroupLjava_net_InetAddress(InetAddress group) throws Exception {
+ MulticastSocket receivingSocket = createReceivingSocket(0);
+ receivingSocket.joinGroup(group);
+
+ String msg = "Hello World";
+ MulticastSocket sendingSocket = new MulticastSocket(receivingSocket.getLocalPort());
+ InetSocketAddress groupAddress =
+ new InetSocketAddress(group, receivingSocket.getLocalPort());
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ sendingSocket.send(sdp, (byte) 10 /* ttl */);
+
+ DatagramPacket rdp = createReceiveDatagramPacket();
+ receivingSocket.receive(rdp);
+ String receivedMessage = extractMessage(rdp);
+ assertEquals("Group member did not recv data", msg, receivedMessage);
+
+ sendingSocket.close();
+ receivingSocket.close();
+ }
+
+ public void test_joinGroup_null_null() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.joinGroup(null, null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_joinGroup_non_multicast_address_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.joinGroup(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), null);
+ fail();
+ } catch (IOException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_joinGroup_non_multicast_address_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.joinGroup(new InetSocketAddress(InetAddress.getByName("::1"), 0), null);
+ fail();
+ } catch (IOException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_IPv4()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ ipv4NetworkInterface, GOOD_IPv4, BAD_IPv4);
+ }
+
+ public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_IPv6()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ ipv6NetworkInterface, GOOD_IPv6, BAD_IPv6);
+ }
+
+ private void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ NetworkInterface networkInterface, InetAddress group, InetAddress group2)
+ throws Exception {
+ // Check that we can join a group using a null network interface.
+ MulticastSocket sendingSocket = new MulticastSocket(0);
+ SocketAddress groupSockAddr = new InetSocketAddress(group, sendingSocket.getLocalPort());
+ sendingSocket.joinGroup(groupSockAddr, null);
+ sendingSocket.setTimeToLive(2);
+
+ MulticastSocket receivingSocket = createReceivingSocket(0);
+ InetSocketAddress groupAddress =
+ new InetSocketAddress(group, receivingSocket.getLocalPort());
+ receivingSocket.joinGroup(groupAddress, networkInterface);
+
+ String msg = "Hello World";
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ sendingSocket.send(sdp);
+
+ DatagramPacket rdp = createReceiveDatagramPacket();
+ receivingSocket.receive(rdp);
+ // Now validate that we received the data as expected.
+ assertEquals("Group member did not recv data", msg, extractMessage(rdp));
+ receivingSocket.close();
+ sendingSocket.close();
+
+ receivingSocket = createReceivingSocket(0);
+ groupAddress = new InetSocketAddress(group, receivingSocket.getLocalPort());
+ receivingSocket.joinGroup(groupAddress, networkInterface);
+
+ sendingSocket = new MulticastSocket(0);
+ sendingSocket.setTimeToLive(10);
+ msg = "Hello World - Different Group";
+ InetSocketAddress group2Address =
+ new InetSocketAddress(group2, receivingSocket.getLocalPort());
+ sdp = createSendDatagramPacket(group2Address, msg);
+ sendingSocket.send(sdp);
+
+ rdp = createReceiveDatagramPacket();
+ try {
+ receivingSocket.receive(rdp);
+ fail("Expected timeout");
+ } catch (SocketTimeoutException expected) {
+ }
+
+ receivingSocket.close();
+ sendingSocket.close();
+ }
+
+ public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Check that we can join on specific interfaces and that we only receive if data is
+ // received on that interface. This test is only really useful on devices with multiple
+ // non-loopback interfaces.
+
+ List<NetworkInterface> realInterfaces = new ArrayList<NetworkInterface>();
+ Enumeration<NetworkInterface> theInterfaces = NetworkInterface.getNetworkInterfaces();
+ while (theInterfaces.hasMoreElements()) {
+ NetworkInterface thisInterface = theInterfaces.nextElement();
+ // Skip interfaces that do not support multicast - there's no point in proving
+ // they cannot send / receive multicast messages.
+ if (willWorkForMulticast(thisInterface)) {
+ realInterfaces.add(thisInterface);
+ }
+ }
+
+ for (NetworkInterface thisInterface : realInterfaces) {
+ // Find a suitable group IP and interface to use to sent packets to thisInterface.
+ Enumeration<InetAddress> addresses = thisInterface.getInetAddresses();
+
+ NetworkInterface sendingInterface = null;
+ InetAddress group = null;
+ if (addresses.hasMoreElements()) {
+ InetAddress firstAddress = addresses.nextElement();
+ if (firstAddress instanceof Inet4Address) {
+ group = GOOD_IPv4;
+ sendingInterface = ipv4NetworkInterface;
+ } else {
+ // if this interface only seems to support IPV6 addresses
+ group = GOOD_IPv6;
+ sendingInterface = ipv6NetworkInterface;
+ }
+ }
+
+ // Create a receivingSocket which is joined to the group and has only asked for packets
+ // on thisInterface.
+ MulticastSocket receivingSocket = createReceivingSocket(0);
+ InetSocketAddress groupAddress =
+ new InetSocketAddress(group, receivingSocket.getLocalPort());
+ receivingSocket.joinGroup(groupAddress, thisInterface);
+
+ // Now send out a packet on sendingInterface. We should only see the packet if we send
+ // it on thisInterface.
+ MulticastSocket sendingSocket = new MulticastSocket(0);
+ sendingSocket.setNetworkInterface(sendingInterface);
+ String msg = "Hello World - Again " + thisInterface.getName();
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ sendingSocket.send(sdp);
+
+ DatagramPacket rdp = createReceiveDatagramPacket();
+ try {
+ receivingSocket.receive(rdp);
+
+ // If the packet is received....
+ assertEquals(thisInterface, sendingInterface);
+ assertEquals("Group member did not recv data when bound on specific interface",
+ msg, extractMessage(rdp));
+ } catch (SocketTimeoutException e) {
+ // If the packet was not received...
+ assertTrue(!thisInterface.equals(sendingInterface));
+ }
+
+ receivingSocket.close();
+ sendingSocket.close();
+ }
+ }
+
+ public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins_IPv4()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins(
+ ipv4NetworkInterface, GOOD_IPv4);
+ }
+
+ public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins_IPv6()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins(
+ ipv6NetworkInterface, GOOD_IPv6);
+ }
+
+ private void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins(
+ NetworkInterface networkInterface, InetAddress group) throws Exception {
+ // Validate that we can join the same address on two different interfaces but not on the
+ // same interface.
+ MulticastSocket mss = new MulticastSocket(0);
+ SocketAddress groupSockAddr = new InetSocketAddress(group, mss.getLocalPort());
+ mss.joinGroup(groupSockAddr, networkInterface);
+ mss.joinGroup(groupSockAddr, loopbackInterface);
+ try {
+ mss.joinGroup(groupSockAddr, networkInterface);
+ fail("Did not get expected exception when joining for second time on same interface");
+ } catch (IOException e) {
+ }
+ mss.close();
+ }
+
+ public void test_leaveGroupLjava_net_InetAddress_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_leaveGroupLjava_net_InetAddress(GOOD_IPv4);
+ }
+
+ public void test_leaveGroupLjava_net_InetAddress_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_leaveGroupLjava_net_InetAddress(GOOD_IPv6);
+ }
+
+ private void test_leaveGroupLjava_net_InetAddress(InetAddress group) throws Exception {
+ String msg = "Hello World";
+ MulticastSocket mss = new MulticastSocket(0);
+ InetSocketAddress groupAddress = new InetSocketAddress(group, mss.getLocalPort());
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ mss.send(sdp, (byte) 10 /* ttl */);
+ try {
+ // Try to leave a group we didn't join.
+ mss.leaveGroup(group);
+ fail();
+ } catch (IOException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_leaveGroup_null_null() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.leaveGroup(null, null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_leaveGroup_non_multicast_address_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.leaveGroup(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), null);
+ fail();
+ } catch (IOException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_leaveGroup_non_multicast_address_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket(0);
+ try {
+ mss.leaveGroup(new InetSocketAddress(InetAddress.getByName("::1"), 0), null);
+ fail();
+ } catch (IOException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface_IPv4()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ ipv4NetworkInterface, GOOD_IPv4, BAD_IPv4);
+ }
+
+ public void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface_IPv6()
+ throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ ipv6NetworkInterface, GOOD_IPv6, BAD_IPv6);
+ }
+
+ private void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface(
+ NetworkInterface networkInterface, InetAddress group, InetAddress group2)
+ throws Exception {
+ SocketAddress groupSockAddr = null;
+ SocketAddress groupSockAddr2 = null;
+
+ MulticastSocket mss = new MulticastSocket(0);
+ groupSockAddr = new InetSocketAddress(group, mss.getLocalPort());
+ mss.joinGroup(groupSockAddr, null);
+ mss.leaveGroup(groupSockAddr, null);
+ try {
+ mss.leaveGroup(groupSockAddr, null);
+ fail("Did not get exception when trying to leave group that was already left");
+ } catch (IOException expected) {
+ }
+
+ groupSockAddr2 = new InetSocketAddress(group2, mss.getLocalPort());
+ mss.joinGroup(groupSockAddr, networkInterface);
+ try {
+ mss.leaveGroup(groupSockAddr2, networkInterface);
+ fail("Did not get exception when trying to leave group that was never joined");
+ } catch (IOException expected) {
+ }
+
+ mss.leaveGroup(groupSockAddr, networkInterface);
+
+ mss.joinGroup(groupSockAddr, networkInterface);
+ try {
+ mss.leaveGroup(groupSockAddr, loopbackInterface);
+ fail("Did not get exception when trying to leave group on wrong interface " +
+ "joined on [" + networkInterface + "] left on [" + loopbackInterface + "]");
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_sendLjava_net_DatagramPacketB_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_sendLjava_net_DatagramPacketB(GOOD_IPv4);
+ }
+
+ public void test_sendLjava_net_DatagramPacketB_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_sendLjava_net_DatagramPacketB(GOOD_IPv6);
+ }
+
+ private void test_sendLjava_net_DatagramPacketB(InetAddress group) throws Exception {
+ String msg = "Hello World";
+ MulticastSocket sendingSocket = new MulticastSocket(0);
+ MulticastSocket receivingSocket = createReceivingSocket(sendingSocket.getLocalPort());
+ receivingSocket.joinGroup(group);
+
+ InetSocketAddress groupAddress = new InetSocketAddress(group, sendingSocket.getLocalPort());
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ sendingSocket.send(sdp, (byte) 10 /* ttl */);
+ sendingSocket.close();
+
+ DatagramPacket rdp = createReceiveDatagramPacket();
+ receivingSocket.receive(rdp);
+ String receivedMessage = extractMessage(rdp);
+ assertEquals("Failed to send data. Received " + rdp.getLength(), msg, receivedMessage);
+ receivingSocket.close();
+ }
+
+ public void test_setInterfaceLjava_net_InetAddress() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket();
+ mss.setInterface(InetAddress.getLocalHost());
+ InetAddress theInterface = mss.getInterface();
+ // Under IPV6 we are not guaranteed to get the same address back as the address that was
+ // set, all we should be guaranteed is that we get an address on the same interface.
+ if (theInterface instanceof Inet6Address) {
+ assertEquals("Failed to return correct interface IPV6",
+ NetworkInterface.getByInetAddress(mss.getInterface()),
+ NetworkInterface.getByInetAddress(theInterface));
+ } else {
+ assertTrue("Failed to return correct interface IPV4 got:" + mss.getInterface() +
+ " expected: " + InetAddress.getLocalHost(),
+ mss.getInterface().equals(InetAddress.getLocalHost()));
+ }
+ mss.close();
+ }
+
+ public void test_setInterface_unbound_address_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setInterface_unbound_address(GOOD_IPv4);
+ }
+
+ public void test_setInterface_unbound_address_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setInterface_unbound_address(GOOD_IPv6);
+ }
+
+ // Regression test for Harmony-2410.
+ private void test_setInterface_unbound_address(InetAddress address) throws Exception {
+ MulticastSocket mss = new MulticastSocket();
+ try {
+ mss.setInterface(address);
+ fail();
+ } catch (SocketException expected) {
+ }
+ mss.close();
+ }
+
+ public void test_setNetworkInterfaceLjava_net_NetworkInterface_null() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Validate that null interface is handled ok.
+ MulticastSocket mss = new MulticastSocket();
+ try {
+ mss.setNetworkInterface(null);
+ fail("No socket exception when we set then network interface with NULL");
+ } catch (SocketException ex) {
+ }
+ mss.close();
+ }
+
+ public void test_setNetworkInterfaceLjava_net_NetworkInterface_round_trip() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Validate that we can get and set the interface.
+ MulticastSocket mss = new MulticastSocket();
+ mss.setNetworkInterface(ipv4NetworkInterface);
+ assertEquals("Interface did not seem to be set by setNeworkInterface",
+ ipv4NetworkInterface, mss.getNetworkInterface());
+ mss.close();
+ }
+
+ public void test_setNetworkInterfaceLjava_net_NetworkInterface_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setNetworkInterfaceLjava_net_NetworkInterface(GOOD_IPv4);
+ }
+
+ public void test_setNetworkInterfaceLjava_net_NetworkInterface_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setNetworkInterfaceLjava_net_NetworkInterface(GOOD_IPv6);
+ }
+
+ private void test_setNetworkInterfaceLjava_net_NetworkInterface(InetAddress group)
+ throws IOException, InterruptedException {
+ // Set up the receiving socket and join the group.
+ Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
+ while (theInterfaces.hasMoreElements()) {
+ NetworkInterface thisInterface = (NetworkInterface) theInterfaces.nextElement();
+ if (willWorkForMulticast(thisInterface)) {
+ if ((!(thisInterface.getInetAddresses().nextElement()).isLoopbackAddress())) {
+ MulticastSocket receivingSocket = createReceivingSocket(0);
+ InetSocketAddress groupAddress =
+ new InetSocketAddress(group, receivingSocket.getLocalPort());
+ receivingSocket.joinGroup(groupAddress, thisInterface);
+
+ // Send the packets on a particular interface. The source address in the
+ // received packet should be one of the addresses for the interface set.
+ MulticastSocket sendingSocket = new MulticastSocket(0);
+ sendingSocket.setNetworkInterface(thisInterface);
+ String msg = thisInterface.getName();
+ DatagramPacket sdp = createSendDatagramPacket(groupAddress, msg);
+ sendingSocket.send(sdp);
+
+ DatagramPacket rdp = createReceiveDatagramPacket();
+ receivingSocket.receive(rdp);
+ String receivedMessage = extractMessage(rdp);
+ assertEquals("Group member did not recv data sent on a specific interface",
+ msg, receivedMessage);
+ // Stop the server.
+ receivingSocket.close();
+ sendingSocket.close();
+ }
+ }
+ }
+ }
+
+ public void test_setTimeToLiveI() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket();
+ mss.setTimeToLive(120);
+ assertEquals("Returned incorrect 1st TTL", 120, mss.getTimeToLive());
+ mss.setTimeToLive(220);
+ assertEquals("Returned incorrect 2nd TTL", 220, mss.getTimeToLive());
+ mss.close();
+ }
+
+ public void test_setTTLB() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket mss = new MulticastSocket();
+ mss.setTTL((byte) 120);
+ assertEquals("Failed to set TTL", 120, mss.getTTL());
+ mss.close();
+ }
+
+ public void test_ConstructorLjava_net_SocketAddress() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket ms = new MulticastSocket((SocketAddress) null);
+ assertTrue("should not be bound", !ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.bind(null);
+ assertTrue("should be bound", ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.close();
+ assertTrue("should be closed", ms.isClosed());
+
+ ms = new MulticastSocket(0);
+ assertTrue("should be bound", ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.close();
+ assertTrue("should be closed", ms.isClosed());
+
+ ms = new MulticastSocket(0);
+ assertTrue("should be bound", ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.close();
+ assertTrue("should be closed", ms.isClosed());
+
+ try {
+ new MulticastSocket(new InetSocketAddress("unresolvedname", 31415));
+ fail();
+ } catch (IOException expected) {
+ }
+
+ // Regression test for Harmony-1162.
+ InetSocketAddress addr = new InetSocketAddress("0.0.0.0", 0);
+ MulticastSocket s = new MulticastSocket(addr);
+ assertTrue(s.getReuseAddress());
+ s.close();
+ }
+
+ public void test_getLoopbackMode() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket ms = new MulticastSocket(null);
+ assertTrue("should not be bound", !ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.getLoopbackMode();
+ assertTrue("should not be bound", !ms.isBound() && !ms.isClosed() && !ms.isConnected());
+ ms.close();
+ assertTrue("should be closed", ms.isClosed());
+ }
+
+ public void test_setLoopbackModeZ() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ MulticastSocket ms = new MulticastSocket();
+ ms.setLoopbackMode(true);
+ assertTrue("loopback should be true", ms.getLoopbackMode());
+ ms.setLoopbackMode(false);
+ assertTrue("loopback should be false", !ms.getLoopbackMode());
+ ms.close();
+ assertTrue("should be closed", ms.isClosed());
+ }
+
+ public void test_setLoopbackModeSendReceive_IPv4() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setLoopbackModeSendReceive(GOOD_IPv4);
+ }
+
+ public void test_setLoopbackModeSendReceive_IPv6() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ test_setLoopbackModeSendReceive(GOOD_IPv6);
+ }
+
+ private void test_setLoopbackModeSendReceive(InetAddress group) throws IOException {
+ // Test send receive.
+ final String message = "Hello, world!";
+
+ MulticastSocket socket = new MulticastSocket(0);
+ socket.setLoopbackMode(false); // false indicates doing loop back
+ socket.joinGroup(group);
+
+ // Send the datagram.
+ InetSocketAddress groupAddress = new InetSocketAddress(group, socket.getLocalPort());
+ DatagramPacket sendDatagram = createSendDatagramPacket(groupAddress, message);
+ socket.send(sendDatagram);
+
+ // Receive the datagram.
+ DatagramPacket recvDatagram = createReceiveDatagramPacket();
+ socket.setSoTimeout(5000); // Prevent eternal block in.
+ socket.receive(recvDatagram);
+ String recvMessage = extractMessage(recvDatagram);
+ assertEquals(message, recvMessage);
+ socket.close();
+ }
+
+ public void test_setReuseAddressZ() throws Exception {
+ if (!supportsMulticast) {
+ return;
+ }
+ // Test case were we to set ReuseAddress to false.
+ MulticastSocket theSocket1 = new MulticastSocket(null);
+ theSocket1.setReuseAddress(false);
+
+ MulticastSocket theSocket2 = new MulticastSocket(null);
+ theSocket2.setReuseAddress(false);
+
+ InetSocketAddress addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ try {
+ theSocket2.bind(addr);
+ fail("No exception when trying to connect to do duplicate socket bind with re-useaddr"
+ + " set to false");
+ } catch (BindException expected) {
+ }
+ theSocket1.close();
+ theSocket2.close();
+
+ // Test case were we set it to true.
+ theSocket1 = new MulticastSocket(null);
+ theSocket2 = new MulticastSocket(null);
+ theSocket1.setReuseAddress(true);
+ theSocket2.setReuseAddress(true);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ theSocket2.bind(addr);
+
+ theSocket1.close();
+ theSocket2.close();
+
+ // Test the default case which we expect to be the same on all platforms.
+ theSocket1 = new MulticastSocket(null);
+ theSocket2 = new MulticastSocket(null);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ theSocket2.bind(addr);
+ theSocket1.close();
+ theSocket2.close();
+ }
+
+ private static boolean willWorkForMulticast(NetworkInterface iface) throws IOException {
+ return iface.isUp()
+ // Typically loopback interfaces do not support multicast, but we rule them out
+ // explicitly anyway.
+ && !iface.isLoopback() && iface.supportsMulticast()
+ && iface.getInetAddresses().hasMoreElements();
+ }
+
+ private static MulticastSocket createReceivingSocket(int aPort) throws IOException {
+ MulticastSocket ms = new MulticastSocket(aPort);
+ ms.setSoTimeout(2000);
+ return ms;
+ }
+
+ private static DatagramPacket createReceiveDatagramPacket() {
+ byte[] rbuf = new byte[512];
+ return new DatagramPacket(rbuf, rbuf.length);
+ }
+
+ private static DatagramPacket createSendDatagramPacket(
+ InetSocketAddress groupAndPort, String msg) {
+ return new DatagramPacket(
+ msg.getBytes(), msg.length(), groupAndPort.getAddress(), groupAndPort.getPort());
+ }
+
+ private static String extractMessage(DatagramPacket rdp) {
+ return new String(rdp.getData(), 0, rdp.getLength());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NetworkInterfaceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NetworkInterfaceTest.java
new file mode 100644
index 0000000..2a93f12
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NetworkInterfaceTest.java
@@ -0,0 +1,496 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.InetAddress;
+import java.net.InterfaceAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+public class NetworkInterfaceTest extends junit.framework.TestCase {
+
+ // 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;
+
+ /**
+ * 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()));
+ }
+ }
+
+ /**
+ * java.net.NetworkInterface#getInetAddresses()
+ */
+ public void test_getInetAddresses() throws Exception {
+ if (atLeastOneInterface) {
+ Enumeration theAddresses = networkInterface1.getInetAddresses();
+ while (theAddresses.hasMoreElements()) {
+ InetAddress theAddress = (InetAddress) theAddresses
+ .nextElement();
+ assertNotNull("validate that address is not 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();
+ okAddresses.add(theAddress);
+ index++;
+ }
+
+ // 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();
+ okAddresses.add(theAddress);
+ index++;
+ }
+ }
+
+ // 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 without permission is not returned",
+ !nextAddress.equals(notOkAddresses.get(i)));
+ }
+ 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 (nextAddress.equals(okAddresses.get(i))) {
+ addressReturned = true;
+ }
+ }
+ 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)));
+ }
+
+ // 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)));
+ }
+ }
+ }
+
+ /**
+ * 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()));
+ }
+ }
+
+ /**
+ * 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 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));
+ }
+ }
+ }
+
+ /**
+ * 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 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));
+ }
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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);
+ }
+ if (atLeastTwoInterfaces) {
+ assertFalse("If objects are different false is returned",
+ networkInterface1.equals(networkInterface2));
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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()));
+
+ }
+ }
+
+ /**
+ * java.net.NetworkInterface#getInterfaceAddresses()
+ * @since 1.6
+ */
+ public void test_getInterfaceAddresses() throws SocketException {
+ if (theInterfaces != null) {
+ while (theInterfaces.hasMoreElements()) {
+ NetworkInterface netif = theInterfaces.nextElement();
+ assertEquals(netif.getName()
+ + " getInterfaceAddresses should contain no element", 0,
+ netif.getInterfaceAddresses().size());
+ }
+
+ 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);
+ }
+ }
+ }
+
+ /**
+ * java.net.NetworkInterface#isLoopback()
+ * @since 1.6
+ */
+ 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());
+ }
+ }
+ }
+
+ /**
+ * java.net.NetworkInterface#getHardwareAddress()
+ * @since 1.6
+ */
+ 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);
+ }
+ }
+ }
+ }
+
+ /**
+ * java.net.NetworkInterface#getHardwareAddress()
+ * @since 1.6
+ */
+ 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);
+ }
+ }
+ }
+
+ 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();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NoRouteToHostExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NoRouteToHostExceptionTest.java
new file mode 100644
index 0000000..89fe4fd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/NoRouteToHostExceptionTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.NoRouteToHostException;
+
+public class NoRouteToHostExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.NoRouteToHostException#NoRouteToHostException()
+ */
+ public void test_Constructor() {
+ try {
+ if (true) {
+ throw new NoRouteToHostException();
+ }
+ fail("Failed to generate expected exception");
+ } catch (NoRouteToHostException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.NoRouteToHostException#NoRouteToHostException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Cannot test correctly without changing some routing tables !!
+ try {
+ if (true) {
+ throw new NoRouteToHostException("test");
+ }
+ fail("Failed to generate expected exception");
+ } catch (NoRouteToHostException e) {
+ assertEquals("Threw exception with incorrect message", "test", e
+ .getMessage());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/PasswordAuthenticationTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/PasswordAuthenticationTest.java
new file mode 100644
index 0000000..bbb3011
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/PasswordAuthenticationTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.PasswordAuthentication;
+
+public class PasswordAuthenticationTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.PasswordAuthentication#PasswordAuthentication(java.lang.String,
+ *char[])
+ */
+ public void test_ConstructorLjava_lang_String$C() {
+ // Test for method java.net.PasswordAuthentication(java.lang.String,
+ // char [])
+ char[] password = new char[] { 'd', 'r', 'o', 'w', 's', 's', 'a', 'p' };
+ final String name = "Joe Blow";
+ PasswordAuthentication pa = new PasswordAuthentication(name, password);
+ char[] returnedPassword = pa.getPassword();
+ assertTrue("Incorrect name", pa.getUserName().equals(name));
+ assertTrue("Password was not cloned", returnedPassword != password);
+ assertTrue("Passwords not equal length",
+ returnedPassword.length == password.length);
+ for (int counter = password.length - 1; counter >= 0; counter--)
+ assertTrue("Passwords not equal",
+ returnedPassword[counter] == password[counter]);
+ }
+
+ /**
+ * java.net.PasswordAuthentication#getPassword()
+ */
+ public void test_getPassword() {
+ // Test for method char [] java.net.PasswordAuthentication.getPassword()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.net.PasswordAuthentication#getUserName()
+ */
+ public void test_getUserName() {
+ // Test for method java.lang.String
+ // java.net.PasswordAuthentication.getUserName()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProtocolExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProtocolExceptionTest.java
new file mode 100644
index 0000000..d0fe2d9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProtocolExceptionTest.java
@@ -0,0 +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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.tests.java.net;
+
+import java.net.ProtocolException;
+
+public class ProtocolExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.ProtocolException#ProtocolException()
+ */
+ public void test_Constructor() {
+ // Test for method java.net.ProtocolException()
+ try {
+ throw new ProtocolException();
+ } catch (ProtocolException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during ProtocolException test : " + e.getMessage());
+ }
+ fail("Failed to generate expected exception");
+ }
+
+ /**
+ * java.net.ProtocolException#ProtocolException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.net.ProtocolException(java.lang.String)
+ try {
+ throw new ProtocolException("Some error message");
+ } catch (ProtocolException e) {
+ return;
+ } catch (Exception e) {
+ fail("Exception during ProtocolException test : " + e.getMessage());
+ }
+ fail("Failed to generate expected exception");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxySelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxySelectorTest.java
new file mode 100644
index 0000000..3a3bbfe
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxySelectorTest.java
@@ -0,0 +1,562 @@
+/* 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.NetPermission;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.security.Permission;
+import java.util.List;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+public class ProxySelectorTest extends TestCase {
+
+ private static final String HTTP_PROXY_HOST = "127.0.0.1";
+
+ private static final int HTTP_PROXY_PORT = 80;
+
+ private static final String HTTPS_PROXY_HOST = "127.0.0.2";
+
+ private static final int HTTPS_PROXY_PORT = 443;
+
+ private static final String FTP_PROXY_HOST = "127.0.0.3";
+
+ private static final int FTP_PROXY_PORT = 80;
+
+ private static final String SOCKS_PROXY_HOST = "127.0.0.4";
+
+ private static final int SOCKS_PROXY_PORT = 1080;
+
+ private static URI httpUri;
+
+ private static URI ftpUri;
+
+ private static URI httpsUri;
+
+ private static URI tcpUri;
+
+ private List proxyList;
+
+ private ProxySelector selector = ProxySelector.getDefault();
+
+ static {
+ try {
+ httpUri = new URI("http://test.com");
+ ftpUri = new URI("ftp://test.com");
+ httpsUri = new URI("https://test.com");
+ tcpUri = new URI("socket://host.com");
+ } catch (URISyntaxException e) {
+
+ }
+ }
+
+ /*
+ * Original system properties must be restored after running each test case.
+ */
+ private Properties originalSystemProperties;
+
+ /**
+ * java.net.ProxySelector#getDefault()
+ */
+ public void test_getDefault() {
+ ProxySelector selector1 = ProxySelector.getDefault();
+ assertNotNull(selector1);
+
+ ProxySelector selector2 = ProxySelector.getDefault();
+ assertSame(selector1, selector2);
+ }
+
+ /**
+ * java.net.ProxySelector#setDefault(ProxySelector)}
+ */
+ public void test_setDefaultLjava_net_ProxySelector() {
+ ProxySelector originalSelector = ProxySelector.getDefault();
+ try {
+ ProxySelector newSelector = new MockProxySelector();
+ ProxySelector.setDefault(newSelector);
+ assertSame(newSelector, ProxySelector.getDefault());
+ // use null to unset
+ ProxySelector.setDefault(null);
+ assertSame(null, ProxySelector.getDefault());
+ } finally {
+ ProxySelector.setDefault(originalSelector);
+ }
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectExact()
+ throws URISyntaxException {
+ // no proxy, return a proxyList only contains NO_PROXY
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST, HTTP_PROXY_PORT);
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST, HTTPS_PROXY_PORT);
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST, FTP_PROXY_PORT);
+
+ proxyList = selector.select(tcpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectExact_NullHost()
+ throws URISyntaxException {
+ // regression test for Harmony-1063
+ httpUri = new URI("http://a@");
+ ftpUri = new URI("ftp://a@");
+ httpsUri = new URI("https://a@");
+ tcpUri = new URI("socket://a@");
+ // no proxy, return a proxyList only contains NO_PROXY
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST,
+ HTTP_PROXY_PORT);
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST,
+ HTTPS_PROXY_PORT);
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST,
+ FTP_PROXY_PORT);
+
+ proxyList = selector.select(tcpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST,
+ SOCKS_PROXY_PORT);
+
+ }
+
+ //Regression for HARMONY-4281
+ public void test_selectLjava_net_URI_SelectExact_NullHost_withNoProxyHostsProperty() {
+ System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1");
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST,
+ HTTP_PROXY_PORT);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectExact_DefaultPort()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST, HTTP_PROXY_PORT);
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST, HTTPS_PROXY_PORT);
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST, FTP_PROXY_PORT);
+
+ proxyList = selector.select(tcpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectExact_InvalidPort()
+ throws URISyntaxException {
+ final String INVALID_PORT = "abc";
+
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", INVALID_PORT);
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", INVALID_PORT);
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", INVALID_PORT);
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksproxyPort", INVALID_PORT);
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST, HTTP_PROXY_PORT);
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST, HTTPS_PROXY_PORT);
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST, FTP_PROXY_PORT);
+
+ proxyList = selector.select(tcpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ // RI may fail this test case.
+ // Uncomment this test case when regex.jar is ready.
+ /*
+ public void test_selectLjava_net_URI_Select_NonProxyHosts()
+ throws URISyntaxException {
+ // RI's bug. Some RIs may fail this test case.
+ URI[] httpUris = { new URI("http://test.com"),
+ new URI("http://10.10.1.2"), new URI("http://a"),
+ new URI("http://def.abc.com") };
+ URI[] ftpUris = { new URI("ftp://test.com"),
+ new URI("ftp://10.10.1.2"), new URI("ftp://a"),
+ new URI("ftp://def.abc.com") };
+
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
+
+ for (int i = 0; i < httpUris.length; i++) {
+ proxyList = selector.select(httpUris[i]);
+ assertProxyEquals(proxyList,Proxy.NO_PROXY);
+ }
+
+ for (int i = 0; i < ftpUris.length; i++) {
+ proxyList = selector.select(ftpUris[i]);
+ assertProxyEquals(proxyList,Proxy.NO_PROXY);
+ }
+ }*/
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectLikeHTTP()
+ throws URISyntaxException {
+ System.setProperty("http.proxyHost", "");
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectNoHTTP()
+ throws URISyntaxException {
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+
+ proxyList = selector.select(httpUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectLikeHTTPS()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy host empty
+ System.setProperty("http.proxyHost", "");
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectNoHTTPS()
+ throws URISyntaxException {
+ // set https proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+
+ proxyList = selector.select(httpsUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectLikeFTP()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set ftp host empty
+ System.setProperty("ftp.proxyHost", "");
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST, SOCKS_PROXY_PORT);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectNoFTP()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+
+ proxyList = selector.select(ftpUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_SelectNoSOCKS()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+
+ proxyList = selector.select(tcpUri);
+ assertProxyEquals(proxyList, Proxy.NO_PROXY);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException()
+ throws URISyntaxException {
+ // set http proxy
+ System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
+ System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
+ // set https proxy
+ System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
+ System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
+ // set ftp proxy
+ System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
+ System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
+ // set socks proxy
+ System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
+ System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+
+ List proxyList1 = selector.select(httpUri);
+ assertNotNull(proxyList1);
+ assertEquals(1, proxyList1.size());
+ Proxy proxy1 = (Proxy) proxyList1.get(0);
+ selector
+ .connectFailed(httpUri, proxy1.address(), new SocketException());
+
+ List proxyList2 = selector.select(httpUri);
+ assertNotNull(proxyList2);
+ assertEquals(1, proxyList2.size());
+ Proxy proxy2 = (Proxy) proxyList2.get(0);
+ // Default implementation doesn't change the proxy list
+ assertEquals(proxy1, proxy2);
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException_IllegalArguement()
+ throws URISyntaxException {
+ SocketAddress sa = InetSocketAddress.createUnresolved("127.0.0.1", 0);
+ try {
+ selector.connectFailed(null, sa, new SocketException());
+ fail("should throw IllegalArgumentException if any argument is null.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ selector.connectFailed(httpUri, null, new SocketException());
+ fail("should throw IllegalArgumentException if any argument is null.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ selector.connectFailed(httpUri, sa, null);
+ fail("should throw IllegalArgumentException if any argument is null.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.net.ProxySelector#select(URI)
+ */
+ public void test_selectLjava_net_URI_IllegalArgument()
+ throws URISyntaxException {
+ URI[] illegalUris = { new URI("abc"), new URI("http"), null };
+ for (int i = 0; i < illegalUris.length; i++) {
+ try {
+ selector.select(illegalUris[i]);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+ }
+
+ /*
+ * asserts whether selectedProxyList contains one and only one element,
+ * and the element equals proxy.
+ */
+ private void assertProxyEquals(List selectedProxyList, Proxy proxy) {
+ assertNotNull(selectedProxyList);
+ assertEquals(1, selectedProxyList.size());
+ assertEquals((Proxy) selectedProxyList.get(0), proxy);
+ }
+
+ /*
+ * asserts whether selectedProxyList contains one and only one element,
+ * and the element equals proxy which is represented by arguments "type",
+ * "host","port".
+ */
+ private void assertProxyEquals(List selectedProxyList, Proxy.Type type,
+ String host, int port) {
+ SocketAddress sa = InetSocketAddress.createUnresolved(host, port);
+ Proxy proxy = new Proxy(type, sa);
+ assertProxyEquals(selectedProxyList, proxy);
+ }
+
+ /*
+ * Mock selector for setDefault test
+ */
+ static class MockProxySelector extends ProxySelector {
+
+ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
+
+ }
+
+ public List<Proxy> select(URI uri) {
+ return null;
+ }
+ }
+
+ /*
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ // save original system properties
+ originalSystemProperties = (Properties) System.getProperties().clone();
+ }
+
+ /*
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ // restore original system properties
+ System.setProperties(originalSystemProperties);
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxyTest.java
new file mode 100644
index 0000000..0487537
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ProxyTest.java
@@ -0,0 +1,238 @@
+/* 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.tests.java.net;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.SocketAddress;
+
+import junit.framework.TestCase;
+
+public class ProxyTest extends TestCase {
+
+ private SocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
+
+ /**
+ * java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
+ */
+ public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal() {
+ // test HTTP type proxy
+ Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
+ assertEquals(Proxy.Type.HTTP, proxy.type());
+ assertEquals(address, proxy.address());
+
+ // test SOCKS type proxy
+ proxy = new Proxy(Proxy.Type.SOCKS, address);
+ assertEquals(Proxy.Type.SOCKS, proxy.type());
+ assertEquals(address, proxy.address());
+
+ // test DIRECT type proxy
+ proxy = Proxy.NO_PROXY;
+ assertEquals(Proxy.Type.DIRECT, proxy.type());
+ assertNull(proxy.address());
+ }
+
+ /**
+ * java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
+ */
+ public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_IllegalAddress() {
+ Proxy proxy = null;
+ // test HTTP type proxy
+ try {
+ proxy = new Proxy(Proxy.Type.HTTP, null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ // test SOCKS type proxy
+ try {
+ proxy = new Proxy(Proxy.Type.SOCKS, null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ // test DIRECT type proxy
+ try {
+ proxy = new Proxy(Proxy.Type.DIRECT, null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ // test DIRECT type proxy, any address is illegal
+ try {
+ proxy = new Proxy(Proxy.Type.DIRECT, address);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.net.Proxy#hashCode()
+ * @see also see test_equalsLjava_lang_Object_Equals
+ */
+ public void test_hashCode() {
+ // This method has been tested in test_equalsLjava_lang_Object_Equals.
+ }
+
+ /**
+ * java.net.Proxy#type()
+ */
+ public void test_type() {
+ // This method has been tested in test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal.
+ }
+
+ /**
+ * java.net.Proxy#address() This method has been tested in
+ * Constructor test case.
+ */
+ public void test_address() {
+ // This method has been tested in test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal.
+ }
+
+ /**
+ * java.net.Proxy#toString()
+ */
+ public void test_toString() {
+ Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
+ // include type String
+ assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
+ // include address String
+ assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
+
+ proxy = new Proxy(Proxy.Type.SOCKS, address);
+ // include type String
+ assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
+ // include address String
+ assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
+
+ proxy = Proxy.NO_PROXY;
+ // include type String
+ assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
+
+ proxy = new Proxy(null, address);
+ // ensure no NPE is thrown
+ proxy.toString();
+
+ // Regression test for Java 6 spec change
+ proxy = new Proxy(Proxy.Type.HTTP, address);
+ assertTrue(proxy.toString().contains("@"));
+ proxy = new Proxy(Proxy.Type.SOCKS, address);
+ assertTrue(proxy.toString().contains(address.toString()));
+ }
+
+ /**
+ * java.net.Proxy#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object_Equals() {
+ SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
+ SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1234);
+ // HTTP type
+ Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
+ Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address2);
+ assertTrue(proxy1.equals(proxy2));
+ // assert hashCode
+ assertTrue(proxy1.hashCode() == proxy2.hashCode());
+
+ // SOCKS type
+ Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, address1);
+ Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address2);
+ assertTrue(proxy3.equals(proxy4));
+ // assert hashCode
+ assertTrue(proxy3.hashCode() == proxy4.hashCode());
+
+ // null type
+ Proxy proxy5 = new Proxy(null, address1);
+ Proxy proxy6 = new Proxy(null, address2);
+ assertTrue(proxy5.equals(proxy6));
+ }
+
+ /**
+ * java.net.Proxy#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object_NotEquals() {
+ SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
+ SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
+ Proxy proxy[] = { new Proxy(Proxy.Type.HTTP, address1),
+ new Proxy(Proxy.Type.HTTP, address2),
+ new Proxy(Proxy.Type.SOCKS, address1),
+ new Proxy(Proxy.Type.SOCKS, address2), Proxy.NO_PROXY,
+ new Proxy(null, address1), new Proxy(null, address2) };
+ // All of them are not equals
+ for (int i = 0; i < proxy.length; i++) {
+ for (int j = i + 1; j < proxy.length; j++) {
+ assertFalse(proxy[i].equals(proxy[j]));
+ }
+ }
+ // Not equals to an Object type instance. Ensure no exception is thrown.
+ assertFalse(proxy[0].equals(new Object()));
+ }
+
+ /**
+ * java.net.Proxy.Type#valueOf(String)
+ */
+ public void test_Type_valueOfLjava_lang_String_Normal() {
+ assertEquals(Proxy.Type.DIRECT, Proxy.Type.valueOf("DIRECT"));
+ assertEquals(Proxy.Type.HTTP, Proxy.Type.valueOf("HTTP"));
+ assertEquals(Proxy.Type.SOCKS, Proxy.Type.valueOf("SOCKS"));
+ }
+
+ /**
+ * java.net.Proxy.Type#valueOf(String)
+ */
+ public void test_Type_valueOfLjava_lang_String_IllegalName() {
+ String[] illegalName = { "Direct", "direct", "http", "socks",
+ "illegalName", "" };
+ for (int i = 0; i < illegalName.length; i++) {
+ try {
+ Proxy.Type.valueOf(illegalName[i]);
+ fail("should throw IllegalArgumentException, illegalName:"
+ + illegalName);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+ }
+
+ /**
+ * java.net.Proxy.Type#valueOf(String)
+ */
+ public void test_Type_valueOfLjava_lang_String_NullPointerException() {
+ // Some old RIs,which throw IllegalArgumentException.
+ // Latest RIs throw NullPointerException.
+ try {
+ Proxy.Type.valueOf(null);
+ fail("should throw an exception.");
+ } catch (NullPointerException e) {
+ // May be caused by some compilers' code
+ } catch (IllegalArgumentException e) {
+ // other compilers will throw this
+ }
+ }
+
+ /**
+ * java.net.Proxy.Type#values()
+ */
+ public void test_Type_values() {
+ Proxy.Type types[] = Proxy.Type.values();
+ assertEquals(3, types.length);
+ assertEquals(Proxy.Type.DIRECT, types[0]);
+ assertEquals(Proxy.Type.HTTP, types[1]);
+ assertEquals(Proxy.Type.SOCKS, types[2]);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ResponseCacheTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ResponseCacheTest.java
new file mode 100644
index 0000000..4e79e4a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ResponseCacheTest.java
@@ -0,0 +1,70 @@
+/* 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.NetPermission;
+import java.net.ResponseCache;
+import java.net.URI;
+import java.net.URLConnection;
+import java.security.Permission;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+public class ResponseCacheTest extends TestCase {
+
+ /**
+ * java.net.ResponseCache#getDefault()
+ */
+ public void test_GetDefault() throws Exception {
+ assertNull(ResponseCache.getDefault());
+ }
+
+ /**
+ * java.net.ResponseCache#setDefault(ResponseCache)
+ */
+ public void test_SetDefaultLjava_net_ResponseCache_Normal()
+ throws Exception {
+ ResponseCache rc1 = new MockResponseCache();
+ ResponseCache rc2 = new MockResponseCache();
+ ResponseCache.setDefault(rc1);
+ assertSame(ResponseCache.getDefault(), rc1);
+ ResponseCache.setDefault(rc2);
+ assertSame(ResponseCache.getDefault(), rc2);
+ ResponseCache.setDefault(null);
+ assertNull(ResponseCache.getDefault());
+ }
+
+ /*
+ * MockResponseCache for testSetDefault(ResponseCache)
+ */
+ class MockResponseCache extends ResponseCache {
+
+ public CacheResponse get(URI arg0, String arg1, Map arg2)
+ throws IOException {
+ return null;
+ }
+
+ public CacheRequest put(URI arg0, URLConnection arg1)
+ throws IOException {
+ return null;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SecureCacheResponseTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SecureCacheResponseTest.java
new file mode 100644
index 0000000..ab78d65
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SecureCacheResponseTest.java
@@ -0,0 +1,85 @@
+/* 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.tests.java.net;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.SecureCacheResponse;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.util.List;
+import java.util.Map;
+
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+import junit.framework.TestCase;
+
+public class SecureCacheResponseTest extends TestCase {
+
+ public void testSecureCacheResponse() {
+ // test constructor
+ SecureCacheResponse sc = new MockCacheResponse();
+ // nothing happened
+ assertNull(sc.getCipherSuite());
+ }
+
+ class MockCacheResponse extends SecureCacheResponse {
+
+ @Override
+ public String getCipherSuite() {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public List<Certificate> getLocalCertificateChain() {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public Principal getLocalPrincipal() {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public InputStream getBody() throws IOException {
+ // do nothing
+ return null;
+ }
+
+ @Override
+ public Map<String, List<String>> getHeaders() throws IOException {
+ // do nothing
+ return null;
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ServerSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ServerSocketTest.java
new file mode 100644
index 0000000..d7ef745
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ServerSocketTest.java
@@ -0,0 +1,950 @@
+/*
+ * 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.tests.java.net;
+
+import tests.support.Support_Configuration;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.net.BindException;
+import java.net.ConnectException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.PlainServerSocketImpl;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketImpl;
+import java.net.SocketImplFactory;
+import java.net.UnknownHostException;
+import java.util.Date;
+import java.util.Locale;
+import java.util.Properties;
+
+public class ServerSocketTest extends junit.framework.TestCase {
+
+ boolean interrupted;
+
+ ServerSocket s;
+
+ Socket sconn;
+
+ Thread t;
+
+ static class SSClient implements Runnable {
+ Socket cs;
+
+ int port;
+
+ public SSClient(int prt) {
+ port = prt;
+ }
+
+ public void run() {
+ try {
+ // Go to sleep so the server can setup and wait for connection
+ Thread.sleep(1000);
+ cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
+ // Sleep again to allow server side processing. Thread is
+ // stopped by server.
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ return;
+ } catch (Throwable e) {
+ System.out
+ .println("Error establishing client: " + e.toString());
+ } finally {
+ try {
+ if (cs != null)
+ cs.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#ServerSocket()
+ */
+ public void test_Constructor() {
+ // Test for method java.net.ServerSocket(int)
+ assertTrue("Used during tests", true);
+ }
+
+ /**
+ * java.net.ServerSocket#ServerSocket(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.net.ServerSocket(int)
+ assertTrue("Used during tests", true);
+ }
+
+ /**
+ * java.net.ServerSocket#ServerSocket(int)
+ */
+ public void test_ConstructorI_SocksSet() throws IOException {
+ // Harmony-623 regression test
+ ServerSocket ss = null;
+ Properties props = (Properties) System.getProperties().clone();
+ try {
+ System.setProperty("socksProxyHost", "127.0.0.1");
+ System.setProperty("socksProxyPort", "12345");
+ ss = new ServerSocket(0);
+ } finally {
+ System.setProperties(props);
+ if (null != ss) {
+ ss.close();
+ }
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#ServerSocket(int, int)
+ */
+ public void test_ConstructorII() throws IOException {
+ try {
+ s = new ServerSocket(0, 10);
+ s.setSoTimeout(2000);
+ startClient(s.getLocalPort());
+ sconn = s.accept();
+ } catch (InterruptedIOException e) {
+ return;
+ }
+
+ ServerSocket s1 = new ServerSocket(0);
+ try {
+ try {
+ ServerSocket s2 = new ServerSocket(s1.getLocalPort());
+ s2.close();
+ fail("Was able to create two serversockets on same port");
+ } catch (BindException e) {
+ // Expected
+ }
+ } finally {
+ s1.close();
+ }
+
+ s1 = new ServerSocket(0);
+ int allocatedPort = s1.getLocalPort();
+ s1.close();
+ s1 = new ServerSocket(allocatedPort);
+ s1.close();
+ }
+
+ /**
+ * java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
+ */
+ public void test_ConstructorIILjava_net_InetAddress()
+ throws UnknownHostException, IOException {
+ s = new ServerSocket(0, 10, InetAddress.getLocalHost());
+ try {
+ s.setSoTimeout(5000);
+ startClient(s.getLocalPort());
+ sconn = s.accept();
+ assertNotNull("Was unable to accept connection", sconn);
+ sconn.close();
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#accept()
+ */
+ public void test_accept() throws IOException {
+ s = new ServerSocket(0);
+ try {
+ s.setSoTimeout(5000);
+ startClient(s.getLocalPort());
+ sconn = s.accept();
+ int localPort1 = s.getLocalPort();
+ int localPort2 = sconn.getLocalPort();
+ sconn.close();
+ assertEquals("Bad local port value", localPort1, localPort2);
+ } finally {
+ s.close();
+ }
+
+ try {
+ interrupted = false;
+ final ServerSocket ss = new ServerSocket(0);
+ ss.setSoTimeout(12000);
+ Runnable runnable = new Runnable() {
+ public void run() {
+ try {
+ ss.accept();
+ } catch (InterruptedIOException e) {
+ interrupted = true;
+ } catch (IOException e) {
+ }
+ }
+ };
+ Thread thread = new Thread(runnable, "ServerSocket.accept");
+ thread.start();
+ try {
+ do {
+ Thread.sleep(500);
+ } while (!thread.isAlive());
+ } catch (InterruptedException e) {
+ }
+ ss.close();
+ int c = 0;
+ do {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ }
+ if (interrupted) {
+ fail("accept interrupted");
+ }
+ if (++c > 4) {
+ fail("accept call did not exit");
+ }
+ } while (thread.isAlive());
+
+ interrupted = false;
+ ServerSocket ss2 = new ServerSocket(0);
+ ss2.setSoTimeout(500);
+ Date start = new Date();
+ try {
+ ss2.accept();
+ } catch (InterruptedIOException e) {
+ interrupted = true;
+ }
+ assertTrue("accept not interrupted", interrupted);
+ Date finish = new Date();
+ int delay = (int) (finish.getTime() - start.getTime());
+ assertTrue("timeout too soon: " + delay + " " + start.getTime()
+ + " " + finish.getTime(), delay >= 490);
+ ss2.close();
+ } catch (IOException e) {
+ fail("Unexpected IOException : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#close()
+ */
+ public void test_close() throws IOException {
+ try {
+ s = new ServerSocket(0);
+ try {
+ s.close();
+ s.accept();
+ fail("Close test failed");
+ } catch (SocketException e) {
+ // expected;
+ }
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#getInetAddress()
+ */
+ public void test_getInetAddress() throws IOException {
+ InetAddress addr = InetAddress.getLocalHost();
+ s = new ServerSocket(0, 10, addr);
+ try {
+ assertEquals("Returned incorrect InetAdrees", addr, s
+ .getInetAddress());
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#getLocalPort()
+ */
+ public void test_getLocalPort() throws IOException {
+ // Try a specific port number, but don't complain if we don't get it
+ int portNumber = 63024; // I made this up
+ try {
+ try {
+ s = new ServerSocket(portNumber);
+ } catch (BindException e) {
+ // we could not get the port, give up
+ return;
+ }
+ assertEquals("Returned incorrect port", portNumber, s
+ .getLocalPort());
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#getSoTimeout()
+ */
+ public void test_getSoTimeout() throws IOException {
+ s = new ServerSocket(0);
+ try {
+ s.setSoTimeout(100);
+ assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
+ */
+ public void test_setSocketFactoryLjava_net_SocketImplFactory()
+ throws IOException {
+ SocketImplFactory factory = new MockSocketImplFactory();
+ // Should not throw SocketException when set DatagramSocketImplFactory
+ // for the first time.
+ ServerSocket.setSocketFactory(factory);
+
+ try {
+ ServerSocket.setSocketFactory(null);
+ fail("Should throw SocketException");
+ } catch (SocketException e) {
+ // Expected
+ }
+
+ try {
+ ServerSocket.setSocketFactory(factory);
+ fail("Should throw SocketException");
+ } catch (SocketException e) {
+ // Expected
+ }
+ }
+
+ private static class MockSocketImplFactory implements SocketImplFactory {
+ public SocketImpl createSocketImpl() {
+ return new PlainServerSocketImpl();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#setSoTimeout(int)
+ */
+ public void test_setSoTimeoutI() throws IOException {
+ // Timeout should trigger and throw InterruptedIOException
+ try {
+ s = new ServerSocket(0);
+ s.setSoTimeout(100);
+ s.accept();
+ } catch (InterruptedIOException e) {
+ assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
+ return;
+ }
+
+ // Timeout should not trigger in this case
+ s = new ServerSocket(0);
+ startClient(s.getLocalPort());
+ s.setSoTimeout(10000);
+ sconn = s.accept();
+ }
+
+ /**
+ * java.net.ServerSocket#toString()
+ */
+ public void test_toString() throws Exception {
+ s = new ServerSocket(0);
+ try {
+ int portNumber = s.getLocalPort();
+ // In IPv6, the all-zeros-address is written as "::"
+ assertEquals("ServerSocket[addr=::/::,port=0,localport="
+ + portNumber + "]", s.toString());
+ } finally {
+ s.close();
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#bind(java.net.SocketAddress)
+ */
+ public void test_bindLjava_net_SocketAddress() throws IOException {
+ class mySocketAddress extends SocketAddress {
+ public mySocketAddress() {
+ }
+ }
+ // create servers socket, bind it and then validate basic state
+ ServerSocket theSocket = new ServerSocket();
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ theSocket.bind(theAddress);
+ int portNumber = theSocket.getLocalPort();
+ assertTrue(
+ "Returned incorrect InetSocketAddress(2):"
+ + theSocket.getLocalSocketAddress().toString()
+ + "Expected: "
+ + (new InetSocketAddress(InetAddress.getLocalHost(),
+ portNumber)).toString(), theSocket
+ .getLocalSocketAddress().equals(
+ new InetSocketAddress(InetAddress
+ .getLocalHost(), portNumber)));
+ assertTrue("Server socket not bound when it should be:", theSocket
+ .isBound());
+
+ // now make sure that it is actually bound and listening on the
+ // address we provided
+ Socket clientSocket = new Socket();
+ InetSocketAddress clAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), portNumber);
+ clientSocket.connect(clAddress);
+ Socket servSock = theSocket.accept();
+
+ assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
+ theSocket.close();
+ servSock.close();
+ clientSocket.close();
+
+ // validate we can specify null for the address in the bind and all
+ // goes ok
+ theSocket = new ServerSocket();
+ theSocket.bind(null);
+ theSocket.close();
+
+ // Address that we have already bound to
+ theSocket = new ServerSocket();
+ ServerSocket theSocket2 = new ServerSocket();
+ try {
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket.bind(theAddress);
+ SocketAddress localAddress = theSocket.getLocalSocketAddress();
+ theSocket2.bind(localAddress);
+ fail("No exception binding to address that is not available");
+ } catch (IOException ex) {
+ }
+ theSocket.close();
+ theSocket2.close();
+
+ // validate we get io address when we try to bind to address we
+ // cannot bind to
+ theSocket = new ServerSocket();
+ try {
+ theSocket.bind(new InetSocketAddress(InetAddress
+ .getByAddress(Support_Configuration.nonLocalAddressBytes),
+ 0));
+ fail("No exception was thrown when binding to bad address");
+ } catch (IOException ex) {
+ }
+ theSocket.close();
+
+ // now validate case where we pass in an unsupported subclass of
+ // SocketAddress
+ theSocket = new ServerSocket();
+ try {
+ theSocket.bind(new mySocketAddress());
+ fail("No exception when binding using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException ex) {
+ }
+ theSocket.close();
+ }
+
+ /**
+ * java.net.ServerSocket#bind(java.net.SocketAddress, int)
+ */
+ public void test_bindLjava_net_SocketAddressI() throws IOException {
+ class mySocketAddress extends SocketAddress {
+
+ public mySocketAddress() {
+ }
+ }
+
+ // create servers socket, bind it and then validate basic state
+ ServerSocket theSocket = new ServerSocket();
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ theSocket.bind(theAddress, 5);
+ int portNumber = theSocket.getLocalPort();
+ assertTrue(
+ "Returned incorrect InetSocketAddress(2):"
+ + theSocket.getLocalSocketAddress().toString()
+ + "Expected: "
+ + (new InetSocketAddress(InetAddress.getLocalHost(),
+ portNumber)).toString(), theSocket
+ .getLocalSocketAddress().equals(
+ new InetSocketAddress(InetAddress
+ .getLocalHost(), portNumber)));
+ assertTrue("Server socket not bound when it should be:", theSocket
+ .isBound());
+
+ // now make sure that it is actually bound and listening on the
+ // address we provided
+ SocketAddress localAddress = theSocket.getLocalSocketAddress();
+ Socket clientSocket = new Socket();
+ clientSocket.connect(localAddress);
+ Socket servSock = theSocket.accept();
+
+ assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
+ theSocket.close();
+ servSock.close();
+ clientSocket.close();
+
+ // validate we can specify null for the address in the bind and all
+ // goes ok
+ theSocket = new ServerSocket();
+ theSocket.bind(null, 5);
+ theSocket.close();
+
+ // Address that we have already bound to
+ theSocket = new ServerSocket();
+ ServerSocket theSocket2 = new ServerSocket();
+ try {
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket.bind(theAddress, 5);
+ SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
+ theSocket2.bind(inuseAddress, 5);
+ fail("No exception binding to address that is not available");
+ } catch (IOException ex) {
+ // expected
+ }
+ theSocket.close();
+ theSocket2.close();
+
+ // validate we get ioException when we try to bind to address we
+ // cannot bind to
+ theSocket = new ServerSocket();
+ try {
+ theSocket.bind(new InetSocketAddress(InetAddress
+ .getByAddress(Support_Configuration.nonLocalAddressBytes),
+ 0), 5);
+ fail("No exception was thrown when binding to bad address");
+ } catch (IOException ex) {
+ }
+ theSocket.close();
+
+ // now validate case where we pass in an unsupported subclass of
+ // SocketAddress
+ theSocket = new ServerSocket();
+ try {
+ theSocket.bind(new mySocketAddress(), 5);
+ fail("Binding using unsupported SocketAddress subclass should have thrown exception");
+ } catch (IllegalArgumentException ex) {
+ }
+ theSocket.close();
+
+ // now validate that backlog is respected. We have to do a test that
+ // checks if it is a least a certain number as some platforms make
+ // it higher than we request. Unfortunately non-server versions of
+ // windows artificially limit the backlog to 5 and 5 is the
+ // historical default so it is not a great test.
+ theSocket = new ServerSocket();
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket.bind(theAddress, 4);
+ localAddress = theSocket.getLocalSocketAddress();
+ Socket theSockets[] = new Socket[4];
+ int i = 0;
+ try {
+ for (i = 0; i < 4; i++) {
+ theSockets[i] = new Socket();
+ theSockets[i].connect(localAddress);
+ }
+ } catch (ConnectException ex) {
+ fail("Backlog does not seem to be respected in bind:" + i + ":"
+ + ex.toString());
+ }
+
+ for (i = 0; i < 4; i++) {
+ theSockets[i].close();
+ }
+
+ theSocket.close();
+ servSock.close();
+ }
+
+ /**
+ * java.net.ServerSocket#getLocalSocketAddress()
+ */
+ public void test_getLocalSocketAddress() throws Exception {
+ // set up server connect and then validate that we get the right
+ // response for the local address
+ ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
+ .getLocalHost());
+ int portNumber = theSocket.getLocalPort();
+ assertTrue("Returned incorrect InetSocketAddress(1):"
+ + theSocket.getLocalSocketAddress().toString()
+ + "Expected: "
+ + (new InetSocketAddress(InetAddress.getLocalHost(),
+ portNumber)).toString(), theSocket
+ .getLocalSocketAddress().equals(
+ new InetSocketAddress(InetAddress.getLocalHost(),
+ portNumber)));
+ theSocket.close();
+
+ // now create a socket that is not bound and validate we get the
+ // right answer
+ theSocket = new ServerSocket();
+ assertNull(
+ "Returned incorrect InetSocketAddress -unbound socket- Expected null",
+ theSocket.getLocalSocketAddress());
+
+ // now bind the socket and make sure we get the right answer
+ theSocket
+ .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ int localPort = theSocket.getLocalPort();
+ assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
+ .getLocalSocketAddress(), new InetSocketAddress(InetAddress
+ .getLocalHost(), localPort));
+ theSocket.close();
+ }
+
+ /**
+ * java.net.ServerSocket#isBound()
+ */
+ public void test_isBound() throws IOException {
+ InetAddress addr = InetAddress.getLocalHost();
+ ServerSocket serverSocket = new ServerSocket();
+ assertFalse("Socket indicated bound when it should be (1)",
+ serverSocket.isBound());
+
+ // now bind and validate bound ok
+ serverSocket.bind(new InetSocketAddress(addr, 0));
+ assertTrue("Socket indicated not bound when it should be (1)",
+ serverSocket.isBound());
+ serverSocket.close();
+
+ // now do with some of the other constructors
+ serverSocket = new ServerSocket(0);
+ assertTrue("Socket indicated not bound when it should be (2)",
+ serverSocket.isBound());
+ serverSocket.close();
+
+ serverSocket = new ServerSocket(0, 5, addr);
+ assertTrue("Socket indicated not bound when it should be (3)",
+ serverSocket.isBound());
+ serverSocket.close();
+
+ serverSocket = new ServerSocket(0, 5);
+ assertTrue("Socket indicated not bound when it should be (4)",
+ serverSocket.isBound());
+ serverSocket.close();
+ }
+
+ /**
+ * java.net.ServerSocket#isClosed()
+ */
+ public void test_isClosed() throws IOException {
+ InetAddress addr = InetAddress.getLocalHost();
+ ServerSocket serverSocket = new ServerSocket(0, 5, addr);
+
+ // validate isClosed returns expected values
+ assertFalse("Socket should indicate it is not closed(1):", serverSocket
+ .isClosed());
+ serverSocket.close();
+ assertTrue("Socket should indicate it is closed(1):", serverSocket
+ .isClosed());
+
+ // now do with some of the other constructors
+ serverSocket = new ServerSocket(0);
+ assertFalse("Socket should indicate it is not closed(1):", serverSocket
+ .isClosed());
+ serverSocket.close();
+ assertTrue("Socket should indicate it is closed(1):", serverSocket
+ .isClosed());
+
+ serverSocket = new ServerSocket(0, 5, addr);
+ assertFalse("Socket should indicate it is not closed(1):", serverSocket
+ .isClosed());
+ serverSocket.close();
+ assertTrue("Socket should indicate it is closed(1):", serverSocket
+ .isClosed());
+
+ serverSocket = new ServerSocket(0, 5);
+ assertFalse("Socket should indicate it is not closed(1):", serverSocket
+ .isClosed());
+ serverSocket.close();
+ assertTrue("Socket should indicate it is closed(1):", serverSocket
+ .isClosed());
+ }
+
+ /*
+ * Regression HARMONY-6090
+ */
+ public void test_defaultValueReuseAddress() throws Exception {
+ String platform = System.getProperty("os.name").toLowerCase(Locale.US);
+ if (!platform.startsWith("windows")) {
+ // on Unix
+ assertTrue(new ServerSocket().getReuseAddress());
+ assertTrue(new ServerSocket(0).getReuseAddress());
+ assertTrue(new ServerSocket(0, 50).getReuseAddress());
+ assertTrue(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
+ } else {
+ // on Windows
+ assertFalse(new ServerSocket().getReuseAddress());
+ assertFalse(new ServerSocket(0).getReuseAddress());
+ assertFalse(new ServerSocket(0, 50).getReuseAddress());
+ assertFalse(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
+ }
+ }
+
+ public void test_setReuseAddressZ() throws Exception {
+ // set up server and connect
+ InetSocketAddress anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ ServerSocket serverSocket = new ServerSocket();
+ serverSocket.setReuseAddress(false);
+ serverSocket.bind(anyAddress);
+ SocketAddress theAddress = serverSocket.getLocalSocketAddress();
+
+ // make a connection to the server, then close the server
+ Socket theSocket = new Socket();
+ theSocket.connect(theAddress);
+ Socket stillActiveSocket = serverSocket.accept();
+ serverSocket.close();
+
+ // now try to rebind the server which should fail with
+ // setReuseAddress to false. On windows platforms the bind is
+ // allowed even then reUseAddress is false so our test uses
+ // the platform to determine what the expected result is.
+ String platform = System.getProperty("os.name");
+ try {
+ serverSocket = new ServerSocket();
+ serverSocket.setReuseAddress(false);
+ serverSocket.bind(theAddress);
+ fail("No exception when setReuseAddress is false and we bind:" + theAddress.toString());
+ } catch (IOException expected) {
+ }
+ stillActiveSocket.close();
+ theSocket.close();
+
+ // now test case were we set it to true
+ anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ serverSocket = new ServerSocket();
+ serverSocket.setReuseAddress(true);
+ serverSocket.bind(anyAddress);
+ theAddress = serverSocket.getLocalSocketAddress();
+
+ // make a connection to the server, then close the server
+ theSocket = new Socket();
+ theSocket.connect(theAddress);
+ stillActiveSocket = serverSocket.accept();
+ serverSocket.close();
+
+ // now try to rebind the server which should pass with
+ // setReuseAddress to true
+ try {
+ serverSocket = new ServerSocket();
+ serverSocket.setReuseAddress(true);
+ serverSocket.bind(theAddress);
+ } catch (IOException ex) {
+ fail("Unexpected exception when setReuseAddress is true and we bind:"
+ + theAddress.toString() + ":" + ex.toString());
+ }
+ stillActiveSocket.close();
+ theSocket.close();
+
+ // now test default case were we expect this to work regardless of
+ // the value set
+ anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ serverSocket = new ServerSocket();
+ serverSocket.bind(anyAddress);
+ theAddress = serverSocket.getLocalSocketAddress();
+
+ // make a connection to the server, then close the server
+ theSocket = new Socket();
+ theSocket.connect(theAddress);
+ stillActiveSocket = serverSocket.accept();
+ serverSocket.close();
+
+ // now try to rebind the server which should pass
+ try {
+ serverSocket = new ServerSocket();
+ serverSocket.bind(theAddress);
+ } catch (IOException ex) {
+ fail("Unexpected exception when setReuseAddress is the default case and we bind:"
+ + theAddress.toString() + ":" + ex.toString());
+ }
+ stillActiveSocket.close();
+ theSocket.close();
+ }
+
+ public void test_getReuseAddress() throws Exception {
+ ServerSocket theSocket = new ServerSocket();
+ theSocket.setReuseAddress(true);
+ assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
+ theSocket.setReuseAddress(false);
+ assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
+ }
+
+ public void test_setReceiveBufferSizeI() throws Exception {
+ // now validate case where we try to set to 0
+ ServerSocket theSocket = new ServerSocket();
+ try {
+ theSocket.setReceiveBufferSize(0);
+ fail("No exception when receive buffer size set to 0");
+ } catch (IllegalArgumentException ex) {
+ }
+ theSocket.close();
+
+ // now validate case where we try to set to a negative value
+ theSocket = new ServerSocket();
+ try {
+ theSocket.setReceiveBufferSize(-1000);
+ fail("No exception when receive buffer size set to -1000");
+ } catch (IllegalArgumentException ex) {
+ }
+ theSocket.close();
+
+ // now just try to set a good value to make sure it is set and there
+ // are not exceptions
+ theSocket = new ServerSocket();
+ theSocket.setReceiveBufferSize(1000);
+ theSocket.close();
+ }
+
+ public void test_getReceiveBufferSize() throws Exception {
+ ServerSocket theSocket = new ServerSocket();
+
+ // since the value returned is not necessary what we set we are
+ // limited in what we can test
+ // just validate that it is not 0 or negative
+ assertFalse("get Buffer size returns 0:", 0 == theSocket.getReceiveBufferSize());
+ assertFalse("get Buffer size returns a negative value:", 0 > theSocket.getReceiveBufferSize());
+ }
+
+ public void test_getChannel() throws Exception {
+ assertNull(new ServerSocket().getChannel());
+ }
+
+ public void test_setPerformancePreference_Int_Int_Int() throws Exception {
+ ServerSocket theSocket = new ServerSocket();
+ theSocket.setPerformancePreferences(1, 1, 1);
+ }
+
+ /**
+ * 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 {
+ if (s != null)
+ s.close();
+ if (sconn != null)
+ sconn.close();
+ if (t != null)
+ t.interrupt();
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void startClient(int port) {
+ t = new Thread(new SSClient(port), "SSClient");
+ t.start();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ System.out.println("Exception during startClinet()" + e.toString());
+ }
+ }
+
+ /**
+ * java.net.ServerSocket#implAccept
+ */
+ public void test_implAcceptLjava_net_Socket() throws Exception {
+ // regression test for Harmony-1235
+ try {
+ new MockServerSocket().mockImplAccept(new MockSocket(
+ new MockSocketImpl()));
+ } catch (SocketException e) {
+ // expected
+ }
+ }
+
+ static class MockSocketImpl extends SocketImpl {
+ protected void create(boolean arg0) throws IOException {
+ // empty
+ }
+
+ protected void connect(String arg0, int arg1) throws IOException {
+ // empty
+ }
+
+ protected void connect(InetAddress arg0, int arg1) throws IOException {
+ // empty
+ }
+
+ protected void connect(SocketAddress arg0, int arg1) throws IOException {
+ // empty
+ }
+
+ protected void bind(InetAddress arg0, int arg1) throws IOException {
+ // empty
+ }
+
+ protected void listen(int arg0) throws IOException {
+ // empty
+ }
+
+ protected void accept(SocketImpl arg0) throws IOException {
+ // empty
+ }
+
+ protected InputStream getInputStream() throws IOException {
+ return null;
+ }
+
+ protected OutputStream getOutputStream() throws IOException {
+ return null;
+ }
+
+ protected int available() throws IOException {
+ return 0;
+ }
+
+ protected void close() throws IOException {
+ // empty
+ }
+
+ protected void sendUrgentData(int arg0) throws IOException {
+ // empty
+ }
+
+ public void setOption(int arg0, Object arg1) throws SocketException {
+ // empty
+ }
+
+ public Object getOption(int arg0) throws SocketException {
+ return null;
+ }
+ }
+
+ static class MockSocket extends Socket {
+ public MockSocket(SocketImpl impl) throws SocketException {
+ super(impl);
+ }
+ }
+
+ static class MockServerSocket extends ServerSocket {
+ public MockServerSocket() throws Exception {
+ super();
+ }
+
+ public void mockImplAccept(Socket s) throws Exception {
+ super.implAccept(s);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketExceptionTest.java
new file mode 100644
index 0000000..32c9eb8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketExceptionTest.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.net;
+
+import java.net.SocketException;
+
+public class SocketExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.SocketException#SocketException()
+ */
+ public void test_Constructor() {
+ try {
+ if (true) {
+ throw new SocketException();
+ }
+ fail("Failed to generate expected exception");
+ } catch (SocketException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.SocketException#SocketException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ if (true) {
+ throw new SocketException("Some error message");
+ }
+ fail("Failed to generate expected exception");
+ } catch (SocketException e) {
+ // Expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketImplTest.java
new file mode 100644
index 0000000..f6122e5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketImplTest.java
@@ -0,0 +1,155 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketImpl;
+
+public class SocketImplTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.SocketImpl#SocketImpl()
+ */
+ public void test_Constructor_fd() {
+ // Regression test for HARMONY-1117
+ MockSocketImpl mockSocketImpl = new MockSocketImpl();
+ assertNull(mockSocketImpl.getFileDescriptor());
+ }
+
+ /**
+ * java.net.SocketImpl#setPerformancePreference()
+ */
+ public void test_setPerformancePreference_Int_Int_Int() {
+ MockSocketImpl theSocket = new MockSocketImpl();
+ theSocket.setPerformancePreference(1, 1, 1);
+ }
+
+ /**
+ * java.net.SocketImpl#shutdownOutput()
+ */
+ public void test_shutdownOutput() {
+ MockSocketImpl s = new MockSocketImpl();
+ try {
+ s.shutdownOutput();
+ fail("This method is still not implemented yet,It should throw IOException.");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.net.SocketImpl#shutdownInput()
+ */
+ public void test_shutdownInput() {
+ MockSocketImpl s = new MockSocketImpl();
+ try {
+ s.shutdownInput();
+ fail("This method is still not implemented yet,It should throw IOException.");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.SocketImpl#supportsUrgentData()
+ */
+ public void test_supportsUrgentData() {
+ MockSocketImpl s = new MockSocketImpl();
+ assertFalse(s.testSupportsUrgentData());
+ }
+
+ // the mock class for test, leave all methods empty
+ class MockSocketImpl extends SocketImpl {
+
+ protected void accept(SocketImpl newSocket) throws IOException {
+ }
+
+ protected int available() throws IOException {
+ return 0;
+ }
+
+ protected void bind(InetAddress address, int port) throws IOException {
+ }
+
+ protected void close() throws IOException {
+ }
+
+ protected void connect(String host, int port) throws IOException {
+ }
+
+ protected void connect(InetAddress address, int port)
+ throws IOException {
+ }
+
+ protected void create(boolean isStreaming) throws IOException {
+ }
+
+ protected InputStream getInputStream() throws IOException {
+ return null;
+ }
+
+ public Object getOption(int optID) throws SocketException {
+ return null;
+ }
+
+ protected OutputStream getOutputStream() throws IOException {
+ return null;
+ }
+
+ protected void listen(int backlog) throws IOException {
+ }
+
+ public void setOption(int optID, Object val) throws SocketException {
+ }
+
+ protected void connect(SocketAddress remoteAddr, int timeout)
+ throws IOException {
+ }
+
+ protected void sendUrgentData(int value) throws IOException {
+ }
+
+ public void setPerformancePreference(int connectionTime, int latency,
+ int bandwidth) {
+ super.setPerformancePreferences(connectionTime, latency, bandwidth);
+ }
+
+ public FileDescriptor getFileDescriptor() {
+ return super.getFileDescriptor();
+ }
+
+ public void shutdownOutput() throws IOException {
+ super.shutdownOutput();
+ }
+
+ public void shutdownInput() throws IOException {
+ super.shutdownInput();
+ }
+
+ public boolean testSupportsUrgentData() {
+ return super.supportsUrgentData();
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTest.java
new file mode 100644
index 0000000..4df92e2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTest.java
@@ -0,0 +1,1634 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ConnectException;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketImpl;
+import java.net.SocketImplFactory;
+import java.net.SocketTimeoutException;
+import java.net.UnknownHostException;
+import java.security.Permission;
+import java.util.Arrays;
+import java.util.Locale;
+
+import tests.support.Support_Configuration;
+
+public class SocketTest extends junit.framework.TestCase {
+ private class ClientThread implements Runnable {
+
+ public void run() {
+ try {
+ Socket socket = new Socket();
+ InetSocketAddress addr = new InetSocketAddress(host, port);
+ socket.connect(addr);
+
+ socket.close();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private class ServerThread implements Runnable {
+ private static final int FIRST_TIME = 1;
+
+ private static final int SECOND_TIME = 2;
+
+ private int backlog = 10;
+
+ public boolean ready = false;
+
+ private int serverSocketConstructor = 0;
+
+ public void run() {
+ try {
+
+ ServerSocket socket;
+ switch (serverSocketConstructor) {
+ case FIRST_TIME:
+ socket = new ServerSocket(port, backlog,
+ new InetSocketAddress(host, port).getAddress());
+ port = socket.getLocalPort();
+ break;
+ case SECOND_TIME:
+ socket = new ServerSocket(port, backlog);
+ host = socket.getInetAddress().getHostName();
+ port = socket.getLocalPort();
+ break;
+ default:
+ socket = new ServerSocket();
+ break;
+ }
+
+ synchronized (this) {
+ ready = true;
+ this.notifyAll();
+ }
+
+ socket.setSoTimeout(5000);
+ Socket client = socket.accept();
+ client.close();
+ socket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ }
+
+ public synchronized void waitCreated() throws Exception {
+ while (!ready) {
+ this.wait();
+ }
+ }
+ }
+
+ boolean interrupted;
+
+ String host = "localhost";
+ int port;
+
+ Thread t;
+
+ private void connectTestImpl(int ssConsType) throws Exception {
+ ServerThread server = new ServerThread();
+ server.serverSocketConstructor = ssConsType;
+ Thread serverThread = new Thread(server);
+ serverThread.start();
+ server.waitCreated();
+
+ ClientThread client = new ClientThread();
+ Thread clientThread = new Thread(client);
+ clientThread.start();
+ try {
+ serverThread.join();
+ clientThread.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ protected void tearDown() {
+ try {
+ if (t != null) {
+ t.interrupt();
+ }
+ } catch (Exception e) {
+ }
+ this.t = null;
+ this.interrupted = false;
+ }
+
+ /**
+ * java.net.Socket#bind(java.net.SocketAddress)
+ */
+ public void test_bindLjava_net_SocketAddress() throws IOException {
+
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ // Address we cannot bind to
+ Socket theSocket = new Socket();
+ InetSocketAddress bogusAddress = new InetSocketAddress(InetAddress
+ .getByAddress(Support_Configuration.nonLocalAddressBytes), 42);
+ try {
+ theSocket.bind(bogusAddress);
+ fail("No exception when binding to bad address");
+ } catch (IOException ex) {
+ // Expected
+ }
+ theSocket.close();
+
+ // Now create a socket that is not bound and then bind it
+ theSocket = new Socket();
+ theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ int portNumber = theSocket.getLocalPort();
+
+ // Validate that the localSocketAddress reflects the address we
+ // bound to
+ assertEquals("Local address not correct after bind",
+ new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
+ theSocket.getLocalSocketAddress());
+
+ // Make sure we can now connect and that connections appear to come
+ // from the address we bound to.
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ ServerSocket server = new ServerSocket();
+ server.bind(theAddress);
+ int sport = server.getLocalPort();
+ InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), sport);
+
+ theSocket.connect(boundAddress);
+ Socket worker = server.accept();
+ assertEquals(
+ "Returned Remote address from server connected to does not match expected local address",
+ new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
+ worker.getRemoteSocketAddress());
+ theSocket.close();
+ worker.close();
+ server.close();
+
+ // Validate if we pass in null that it picks an address for us and
+ // all is ok
+ theSocket = new Socket();
+ theSocket.bind(null);
+ assertNotNull("Bind with null did not work", theSocket
+ .getLocalSocketAddress());
+ theSocket.close();
+
+ // now check the error conditions
+
+ // Address that we have already bound to
+ theSocket = new Socket();
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ theSocket.bind(theAddress);
+
+ Socket theSocket2 = new Socket();
+ try {
+ theSocket2.bind(theSocket.getLocalSocketAddress());
+ fail("No exception binding to address that is not available");
+ } catch (IOException ex) {
+ // Expected
+ }
+ theSocket.close();
+ theSocket2.close();
+
+ // Unsupported SocketAddress subclass
+ theSocket = new Socket();
+ try {
+ theSocket.bind(new UnsupportedSocketAddress());
+ fail("No exception when binding using unsupported SocketAddress subclass");
+ } catch (IllegalArgumentException ex) {
+ // Expected
+ }
+ theSocket.close();
+ }
+
+ /**
+ * java.net.Socket#bind(java.net.SocketAddress)
+ */
+ public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
+ // The Proxy will not impact on the bind operation. It can be assigned
+ // with any address.
+ Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(
+ "127.0.0.1", 0));
+ Socket socket = new Socket(proxy);
+
+ InetAddress address = InetAddress.getByName("localhost");
+ socket.bind(new InetSocketAddress(address, 0));
+
+ assertEquals(address, socket.getLocalAddress());
+ assertTrue(0 != socket.getLocalPort());
+
+ socket.close();
+ }
+
+ public void test_close() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ client.setSoLinger(false, 100);
+
+ client.close();
+ try {
+ client.getOutputStream();
+ fail("Failed to close socket");
+ } catch (IOException expected) {
+ }
+
+ server.close();
+ }
+
+ public void test_connect_unknownhost() throws Exception {
+ Socket socket = new Socket();
+ try {
+ socket.connect(new InetSocketAddress("1.2.3.4hello", 12345));
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ }
+
+ public void test_connect_unresolved() throws IOException {
+ Socket socket = new Socket();
+ InetSocketAddress unresolved = InetSocketAddress.createUnresolved("www.apache.org", 80);
+ try {
+ socket.connect(unresolved);
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ try {
+ socket.connect(unresolved, 123);
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ }
+
+ public void test_connectLjava_net_SocketAddress() throws Exception {
+
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ Socket theSocket = new Socket();
+ try {
+ theSocket.connect(null);
+ fail("No exception for null arg");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ theSocket.connect(new UnsupportedSocketAddress());
+ fail("No exception for invalid socket address");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ theSocket.connect(new InetSocketAddress(InetAddress
+ .getByAddress(new byte[] { 0, 0, 0, 0 }), 42));
+ fail("No exception with non-connectable address");
+ } catch (ConnectException e) {
+ // Expected
+ }
+
+ // now validate that we get a connect exception if we try to connect to
+ // an address on which nobody is listening
+ theSocket = new Socket();
+ try {
+ theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
+ 0));
+ fail("No exception when connecting to address nobody listening on");
+ } catch (ConnectException e) {
+ // Expected
+ }
+
+ // Now validate that we can actually connect when somebody is listening
+ ServerSocket server = new ServerSocket(0);
+ InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), server.getLocalPort());
+ Socket client = new Socket();
+ client.connect(boundAddress);
+
+ // validate that when a socket is connected that it answers
+ // correctly to related queries
+ assertTrue("Wrong connected status", client.isConnected());
+ assertFalse("Wrong closed status", client.isClosed());
+ assertTrue("Wrong bound status", client.isBound());
+ assertFalse("Wrong input shutdown status", client.isInputShutdown());
+ assertFalse("Wrong output shutdown status", client.isOutputShutdown());
+ assertTrue("Local port was 0", client.getLocalPort() != 0);
+
+ client.close();
+ server.close();
+
+ // Now validate that we get the right exception if we connect when we
+ // are already connected
+ server = new ServerSocket(0);
+ boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ client = new Socket();
+ client.connect(boundAddress);
+
+ try {
+ client.connect(boundAddress);
+ fail("No exception when we try to connect on a connected socket: ");
+ } catch (SocketException e) {
+ // Expected
+ }
+ client.close();
+ server.close();
+ }
+
+ /**
+ * Regression for Harmony-2503
+ */
+ public void test_connectLjava_net_SocketAddress_AnyAddress()
+ throws Exception {
+ connectTestImpl(ServerThread.FIRST_TIME);
+ connectTestImpl(ServerThread.SECOND_TIME);
+ }
+
+ /**
+ * java.net.Socket#connect(java.net.SocketAddress, int)
+ */
+ public void test_connectLjava_net_SocketAddressI() throws Exception {
+
+ @SuppressWarnings("serial")
+ class UnsupportedSocketAddress extends SocketAddress {
+ public UnsupportedSocketAddress() {
+ }
+ }
+
+ // Start by validating the error checks
+ Socket theSocket = new Socket();
+ try {
+ theSocket.connect(new InetSocketAddress(0), -100);
+ fail("No exception for negative timeout");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ theSocket.connect(null, 0);
+ fail("No exception for null address");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ theSocket.connect(new UnsupportedSocketAddress(), 1000);
+ fail("No exception for invalid socket address type");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ SocketAddress nonConnectableAddress = new InetSocketAddress(InetAddress
+ .getByAddress(new byte[] { 0, 0, 0, 0 }), 0);
+ try {
+ theSocket.connect(nonConnectableAddress, 1000);
+ fail("No exception when non Connectable Address passed in: ");
+ } catch (SocketException e) {
+ // Expected
+ }
+
+ // Now validate that we get a connect exception if we try to connect to
+ // an address on which nobody is listening
+ theSocket = new Socket();
+ try {
+ theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
+ 0), 0);
+ fail("No exception when connecting to address nobody listening on");
+ } catch (ConnectException e) {
+ // Expected
+ }
+ theSocket.close();
+
+ // Now validate that we can actually connect when somebody is listening
+ ServerSocket server = new ServerSocket(0);
+ InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), server.getLocalPort());
+ Socket client = new Socket();
+ client.connect(boundAddress, 0);
+
+ // Validate that when a socket is connected that it answers
+ // correctly to related queries
+ assertTrue("Wrong connected status", client.isConnected());
+ assertFalse("Wrong closed status", client.isClosed());
+ assertTrue("Wrong bound status", client.isBound());
+ assertFalse("Wrong input shutdown status", client.isInputShutdown());
+ assertFalse("Wrong output shutdown status", client.isOutputShutdown());
+ assertTrue("Local port was 0", client.getLocalPort() != 0);
+
+ client.close();
+ server.close();
+
+ // Now validate that we get a connect exception if we try to connect to
+ // an address on which nobody is listening
+ theSocket = new Socket();
+ SocketAddress nonListeningAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 42);
+ try {
+ theSocket.connect(nonListeningAddress, 1000);
+ fail("No exception when connecting to address nobody listening on");
+ } catch (ConnectException e) {
+ // Expected
+ } catch (SocketTimeoutException e) {
+ // The other possibility is that the system timed us out.
+ }
+ theSocket.close();
+
+ // Now validate that we get the right exception if we connect when we
+ // are already connected
+ server = new ServerSocket(0);
+ boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ client = new Socket();
+ client.connect(boundAddress, 10000);
+
+ try {
+ client.connect(boundAddress, 10000);
+ fail("No exception when we try to connect on a connected socket: ");
+ } catch (SocketException e) {
+ // Expected
+ }
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#Socket()
+ */
+ public void test_Constructor() {
+ // create the socket and then validate some basic state
+ Socket s = new Socket();
+ assertFalse("new socket should not be connected", s.isConnected());
+ assertFalse("new socket should not be bound", s.isBound());
+ assertFalse("new socket should not be closed", s.isClosed());
+ assertFalse("new socket should not be in InputShutdown", s
+ .isInputShutdown());
+ assertFalse("new socket should not be in OutputShutdown", s
+ .isOutputShutdown());
+ }
+
+ /**
+ * java.net.Socket#Socket(java.lang.String, int)
+ */
+ public void test_ConstructorLjava_lang_StringI() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ assertEquals("Failed to create socket", server.getLocalPort(), client
+ .getPort());
+
+ // Regression for HARMONY-946
+ ServerSocket ss = new ServerSocket(0);
+ Socket s = new Socket("0.0.0.0", ss.getLocalPort());
+ ss.close();
+ s.close();
+ }
+
+ /**
+ * java.net.Socket#Socket(java.lang.String, int,
+ *java.net.InetAddress, int)
+ */
+ public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
+ throws IOException {
+
+ ServerSocket server = new ServerSocket(0);
+ int serverPort = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost().getHostName(),
+ serverPort, InetAddress.getLocalHost(), 0);
+ assertTrue("Failed to create socket", client.getPort() == serverPort);
+ client.close();
+
+ Socket theSocket;
+ try {
+ theSocket = new Socket("127.0.0.1", serverPort, InetAddress
+ .getLocalHost(), 0);
+ } catch (IOException e) {
+ // check here if InetAddress.getLocalHost() is returning the
+ // loopback address, if so that is likely the cause of the failure
+ assertFalse(
+ "Misconfiguration - local host is the loopback address",
+ InetAddress.getLocalHost().isLoopbackAddress());
+ throw e;
+ }
+
+ assertTrue(theSocket.isConnected());
+
+ try {
+ new Socket("127.0.0.1", serverPort, theSocket.getLocalAddress(),
+ theSocket.getLocalPort());
+ fail("Was able to create two sockets on same port");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ theSocket.close();
+ server.close();
+ }
+
+ @SuppressWarnings("deprecation")
+ public void test_ConstructorLjava_lang_StringIZ() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ int serverPort = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost().getHostAddress(),
+ serverPort, true);
+
+ assertEquals("Failed to create socket", serverPort, client.getPort());
+ client.close();
+
+ client = new Socket(InetAddress.getLocalHost().getHostName(),
+ serverPort, false);
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#Socket(java.net.InetAddress, int)
+ */
+ public void test_ConstructorLjava_net_InetAddressI() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ assertEquals("Failed to create socket", server.getLocalPort(), client
+ .getPort());
+
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#Socket(java.net.InetAddress, int,
+ *java.net.InetAddress, int)
+ */
+ public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
+ throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort(), InetAddress.getLocalHost(), 0);
+ assertNotSame("Failed to create socket", 0, client.getLocalPort());
+ }
+
+ /**
+ * java.net.Socket#Socket(java.net.InetAddress, int, boolean)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ int serverPort = server.getLocalPort();
+
+ Socket client = new Socket(InetAddress.getLocalHost(), serverPort, true);
+ assertEquals("Failed to create socket", serverPort, client.getPort());
+
+ client = new Socket(InetAddress.getLocalHost(), serverPort, false);
+ client.close();
+ }
+
+ /**
+ * java.net.Socket#Socket(Proxy)
+ */
+ public void test_ConstructorLjava_net_Proxy_Exception() {
+
+ SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1", 80);
+
+ Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
+ // IllegalArgumentException test
+ try {
+ new Socket(proxy1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
+ // should not throw any exception
+ new Socket(proxy2);
+ new Socket(Proxy.NO_PROXY);
+ }
+
+ /**
+ * java.net.Socket#getChannel()
+ */
+ public void test_getChannel() {
+ assertNull(new Socket().getChannel());
+ }
+
+ /**
+ * java.net.Socket#getInetAddress()
+ */
+ public void test_getInetAddress() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ assertTrue("Returned incorrect InetAdrees", client.getInetAddress()
+ .equals(InetAddress.getLocalHost()));
+
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#getInputStream()
+ */
+ public void test_getInputStream() throws IOException {
+ // Simple fetch test
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ InputStream is = client.getInputStream();
+ assertNotNull("Failed to get stream", is);
+ is.close();
+ client.close();
+ server.close();
+ }
+
+ private boolean isUnix() {
+ String osName = System.getProperty("os.name");
+
+ // only comparing ASCII, so assume english locale
+ osName = (osName == null ? null : osName.toLowerCase(Locale.ENGLISH));
+
+ if (osName != null && osName.startsWith("windows")) { //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
+
+ public void test_getKeepAlive() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort(), null, 0);
+
+ client.setKeepAlive(true);
+ assertTrue("getKeepAlive false when it should be true", client.getKeepAlive());
+
+ client.setKeepAlive(false);
+ assertFalse("getKeepAlive true when it should be False", client.getKeepAlive());
+ }
+
+ public void test_getLocalAddress() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ assertTrue("Returned incorrect InetAddress", client.getLocalAddress()
+ .equals(InetAddress.getLocalHost()));
+
+ client = new Socket();
+ client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
+ assertTrue(client.getLocalAddress().isAnyLocalAddress());
+
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#getLocalPort()
+ */
+ public void test_getLocalPort() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ assertNotSame("Returned incorrect port", 0, client.getLocalPort());
+
+ client.close();
+ server.close();
+ }
+
+ public void test_getLocalSocketAddress() throws IOException {
+ // set up server connect and then validate that we get the right
+ // response for the local address
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ int clientPort = client.getLocalPort();
+
+ assertEquals("Returned incorrect InetSocketAddress(1):",
+ new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
+ client.getLocalSocketAddress());
+ client.close();
+ server.close();
+
+ // now create a socket that is not bound and validate we get the
+ // right answer
+ client = new Socket();
+ assertNull(
+ "Returned incorrect InetSocketAddress -unbound socket- Expected null",
+ client.getLocalSocketAddress());
+
+ // now bind the socket and make sure we get the right answer
+ client.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ clientPort = client.getLocalPort();
+ assertEquals("Returned incorrect InetSocketAddress(2):",
+ new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
+ client.getLocalSocketAddress());
+ client.close();
+
+ // now validate the behaviour when the any address is returned
+ client = new Socket();
+ client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
+ assertTrue(((InetSocketAddress) client.getLocalSocketAddress()).getAddress().isAnyLocalAddress());
+ client.close();
+
+ // now validate the same for getLocalAddress
+ client = new Socket();
+ client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
+ assertTrue(client.getLocalAddress().isAnyLocalAddress());
+ client.close();
+ }
+
+ public void test_getOOBInline() throws Exception {
+ Socket theSocket = new Socket();
+
+ theSocket.setOOBInline(true);
+ assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
+
+ theSocket.setOOBInline(false);
+ assertFalse("expected OOBIline to be false", theSocket.getOOBInline());
+
+ theSocket.setOOBInline(false);
+ assertFalse("expected OOBIline to be false", theSocket.getOOBInline());
+ }
+
+ /**
+ * java.net.Socket#getOutputStream()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_getOutputStream() throws IOException {
+ // Simple fetch test
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ OutputStream os = client.getOutputStream();
+ assertNotNull("Failed to get stream", os);
+ os.close();
+ client.close();
+ server.close();
+
+ // Simple read/write test over the IO streams
+ final ServerSocket sinkServer = new ServerSocket(0);
+ Runnable runnable = new Runnable() {
+ public void run() {
+ try {
+ Socket worker = sinkServer.accept();
+ sinkServer.close();
+ InputStream in = worker.getInputStream();
+ in.read();
+ in.close();
+ worker.close();
+ } catch (IOException e) {
+ fail();
+ }
+ }
+ };
+ Thread thread = new Thread(runnable, "Socket.getOutputStream");
+ thread.start();
+
+ Socket pingClient = new Socket(InetAddress.getLocalHost(), sinkServer
+ .getLocalPort());
+
+ // Busy wait until the client is connected.
+ int c = 0;
+ while (!pingClient.isConnected()) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ }
+ if (++c > 4) {
+ fail("thread is not alive");
+ }
+ }
+
+ // Write some data to the server
+ OutputStream out = pingClient.getOutputStream();
+ out.write(new byte[256]);
+
+ // Wait for the server to finish
+ Thread.yield();
+ c = 0;
+ while (thread.isAlive()) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ }
+ if (++c > 4) {
+ fail("read call did not exit");
+ }
+ }
+
+ // Subsequent writes should throw an exception
+ try {
+ // The output buffer may remain valid until the close completes
+ for (int i = 0; i < 400; i++) {
+ out.write(new byte[256]);
+ }
+ fail("write to closed socket did not cause exception");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ out.close();
+ pingClient.close();
+ sinkServer.close();
+
+ // Regression test for HARMONY-873
+ ServerSocket ss2 = new ServerSocket(0);
+ Socket s = new Socket("127.0.0.1", ss2.getLocalPort());
+ ss2.accept();
+ s.shutdownOutput();
+ try {
+ s.getOutputStream();
+ fail("should throw SocketException");
+ } catch (SocketException e) {
+ // expected
+ }
+ }
+
+ public void test_getPort() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ int serverPort = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
+
+ assertEquals("Returned incorrect port", serverPort, client.getPort());
+
+ client.close();
+ server.close();
+ }
+
+ public void test_getReceiveBufferSize() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setReceiveBufferSize(130);
+
+ assertTrue("Incorrect buffer size", client.getReceiveBufferSize() >= 130);
+
+ client.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#getRemoteSocketAddress()
+ */
+ public void test_getRemoteSocketAddress() throws IOException {
+ // set up server connect and then validate that we get the right
+ // response for the remote address
+ ServerSocket server = new ServerSocket(0);
+ int serverPort = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
+
+ assertEquals("Returned incorrect InetSocketAddress(1):",
+ new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
+ client.getRemoteSocketAddress());
+ client.close();
+
+ // now create one that is not connected and validate that we get the
+ // right answer
+ Socket theSocket = new Socket();
+ theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ assertNull("Returned incorrect InetSocketAddress -unconnected socket:",
+ theSocket.getRemoteSocketAddress());
+
+ // now connect and validate we get the right answer
+ theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
+ serverPort));
+ assertEquals("Returned incorrect InetSocketAddress(2):",
+ new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
+ theSocket.getRemoteSocketAddress());
+ theSocket.close();
+
+ server.close();
+ }
+
+ public void test_getReuseAddress() throws Exception {
+ Socket theSocket = new Socket();
+ theSocket.setReuseAddress(true);
+ assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
+ theSocket.setReuseAddress(false);
+ assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
+ }
+
+ public void test_getSendBufferSize() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSendBufferSize(134);
+ assertTrue("Incorrect buffer size", client.getSendBufferSize() >= 134);
+ client.close();
+ server.close();
+ }
+
+ public void test_getSoLinger() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSoLinger(true, 200);
+ assertEquals("Returned incorrect linger", 200, client.getSoLinger());
+ client.setSoLinger(false, 0);
+ client.close();
+ server.close();
+ }
+
+ public void test_getSoTimeout() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSoTimeout(100);
+ assertEquals("Returned incorrect sotimeout", 100, client.getSoTimeout());
+ client.close();
+ server.close();
+ }
+
+ public void test_getTcpNoDelay() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ boolean bool = !client.getTcpNoDelay();
+ client.setTcpNoDelay(bool);
+ assertTrue("Failed to get no delay setting: " + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
+
+ client.close();
+ server.close();
+ }
+
+ public void test_getTrafficClass() throws Exception {
+ /*
+ * We cannot actually check that the values are set as if a platform
+ * does not support the option then it may come back unset even
+ * though we set it so just get the value to make sure we can get it
+ */
+ int trafficClass = new Socket().getTrafficClass();
+ assertTrue(0 <= trafficClass);
+ assertTrue(trafficClass <= 255);
+ }
+
+ /**
+ * java.net.Socket#isBound()
+ */
+ public void test_isBound() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ Socket worker = server.accept();
+
+ assertTrue("Socket indicated not bound when it should be (1)", client
+ .isBound());
+ worker.close();
+ client.close();
+ server.close();
+
+ client = new Socket();
+ assertFalse("Socket indicated bound when it was not (2)", client
+ .isBound());
+
+ server = new ServerSocket();
+ server.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ InetSocketAddress boundAddress = new InetSocketAddress(server
+ .getInetAddress(), server.getLocalPort());
+ client.connect(boundAddress);
+ worker = server.accept();
+ assertTrue("Socket indicated not bound when it should be (2)", client
+ .isBound());
+ worker.close();
+ client.close();
+ server.close();
+
+ // now test when we bind explicitly
+ InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ client = new Socket();
+ assertFalse("Socket indicated bound when it was not (3)", client
+ .isBound());
+ client.bind(theLocalAddress);
+ assertTrue("Socket indicated not bound when it should be (3a)", client
+ .isBound());
+ client.close();
+ assertTrue("Socket indicated not bound when it should be (3b)", client
+ .isBound());
+ }
+
+ /**
+ * java.net.Socket#isClosed()
+ */
+ public void test_isClosed() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ Socket worker = server.accept();
+
+ // validate isClosed returns expected values
+ assertFalse("Socket should indicate it is not closed(1):", client
+ .isClosed());
+ client.close();
+ assertTrue("Socket should indicate it is closed(1):", client.isClosed());
+
+ // validate that isClosed works ok for sockets returned from
+ // ServerSocket.accept()
+ assertFalse("Accepted Socket should indicate it is not closed:", worker
+ .isClosed());
+ worker.close();
+ assertTrue("Accepted Socket should indicate it is closed:", worker
+ .isClosed());
+
+ // and finally for the server socket
+ assertFalse("Server Socket should indicate it is not closed:", server
+ .isClosed());
+ server.close();
+ assertTrue("Server Socket should indicate it is closed:", server
+ .isClosed());
+ }
+
+ /**
+ * java.net.Socket#isConnected()
+ */
+ public void test_isConnected() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+ Socket worker = server.accept();
+
+ assertTrue("Socket indicated not connected when it should be", client
+ .isConnected());
+ client.close();
+ worker.close();
+ server.close();
+
+ // now do it with the new constructors and revalidate
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ client = new Socket();
+ assertFalse("Socket indicated connected when it was not", client
+ .isConnected());
+
+ server = new ServerSocket();
+ server.bind(theAddress);
+ InetSocketAddress boundAddress = new InetSocketAddress(server
+ .getInetAddress(), server.getLocalPort());
+ client.connect(boundAddress);
+ worker = server.accept();
+ assertTrue("Socket indicated not connected when it should be", client
+ .isConnected());
+ client.close();
+ worker.close();
+ server.close();
+ }
+
+ /**
+ * java.net.Socket#isInputShutdown()
+ */
+ public void test_isInputShutdown() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ Socket worker = server.accept();
+ InputStream theInput = client.getInputStream();
+ OutputStream theOutput = worker.getOutputStream();
+
+ // make sure we get the right answer with newly connected socket
+ assertFalse("Socket indicated input shutdown when it should not have",
+ client.isInputShutdown());
+
+ // shutdown the output
+ client.shutdownInput();
+
+ // make sure we get the right answer once it is shut down
+ assertTrue(
+ "Socket indicated input was NOT shutdown when it should have been",
+ client.isInputShutdown());
+
+ client.close();
+ worker.close();
+ server.close();
+
+ // make sure we get the right answer for closed sockets
+ assertFalse(
+ "Socket indicated input was shutdown when socket was closed",
+ worker.isInputShutdown());
+
+ theInput.close();
+ theOutput.close();
+ }
+
+ /**
+ * java.net.Socket#isOutputShutdown()
+ */
+ public void test_isOutputShutdown() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server
+ .getLocalPort());
+
+ Socket worker = server.accept();
+ InputStream theInput = client.getInputStream();
+ OutputStream theOutput = worker.getOutputStream();
+
+ // make sure we get the right answer with newly connected socket
+ assertFalse("Socket indicated output shutdown when it should not have",
+ worker.isOutputShutdown());
+
+ // shutdown the output
+ worker.shutdownOutput();
+
+ // make sure we get the right answer once it is shut down
+ assertTrue(
+ "Socket indicated output was NOT shutdown when it should have been",
+ worker.isOutputShutdown());
+
+ client.close();
+ worker.close();
+ server.close();
+
+ // make sure we get the right answer for closed sockets
+ assertFalse(
+ "Socket indicated output was output shutdown when the socket was closed",
+ client.isOutputShutdown());
+
+ theInput.close();
+ theOutput.close();
+ }
+
+ /**
+ * java.net.Socket#sendUrgentData(int)
+ */
+ public void test_sendUrgentDataI() throws Exception {
+ /*
+ * Some platforms may not support urgent data in this case we will not
+ * run these tests. For now run on all platforms until we find those
+ * that do not support urgent data
+ */
+ String platform = System.getProperty("os.name");
+ if (platform.equals("Dummy")) {
+ return;
+ }
+
+ /*
+ * Test 1: Validate that when OOBInline is false that any urgent data is
+ * silently ignored
+ */
+ InetAddress localHost = InetAddress.getLocalHost();
+ ServerSocket server = new ServerSocket(0, 5, localHost);
+ SocketAddress serverAddress = new InetSocketAddress(localHost, server
+ .getLocalPort());
+
+ Socket client = new Socket();
+ client.setOOBInline(false);
+
+ client.connect(serverAddress);
+ Socket worker = server.accept();
+ worker.setTcpNoDelay(true);
+ OutputStream theOutput = worker.getOutputStream();
+
+ // Send the regular data
+ byte[] sendBytes = "Test".getBytes();
+ theOutput.write(sendBytes);
+ theOutput.flush();
+
+ // Send the urgent data byte which should not be received
+ worker.sendUrgentData("UrgentData".getBytes()[0]);
+ theOutput.write(sendBytes);
+ worker.shutdownOutput();
+ worker.close();
+
+ // Try to read the bytes back
+ int totalBytesRead = 0;
+ byte[] myBytes = new byte[100];
+ InputStream theInput = client.getInputStream();
+ while (true) {
+ int bytesRead = theInput.read(myBytes, totalBytesRead,
+ myBytes.length - totalBytesRead);
+ if (bytesRead == -1) {
+ break;
+ }
+ totalBytesRead = totalBytesRead + bytesRead;
+ }
+
+ client.close();
+ server.close();
+
+ byte[] expectBytes = new byte[2 * sendBytes.length];
+ System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
+ System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length,
+ sendBytes.length);
+
+ byte[] resultBytes = new byte[totalBytesRead];
+ System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
+
+ assertTrue("Urgent data was received", Arrays.equals(expectBytes,
+ resultBytes));
+
+ /*
+ * Test 2: Now validate that urgent data is received as expected. Expect
+ * that it should be between the two writes.
+ */
+ server = new ServerSocket(0, 5, localHost);
+ serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
+
+ client = new Socket();
+ client.setOOBInline(true);
+
+ client.connect(serverAddress);
+ worker = server.accept();
+ worker.setTcpNoDelay(true);
+ theOutput = worker.getOutputStream();
+
+ // Send the regular data
+ sendBytes = "Test - Urgent Data".getBytes();
+ theOutput.write(sendBytes);
+
+ // Send the urgent data (one byte) which should be received
+ client.setOOBInline(true);
+ byte urgentByte = "UrgentData".getBytes()[0];
+ worker.sendUrgentData(urgentByte);
+
+ // Send more data, the urgent byte must stay in position
+ theOutput.write(sendBytes);
+ worker.shutdownOutput();
+ worker.close();
+
+ // Try to read the bytes back
+ totalBytesRead = 0;
+ myBytes = new byte[100];
+ theInput = client.getInputStream();
+ while (true) {
+ int bytesRead = theInput.read(myBytes, totalBytesRead,
+ myBytes.length - totalBytesRead);
+ if (bytesRead == -1) {
+ break;
+ }
+ totalBytesRead = totalBytesRead + bytesRead;
+ }
+
+ client.close();
+ server.close();
+
+ expectBytes = new byte[2 * sendBytes.length + 1];
+ System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
+ expectBytes[sendBytes.length] = urgentByte;
+ System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 1,
+ sendBytes.length);
+
+ resultBytes = new byte[totalBytesRead];
+ System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
+
+ assertTrue("Urgent data was not received with one urgent byte", Arrays
+ .equals(expectBytes, resultBytes));
+
+ /*
+ * Test 3: Now validate that urgent data is received as expected. Expect
+ * that it should be between the two writes.
+ */
+ server = new ServerSocket(0, 5, localHost);
+ serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
+
+ client = new Socket();
+ client.setOOBInline(true);
+
+ client.connect(serverAddress);
+ worker = server.accept();
+ worker.setTcpNoDelay(true);
+ theOutput = worker.getOutputStream();
+
+ // Send the regular data
+ sendBytes = "Test - Urgent Data".getBytes();
+ theOutput.write(sendBytes);
+
+ // Send the urgent data (one byte) which should be received
+ client.setOOBInline(true);
+ byte urgentByte1 = "UrgentData".getBytes()[0];
+ byte urgentByte2 = "UrgentData".getBytes()[1];
+ worker.sendUrgentData(urgentByte1);
+ worker.sendUrgentData(urgentByte2);
+
+ // Send more data, the urgent byte must stay in position
+ theOutput.write(sendBytes);
+ worker.shutdownOutput();
+ worker.close();
+
+ // Try to read the bytes back
+ totalBytesRead = 0;
+ myBytes = new byte[100];
+ theInput = client.getInputStream();
+ while (true) {
+ int bytesRead = theInput.read(myBytes, totalBytesRead,
+ myBytes.length - totalBytesRead);
+ if (bytesRead == -1) {
+ break;
+ }
+ totalBytesRead = totalBytesRead + bytesRead;
+ }
+
+ client.close();
+ server.close();
+
+ expectBytes = new byte[2 * sendBytes.length + 2];
+ System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
+ expectBytes[sendBytes.length] = urgentByte1;
+ expectBytes[sendBytes.length + 1] = urgentByte2;
+ System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 2,
+ sendBytes.length);
+
+ resultBytes = new byte[totalBytesRead];
+ System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
+
+ assertTrue("Urgent data was not received with two urgent bytes", Arrays
+ .equals(expectBytes, resultBytes));
+
+ /*
+ * Test 4: Now test the case where there is only urgent data.
+ */
+ server = new ServerSocket(0, 5, localHost);
+ serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
+
+ client = new Socket();
+ client.setOOBInline(true);
+
+ client.connect(serverAddress);
+ worker = server.accept();
+ worker.setTcpNoDelay(true);
+
+ // Send the urgent data (one byte) which should be received
+ client.setOOBInline(true);
+ urgentByte = "UrgentData".getBytes()[0];
+ worker.sendUrgentData(urgentByte);
+ worker.close();
+
+ // Try to read the bytes back
+ theInput = client.getInputStream();
+ int byteRead = theInput.read();
+
+ client.close();
+ server.close();
+
+ assertEquals("Sole urgent data was not received",
+ (int) (urgentByte & 0xff), byteRead);
+ }
+
+ /**
+ * java.net.Socket#setKeepAlive(boolean)
+ */
+ public void test_setKeepAliveZ() throws IOException {
+
+ class TestSocket extends Socket {
+ public TestSocket(SocketImpl impl) throws SocketException {
+ super(impl);
+ }
+ }
+
+ // There is not really a good test for this as it is there to detect
+ // crashed machines. Just make sure we can set it
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ client.setKeepAlive(true);
+ client.setKeepAlive(false);
+ client.close();
+ server.close();
+
+ // Regression test for HARMONY-1136
+ new TestSocket(null).setKeepAlive(true);
+ }
+
+ public void test_setOOBInlineZ() throws Exception {
+ Socket theSocket = new Socket();
+ theSocket.setOOBInline(true);
+ assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
+ }
+
+ public void test_setPerformancePreference_Int_Int_Int() throws IOException {
+ Socket theSocket = new Socket();
+ theSocket.setPerformancePreferences(1, 1, 1);
+ }
+
+ public void test_setReceiveBufferSizeI() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ client.setReceiveBufferSize(130);
+ assertTrue("Incorrect buffer size", client.getReceiveBufferSize() >= 130);
+
+ client.close();
+ server.close();
+ }
+
+ public void test_setReuseAddressZ() throws Exception {
+ Socket theSocket = new Socket();
+ theSocket.setReuseAddress(false);
+ // Bind to any available port on the given address
+ theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ InetSocketAddress localAddress1 = new InetSocketAddress(theSocket.getLocalAddress(), theSocket.getLocalPort());
+
+ Socket theSocket2 = new Socket();
+ theSocket2.setReuseAddress(false);
+
+ /*
+ * Try to invoke a bind while the port is busy (TIME_WAIT). Note
+ * that we may not succeed, which will cause the test to pass
+ * without testing the reuseaddr behavior.
+ */
+ theSocket.close();
+ theSocket2.bind(localAddress1);
+
+ theSocket2.close();
+ }
+
+ public void test_setSendBufferSizeI() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSendBufferSize(134);
+ assertTrue("Incorrect buffer size", client.getSendBufferSize() >= 134);
+ client.close();
+ server.close();
+ }
+
+ public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
+ // Cannot test as setting will cause the factory to be changed for
+ // all subsequent sockets
+ }
+
+ public void test_setSoLingerZI() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSoLinger(true, 500);
+ assertEquals("Set incorrect linger", 500, client.getSoLinger());
+ client.setSoLinger(false, 0);
+ client.close();
+ server.close();
+ }
+
+ public void test_setSoTimeoutI() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ client.setSoTimeout(100);
+ assertEquals("Set incorrect sotimeout", 100, client.getSoTimeout());
+ client.close();
+ server.close();
+ }
+
+ public void test_setTcpNoDelayZ() throws Exception {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+
+ boolean bool;
+ client.setTcpNoDelay(bool = !client.getTcpNoDelay());
+ assertTrue("Failed to set no delay setting: " + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
+
+ client.close();
+ server.close();
+ }
+
+ public void test_setTrafficClassI() throws Exception {
+ int IPTOS_LOWCOST = 0x2;
+ int IPTOS_RELIABILTY = 0x4;
+ int IPTOS_THROUGHPUT = 0x8;
+ int IPTOS_LOWDELAY = 0x10;
+
+ Socket theSocket = new Socket();
+
+ // validate that value set must be between 0 and 255
+ try {
+ theSocket.setTrafficClass(256);
+ fail("No exception was thrown when traffic class set to 256");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ theSocket.setTrafficClass(-1);
+ fail("No exception was thrown when traffic class set to -1");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ // now validate that we can set it to some good values
+ theSocket.setTrafficClass(IPTOS_LOWCOST);
+ theSocket.setTrafficClass(IPTOS_RELIABILTY);
+ theSocket.setTrafficClass(IPTOS_THROUGHPUT);
+ theSocket.setTrafficClass(IPTOS_LOWDELAY);
+ }
+
+ @SuppressWarnings("deprecation")
+ public void test_shutdownInput() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ int port = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost(), port);
+
+ Socket worker = server.accept();
+ worker.setTcpNoDelay(true);
+
+ InputStream theInput = client.getInputStream();
+ OutputStream theOutput = worker.getOutputStream();
+
+ // shutdown the input
+ client.shutdownInput();
+
+ // send the regular data
+ String sendString = "Test";
+ theOutput.write(sendString.getBytes());
+ theOutput.flush();
+
+ // RI fails here. It is a RI bug not to return 0 to indicate EOF
+ assertEquals(0, theInput.available());
+
+ client.close();
+ server.close();
+
+ // Regression test for HARMONY-2944
+ // Port 0 is not allowed to be used in connect() on some platforms,
+ // Since server has been closed here, so the port is free now
+ Socket s = new Socket("0.0.0.0", port, false);
+ s.shutdownInput();
+ try {
+ s.shutdownInput();
+ fail("should throw SocketException");
+ } catch (SocketException se) {
+ // Expected
+ }
+ s.close();
+ }
+
+ /**
+ * java.net.Socket#shutdownOutput()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_shutdownOutput() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ int port = server.getLocalPort();
+ Socket client = new Socket(InetAddress.getLocalHost(), port);
+
+ Socket worker = server.accept();
+ OutputStream theOutput = worker.getOutputStream();
+
+ // shutdown the output
+ worker.shutdownOutput();
+
+ // send the regular data
+ String sendString = "Test";
+ try {
+ theOutput.write(sendString.getBytes());
+ theOutput.flush();
+ fail("No exception when writing on socket with output shutdown");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ client.close();
+ server.close();
+
+ // Regression test for HARMONY-2944
+ // Port 0 is not allowed to be used in connect() on some platforms,
+ // Since server has been closed here, so the port is free now
+ Socket s = new Socket("0.0.0.0", port, false);
+ s.shutdownOutput();
+ try {
+ s.shutdownOutput();
+ fail("should throw SocketException");
+ } catch (SocketException se) {
+ // Expected
+ }
+ s.close();
+ }
+
+ public void test_toString() throws IOException {
+ ServerSocket server = new ServerSocket(0);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
+ // RI has "addr" and "localport" instead of "address" and "localPort".
+ String expected = "Socket[address=" + InetAddress.getLocalHost()
+ + ",port=" + client.getPort() + ",localPort="
+ + client.getLocalPort() + "]";
+ assertEquals(expected, client.toString());
+ client.close();
+ server.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTimeoutExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTimeoutExceptionTest.java
new file mode 100644
index 0000000..14b813c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/SocketTimeoutExceptionTest.java
@@ -0,0 +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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.tests.java.net;
+
+import java.net.SocketTimeoutException;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class SocketTimeoutExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * {@link java.net.SocketTimeoutException#SocketTimeoutException()}
+ */
+ public void test_Constructor() {
+ SocketTimeoutException e = new SocketTimeoutException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * {@link java.net.SocketTimeoutException#SocketTimeoutException(String)}
+ */
+ public void test_ConstructorLjava_lang_String() {
+ SocketTimeoutException e = new SocketTimeoutException("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new SocketTimeoutException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SerializationTest.verifyGolden(this, new SocketTimeoutException());
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/TestServerSocketInit.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/TestServerSocketInit.java
new file mode 100644
index 0000000..31aa5b6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/TestServerSocketInit.java
@@ -0,0 +1,30 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+
+public class TestServerSocketInit {
+
+ public static void main(String[] args) throws IOException {
+ ServerSocket serverSocket = new ServerSocket();
+ serverSocket.setReuseAddress(true);
+ serverSocket.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URISyntaxExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URISyntaxExceptionTest.java
new file mode 100644
index 0000000..ff8ac40
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URISyntaxExceptionTest.java
@@ -0,0 +1,115 @@
+/* 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.tests.java.net;
+
+import java.net.URISyntaxException;
+import java.util.Locale;
+
+public class URISyntaxExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.net.URISyntaxException#URISyntaxException(java.lang.String,
+ *java.lang.String, int)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringI() {
+ try {
+ new URISyntaxException(null, "problem", 2);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException npe) {
+ // Expected
+ }
+
+ try {
+ new URISyntaxException("str", null, 2);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException npe) {
+ // Expected
+ }
+
+ try {
+ new URISyntaxException("str", "problem", -2);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException iae) {
+ // Expected
+ }
+
+ URISyntaxException e = new URISyntaxException("str", "problem", 2);
+ assertEquals("returned incorrect reason", "problem", e.getReason());
+ assertEquals("returned incorrect input", "str", e.getInput());
+ assertEquals("returned incorrect index", 2, e.getIndex());
+ }
+
+ /**
+ * java.net.URISyntaxException#URISyntaxException(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() {
+ try {
+ new URISyntaxException(null, "problem");
+ fail("Expected NullPointerException");
+ } catch (NullPointerException npe) {
+ // Expected
+ }
+
+ try {
+ new URISyntaxException("str", null);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException npe) {
+ // Expected
+ }
+
+ URISyntaxException e = new URISyntaxException("str", "problem");
+ assertEquals("returned incorrect reason", "problem", e.getReason());
+ assertEquals("returned incorrect input", "str", e.getInput());
+ assertEquals("returned incorrect index", -1, e.getIndex());
+ }
+
+ /**
+ * java.net.URISyntaxException#getIndex()
+ */
+ public void test_getIndex() {
+ // see constructor tests
+ }
+
+ /**
+ * java.net.URISyntaxException#getReason()
+ */
+ public void test_getReason() {
+ // see constructor tests
+ }
+
+ /**
+ * java.net.URISyntaxException#getInput()
+ */
+ public void test_getInput() {
+ // see constructor tests
+ }
+
+ /**
+ * java.net.URISyntaxException#getMessage()
+ */
+ public void test_getMessage() {
+ Locale.setDefault(Locale.US);
+ URISyntaxException e = new URISyntaxException("str", "problem", 3);
+ assertEquals("Returned incorrect message", "problem at index 3: str", e
+ .getMessage());
+
+ e = new URISyntaxException("str", "problem");
+ assertEquals("Returned incorrect message", "problem: str", e
+ .getMessage());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URITest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URITest.java
new file mode 100644
index 0000000..f81c975
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URITest.java
@@ -0,0 +1,1841 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import junit.framework.TestCase;
+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;
+ }
+
+ /**
+ * java.net.URI#URI(java.lang.String)
+ */
+ 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());
+ }
+
+ // Regression test for HARMONY-25
+ // 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) {
+ // Expected
+ }
+
+ 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) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.URI#URI(java.lang.String)
+ */
+ public void test_URI_String() {
+ try {
+ 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());
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ * 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
+ * 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
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ * 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ * 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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]);
+ }
+ }
+
+ }
+
+ /**
+ * 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]);
+ }
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ }
+
+ /**
+ * 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);
+ }
+ }
+
+ /**
+ * 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);
+ }
+ }
+
+ /**
+ * java.net.URI#normalize()
+ */
+ public void test_normalize() throws Exception {
+ // normal
+ testNormalize("/", "/");
+ testNormalize("/a", "/a");
+ testNormalize("/a/b", "/a/b");
+ testNormalize("/a/b/c", "/a/b/c");
+ // single, '.'
+ testNormalize("/.", "/");
+ testNormalize("/./", "/");
+ testNormalize("/./.", "/");
+ testNormalize("/././", "/");
+ testNormalize("/./a", "/a");
+ testNormalize("/./a/", "/a/");
+ testNormalize("/././a", "/a");
+ testNormalize("/././a/", "/a/");
+ testNormalize("/a/.", "/a/");
+ testNormalize("/a/./", "/a/");
+ testNormalize("/a/./.", "/a/");
+ testNormalize("/a/./b", "/a/b");
+ // double, '..'
+ testNormalize("/a/..", "/");
+ testNormalize("/a/../", "/");
+ testNormalize("/a/../b", "/b");
+ testNormalize("/a/../b/..", "/");
+ testNormalize("/a/../b/../", "/");
+ testNormalize("/a/../b/../c", "/c");
+ testNormalize("/..", "/..");
+ testNormalize("/../", "/../");
+ testNormalize("/../..", "/../..");
+ testNormalize("/../../", "/../../");
+ testNormalize("/../a", "/../a");
+ testNormalize("/../a/", "/../a/");
+ testNormalize("/../../a", "/../../a");
+ testNormalize("/../../a/", "/../../a/");
+ testNormalize("/a/b/../../c", "/c");
+ testNormalize("/a/b/../..", "/");
+ testNormalize("/a/b/../../", "/");
+ testNormalize("/a/b/../../c", "/c");
+ testNormalize("/a/b/c/../../../d", "/d");
+ testNormalize("/a/b/..", "/a/");
+ testNormalize("/a/b/../", "/a/");
+ testNormalize("/a/b/../c", "/a/c");
+ // miscellaneous
+ testNormalize("/a/b/.././../../c/./d/../e", "/../c/e");
+ testNormalize("/a/../../.c././../././c/d/../g/..", "/../c/");
+ // '.' in the middle of segments
+ testNormalize("/a./b", "/a./b");
+ testNormalize("/.a/b", "/.a/b");
+ testNormalize("/a.b/c", "/a.b/c");
+ testNormalize("/a/b../c", "/a/b../c");
+ testNormalize("/a/..b/c", "/a/..b/c");
+ testNormalize("/a/b..c/d", "/a/b..c/d");
+ // no leading slash, miscellaneous
+ testNormalize("", "");
+ testNormalize("a", "a");
+ testNormalize("a/b", "a/b");
+ testNormalize("a/b/c", "a/b/c");
+ testNormalize("../", "../");
+ testNormalize(".", "");
+ testNormalize("..", "..");
+ testNormalize("../g", "../g");
+ testNormalize("g/a/../../b/c/./g", "b/c/g");
+ testNormalize("a/b/.././../../c/./d/../e", "../c/e");
+ testNormalize("a/../../.c././../././c/d/../g/..", "../c/");
+ }
+
+ private void testNormalize(String original, String expected) throws URISyntaxException {
+ assertEquals(expected, new URI(original).normalize().toString());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.net.URI#relativize(java.net.URI)
+ */
+ public void test_relativizeLjava_net_URI() throws URISyntaxException {
+ // rel = opaque
+ testRelativize("http://www.google.com/dir1/dir2", "mailto:test", "mailto:test");
+ // base = opaque
+ testRelativize("mailto:test", "http://www.google.com", "http://www.google.com");
+ // different authority
+ testRelativize("http://www.eclipse.org/dir1", "http://www.google.com/dir1/dir2",
+ "http://www.google.com/dir1/dir2");
+ // different scheme
+ testRelativize("http://www.google.com", "ftp://www.google.com", "ftp://www.google.com");
+ testRelativize("http://www.google.com/dir1/dir2/",
+ "http://www.google.com/dir3/dir4/file.txt",
+ "http://www.google.com/dir3/dir4/file.txt");
+ testRelativize("http://www.google.com/dir1/", "http://www.google.com/dir1/dir2/file.txt",
+ "dir2/file.txt");
+ testRelativize("./dir1/", "./dir1/hi", "hi");
+ testRelativize("/dir1/./dir2", "/dir1/./dir2/hi", "dir2/hi");
+ testRelativize("/dir1/dir2/..", "/dir1/dir2/../hi", "hi");
+ testRelativize("/dir1/dir2/..", "/dir1/dir2/hi", "dir2/hi");
+ testRelativize("/dir1/dir2/", "/dir1/dir3/../dir2/text", "text");
+ testRelativize("//www.google.com", "//www.google.com/dir1/file", "/dir1/file");
+ testRelativize("/dir1", "/dir1/hi", "dir1/hi");
+ testRelativize("/dir1/", "/dir1/hi", "hi");
+
+ URI a = new URI("http://host/dir");
+ URI b = new URI("http://host/dir/file?query");
+ assertEquals("Assert 0: URI relativized incorrectly,",
+ new URI("dir/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));
+
+ // Both URIs with empty hosts
+ b = new URI("file:///~/second");
+ assertEquals("Assert 3: URI relativized incorrectly,", new URI("second"), a.relativize(b));
+ assertEquals("Assert 4: URI relativized incorrectly,", new URI("first"), b.relativize(a));
+ }
+
+ private void testRelativize(String base, String target, String expected)
+ throws URISyntaxException {
+ assertEquals(expected, new URI(base).relativize(new URI(target)).toString());
+ }
+
+ // 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("test/location", relative.getSchemeSpecificPart());
+ assertNull(relative.getScheme());
+ }
+
+ /**
+ * 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("dir/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:///~/thesaurus");
+ assertEquals("relativized incorrectly,", new URI("thesaurus"), a.relativize(b));
+ assertEquals("relativized incorrectly,", new URI("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");
+ assertEquals(new URI("ws/p1"), one.relativize(two));
+
+ one = new URI("file:/C:/test/ws/");
+ assertEquals(new URI("p1"), one.relativize(two));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+ }
+ }
+
+ /**
+ * 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]));
+ }
+ }
+
+ /**
+ * 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]));
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ URI uri = new URI("http://harmony.apache.org/");
+
+ SerializationTest.verifySelf(uri);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLDecoderTest.java
new file mode 100644
index 0000000..f0a8a6d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLDecoderTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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.tests.java.net;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+
+import junit.framework.TestCase;
+import tests.support.Support_Configuration;
+
+public class URLDecoderTest extends TestCase {
+
+ /**
+ * java.net.URLDecoder#URLDecoder()
+ */
+ public void test_Constructor() throws Exception {
+ URLDecoder ud = new URLDecoder();
+ assertNotNull("Constructor failed.", ud);
+ }
+
+ /**
+ * java.net.URLDecoder#decode(java.lang.String)
+ */
+ public void test_decodeLjava_lang_String() throws Exception {
+ 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));
+ }
+
+ /**
+ * java.net.URLDecoder#decode(java.lang.String, java.lang.String)
+ */
+ public void test_decodeLjava_lang_String_Ljava_lang_String() {
+ // Regression for HARMONY-467
+ try {
+ URLDecoder.decode("", "");
+ fail("UnsupportedEncodingException expected");
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLTest.java
new file mode 100644
index 0000000..3502e72
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/URLTest.java
@@ -0,0 +1,1155 @@
+/*
+ * 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.tests.java.net;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.util.ArrayList;
+import java.util.List;
+
+public class URLTest extends TestCase {
+
+ public static class MyHandler extends URLStreamHandler {
+ protected URLConnection openConnection(URL u)
+ throws IOException {
+ return null;
+ }
+ }
+
+ URL u;
+
+ URL u1;
+
+ URL u2;
+
+ URL u3;
+
+ URL u4;
+
+ URL u5;
+
+ URL u6;
+
+ boolean caught = false;
+
+ static boolean isSelectCalled;
+
+ /**
+ * java.net.URL#URL(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ // Tests for multiple URL instantiation basic parsing test
+ u = new URL(
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
+ assertEquals("u returns a wrong protocol", "http", u.getProtocol());
+ assertEquals("u returns a wrong host", "www.yahoo1.com", u.getHost());
+ assertEquals("u returns a wrong port", 8080, u.getPort());
+ assertEquals("u returns a wrong file",
+ "/dir1/dir2/test.cgi?point1.html", u.getFile());
+ assertEquals("u returns a wrong anchor", "anchor1", u.getRef());
+
+ // test for no file
+ u1 = new URL("http://www.yahoo2.com:9999");
+ assertEquals("u1 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("u1 returns a wrong host", "www.yahoo2.com", u1.getHost());
+ assertEquals("u1 returns a wrong port", 9999, u1.getPort());
+ assertTrue("u1 returns a wrong file", u1.getFile().equals(""));
+ assertNull("u1 returns a wrong anchor", u1.getRef());
+
+ // test for no port
+ u2 = new URL(
+ "http://www.yahoo3.com/dir1/dir2/test.cgi?point1.html#anchor1");
+ assertEquals("u2 returns a wrong protocol", "http", u2.getProtocol());
+ assertEquals("u2 returns a wrong host", "www.yahoo3.com", u2.getHost());
+ assertEquals("u2 returns a wrong port", -1, u2.getPort());
+ assertEquals("u2 returns a wrong file",
+ "/dir1/dir2/test.cgi?point1.html", u2.getFile());
+ assertEquals("u2 returns a wrong anchor", "anchor1", u2.getRef());
+
+ // test for no port
+ URL u2a = new URL("file://www.yahoo3.com/dir1/dir2/test.cgi#anchor1");
+ assertEquals("u2a returns a wrong protocol", "file", u2a.getProtocol());
+ assertEquals("u2a returns a wrong host", "www.yahoo3.com", u2a
+ .getHost());
+ assertEquals("u2a returns a wrong port", -1, u2a.getPort());
+ assertEquals("u2a returns a wrong file", "/dir1/dir2/test.cgi", u2a
+ .getFile());
+ assertEquals("u2a returns a wrong anchor", "anchor1", u2a.getRef());
+
+ // test for no file, no port
+ u3 = new URL("http://www.yahoo4.com/");
+ assertEquals("u3 returns a wrong protocol", "http", u3.getProtocol());
+ assertEquals("u3 returns a wrong host", "www.yahoo4.com", u3.getHost());
+ assertEquals("u3 returns a wrong port", -1, u3.getPort());
+ assertEquals("u3 returns a wrong file", "/", u3.getFile());
+ assertNull("u3 returns a wrong anchor", u3.getRef());
+
+ // test for no file, no port
+ URL u3a = new URL("file://www.yahoo4.com/");
+ assertEquals("u3a returns a wrong protocol", "file", u3a.getProtocol());
+ assertEquals("u3a returns a wrong host", "www.yahoo4.com", u3a
+ .getHost());
+ assertEquals("u3a returns a wrong port", -1, u3a.getPort());
+ assertEquals("u3a returns a wrong file", "/", u3a.getFile());
+ assertNull("u3a returns a wrong anchor", u3a.getRef());
+
+ // test for no file, no port
+ URL u3b = new URL("file://www.yahoo4.com");
+ assertEquals("u3b returns a wrong protocol", "file", u3b.getProtocol());
+ assertEquals("u3b returns a wrong host", "www.yahoo4.com", u3b
+ .getHost());
+ assertEquals("u3b returns a wrong port", -1, u3b.getPort());
+ assertTrue("u3b returns a wrong file", u3b.getFile().equals(""));
+ assertNull("u3b returns a wrong anchor", u3b.getRef());
+
+ // test for non-port ":" and wierd characters occurrences
+ u4 = new URL(
+ "http://www.yahoo5.com/di!@$%^&*()_+r1/di:::r2/test.cgi?point1.html#anchor1");
+ assertEquals("u4 returns a wrong protocol", "http", u4.getProtocol());
+ assertEquals("u4 returns a wrong host", "www.yahoo5.com", u4.getHost());
+ assertEquals("u4 returns a wrong port", -1, u4.getPort());
+ assertEquals("u4 returns a wrong file",
+ "/di!@$%^&*()_+r1/di:::r2/test.cgi?point1.html", u4.getFile());
+ assertEquals("u4 returns a wrong anchor", "anchor1", u4.getRef());
+
+ u5 = new URL("file:/testing.tst");
+ assertEquals("u5 returns a wrong protocol", "file", u5.getProtocol());
+ assertTrue("u5 returns a wrong host", u5.getHost().equals(""));
+ assertEquals("u5 returns a wrong port", -1, u5.getPort());
+ assertEquals("u5 returns a wrong file", "/testing.tst", u5.getFile());
+ assertNull("u5 returns a wrong anchor", u5.getRef());
+
+ URL u5a = new URL("file:testing.tst");
+ assertEquals("u5a returns a wrong protocol", "file", u5a.getProtocol());
+ assertTrue("u5a returns a wrong host", u5a.getHost().equals(""));
+ assertEquals("u5a returns a wrong port", -1, u5a.getPort());
+ assertEquals("u5a returns a wrong file", "testing.tst", u5a.getFile());
+ assertNull("u5a returns a wrong anchor", u5a.getRef());
+
+ URL u6 = new URL("http://host:/file");
+ assertEquals("u6 return a wrong port", -1, u6.getPort());
+
+ URL u7 = new URL("file:../../file.txt");
+ assertTrue("u7 returns a wrong file: " + u7.getFile(), u7.getFile()
+ .equals("../../file.txt"));
+
+ URL u8 = new URL("http://[fec0::1:20d:60ff:fe24:7410]:35/file.txt");
+ assertTrue("u8 returns a wrong protocol " + u8.getProtocol(), u8
+ .getProtocol().equals("http"));
+ assertTrue("u8 returns a wrong host " + u8.getHost(), u8.getHost()
+ .equals("[fec0::1:20d:60ff:fe24:7410]"));
+ assertTrue("u8 returns a wrong port " + u8.getPort(),
+ u8.getPort() == 35);
+ assertTrue("u8 returns a wrong file " + u8.getFile(), u8.getFile()
+ .equals("/file.txt"));
+ assertNull("u8 returns a wrong anchor " + u8.getRef(), u8.getRef());
+
+ URL u9 = new URL("file://[fec0::1:20d:60ff:fe24:7410]/file.txt#sogood");
+ assertTrue("u9 returns a wrong protocol " + u9.getProtocol(), u9
+ .getProtocol().equals("file"));
+ assertTrue("u9 returns a wrong host " + u9.getHost(), u9.getHost()
+ .equals("[fec0::1:20d:60ff:fe24:7410]"));
+ assertTrue("u9 returns a wrong port " + u9.getPort(),
+ u9.getPort() == -1);
+ assertTrue("u9 returns a wrong file " + u9.getFile(), u9.getFile()
+ .equals("/file.txt"));
+ assertTrue("u9 returns a wrong anchor " + u9.getRef(), u9.getRef()
+ .equals("sogood"));
+
+ URL u10 = new URL("file://[fec0::1:20d:60ff:fe24:7410]");
+ assertTrue("u10 returns a wrong protocol " + u10.getProtocol(), u10
+ .getProtocol().equals("file"));
+ assertTrue("u10 returns a wrong host " + u10.getHost(), u10.getHost()
+ .equals("[fec0::1:20d:60ff:fe24:7410]"));
+ assertTrue("u10 returns a wrong port " + u10.getPort(),
+ u10.getPort() == -1);
+
+ URL u11 = new URL("file:////file.txt");
+ // Harmony returned null here
+ assertEquals("u11 returns a wrong authority", "", u11.getAuthority());
+ assertEquals("u11 returns a wrong file " + u11.getFile(), "//file.txt",
+ u11.getFile());
+
+ URL u12 = new URL("file:///file.txt");
+ assertTrue("u12 returns a wrong authority", u12.getAuthority().equals(
+ ""));
+ assertTrue("u12 returns a wrong file " + u12.getFile(), u12.getFile()
+ .equals("/file.txt"));
+
+
+ // test for error catching
+
+ // Bad HTTP format - no "//"
+ u = new URL(
+ "http:www.yahoo5.com::22/dir1/di:::r2/test.cgi?point1.html#anchor1");
+
+ caught = false;
+ try {
+ u = new URL(
+ "http://www.yahoo5.com::22/dir1/di:::r2/test.cgi?point1.html#anchor1");
+ } catch (MalformedURLException e) {
+ caught = true;
+ }
+ assertTrue("Should have throw MalformedURLException", caught);
+
+ // unknown protocol
+ try {
+ u = new URL("myProtocol://www.yahoo.com:22");
+ } catch (MalformedURLException e) {
+ caught = true;
+ }
+ assertTrue("3 Failed to throw MalformedURLException", caught);
+
+ caught = false;
+ // no protocol
+ try {
+ u = new URL("www.yahoo.com");
+ } catch (MalformedURLException e) {
+ caught = true;
+ }
+ assertTrue("4 Failed to throw MalformedURLException", caught);
+
+ caught = false;
+
+ URL u1 = null;
+ try {
+ // No leading or trailing spaces.
+ u1 = new URL("file:/some/path");
+ assertEquals("5 got wrong file length1", 10, u1.getFile().length());
+
+ // Leading spaces.
+ u1 = new URL(" file:/some/path");
+ assertEquals("5 got wrong file length2", 10, u1.getFile().length());
+
+ // Trailing spaces.
+ u1 = new URL("file:/some/path ");
+ assertEquals("5 got wrong file length3", 10, u1.getFile().length());
+
+ // Leading and trailing.
+ u1 = new URL(" file:/some/path ");
+ assertEquals("5 got wrong file length4", 10, u1.getFile().length());
+
+ // in-place spaces.
+ u1 = new URL(" file: /some/path ");
+ assertEquals("5 got wrong file length5", 12, u1.getFile().length());
+
+ } catch (MalformedURLException e) {
+ fail("5 Did not expect the exception " + e);
+ }
+
+ // testing jar protocol with relative path
+ // to make sure it's not canonicalized
+ try {
+ String file = "file:/a!/b/../d";
+
+ u = new URL("jar:" + file);
+ assertEquals("Wrong file (jar protocol, relative path)", file, u
+ .getFile());
+ } catch (MalformedURLException e) {
+ fail("Unexpected exception (jar protocol, relative path)" + e);
+ }
+ }
+
+ /**
+ * java.net.URL#URL(java.net.URL, java.lang.String)
+ */
+ public void test_ConstructorLjava_net_URLLjava_lang_String()
+ throws Exception {
+ // Test for method java.net.URL(java.net.URL, java.lang.String)
+ u = new URL("http://www.yahoo.com");
+ URL uf = new URL("file://www.yahoo.com");
+ // basic ones
+ u1 = new URL(u, "file.java");
+ assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
+ assertEquals("1 returns a wrong port", -1, u1.getPort());
+ assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
+ assertNull("1 returns a wrong anchor", u1.getRef());
+
+ URL u1f = new URL(uf, "file.java");
+ assertEquals("1f returns a wrong protocol", "file", u1f.getProtocol());
+ assertEquals("1f returns a wrong host", "www.yahoo.com", u1f.getHost());
+ assertEquals("1f returns a wrong port", -1, u1f.getPort());
+ assertEquals("1f returns a wrong file", "/file.java", u1f.getFile());
+ assertNull("1f returns a wrong anchor", u1f.getRef());
+
+ u1 = new URL(u, "dir1/dir2/../file.java");
+ assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
+ assertTrue("3 returns a wrong host: " + u1.getHost(), u1.getHost()
+ .equals("www.yahoo.com"));
+ assertEquals("3 returns a wrong port", -1, u1.getPort());
+ assertEquals("3 returns a wrong file", "/dir1/file.java", u1
+ .getFile());
+ assertNull("3 returns a wrong anchor", u1.getRef());
+
+ u1 = new URL(u, "http:dir1/dir2/../file.java");
+ assertEquals("3a returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("3a returns a wrong host: " + u1.getHost(), "www.yahoo.com", u1.getHost());
+ assertEquals("3a returns a wrong port", -1, u1.getPort());
+ assertEquals("3a returns a wrong file", "/dir1/file.java", u1
+ .getFile());
+ assertNull("3a returns a wrong anchor", u1.getRef());
+
+ u = new URL("http://www.apache.org/testing/");
+ u1 = new URL(u, "file.java");
+ assertEquals("4 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("4 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("4 returns a wrong port", -1, u1.getPort());
+ assertEquals("4 returns a wrong file", "/testing/file.java", u1
+ .getFile());
+ assertNull("4 returns a wrong anchor", u1.getRef());
+
+ uf = new URL("file://www.apache.org/testing/");
+ u1f = new URL(uf, "file.java");
+ assertEquals("4f returns a wrong protocol", "file", u1f.getProtocol());
+ assertEquals("4f returns a wrong host", "www.apache.org", u1f.getHost());
+ assertEquals("4f returns a wrong port", -1, u1f.getPort());
+ assertEquals("4f returns a wrong file", "/testing/file.java", u1f
+ .getFile());
+ assertNull("4f returns a wrong anchor", u1f.getRef());
+
+ uf = new URL("file:/testing/");
+ u1f = new URL(uf, "file.java");
+ assertEquals("4fa returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("4fa returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("4fa returns a wrong port", -1, u1f.getPort());
+ assertEquals("4fa returns a wrong file", "/testing/file.java", u1f
+ .getFile());
+ assertNull("4fa returns a wrong anchor", u1f.getRef());
+
+ uf = new URL("file:testing/");
+ u1f = new URL(uf, "file.java");
+ assertEquals("4fb returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("4fb returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("4fb returns a wrong port", -1, u1f.getPort());
+ assertEquals("4fb returns a wrong file", "testing/file.java", u1f
+ .getFile());
+ assertNull("4fb returns a wrong anchor", u1f.getRef());
+
+ u1f = new URL(uf, "file:file.java");
+ assertEquals("4fc returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("4fc returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("4fc returns a wrong port", -1, u1f.getPort());
+ assertEquals("4fc returns a wrong file", "testing/file.java", u1f.getFile());
+ assertNull("4fc returns a wrong anchor", u1f.getRef());
+
+ u1f = new URL(uf, "file:");
+ assertEquals("4fd returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("4fd returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("4fd returns a wrong port", -1, u1f.getPort());
+ assertEquals("4fd returns a wrong file", "testing/", u1f.getFile());
+ assertNull("4fd returns a wrong anchor", u1f.getRef());
+
+ u = new URL("http://www.apache.org/testing");
+ u1 = new URL(u, "file.java");
+ assertEquals("5 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("5 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("5 returns a wrong port", -1, u1.getPort());
+ assertEquals("5 returns a wrong file", "/file.java", u1.getFile());
+ assertNull("5 returns a wrong anchor", u1.getRef());
+
+ uf = new URL("file://www.apache.org/testing");
+ u1f = new URL(uf, "file.java");
+ assertEquals("5f returns a wrong protocol", "file", u1f.getProtocol());
+ assertEquals("5f returns a wrong host", "www.apache.org", u1f.getHost());
+ assertEquals("5f returns a wrong port", -1, u1f.getPort());
+ assertEquals("5f returns a wrong file", "/file.java", u1f.getFile());
+ assertNull("5f returns a wrong anchor", u1f.getRef());
+
+ uf = new URL("file:/testing");
+ u1f = new URL(uf, "file.java");
+ assertEquals("5fa returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("5fa returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("5fa returns a wrong port", -1, u1f.getPort());
+ assertEquals("5fa returns a wrong file", "/file.java", u1f.getFile());
+ assertNull("5fa returns a wrong anchor", u1f.getRef());
+
+ uf = new URL("file:testing");
+ u1f = new URL(uf, "file.java");
+ assertEquals("5fb returns a wrong protocol", "file", u1f.getProtocol());
+ assertTrue("5fb returns a wrong host", u1f.getHost().equals(""));
+ assertEquals("5fb returns a wrong port", -1, u1f.getPort());
+ assertEquals("5fb returns a wrong file", "file.java", u1f.getFile());
+ assertNull("5fb returns a wrong anchor", u1f.getRef());
+
+ u = new URL("http://www.apache.org/testing/foobaz");
+ u1 = new URL(u, "/file.java");
+ assertEquals("6 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("6 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("6 returns a wrong port", -1, u1.getPort());
+ assertEquals("6 returns a wrong file", "/file.java", u1.getFile());
+ assertNull("6 returns a wrong anchor", u1.getRef());
+
+ uf = new URL("file://www.apache.org/testing/foobaz");
+ u1f = new URL(uf, "/file.java");
+ assertEquals("6f returns a wrong protocol", "file", u1f.getProtocol());
+ assertEquals("6f returns a wrong host", "www.apache.org", u1f.getHost());
+ assertEquals("6f returns a wrong port", -1, u1f.getPort());
+ assertEquals("6f returns a wrong file", "/file.java", u1f.getFile());
+ assertNull("6f returns a wrong anchor", u1f.getRef());
+
+ u = new URL("http://www.apache.org:8000/testing/foobaz");
+ u1 = new URL(u, "/file.java");
+ assertEquals("7 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("7 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("7 returns a wrong port", 8000, u1.getPort());
+ assertEquals("7 returns a wrong file", "/file.java", u1.getFile());
+ assertNull("7 returns a wrong anchor", u1.getRef());
+
+ u = new URL("http://www.apache.org/index.html");
+ u1 = new URL(u, "#bar");
+ assertEquals("8 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("8 returns a wrong file", "/index.html", u1.getFile());
+ assertEquals("8 returns a wrong anchor", "bar", u1.getRef());
+
+ u = new URL("http://www.apache.org/index.html#foo");
+ u1 = new URL(u, "http:#bar");
+ assertEquals("9 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("9 returns a wrong file", "/index.html", u1.getFile());
+ assertEquals("9 returns a wrong anchor", "bar", u1.getRef());
+
+ u = new URL("http://www.apache.org/index.html");
+ u1 = new URL(u, "");
+ assertEquals("10 returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("10 returns a wrong file", "/index.html", u1.getFile());
+ assertNull("10 returns a wrong anchor", u1.getRef());
+
+ uf = new URL("file://www.apache.org/index.html");
+ u1f = new URL(uf, "");
+ assertEquals("10f returns a wrong host", "www.apache.org", u1.getHost());
+ assertEquals("10f returns a wrong file", "/index.html", u1.getFile());
+ assertNull("10f returns a wrong anchor", u1.getRef());
+
+ u = new URL("http://www.apache.org/index.html");
+ u1 = new URL(u, "http://www.apache.org");
+ assertEquals("11 returns a wrong host", "www.apache.org", u1.getHost());
+ assertTrue("11 returns a wrong file", u1.getFile().equals(""));
+ assertNull("11 returns a wrong anchor", u1.getRef());
+
+ // test for question mark processing
+ u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
+
+ // test for relative file and out of bound "/../" processing
+ u1 = new URL(u, "../dir1/./dir2/../file.java");
+ assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
+ .equals("/d0/d1/dir1/file.java"));
+
+ // test for absolute and relative file processing
+ u1 = new URL(u, "/../dir1/./dir2/../file.java");
+ assertEquals("B) returns a wrong file", "/dir1/file.java",
+ u1.getFile());
+
+ try {
+ // u should raise a MalFormedURLException because u, the context is
+ // null
+ u = null;
+ u1 = new URL(u, "file.java");
+ fail("didn't throw the expected MalFormedURLException");
+ } catch (MalformedURLException e) {
+ // valid
+ }
+
+ // Regression test for HARMONY-3258
+ // testing jar context url with relative file
+ try {
+ // check that relative path with null context is not canonicalized
+ String spec = "jar:file:/a!/b/../d";
+ URL ctx = null;
+ u = new URL(ctx, spec);
+ assertEquals("1 Wrong file (jar protocol, relative path)", spec, u
+ .toString());
+
+ spec = "../d";
+ ctx = new URL("jar:file:/a!/b");
+ u = new URL(ctx, spec);
+ assertEquals("2 Wrong file (jar protocol, relative path)",
+ "file:/a!/d", u.getFile());
+
+ spec = "../d";
+ ctx = new URL("jar:file:/a!/b/c");
+ u = new URL(ctx, spec);
+ assertEquals("3 Wrong file (jar protocol, relative path)",
+ "file:/a!/d", u.getFile());
+
+ spec = "../d";
+ ctx = new URL("jar:file:/a!/b/c/d");
+ u = new URL(ctx, spec);
+ assertEquals("4 Wrong file (jar protocol, relative path)",
+ "file:/a!/b/d", u.getFile());
+
+ // added the real example
+ spec = "../pdf/PDF.settings";
+ ctx = new URL(
+ "jar:file:/C:/Program%20Files/Netbeans-5.5/ide7/modules/org-netbeans-modules-utilities.jar!/org/netbeans/modules/utilities/Layer.xml");
+ u = new URL(ctx, spec);
+ assertEquals(
+ "5 Wrong file (jar protocol, relative path)",
+ "file:/C:/Program%20Files/Netbeans-5.5/ide7/modules/org-netbeans-modules-utilities.jar!/org/netbeans/modules/pdf/PDF.settings",
+ u.getFile());
+ } catch (MalformedURLException e) {
+ fail("Testing jar protocol, relative path failed: " + e);
+ }
+ }
+
+ /**
+ * java.net.URL#URL(java.net.URL, java.lang.String,
+ *java.net.URLStreamHandler)
+ */
+ public void test_ConstructorLjava_net_URLLjava_lang_StringLjava_net_URLStreamHandler()
+ throws Exception {
+ // Test for method java.net.URL(java.net.URL, java.lang.String,
+ // java.net.URLStreamHandler)
+ u = new URL("http://www.yahoo.com");
+ // basic ones
+ u1 = new URL(u, "file.java", new MyHandler());
+ assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
+ assertEquals("1 returns a wrong port", -1, u1.getPort());
+ assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
+ assertNull("1 returns a wrong anchor", u1.getRef());
+
+ u1 = new URL(u, "systemresource:/+/FILE0/test.java", new MyHandler());
+ assertEquals("2 returns a wrong protocol", "systemresource", u1
+ .getProtocol());
+ assertTrue("2 returns a wrong host", u1.getHost().equals(""));
+ assertEquals("2 returns a wrong port", -1, u1.getPort());
+ assertEquals("2 returns a wrong file", "/+/FILE0/test.java", u1
+ .getFile());
+ assertNull("2 returns a wrong anchor", u1.getRef());
+
+ u1 = new URL(u, "dir1/dir2/../file.java", null);
+ assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
+ assertEquals("3 returns a wrong host", "www.yahoo.com", u1.getHost());
+ assertEquals("3 returns a wrong port", -1, u1.getPort());
+ assertEquals("3 returns a wrong file", "/dir1/file.java", u1
+ .getFile());
+ assertNull("3 returns a wrong anchor", u1.getRef());
+
+ // test for question mark processing
+ u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
+
+ // test for relative file and out of bound "/../" processing
+ u1 = new URL(u, "../dir1/dir2/../file.java", new MyHandler());
+ assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
+ .equals("/d0/d1/dir1/file.java"));
+
+ // test for absolute and relative file processing
+ u1 = new URL(u, "/../dir1/dir2/../file.java", null);
+ assertEquals("B) returns a wrong file", "/dir1/file.java",
+ u1.getFile());
+
+ URL one;
+ try {
+ one = new URL("http://www.ibm.com");
+ } catch (MalformedURLException ex) {
+ // Should not happen.
+ throw new RuntimeException(ex.getMessage());
+ }
+ try {
+ new URL(one, (String) null);
+ fail("Specifying null spec on URL constructor should throw MalformedURLException");
+ } catch (MalformedURLException e) {
+ // expected
+ }
+
+ try {
+ // u should raise a MalFormedURLException because u, the context is
+ // null
+ u = null;
+ u1 = new URL(u, "file.java", new MyHandler());
+ } catch (MalformedURLException e) {
+ return;
+ }
+ fail("didn't throw expected MalFormedURLException");
+ }
+
+ /**
+ * java.net.URL#URL(java.lang.String, java.lang.String,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws MalformedURLException {
+
+ u = new URL("http", "www.yahoo.com", "test.html#foo");
+ assertEquals("http", u.getProtocol());
+ assertEquals("www.yahoo.com", u.getHost());
+ assertEquals(-1, u.getPort());
+ assertEquals("/test.html", u.getFile());
+ assertEquals("foo", u.getRef());
+
+ // Strange behavior in reference, the hostname contains a ':' so it gets
+ // wrapped in '[', ']'
+ URL testURL = new URL("http", "www.apache.org:8080", "test.html#anch");
+ assertEquals("wrong protocol", "http", testURL.getProtocol());
+ assertEquals("wrong host", "[www.apache.org:8080]", testURL.getHost());
+ assertEquals("wrong port", -1, testURL.getPort());
+ assertEquals("wrong file", "/test.html", testURL.getFile());
+ assertEquals("wrong anchor", "anch", testURL.getRef());
+ }
+
+ /**
+ * java.net.URL#URL(java.lang.String, java.lang.String, int,
+ *java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_String()
+ throws MalformedURLException {
+ u = new URL("http", "www.yahoo.com", 8080, "test.html#foo");
+ assertEquals("SSIS returns a wrong protocol", "http", u.getProtocol());
+ assertEquals("SSIS returns a wrong host", "www.yahoo.com", u.getHost());
+ assertEquals("SSIS returns a wrong port", 8080, u.getPort());
+ // Libcore adds a leading "/"
+ assertEquals("SSIS returns a wrong file", "/test.html", u.getFile());
+ assertTrue("SSIS returns a wrong anchor: " + u.getRef(), u.getRef()
+ .equals("foo"));
+
+ // Regression for HARMONY-83
+ new URL("http", "apache.org", 123456789, "file");
+ try {
+ new URL("http", "apache.org", -123, "file");
+ fail("Assert 0: Negative port should throw exception");
+ } catch (MalformedURLException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.net.URL#URL(java.lang.String, java.lang.String, int,
+ *java.lang.String, java.net.URLStreamHandler)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
+ throws Exception {
+ // Test for method java.net.URL(java.lang.String, java.lang.String, int,
+ // java.lang.String, java.net.URLStreamHandler)
+ u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", null);
+ assertEquals("SSISH1 returns a wrong protocol", "http", u.getProtocol());
+ assertEquals("SSISH1 returns a wrong host", "www.yahoo.com", u
+ .getHost());
+ assertEquals("SSISH1 returns a wrong port", 8080, u.getPort());
+ assertEquals("SSISH1 returns a wrong file", "/test.html", u.getFile());
+ assertTrue("SSISH1 returns a wrong anchor: " + u.getRef(), u.getRef()
+ .equals("foo"));
+
+ u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
+ new MyHandler());
+ assertEquals("SSISH2 returns a wrong protocol", "http", u.getProtocol());
+ assertEquals("SSISH2 returns a wrong host", "www.yahoo.com", u
+ .getHost());
+ assertEquals("SSISH2 returns a wrong port", 8080, u.getPort());
+ assertEquals("SSISH2 returns a wrong file", "/test.html", u.getFile());
+ assertTrue("SSISH2 returns a wrong anchor: " + u.getRef(), u.getRef()
+ .equals("foo"));
+ }
+
+ /**
+ * java.net.URL#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() throws MalformedURLException {
+ u = new URL("http://www.apache.org:8080/dir::23??????????test.html");
+ u1 = new URL("http://www.apache.org:8080/dir::23??????????test.html");
+ assertTrue("A) equals returns false for two identical URLs", u
+ .equals(u1));
+ assertTrue("return true for null comparison", !u1.equals(null));
+ u = new URL("ftp://www.apache.org:8080/dir::23??????????test.html");
+ assertTrue("Returned true for non-equal URLs", !u.equals(u1));
+
+ // Regression for HARMONY-6556
+ u = new URL("file", null, 0, "/test.txt");
+ u1 = new URL("file", null, 0, "/test.txt");
+ assertEquals(u, u1);
+
+ u = new URL("file", "first.invalid", 0, "/test.txt");
+ u1 = new URL("file", "second.invalid", 0, "/test.txt");
+ assertFalse(u.equals(u1));
+
+ u = new URL("file", "harmony.apache.org", 0, "/test.txt");
+ u1 = new URL("file", "www.apache.org", 0, "/test.txt");
+ assertFalse(u.equals(u1));
+ }
+
+ /**
+ * java.net.URL#sameFile(java.net.URL)
+ */
+ public void test_sameFileLjava_net_URL() throws Exception {
+ // Test for method boolean java.net.URL.sameFile(java.net.URL)
+ u = new URL("http://www.yahoo.com");
+ u1 = new URL("http", "www.yahoo.com", "");
+ assertTrue("Should be the same1", u.sameFile(u1));
+ u = new URL("http://www.yahoo.com/dir1/dir2/test.html#anchor1");
+ u1 = new URL("http://www.yahoo.com/dir1/dir2/test.html#anchor2");
+ assertTrue("Should be the same ", u.sameFile(u1));
+
+ // regression test for Harmony-1040
+ u = new URL("file", null, -1, "/d:/somedir/");
+ u1 = new URL("file:/d:/somedir/");
+ assertFalse(u.sameFile(u1));
+
+ // regression test for Harmony-2136
+ URL url1 = new URL("file:///anyfile");
+ URL url2 = new URL("file://localhost/anyfile");
+ assertTrue(url1.sameFile(url2));
+
+ url1 = new URL("http:///anyfile");
+ url2 = new URL("http://localhost/anyfile");
+ assertFalse(url1.sameFile(url2));
+
+ url1 = new URL("ftp:///anyfile");
+ url2 = new URL("ftp://localhost/anyfile");
+ assertFalse(url1.sameFile(url2));
+
+ url1 = new URL("jar:file:///anyfile.jar!/");
+ url2 = new URL("jar:file://localhost/anyfile.jar!/");
+ assertFalse(url1.sameFile(url2));
+ }
+
+ /**
+ * java.net.URL#getContent()
+ */
+ public void test_getContent() {
+ // Test for method java.lang.Object java.net.URL.getContent()
+ byte[] ba;
+ InputStream is;
+ String s;
+ File resources = Support_Resources.createTempFolder();
+ try {
+ Support_Resources.copyFile(resources, null, "hyts_htmltest.html");
+ u = new URL("file", "", resources.getAbsolutePath()
+ + "/hyts_htmltest.html");
+ u.openConnection();
+ is = (InputStream) u.getContent();
+ is.read(ba = new byte[4096]);
+ s = new String(ba);
+ assertTrue(
+ "Incorrect content "
+ + u
+ + " does not contain: \" A Seemingly Non Important String \"",
+ s.indexOf("A Seemingly Non Important String") >= 0);
+ } catch (IOException e) {
+ fail("IOException thrown : " + e.getMessage());
+ } finally {
+ // Support_Resources.deleteTempFolder(resources);
+ }
+ }
+
+ /**
+ * java.net.URL#getContent(class[])
+ */
+ public void test_getContent_LJavaLangClass() throws Exception {
+ byte[] ba;
+ InputStream is;
+ String s;
+
+ File resources = Support_Resources.createTempFolder();
+
+ Support_Resources.copyFile(resources, null, "hyts_htmltest.html");
+ u = new URL("file", "", resources.getAbsolutePath()
+ + "/hyts_htmltest.html");
+ u.openConnection();
+
+ is = (InputStream) u.getContent(new Class[] { Object.class });
+ is.read(ba = new byte[4096]);
+ s = new String(ba);
+ assertTrue("Incorrect content " + u
+ + " does not contain: \" A Seemingly Non Important String \"",
+ s.indexOf("A Seemingly Non Important String") >= 0);
+
+ }
+
+ /**
+ * java.net.URL#openConnection()
+ */
+ public void test_openConnection() {
+ // Test for method java.net.URLConnection java.net.URL.openConnection()
+ try {
+ u = new URL("systemresource:/FILE4/+/types.properties");
+ URLConnection uConn = u.openConnection();
+ assertNotNull("u.openConnection() returns null", uConn);
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * java.net.URL#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.net.URL.toString()
+ try {
+ u1 = new URL("http://www.yahoo2.com:9999");
+ u = new URL(
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
+ assertEquals(
+ "a) Does not return the right url string",
+
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1",
+ u.toString());
+ assertEquals("b) Does not return the right url string",
+ "http://www.yahoo2.com:9999", u1.toString());
+ assertTrue("c) Does not return the right url string", u
+ .equals(new URL(u.toString())));
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * java.net.URL#toExternalForm()
+ */
+ public void test_toExternalForm() {
+ // Test for method java.lang.String java.net.URL.toExternalForm()
+ try {
+ u1 = new URL("http://www.yahoo2.com:9999");
+ u = new URL(
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
+ assertEquals(
+ "a) Does not return the right url string",
+
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1",
+ u.toString());
+ assertEquals("b) Does not return the right url string",
+ "http://www.yahoo2.com:9999", u1.toString());
+ assertTrue("c) Does not return the right url string", u
+ .equals(new URL(u.toString())));
+
+ u = new URL("http:index");
+ assertEquals("2 wrong external form", "http:index", u
+ .toExternalForm());
+
+ u = new URL("http", null, "index");
+ assertEquals("2 wrong external form", "http:index", u
+ .toExternalForm());
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * java.net.URL#getFile()
+ */
+ public void test_getFile() throws Exception {
+ // Test for method java.lang.String java.net.URL.getFile()
+ u = new URL("http", "www.yahoo.com:8080", 1233,
+ "test/!@$%^&*/test.html#foo");
+ assertEquals("returns a wrong file", "/test/!@$%^&*/test.html", u
+ .getFile());
+ u = new URL("http", "www.yahoo.com:8080", 1233, "");
+ assertTrue("returns a wrong file", u.getFile().equals(""));
+ }
+
+ /**
+ * java.net.URL#getHost()
+ */
+ public void test_getHost() throws MalformedURLException {
+ // Regression for HARMONY-60
+ String ipv6Host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210";
+ URL url = new URL("http", ipv6Host, -1, "myfile");
+ assertEquals(("[" + ipv6Host + "]"), url.getHost());
+ }
+
+ /**
+ * java.net.URL#getPort()
+ */
+ public void test_getPort() throws Exception {
+ // Test for method int java.net.URL.getPort()
+ u = new URL("http://member12.c++.com:9999");
+ assertTrue("return wrong port number " + u.getPort(),
+ u.getPort() == 9999);
+ u = new URL("http://member12.c++.com:9999/");
+ assertEquals("return wrong port number", 9999, u.getPort());
+ }
+
+ /**
+ * @throws MalformedURLException
+ * java.net.URL#getDefaultPort()
+ */
+ public void test_getDefaultPort() throws MalformedURLException {
+ u = new URL("http://member12.c++.com:9999");
+ assertEquals(80, u.getDefaultPort());
+ u = new URL("ftp://member12.c++.com:9999/");
+ assertEquals(21, u.getDefaultPort());
+ }
+
+ /**
+ * java.net.URL#getProtocol()
+ */
+ public void test_getProtocol() throws Exception {
+ // Test for method java.lang.String java.net.URL.getProtocol()
+ u = new URL("http://www.yahoo2.com:9999");
+ assertTrue("u returns a wrong protocol: " + u.getProtocol(), u
+ .getProtocol().equals("http"));
+ }
+
+ /**
+ * java.net.URL#getRef()
+ */
+ public void test_getRef() {
+ // Test for method java.lang.String java.net.URL.getRef()
+ try {
+ u1 = new URL("http://www.yahoo2.com:9999");
+ u = new URL(
+ "http://www.yahoo1.com:8080/dir1/dir2/test.cgi?point1.html#anchor1");
+ assertEquals("returns a wrong anchor1", "anchor1", u.getRef());
+ assertNull("returns a wrong anchor2", u1.getRef());
+ u1 = new URL("http://www.yahoo2.com#ref");
+ assertEquals("returns a wrong anchor3", "ref", u1.getRef());
+ u1 = new URL("http://www.yahoo2.com/file#ref1#ref2");
+ assertEquals("returns a wrong anchor4", "ref1#ref2", u1.getRef());
+ } catch (MalformedURLException e) {
+ fail("Incorrect URL format : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.net.URL#getAuthority()
+ */
+ public void test_getAuthority() throws MalformedURLException {
+ URL testURL = new URL("http", "hostname", 80, "/java?q1#ref");
+ assertEquals("hostname:80", testURL.getAuthority());
+ assertEquals("hostname", testURL.getHost());
+ assertNull(testURL.getUserInfo());
+ assertEquals("/java?q1", testURL.getFile());
+ assertEquals("/java", testURL.getPath());
+ assertEquals("q1", testURL.getQuery());
+ assertEquals("ref", testURL.getRef());
+
+ testURL = new URL("http", "u:p@home", 80, "/java?q1#ref");
+ assertEquals("[u:p@home]:80", testURL.getAuthority());
+ assertEquals("[u:p@home]", testURL.getHost());
+ assertNull(testURL.getUserInfo());
+ assertEquals("/java?q1", testURL.getFile());
+ assertEquals("/java", testURL.getPath());
+ assertEquals("q1", testURL.getQuery());
+ assertEquals("ref", testURL.getRef());
+
+ testURL = new URL("http", "home", -1, "/java");
+ assertEquals("wrong authority2", "home", testURL.getAuthority());
+ assertNull("wrong userInfo2", testURL.getUserInfo());
+ assertEquals("wrong host2", "home", testURL.getHost());
+ assertEquals("wrong file2", "/java", testURL.getFile());
+ assertEquals("wrong path2", "/java", testURL.getPath());
+ assertNull("wrong query2", testURL.getQuery());
+ assertNull("wrong ref2", testURL.getRef());
+ }
+
+ /**
+ * java.net.URL#toURL()
+ */
+ public void test_toURI() throws Exception {
+ u = new URL("http://www.apache.org");
+ URI uri = u.toURI();
+ assertTrue(u.equals(uri.toURL()));
+ }
+
+ /**
+ * java.net.URL#openConnection()
+ */
+ public void test_openConnection_FileProtocal() throws Exception {
+ // Regression test for Harmony-5779
+ String basedir = new File("temp.java").getAbsolutePath();
+ String fileUrlString = "file://localhost/" + basedir;
+ URLConnection conn = new URL(fileUrlString).openConnection();
+ assertEquals("file", conn.getURL().getProtocol());
+ assertEquals(new File(basedir), new File(conn.getURL().getFile()));
+
+ String nonLocalUrlString = "file://anything/" + basedir;
+ conn = new URL(nonLocalUrlString).openConnection();
+ assertEquals("ftp", conn.getURL().getProtocol());
+ assertEquals(new File(basedir), new File(conn.getURL().getFile()));
+ }
+
+ /**
+ * URLStreamHandler implementation class necessary for tests.
+ */
+ private class TestURLStreamHandler extends URLStreamHandler {
+ public URLConnection openConnection(URL arg0) throws IOException {
+ try {
+ return arg0.openConnection();
+ } catch (Throwable e) {
+ return null;
+ }
+ }
+
+ public URLConnection openConnection(URL arg0, Proxy proxy)
+ throws IOException {
+ return super.openConnection(u, proxy);
+ }
+ }
+
+ /**
+ * Check NPE throwing in constructor when protocol argument is null and
+ * URLStreamHandler argument is initialized.
+ */
+ public void test_ConstructorLnullLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
+ throws Exception {
+ // Regression for HARMONY-1131
+ TestURLStreamHandler lh = new TestURLStreamHandler();
+
+ try {
+ new URL(null, "1", 0, "file", lh);
+ fail("NullPointerException expected, but nothing was thrown!");
+ } catch (NullPointerException e) {
+ // Expected NullPointerException
+ }
+
+ }
+
+ /**
+ * Check NPE throwing in constructor when protocol argument is null and
+ * URLStreamHandler argument is null.
+ */
+ public void test_ConstructorLnullLjava_lang_StringILjava_lang_StringLnull()
+ throws Exception {
+ // Regression for HARMONY-1131
+ try {
+ new URL(null, "1", 0, "file", null);
+ fail("NullPointerException expected, but nothing was thrown!");
+ } catch (NullPointerException e) {
+ // Expected NullPointerException
+ }
+ }
+
+ /**
+ * Check NPE throwing in constructor with 4 params when protocol argument is
+ * null.
+ */
+ public void test_ConstructorLnullLjava_lang_StringILjava_lang_String()
+ throws Exception {
+ // Regression for HARMONY-1131
+ try {
+ new URL(null, "1", 0, "file");
+ fail("NullPointerException expected, but nothing was thrown!");
+ } catch (NullPointerException e) {
+ // Expected NullPointerException
+ }
+ }
+
+ /**
+ * Check NPE throwing in constructor with 3 params when protocol argument is
+ * null.
+ */
+ public void test_ConstructorLnullLjava_lang_StringLjava_lang_String()
+ throws Exception {
+ // Regression for HARMONY-1131
+ try {
+ new URL(null, "1", "file");
+ fail("NullPointerException expected, but nothing was thrown!");
+ } catch (NullPointerException e) {
+ // Expected NullPointerException
+ }
+ }
+
+ public void test_toExternalForm_Absolute() throws MalformedURLException {
+ String strURL = "http://localhost?name=value";
+ URL url = new URL(strURL);
+ assertEquals(strURL, url.toExternalForm());
+
+ strURL = "http://localhost?name=value/age=12";
+ url = new URL(strURL);
+ assertEquals(strURL, url.toExternalForm());
+ }
+
+ public void test_toExternalForm_Relative() throws MalformedURLException {
+ String strURL = "http://a/b/c/d;p?q";
+ String ref = "?y";
+ URL url = new URL(new URL(strURL), ref);
+ assertEquals("http://a/b/c/d;p?y", url.toExternalForm());
+ }
+
+ // Regression test for HARMONY-6254
+
+ // Bogus handler forces file part of URL to be null
+ static class MyHandler2 extends URLStreamHandler {
+
+ @Override
+ protected URLConnection openConnection(URL arg0) throws IOException {
+ return null;
+ }
+
+ @Override
+ protected void setURL(URL u, String protocol, String host, int port,
+ String authority, String userInfo, String file, String query,
+ String ref) {
+ super.setURL(u, protocol, host, port, authority, userInfo,
+ (String) null, query, ref);
+ }
+ }
+
+ // Test special case of external form with null file part (HARMONY-6254)
+ public void test_toExternalForm_Null() throws IOException {
+ URLStreamHandler myHandler = new MyHandler2();
+ URL url = new URL(null, "foobar://example.com/foobar", myHandler);
+ String s = url.toExternalForm();
+ assertEquals("Got wrong URL external form", "foobar://example.com", s);
+ }
+
+ static class MockProxySelector extends ProxySelector {
+
+ public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
+ System.out.println("connection failed");
+ }
+
+ public List<Proxy> select(URI uri) {
+ isSelectCalled = true;
+ ArrayList<Proxy> proxyList = new ArrayList<Proxy>(1);
+ proxyList.add(Proxy.NO_PROXY);
+ return proxyList;
+ }
+ }
+
+ static class MyURLStreamHandler extends URLStreamHandler {
+
+ @Override
+ protected URLConnection openConnection(URL arg0) throws IOException {
+ return null;
+ }
+
+ public void parse(URL url, String spec, int start, int end) {
+ parseURL(url, spec, start, end);
+ }
+ }
+
+ /**
+ * java.net.URL#URL(String, String, String)
+ */
+ public void test_java_protocol_handler_pkgs_prop()
+ throws MalformedURLException {
+ // Regression test for Harmony-3094
+ final String HANDLER_PKGS = "java.protocol.handler.pkgs";
+ String pkgs = System.getProperty(HANDLER_PKGS);
+ System.setProperty(HANDLER_PKGS,
+ "fake|org.apache.harmony.luni.tests.java.net");
+
+ try {
+ new URL("test_protocol", "", "fake.jar");
+ } finally {
+ if (pkgs == null) {
+ System.clearProperty(HANDLER_PKGS);
+ } else {
+ System.setProperty(HANDLER_PKGS, pkgs);
+ }
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownHostExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownHostExceptionTest.java
new file mode 100644
index 0000000..6d881e7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownHostExceptionTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.tests.java.net;
+
+import java.net.UnknownHostException;
+
+import junit.framework.TestCase;
+
+public class UnknownHostExceptionTest extends TestCase {
+
+ /**
+ * java.net.UnknownHostException#UnknownHostException()
+ */
+ public void test_Constructor() {
+ try {
+ if (true) {
+ throw new UnknownHostException();
+ }
+ fail("Failed to generate Exception");
+ } catch (UnknownHostException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.UnknownHostException#UnknownHostException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ if (true) {
+ throw new UnknownHostException("test");
+ }
+ fail("Failed to generate Exception");
+ } catch (UnknownHostException e) {
+ assertEquals("Threw exception with incorrect message", "test", e
+ .getMessage());
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownServiceExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownServiceExceptionTest.java
new file mode 100644
index 0000000..e141e88
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/UnknownServiceExceptionTest.java
@@ -0,0 +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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.tests.java.net;
+
+import java.net.UnknownServiceException;
+
+import junit.framework.TestCase;
+
+public class UnknownServiceExceptionTest extends TestCase {
+
+ /**
+ * java.net.UnknownServiceException#UnknownServiceException()
+ */
+ public void test_Constructor() {
+ try {
+ if (true) {
+ throw new UnknownServiceException();
+ }
+ fail("Exception not thrown");
+ } catch (UnknownServiceException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.net.UnknownServiceException#UnknownServiceException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ if (true) {
+ throw new UnknownServiceException("test");
+ }
+ fail("Constructor failed");
+ } catch (UnknownServiceException e) {
+ assertEquals("Wrong exception message", "test", e.getMessage());
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/AbstractBufferTest.java
index eb48992..4da5f8c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/AbstractBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.Buffer;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferOverflowExceptionTest.java
index 39059fe..234e2e9 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferOverflowExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferUnderflowExceptionTest.java
index a056ebf..eca02e4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/BufferUnderflowExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteBufferTest.java
index d6d8681..aea177a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteOrderTest.java
index 8f41904..82b5d7a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ByteOrderTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/CharBufferTest.java
index 8a7c5f3..b9f2bc0 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/CharBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.io.IOException;
import java.nio.BufferOverflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectByteBufferTest.java
index f274676..ffdfb2c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectByteBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectCharBufferTest.java
index 83cfc9d..71957c1 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectCharBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectDoubleBufferTest.java
index 561c0fa..0a14a44 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectFloatBufferTest.java
index 8739c1b..e74eb47 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectIntBufferTest.java
index 393366e..e556a31 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectLongBufferTest.java
index 245cd25..df1ade5 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectShortBufferTest.java
index 9ae290a..c5ba915 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DirectShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DoubleBufferTest.java
index 40ff2e0..50e0b82 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DoubleBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateDirectByteBufferTest.java
index 656241a..58ac4c3 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateDirectByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class DuplicateDirectByteBufferTest extends DirectByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateHeapByteBufferTest.java
index 9f44d7a..452f7cb 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateHeapByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class DuplicateHeapByteBufferTest extends HeapByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateWrappedByteBufferTest.java
index 2796b88..8d9c833 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/DuplicateWrappedByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class DuplicateWrappedByteBufferTest extends WrappedByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/FloatBufferTest.java
index cfef096..49903bf 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/FloatBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapByteBufferTest.java
index 2f8e44b..1ce3c6b 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapCharBufferTest.java
index a0c8d74..1ef25c8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapCharBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapDoubleBufferTest.java
index 2985899..059adf6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.DoubleBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapFloatBufferTest.java
index f90b34e..e946857 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.FloatBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapIntBufferTest.java
index 0d68835..1f8e106 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.IntBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapLongBufferTest.java
index f4f2ae1..a368ab6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.LongBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapShortBufferTest.java
index 327a035..aefbcf4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/HeapShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ShortBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/IntBufferTest.java
index 97babcf..7b5f976 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/IntBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/InvalidMarkExceptionTest.java
index 4b7682d..be8b1bd 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/InvalidMarkExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.InvalidMarkException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/LongBufferTest.java
index 371351b..e390db8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/LongBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/MappedByteBufferTest.java
index 308db21..0fe6f35 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/MappedByteBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.io.File;
import java.io.FileInputStream;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyBufferExceptionTest.java
index cbacbc5..d6b553a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyBufferExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyCharBufferTest.java
index f951962..f2669f2 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyCharBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.CharBuffer;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDirectByteBufferTest.java
index 20c7914..dd7d31a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDirectByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class ReadOnlyDirectByteBufferTest extends DirectByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDoubleBufferTest.java
index d87e81d..f2f1ea4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.DoubleBuffer;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyFloatBufferTest.java
index 3acc5c4..56a14ba 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.FloatBuffer;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapByteBufferTest.java
index 7452a24..025eca6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class ReadOnlyHeapByteBufferTest extends HeapByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapCharBufferTest.java
index 4c7792a..45ba320 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapCharBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
index f95c4c2..b978f57 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.DoubleBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
index f2c6644..9b81e3e 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.FloatBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapIntBufferTest.java
index f9a3877..8db2ce9 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.IntBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapLongBufferTest.java
index efba978..3c27dda 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.LongBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapShortBufferTest.java
index bbbd616..34ab778 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyHeapShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ShortBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyIntBufferTest.java
index 61e78a6..e618783 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.IntBuffer;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyLongBufferTest.java
index b670606..fd6438e 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.LongBuffer;
import java.nio.ReadOnlyBufferException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyShortBufferTest.java
index 611f6bf..aab913e 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ReadOnlyBufferException;
import java.nio.ShortBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
index 031d75b..21a39ea 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class ReadOnlyWrappedByteBufferTest extends WrappedByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
index 57c04bf..bfa2033 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
index d1ba9df..83c53ba 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.DoubleBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
index affddaa..645c8a7 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.FloatBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
index a4d0155..9941137 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.IntBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
index 58491da..80f3f88 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.LongBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
index 0ecb3a4..e10a8c0 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ShortBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ShortBufferTest.java
index 98d7659..c1c43d7 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/ShortBufferTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceDirectByteBufferTest.java
index 541cde0..c00694a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceDirectByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class SliceDirectByteBufferTest extends DirectByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceHeapByteBufferTest.java
index 9f9f7aa..949c9a0 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceHeapByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class SliceHeapByteBufferTest extends HeapByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceWrappedByteBufferTest.java
index f1ddfb9..7fabd8d 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/SliceWrappedByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
public class SliceWrappedByteBufferTest extends WrappedByteBufferTest {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedByteBufferTest.java
index 6460d2e..9475e7b 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedByteBufferTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest1.java
index 9181a77..a9a04e8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest1.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest2.java
index 5fa9335..a5c222c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedCharBufferTest2.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedDoubleBufferTest.java
index f970849..c371afa 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedDoubleBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.DoubleBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedFloatBufferTest.java
index 43b13c3..e68d9bc 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedFloatBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.FloatBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedIntBufferTest.java
index 383e964..b1d2bf9 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedIntBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.IntBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedLongBufferTest.java
index 581c912..9bc14c8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedLongBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.LongBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedShortBufferTest.java
index 9c6f781..4c797b5 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/WrappedShortBufferTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio;
+package org.apache.harmony.tests.java.nio;
import java.nio.ShortBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
index ac820a4..8e2a0e6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.AlreadyConnectedException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
index 123eb1f..95eb9fb 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.AsynchronousCloseException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/CancelledKeyExceptionTest.java
index 7a73322..25ee801 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/CancelledKeyExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.CancelledKeyException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java
index 4223fb8..561d661 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileInputStream;
@@ -24,7 +24,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
-import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
@@ -36,9 +35,6 @@ import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
-
-import tests.support.Support_PortManager;
-
import junit.framework.TestCase;
/**
@@ -590,13 +586,11 @@ public class ChannelsTest extends TestCase {
*/
public void test_newReader_LReadableByteChannel_LString()
throws IOException {
- InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr);
+ sc.connect(ssc.socket().getLocalSocketAddress());
sc.configureBlocking(false);
assertFalse(sc.isBlocking());
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
index aba37ec..30a486c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.ClosedByInterruptException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedChannelExceptionTest.java
index 3ba322f..da1a68e 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedChannelExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.ClosedChannelException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedSelectorExceptionTest.java
index 745d697..8969f02 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ClosedSelectorExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.ClosedSelectorException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ConnectionPendingExceptionTest.java
index 0e909ba..bce227d 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ConnectionPendingExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.ConnectionPendingException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java
index cff718e..4469e01 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java
@@ -15,12 +15,12 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
-import java.net.InetAddress;
+import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
@@ -33,14 +33,11 @@ import java.nio.channels.NotYetConnectedException;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException;
import java.nio.channels.spi.SelectorProvider;
-import java.security.Permission;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
+import libcore.io.IoUtils;
/**
* Test for DatagramChannel
- *
*/
public class DatagramChannelTest extends TestCase {
@@ -56,64 +53,45 @@ public class DatagramChannelTest extends TestCase {
private static final int TIME_UNIT = 500;
- private InetSocketAddress localAddr1;
+ private InetSocketAddress datagramSocket1Address;
+ private InetSocketAddress datagramSocket2Address;
- private InetSocketAddress localAddr2;
+ private InetSocketAddress channel1Address;
+ private InetSocketAddress channel2Address;
private DatagramChannel channel1;
-
private DatagramChannel channel2;
private DatagramSocket datagramSocket1;
-
private DatagramSocket datagramSocket2;
- // The port to be used in test cases.
- private int testPort;
-
protected void setUp() throws Exception {
super.setUp();
- this.channel1 = DatagramChannel.open();
- this.channel2 = DatagramChannel.open();
- int[] ports = Support_PortManager.getNextPortsForUDP(5);
- this.localAddr1 = new InetSocketAddress("127.0.0.1", ports[0]);
- this.localAddr2 = new InetSocketAddress("127.0.0.1", ports[1]);
- this.datagramSocket1 = new DatagramSocket(ports[2]);
- this.datagramSocket2 = new DatagramSocket(ports[3]);
- testPort = ports[4];
+
+ channel1 = DatagramChannel.open();
+ channel2 = DatagramChannel.open();
+
+ channel1.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ channel2.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+
+ channel1Address = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
+ channel2Address = (InetSocketAddress) channel2.socket().getLocalSocketAddress();
+
+ this.datagramSocket1 = new DatagramSocket(0, Inet6Address.LOOPBACK);
+ this.datagramSocket2 = new DatagramSocket(0, Inet6Address.LOOPBACK);
+
+ datagramSocket1Address = (InetSocketAddress) datagramSocket1.getLocalSocketAddress();
+ datagramSocket2Address = (InetSocketAddress) datagramSocket2.getLocalSocketAddress();
}
protected void tearDown() throws Exception {
- if (null != this.channel1) {
- try {
- this.channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.channel2) {
- try {
- this.channel2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket1) {
- try {
- this.datagramSocket1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket2) {
- try {
- this.datagramSocket2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- localAddr1 = null;
- localAddr2 = null;
+ IoUtils.closeQuietly(channel1);
+ IoUtils.closeQuietly(channel2);
+ IoUtils.closeQuietly(datagramSocket1);
+ IoUtils.closeQuietly(datagramSocket2);
+
+ datagramSocket1Address = null;
+ datagramSocket2Address = null;
super.tearDown();
}
@@ -151,7 +129,6 @@ public class DatagramChannelTest extends TestCase {
*/
public void testReadByteBufferArray() throws IOException {
final int testNum = 0;
- long readres = testNum;
MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
.provider());
MockDatagramChannel testMocknull = new MockDatagramChannel(null);
@@ -163,6 +140,8 @@ public class DatagramChannelTest extends TestCase {
} catch (NullPointerException e) {
// correct
}
+
+ long readres;
try {
readres = testMock.read(readBuf);
fail("Should throw NPE");
@@ -173,9 +152,9 @@ public class DatagramChannelTest extends TestCase {
try {
readres = this.channel1.read(readBuf);
fail("Should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
+ } catch (NotYetConnectedException expected) {
}
+
readres = testMock.read(readBuf);
assertEquals(testNum, readres);
readres = testMocknull.read(readBuf);
@@ -194,20 +173,17 @@ public class DatagramChannelTest extends TestCase {
try {
this.channel1.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
try {
testMock.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
try {
testMocknull.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
}
@@ -281,137 +257,135 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws SocketException
*/
- public void testSocket_BasicStatusBeforeConnect() throws SocketException {
- assertFalse(this.channel1.isConnected());// not connected
- DatagramSocket s1 = this.channel1.socket();
- assertSocketBeforeConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
+ public void testSocket_BasicStatusBeforeConnect() throws Exception {
+ final DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());// not connected
+ DatagramSocket s1 = dc.socket();
+
+ assertFalse(s1.isBound());
+ assertFalse(s1.isClosed());
+ assertFalse(s1.isConnected());
+ assertFalse(s1.getBroadcast());
+ assertFalse(s1.getReuseAddress());
+ assertNull(s1.getInetAddress());
+ assertTrue(s1.getLocalAddress().isAnyLocalAddress());
+ assertEquals(s1.getLocalPort(), 0);
+ assertNull(s1.getLocalSocketAddress());
+ assertEquals(s1.getPort(), -1);
+ assertTrue(s1.getReceiveBufferSize() >= 8192);
+ assertNull(s1.getRemoteSocketAddress());
+ assertFalse(s1.getReuseAddress());
+ assertTrue(s1.getSendBufferSize() >= 8192);
+ assertEquals(s1.getSoTimeout(), 0);
+ assertEquals(s1.getTrafficClass(), 0);
+
+ DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
+
+ dc.close();
}
/**
* Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
*/
public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
- DatagramSocket s1 = this.channel1.socket();
- assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
- // same
- assertSame(s1, s2);
- }
+ final DatagramChannel dc = DatagramChannel.open();
- public void testSocket_NonBlock_BasicStatusAfterConnect()
- throws IOException {
- this.channel1.connect(localAddr1);
- this.channel1.configureBlocking(false);
- DatagramSocket s1 = this.channel1.socket();
+ dc.connect(datagramSocket1Address);
+ DatagramSocket s1 = dc.socket();
assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
+ DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
- }
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
- */
- public void testSocket_ActionsBeforeConnect() throws IOException {
- assertFalse(this.channel1.isConnected());// not connected
- DatagramSocket s = this.channel1.socket();
- assertSocketActionBeforeConnect(s);
+ dc.close();
}
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
- */
- public void testSocket_Block_ActionsAfterConnect() throws IOException {
- assertFalse(this.channel1.isConnected());// not connected
- this.channel1.connect(localAddr1);
- DatagramSocket s = this.channel1.socket();
- assertSocketActionAfterConnect(s);
- }
+ public void testSocket_NonBlock_BasicStatusAfterConnect() throws IOException {
+ final DatagramChannel dc = DatagramChannel.open();
+ dc.connect(datagramSocket1Address);
+ dc.configureBlocking(false);
- public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
- this.channel1.configureBlocking(false);
- DatagramSocket s = this.channel1.socket();
- assertSocketActionAfterConnect(s);
- }
+ DatagramSocket s1 = dc.socket();
+ assertSocketAfterConnect(s1);
+ DatagramSocket s2 = dc.socket();
+ // same
+ assertSame(s1, s2);
- private void assertSocketBeforeConnect(DatagramSocket s)
- throws SocketException {
- assertFalse(s.isBound());
- assertFalse(s.isClosed());
- assertFalse(s.isConnected());
- assertFalse(s.getBroadcast());
- assertFalse(s.getReuseAddress());
- assertNull(s.getInetAddress());
- assertTrue(s.getLocalAddress().isAnyLocalAddress());
- assertEquals(s.getLocalPort(), 0);
- assertNull(s.getLocalSocketAddress());
- assertEquals(s.getPort(), -1);
- assertTrue(s.getReceiveBufferSize() >= 8192);
- assertNull(s.getRemoteSocketAddress());
- assertFalse(s.getReuseAddress());
- assertTrue(s.getSendBufferSize() >= 8192);
- assertEquals(s.getSoTimeout(), 0);
- assertEquals(s.getTrafficClass(), 0);
+ dc.close();
}
- private void assertSocketAfterConnect(DatagramSocket s)
- throws SocketException {
+ private void assertSocketAfterConnect(DatagramSocket s) throws SocketException {
assertTrue(s.isBound());
assertFalse(s.isClosed());
assertTrue(s.isConnected());
assertFalse(s.getBroadcast());
assertFalse(s.getReuseAddress());
- assertSame(s.getInetAddress(), localAddr1.getAddress());
- assertEquals(s.getLocalAddress(), localAddr1.getAddress());
assertNotNull(s.getLocalSocketAddress());
- assertEquals(s.getPort(), localAddr1.getPort());
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
assertTrue(s.getReceiveBufferSize() >= 8192);
// not same , but equals
- assertNotSame(s.getRemoteSocketAddress(), (SocketAddress) localAddr1);
- assertEquals(s.getRemoteSocketAddress(), (SocketAddress) localAddr1);
+ assertNotSame(s.getRemoteSocketAddress(), datagramSocket1Address);
+ assertEquals(s.getRemoteSocketAddress(), datagramSocket1Address);
assertFalse(s.getReuseAddress());
assertTrue(s.getSendBufferSize() >= 8192);
assertEquals(s.getSoTimeout(), 0);
assertEquals(s.getTrafficClass(), 0);
}
- private void assertSocketActionBeforeConnect(DatagramSocket s)
- throws IOException {
- s.connect(localAddr2);
- assertFalse(this.channel1.isConnected());
- assertFalse(s.isConnected());
+ /**
+ * Test method for 'DatagramChannelImpl.socket()'
+ */
+ public void testSocket_ActionsBeforeConnect() throws IOException {
+ assertFalse(channel1.isConnected());// not connected
+ assertTrue(channel1.isBlocking());
+ DatagramSocket s = channel1.socket();
+
+ s.connect(datagramSocket2Address);
+ assertTrue(channel1.isConnected());
+ assertTrue(s.isConnected());
s.disconnect();
- assertFalse(this.channel1.isConnected());
+ assertFalse(channel1.isConnected());
assertFalse(s.isConnected());
s.close();
assertTrue(s.isClosed());
- assertFalse(this.channel1.isOpen());
+ assertFalse(channel1.isOpen());
}
- private void assertSocketActionAfterConnect(DatagramSocket s)
- throws IOException {
- assertEquals(s.getPort(), localAddr1.getPort());
- s.connect(localAddr2);
+ /**
+ * Test method for 'DatagramChannelImpl.socket()'
+ */
+ public void testSocket_Block_ActionsAfterConnect() throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ this.channel1.connect(datagramSocket1Address);
+ DatagramSocket s = this.channel1.socket();
+ assertSocketActionAfterConnect(s);
+ }
+
+ public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
+ this.channel1.connect(datagramSocket1Address);
+ this.channel1.configureBlocking(false);
+ DatagramSocket s = this.channel1.socket();
+ assertSocketActionAfterConnect(s);
+ }
+
+ private void assertSocketActionAfterConnect(DatagramSocket s) throws IOException {
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
+ try {
+ s.connect(datagramSocket2Address);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+
assertTrue(this.channel1.isConnected());
assertTrue(s.isConnected());
// not changed
- assertEquals(s.getPort(), localAddr1.getPort());
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
s.disconnect();
assertFalse(this.channel1.isConnected());
@@ -423,36 +397,11 @@ public class DatagramChannelTest extends TestCase {
}
// -------------------------------------------------------------------
- // Test for configureBlocking()
- // -------------------------------------------------------------------
-
- public void testConfigureBlocking_Read() throws Exception {
- assertTrue(this.channel1.isBlocking());
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_1KB);
- new Thread() {
- public void run() {
- try {
- sleep(TIME_UNIT * 5);
- channel1.configureBlocking(false);
- assertFalse(channel1.isBlocking());
- datagramSocket1.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
- SocketAddress addr = channel1.receive(buf);
- assertNull(addr);
- }
-
- // -------------------------------------------------------------------
// Test for isConnected()
// -------------------------------------------------------------------
/**
* Test method for 'DatagramChannelImpl.isConnected()'
- *
- * @throws IOException
*/
public void testIsConnected_WithServer() throws IOException {
connectLocalServer();
@@ -487,8 +436,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
*/
public void testConnect_NonBlockWithServer() throws IOException {
// Non blocking mode
@@ -500,8 +447,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
*/
public void testConnect_Null() throws IOException {
assertFalse(this.channel1.isConnected());
@@ -515,8 +460,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
*/
public void testConnect_UnsupportedType() throws IOException {
assertFalse(this.channel1.isConnected());
@@ -538,8 +481,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
*/
public void testConnect_Unresolved() throws IOException {
assertFalse(this.channel1.isConnected());
@@ -563,16 +504,13 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
*/
public void testConnect_ClosedChannelException() throws IOException {
assertFalse(this.channel1.isConnected());
this.channel1.close();
assertFalse(this.channel1.isOpen());
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw ClosedChannelException."); //$NON-NLS-1$
} catch (ClosedChannelException e) {
// OK.
@@ -581,17 +519,14 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
*/
public void testConnect_IllegalStateException() throws IOException {
assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
// connect after connected.
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw IllegalStateException."); //$NON-NLS-1$
} catch (IllegalStateException e) {
// OK.
@@ -600,20 +535,17 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
*/
public void testConnect_CheckOpenBeforeStatus() throws IOException {
assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
// connect after connected.
this.channel1.close();
assertFalse(this.channel1.isOpen());
// checking open is before checking status.
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw ClosedChannelException."); //$NON-NLS-1$
} catch (ClosedChannelException e) {
// OK.
@@ -636,7 +568,7 @@ public class DatagramChannelTest extends TestCase {
private void connectLocalServer() throws IOException {
assertFalse(this.channel1.isConnected());
assertTrue(this.datagramSocket1.isBound());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
+ assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
assertTrue(this.channel1.isConnected());
}
@@ -644,7 +576,7 @@ public class DatagramChannelTest extends TestCase {
assertFalse(this.channel1.isConnected());
this.datagramSocket1.close();
assertTrue(this.datagramSocket1.isClosed());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
+ assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
assertTrue(this.channel1.isConnected());
}
@@ -654,8 +586,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_BeforeConnect() throws IOException {
assertFalse(this.channel1.isConnected());
@@ -665,8 +595,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_UnconnectedClosed() throws IOException {
assertFalse(this.channel1.isConnected());
@@ -678,8 +606,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_BlockWithServerChannelClosed()
throws IOException {
@@ -692,8 +618,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_NonBlockWithServerChannelClosed()
throws IOException {
@@ -706,8 +630,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_BlockWithServerServerClosed() throws IOException {
assertTrue(this.channel1.isBlocking());
@@ -721,8 +643,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
*/
public void testDisconnect_NonBlockWithServerServerClosed()
throws IOException {
@@ -742,8 +662,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedNull() throws Exception {
assertFalse(this.channel1.isConnected());
@@ -757,8 +675,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedReadonly() throws Exception {
assertFalse(this.channel1.isConnected());
@@ -775,8 +691,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedBufEmpty() throws Exception {
this.channel1.configureBlocking(false);
@@ -785,49 +699,48 @@ public class DatagramChannelTest extends TestCase {
assertNull(this.channel1.receive(dst));
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufZero() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufZero() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO);
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
+
+ dc.close();
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufNotEmpty() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufNotEmpty() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
+
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
// buf is not empty
dst.put((byte) 88);
assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit());
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
+
+ dc.close();
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufFull() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufFull() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
+
// buf is full
dst.put((byte) 88);
assertEquals(dst.position(), dst.limit());
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
+
+ dc.close();
}
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedClose() throws Exception {
assertFalse(this.channel1.isConnected());
@@ -844,8 +757,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedCloseNull() throws Exception {
assertFalse(this.channel1.isConnected());
@@ -862,8 +773,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_UnconnectedCloseReadonly() throws Exception {
assertFalse(this.channel1.isConnected());
@@ -882,8 +791,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerBufEmpty() throws Exception {
this.channel1.configureBlocking(false);
@@ -892,8 +799,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_BlockNoServerNull() throws Exception {
assertTrue(this.channel1.isBlocking());
@@ -902,8 +807,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerNull() throws Exception {
this.channel1.configureBlocking(false);
@@ -912,8 +815,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_BlockNoServerReadonly() throws Exception {
assertTrue(this.channel1.isBlocking());
@@ -922,8 +823,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerReadonly() throws Exception {
this.channel1.configureBlocking(false);
@@ -932,8 +831,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerBufZero() throws Exception {
this.channel1.configureBlocking(false);
@@ -942,8 +839,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerBufNotEmpty() throws Exception {
this.channel1.configureBlocking(false);
@@ -955,8 +850,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerBufFull() throws Exception {
this.channel1.configureBlocking(false);
@@ -967,8 +860,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_BlockNoServerChannelClose() throws Exception {
assertTrue(this.channel1.isBlocking());
@@ -977,8 +868,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerChannelClose() throws Exception {
this.channel1.configureBlocking(false);
@@ -987,8 +876,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_BlockNoServerCloseNull() throws Exception {
assertTrue(this.channel1.isBlocking());
@@ -997,8 +884,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerCloseNull() throws Exception {
this.channel1.configureBlocking(false);
@@ -1007,8 +892,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_NonBlockNoServerCloseReadonly() throws Exception {
this.channel1.configureBlocking(false);
@@ -1017,8 +900,6 @@ public class DatagramChannelTest extends TestCase {
/**
* Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
*/
public void testReceive_BlockNoServerCloseReadonly() throws Exception {
assertTrue(this.channel1.isBlocking());
@@ -1141,21 +1022,21 @@ public class DatagramChannelTest extends TestCase {
*/
public void testSend_NoServerBlockingCommon() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
}
public void testSend_NoServerNonblockingCommon() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
+ sendDataNonBlocking(datagramSocket1Address, writeBuf);
}
public void testSend_NoServerTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
// can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
+ assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
try {
- channel1.send(writeBuf, localAddr2);
+ channel1.send(writeBuf, datagramSocket2Address);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
@@ -1164,11 +1045,11 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerNonBlockingTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
+ sendDataNonBlocking(datagramSocket1Address, writeBuf);
// can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
+ assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
try {
- channel1.send(writeBuf, localAddr2);
+ channel1.send(writeBuf, datagramSocket2Address);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
@@ -1177,7 +1058,7 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerBufNull() throws IOException {
try {
- sendDataBlocking(localAddr1, null);
+ sendDataBlocking(datagramSocket1Address, null);
fail("Should throw a NPE here.");
} catch (NullPointerException e) {
// correct
@@ -1187,14 +1068,14 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerBufNullTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
try {
- sendDataBlocking(localAddr1, null);
+ sendDataBlocking(datagramSocket1Address, null);
fail("Should throw a NPE here.");
} catch (NullPointerException e) {
// correct
}
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
try {
- channel1.send(null, localAddr2);
+ channel1.send(null, datagramSocket2Address);
fail("Should throw NPE");
} catch (NullPointerException e) {
// correct
@@ -1219,7 +1100,7 @@ public class DatagramChannelTest extends TestCase {
} catch (NullPointerException e) {
// correct
}
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
try {
channel1.send(writeBuf, null);
fail("Should throw NPE");
@@ -1233,62 +1114,47 @@ public class DatagramChannelTest extends TestCase {
// -------------------------------------------------------------------
public void testReceiveSend_Block_Normal() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
+ sendOnChannel2("some normal string in testReceiveSend_Normal",
+ channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address,
"some normal string in testReceiveSend_Normal");
}
- public void testReceiveSend_Block_NotBound() throws Exception {
- // not bound
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
- assertNull(channel1.receive(buf));
- assertFalse(channel1.socket().isBound());
- }
-
public void testReceiveSend_NonBlock_NotBound() throws Exception {
// not bound
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
+ sendOnChannel2("some normal string in testReceiveSend_Normal",
+ datagramSocket2Address);
ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]);
- assertNull((InetSocketAddress) this.channel1.receive(buf));
+ assertNull(this.channel1.receive(buf));
}
public void testReceiveSend_Block_Normal_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket(
- "some normal string in testReceiveSend_Normal_S2C", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
+ sendOnDatagramSocket1(
+ "some normal string in testReceiveSend_Normal_S2C", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address,
"some normal string in testReceiveSend_Normal_S2C");
}
public void testReceiveSend_Block_Normal_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
+ sendOnChannel2(str1, datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
}
public void testReceiveSend_NonBlock_Normal_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
+ sendOnChannel2(str1, datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
}
public void testReceiveSend_Normal_S2S() throws Exception {
String msg = "normal string in testReceiveSend_Normal_S2S";
- this.datagramSocket1 = new DatagramSocket(testPort);
DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
+ datagramSocket2Address);
this.datagramSocket1.send(rdp);
byte[] buf = new byte[CAPACITY_NORMAL];
this.datagramSocket2.setSoTimeout(TIME_UNIT);
@@ -1298,53 +1164,45 @@ public class DatagramChannelTest extends TestCase {
}
public void testReceiveSend_Block_Empty() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
}
public void testReceiveSend_NonBlock_Empty() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
}
public void testReceiveSend_Block_Empty_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnDatagramSocket1("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
}
public void testReceiveSend_NonBlock_Empty_S2C() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnDatagramSocket1("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
}
public void testReceiveSend_Block_Empty_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
}
public void testReceiveSend_NonBlock_Empty_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
}
public void testReceiveSend_Empty_S2S() throws Exception {
String msg = "";
- this.datagramSocket1 = new DatagramSocket(testPort);
DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
+ datagramSocket2Address);
this.datagramSocket1.send(rdp);
byte[] buf = new byte[CAPACITY_NORMAL];
this.datagramSocket2.setSoTimeout(TIME_UNIT);
@@ -1354,29 +1212,25 @@ public class DatagramChannelTest extends TestCase {
}
public void testReceiveSend_Block_Oversize() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", channel1Address);
+ receiveOnChannel1AndClose(5, channel2Address, "01234");
}
public void testReceiveSend_Block_Oversize_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", datagramSocket1Address);
+ receiveOnDatagramSocket1(5, "01234");
}
public void testReceiveSend_NonBlock_Oversize_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", datagramSocket1Address);
+ receiveOnDatagramSocket1(5, "01234");
}
public void testReceiveSend_Block_Oversize_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
+ sendOnDatagramSocket1("0123456789", channel1Address);
+ receiveOnChannel1AndClose(5, datagramSocket1Address, "01234");
}
public void testReceiveSend_8K() throws Exception {
@@ -1385,9 +1239,9 @@ public class DatagramChannelTest extends TestCase {
str8k.append('a');
}
String str = str8k.toString();
- this.channel1.socket().bind(localAddr2);
- sendByChannel(str, localAddr2);
- receiveByChannel(8 * CAPACITY_1KB, localAddr2, str);
+
+ sendOnChannel2(str, channel1Address);
+ receiveOnChannel1AndClose(8 * CAPACITY_1KB, channel2Address, str);
}
public void testReceiveSend_64K() throws Exception {
@@ -1398,56 +1252,43 @@ public class DatagramChannelTest extends TestCase {
String str = str64k.toString();
try {
Thread.sleep(TIME_UNIT);
- channel2.send(ByteBuffer.wrap(str.getBytes()), localAddr1);
+ channel2.send(ByteBuffer.wrap(str.getBytes()), datagramSocket1Address);
fail("Should throw SocketException!");
- } catch (SocketException e) {
- //expected
+ } catch (SocketException expected) {
}
}
- private void sendByChannel(String data, InetSocketAddress address)
- throws Exception {
- try {
- assertEquals(data.length(), this.channel2.send(ByteBuffer.wrap(data
- .getBytes()), address));
- } finally {
- this.channel2.close();
- }
+ private void sendOnChannel2(String data, SocketAddress address)
+ throws IOException {
+ assertEquals(data.length(), channel2.send(ByteBuffer.wrap(data.getBytes()), address));
}
- private void sendByDatagramSocket(String data, InetSocketAddress address)
+ private void sendOnDatagramSocket1(String data, InetSocketAddress address)
throws Exception {
- this.datagramSocket1 = new DatagramSocket(testPort);
- DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(),
- address);
+ DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(), address);
this.datagramSocket1.send(rdp);
}
- private void receiveByChannel(int bufSize, InetSocketAddress address,
- String expectedString) throws IOException {
+ private void receiveOnChannel1AndClose(int bufSize,
+ InetSocketAddress expectedAddress, String expectedString) throws IOException {
try {
ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]);
- InetSocketAddress returnAddr = null;
+ InetSocketAddress senderAddr;
long startTime = System.currentTimeMillis();
do {
- returnAddr = (InetSocketAddress) this.channel1.receive(buf);
+ senderAddr = (InetSocketAddress) this.channel1.receive(buf);
// continue loop when channel1 is non-blocking and no data was
// received.
- if (channel1.isBlocking() || null != returnAddr) {
+ if (channel1.isBlocking() || senderAddr != null) {
break;
}
// avoid dead loop
assertTimeout(startTime, 10000);
} while (true);
- int length = returnAddr.getAddress().getAddress().length;
- for (int i = 0; i < length; i++) {
- assertEquals(returnAddr.getAddress().getAddress()[i],
- InetAddress.getByName("127.0.0.1").getAddress()[i]);
- }
- // port is NOT equal
- assertFalse(returnAddr.getPort() == address.getPort());
- assertEquals(new String(buf.array(), 0, bufSize).trim(),
- expectedString);
+
+ assertEquals(senderAddr.getAddress(), Inet6Address.LOOPBACK);
+ assertEquals(expectedAddress.getPort(), senderAddr.getPort());
+ assertEquals(new String(buf.array(), 0, buf.position()), expectedString);
} finally {
this.channel1.close();
}
@@ -1464,8 +1305,7 @@ public class DatagramChannelTest extends TestCase {
}
}
- private void receiveByDatagramSocket(int bufSize,
- InetSocketAddress address, String expectedString)
+ private void receiveOnDatagramSocket1(int bufSize, String expectedString)
throws IOException {
byte[] buf = new byte[bufSize];
this.datagramSocket1.setSoTimeout(6000);
@@ -1474,28 +1314,27 @@ public class DatagramChannelTest extends TestCase {
assertEquals(new String(buf, 0, bufSize).trim(), expectedString);
}
- public void testRead_NoSecurity() throws Exception {
+ public void testRead_fromSend() throws Exception {
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
String strHello = "hello";
- localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
- this.channel1.socket().bind(localAddr1);
- this.channel2.socket().bind(localAddr2);
- this.channel1.connect(localAddr2);
- this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), localAddr1);
+
+ this.channel1.connect(channel2Address);
+ this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), channel1Address);
+
assertEquals(strHello.length(), this.channel1.read(buf));
assertAscii(buf, strHello);
}
public void testReceive_Peek_NoSecurity_Nonblocking() throws Exception {
String strHello = "hello";
- localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
- this.channel1.socket().bind(localAddr1);
- sendByChannel(strHello, localAddr1);
+
+ sendOnChannel2(strHello, channel1Address);
this.channel1.configureBlocking(false);
// for accepted addr, no problem.
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
+
InetSocketAddress source = (InetSocketAddress) this.channel1.receive(buf);
- assertEquals(localAddr1.getAddress(), source.getAddress());
+ assertEquals(channel2Address, source);
assertAscii(buf, strHello);
}
@@ -1532,18 +1371,18 @@ public class DatagramChannelTest extends TestCase {
*/
public void testWriteByteBuffer_Block() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- connectWriteBuf(localAddr1, writeBuf);
+ connectWriteBuf(datagramSocket1Address, writeBuf);
}
public void testWriteByteBuffer_NonBlock() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
this.channel1.configureBlocking(false);
- connectWriteBuf(localAddr1, writeBuf);
+ connectWriteBuf(datagramSocket1Address, writeBuf);
}
public void testWriteByteBuffer_Block_closed() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
noconnectWrite(writeBuf);
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
@@ -1558,7 +1397,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_NonBlock_closed() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non block mode
this.channel1.configureBlocking(false);
noconnectWrite(writeBuf);
@@ -1575,7 +1414,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_Block_BufNull() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write((ByteBuffer) null);
fail("Should throw NPE.");
@@ -1602,7 +1441,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_NonBlock_BufNull() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non block mode
this.channel1.configureBlocking(false);
@@ -1638,7 +1477,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write(writeBuf, 0, 2);
fail("Should throw NotYetConnectedException.");
@@ -1657,7 +1496,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non-block mode
this.channel1.configureBlocking(false);
try {
@@ -1679,7 +1518,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write(writeBuf, -1, 2);
fail("should throw IndexOutOfBoundsException");
@@ -1704,7 +1543,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
try {
@@ -1746,7 +1585,7 @@ public class DatagramChannelTest extends TestCase {
throws IOException {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
try {
@@ -1785,7 +1624,7 @@ public class DatagramChannelTest extends TestCase {
} catch (NotYetConnectedException e) {
// correct
}
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
this.channel1.configureBlocking(false);
// note : blocking-mode will make the read process endless!
@@ -1801,7 +1640,7 @@ public class DatagramChannelTest extends TestCase {
public void testReadByteBuffer_bufNull() throws IOException {
ByteBuffer readBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(readBuf);
fail("should throw NotYetConnectedException");
@@ -1829,7 +1668,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] readBuf = new ByteBuffer[2];
readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(readBuf, 0, 2);
fail("should throw NotYetConnectedException");
@@ -1867,7 +1706,7 @@ public class DatagramChannelTest extends TestCase {
public void testReadByteBufferArrayIntInt_BufNull() throws IOException {
ByteBuffer[] readBuf = new ByteBuffer[2];
readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(null, 0, 0);
fail("should throw NPE");
@@ -1904,26 +1743,37 @@ public class DatagramChannelTest extends TestCase {
// test read and write
// -------------------------------------------------------------------
- public void testReadWrite_configureBlock() throws Exception {
+ public static class A {
+ protected int z;
+ }
+
+ public static class B extends A {
+ protected int z;
+
+ void foo() {
+ super.z+=1;
+ }
+ }
+
+
+ public void testReadWrite_asyncClose() throws Exception {
byte[] targetArray = new byte[2];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
+ channel2.connect(channel1Address);
+ channel1.connect(channel2Address);
+
new Thread() {
public void run() {
try {
Thread.sleep(TIME_UNIT);
- channel1.configureBlocking(false);
channel1.close();
} catch (Exception e) {
//ignore
}
}
}.start();
+
try {
this.channel1.read(targetBuf);
fail("should throw AsynchronousCloseException");
@@ -1935,11 +1785,9 @@ public class DatagramChannelTest extends TestCase {
public void testReadWrite_Block_Zero() throws Exception {
byte[] sourceArray = new byte[0];
byte[] targetArray = new byte[0];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -1959,11 +1807,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal");
@@ -1974,12 +1819,8 @@ public class DatagramChannelTest extends TestCase {
byte[] sourceArray = "".getBytes();
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -1996,12 +1837,8 @@ public class DatagramChannelTest extends TestCase {
byte[] sourceArray = "".getBytes();
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2039,11 +1876,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB");
@@ -2089,18 +1923,14 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
try {
channel1.write(sourceBuf);
fail("Should throw IOException");
- } catch (IOException e) {
+ } catch (IOException expected) {
// too big
}
}
@@ -2112,11 +1942,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
+ this.channel1.connect(channel1.socket().getLocalSocketAddress());
+ this.channel2.connect(datagramSocket1Address); // the different addr
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2129,35 +1956,41 @@ public class DatagramChannelTest extends TestCase {
closeBlockedReaderChannel2(targetBuf);
}
- public void testReadWrite_Block_WriterNotBind() throws Exception {
+ public void testReadWrite_Block_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ DatagramChannel dc = DatagramChannel.open();
+ // The writer isn't bound, but is connected.
+ dc.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
+ assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
+
+ // Connect channel2 after data has been written.
+ channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
closeBlockedReaderChannel2(targetBuf);
+
+ dc.close();
}
- public void testReadWrite_Block_WriterBindLater() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_Block_WriterConnectLater() throws Exception {
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
- // writer channel1 is bound later
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ // The reader is bound & connected to channel1.
+ channel2.connect(channel1Address);
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
@@ -2170,8 +2003,8 @@ public class DatagramChannelTest extends TestCase {
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
+
+ channel1.connect(channel2Address);
// write later
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf));
@@ -2184,6 +2017,7 @@ public class DatagramChannelTest extends TestCase {
int count = 0;
int total = 0;
long beginTime = System.currentTimeMillis();
+
while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) {
total = total + count;
// 3s timeout to avoid dead loop
@@ -2199,21 +2033,21 @@ public class DatagramChannelTest extends TestCase {
for (int i = 0; i < targetArray.length; i++) {
assertEquals(targetArray[i], (byte) i);
}
-
}
- public void testReadWrite_Block_ReaderNotBind() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_Block_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- // reader channel2 is not bound
- this.channel2.connect(localAddr2);
+ // reader channel2 is not connected.
+ this.channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2221,24 +2055,29 @@ public class DatagramChannelTest extends TestCase {
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- closeBlockedReaderChannel2(targetBuf);
-
+ try {
+ this.channel2.read(targetBuf);
+ fail();
+ } catch (NotYetConnectedException expected) {
+ }
}
private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
throws IOException {
+ assertTrue(this.channel2.isBlocking());
+
new Thread() {
public void run() {
try {
Thread.sleep(TIME_UNIT);
- channel2.close();
- } catch (Exception e) {
- // do nothing
+ } catch (InterruptedException ie) {
+ fail();
}
+ IoUtils.closeQuietly(channel2);
}
}.start();
+
try {
- assertTrue(this.channel2.isBlocking());
this.channel2.read(targetBuf);
fail("Should throw AsynchronousCloseException");
} catch (AsynchronousCloseException e) {
@@ -2259,11 +2098,8 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal");
@@ -2280,10 +2116,8 @@ public class DatagramChannelTest extends TestCase {
this.channel2.configureBlocking(false);
// bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB");
@@ -2299,11 +2133,8 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
+ channel1.connect(channel2Address);
+ channel2.connect(datagramSocket1Address);// the different addr
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2314,31 +2145,39 @@ public class DatagramChannelTest extends TestCase {
assertEquals(0, this.channel2.read(targetBuf));
}
- public void testReadWrite_NonBlock_WriterNotBind() throws Exception {
+
+ public void testReadWrite_NonBlock_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ DatagramChannel dc = DatagramChannel.open();
+ // The writer isn't bound, but is connected.
+ dc.connect(channel1Address);
+ dc.configureBlocking(false);
+ channel2.configureBlocking(false);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
+ assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
+
+ // Connect channel2 after data has been written.
+ channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
assertEquals(0, this.channel2.read(targetBuf));
+
+ dc.close();
}
- public void testReadWrite_NonBlock_ReaderNotBind() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_NonBlock_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
@@ -2348,10 +2187,7 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2359,7 +2195,12 @@ public class DatagramChannelTest extends TestCase {
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
+
+ try {
+ assertEquals(0, this.channel2.read(targetBuf));
+ fail();
+ } catch (NotYetConnectedException expected) {
+ }
}
public void test_write_LBuffer_positioned() throws Exception {
@@ -2367,7 +2208,7 @@ public class DatagramChannelTest extends TestCase {
int position = 16;
DatagramChannel dc = DatagramChannel.open();
byte[] sourceArray = new byte[CAPACITY_NORMAL];
- dc.connect(localAddr1);
+ dc.connect(datagramSocket1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
sourceBuf.position(position);
@@ -2384,7 +2225,7 @@ public class DatagramChannelTest extends TestCase {
// send ByteBuffer whose position is not zero
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
sourceBuf.position(position);
- int ret = dc.send(sourceBuf, localAddr1);
+ int ret = dc.send(sourceBuf, datagramSocket1Address);
// assert send (256 - 16) bytes
assertEquals(CAPACITY_NORMAL - position, ret);
// assert the position of ByteBuffer has been set
@@ -2395,11 +2236,10 @@ public class DatagramChannelTest extends TestCase {
* @tests DatagramChannel#read(ByteBuffer[])
*/
public void test_read_$LByteBuffer() throws Exception {
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
+
// regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
ByteBuffer[] readBuf = new ByteBuffer[2];
@@ -2414,11 +2254,10 @@ public class DatagramChannelTest extends TestCase {
* @tests DatagramChannel#read(ByteBuffer[],int,int)
*/
public void test_read_$LByteBufferII() throws Exception {
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
+
// regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
ByteBuffer[] readBuf = new ByteBuffer[2];
@@ -2426,7 +2265,7 @@ public class DatagramChannelTest extends TestCase {
readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
channel1.configureBlocking(true);
- assertEquals(CAPACITY_NORMAL, channel1.read(readBuf,0,2));
+ assertEquals(CAPACITY_NORMAL, channel1.read(readBuf, 0, 2));
}
/**
@@ -2474,7 +2313,7 @@ public class DatagramChannelTest extends TestCase {
} catch (IllegalArgumentException e){
// expected
}
- channel.connect(localAddr1);
+ channel.connect(datagramSocket1Address);
try{
channel.read(c.asReadOnlyBuffer());
fail("Should throw IllegalArgumentException");
@@ -2491,13 +2330,13 @@ public class DatagramChannelTest extends TestCase {
channel1.close();
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
try {
- channel1.send(buf, localAddr1);
+ channel1.send(buf, datagramSocket1Address);
fail("Should throw ClosedChannelException");
} catch (ClosedChannelException e) {
//pass
}
try {
- channel1.send(null,localAddr1);
+ channel1.send(null, datagramSocket1Address);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
//pass
@@ -2536,6 +2375,8 @@ public class DatagramChannelTest extends TestCase {
} catch (IllegalBlockingModeException e) {
// expected
}
+
+ channel.close();
}
public void test_bounded_harmony6493() throws IOException {
@@ -2554,4 +2395,129 @@ public class DatagramChannelTest extends TestCase {
server.close();
client.close();
}
+
+ public void test_bind_null() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ try {
+ assertNull(dc.socket().getLocalSocketAddress());
+
+ dc.socket().bind(null);
+
+ InetSocketAddress localAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertTrue(localAddress.getAddress().isAnyLocalAddress());
+ assertTrue(localAddress.getPort() > 0);
+ } finally {
+ dc.close();
+ }
+ }
+
+ public void test_bind_failure() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ try {
+ // Bind to a local address that is in use
+ dc.socket().bind(channel1Address);
+ fail();
+ } catch (IOException expected) {
+ } finally {
+ dc.close();
+ }
+ }
+
+ public void test_bind_closed() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.close();
+
+ try {
+ dc.socket().bind(null);
+ fail();
+ } catch (IOException expected) {
+ } finally {
+ dc.close();
+ }
+ }
+
+ public void test_bind_explicitPort() throws Exception {
+ InetSocketAddress address = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
+ assertTrue(address.getPort() > 0);
+
+ DatagramChannel dc = DatagramChannel.open();
+ // Allow the socket to bind to a port we know is already in use.
+ dc.socket().setReuseAddress(true);
+ InetSocketAddress bindAddress = new InetSocketAddress("localhost", address.getPort());
+ dc.socket().bind(bindAddress);
+
+ InetSocketAddress boundAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertEquals(bindAddress.getHostName(), boundAddress.getHostName());
+ assertEquals(bindAddress.getPort(), boundAddress.getPort());
+
+ dc.close();
+ channel1.close();
+ }
+
+ /** Checks that the SocketChannel and associated Socket agree on the socket state. */
+ public void test_bind_socketSync() throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ assertNull(dc.socket().getLocalSocketAddress());
+
+ DatagramSocket socket = dc.socket();
+ assertNull(socket.getLocalSocketAddress());
+ assertFalse(socket.isBound());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ dc.socket().bind(bindAddr);
+
+ InetSocketAddress actualAddr = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isConnected());
+ assertFalse(socket.isClosed());
+
+ dc.close();
+
+ assertFalse(dc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ /**
+ * Checks that the SocketChannel and associated Socket agree on the socket state, even if
+ * the Socket object is requested/created after bind().
+ */
+ public void test_bind_socketSyncAfterBind() throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ assertNull(dc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ dc.socket().bind(bindAddr);
+
+ // Socket creation after bind().
+ DatagramSocket socket = dc.socket();
+ InetSocketAddress actualAddr = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isConnected());
+ assertFalse(socket.isClosed());
+
+ dc.close();
+
+ assertFalse(dc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ public void test_getLocalSocketAddress_afterClose() throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ assertNull(dc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ dc.socket().bind(bindAddr);
+
+ assertNotNull(dc.socket().getLocalSocketAddress());
+
+ dc.close();
+
+ assertFalse(dc.isOpen());
+
+ dc.socket().getLocalSocketAddress();
+ }
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelLockingTest.java
index cb34343..40daa20 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelLockingTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileInputStream;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelTest.java
index 9a89f7e..990badc 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileInputStream;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
index b60096c..08a7421 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.FileLockInterruptionException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockTest.java
index 12142e8..7e3b671 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/FileLockTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileOutputStream;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
index a8cdf83..3384ee5 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.IllegalBlockingModeException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalSelectorExceptionTest.java
index 2fa3171..dabb95f 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/IllegalSelectorExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.IllegalSelectorException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MapModeTest.java
index 33234eb..13fe11b 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MapModeTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.FileChannel;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java
index c8dc2af..41388ec 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.DatagramSocket;
@@ -30,50 +30,62 @@ class MockDatagramChannel extends DatagramChannel {
super(arg0);
}
+ @Override
public DatagramSocket socket() {
return null;
}
+ @Override
public boolean isConnected() {
return false;
}
+ @Override
public DatagramChannel connect(SocketAddress arg0) throws IOException {
return null;
}
+ @Override
public DatagramChannel disconnect() throws IOException {
return null;
}
+ @Override
public SocketAddress receive(ByteBuffer arg0) throws IOException {
return null;
}
+ @Override
public int send(ByteBuffer arg0, SocketAddress arg1) throws IOException {
return 0;
}
+ @Override
public int read(ByteBuffer arg0) throws IOException {
return 0;
}
+ @Override
public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
return 0;
}
+ @Override
public int write(ByteBuffer arg0) throws IOException {
return 0;
}
+ @Override
public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
return 0;
}
+ @Override
protected void implCloseSelectableChannel() throws IOException {
// empty
}
+ @Override
protected void implConfigureBlocking(boolean arg0) throws IOException {
// empty
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockServerSocketChannel.java
index 2058a7a..783d2ce 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockServerSocketChannel.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.ServerSocket;
@@ -29,17 +29,21 @@ class MockServerSocketChannel extends ServerSocketChannel {
super(arg0);
}
+ @Override
public ServerSocket socket() {
return null;
}
+ @Override
public SocketChannel accept() throws IOException {
return null;
}
+ @Override
protected void implCloseSelectableChannel() throws IOException {
}
+ @Override
protected void implConfigureBlocking(boolean arg0) throws IOException {
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockSocketChannel.java
index 9d130ca..47dad9d 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockSocketChannel.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.Socket;
@@ -30,45 +30,56 @@ class MockSocketChannel extends SocketChannel {
super(arg0);
}
+ @Override
public Socket socket() {
return null;
}
+ @Override
public boolean isConnected() {
return false;
}
+ @Override
public boolean isConnectionPending() {
return false;
}
+ @Override
public boolean connect(SocketAddress arg0) throws IOException {
return false;
}
+ @Override
public boolean finishConnect() throws IOException {
return false;
}
+ @Override
public int read(ByteBuffer arg0) throws IOException {
return 0;
}
+ @Override
public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
return 0;
}
+ @Override
public int write(ByteBuffer arg0) throws IOException {
return 0;
}
+ @Override
public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
return 0;
}
+ @Override
protected void implCloseSelectableChannel() throws IOException {
}
+ @Override
protected void implConfigureBlocking(boolean arg0) throws IOException {
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
index 2ba7ba6..7a99a77 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.NoConnectionPendingException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonReadableChannelExceptionTest.java
index 8c44f17..0f59d92 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonReadableChannelExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.NonReadableChannelException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonWritableChannelExceptionTest.java
index 459d85a..ffafb38 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NonWritableChannelExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.NonWritableChannelException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetBoundExceptionTest.java
index d1c2d86..eef3185 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetBoundExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.NotYetBoundException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetConnectedExceptionTest.java
index 09e4c1c..00284bd 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/NotYetConnectedExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.NotYetConnectedException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
index d06f807..fd11abf 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.OverlappingFileLockException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/PipeTest.java
index 53f19c4..e1de1f5 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/PipeTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.NetPermission;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectableChannelTest.java
index 25b5f00..a4698bd 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectableChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java
index ed33752..150d11c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -24,9 +24,7 @@ import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/*
* Tests for SelectionKey and its default implementation
@@ -295,10 +293,9 @@ public class SelectionKeyTest extends TestCase {
* @tests java.nio.channels.SelectionKey#readyOps()
*/
public void test_readyOps() throws IOException {
- int port = Support_PortManager.getNextPort();
- ServerSocket ss = new ServerSocket(port);
+ ServerSocket ss = new ServerSocket(0);
try {
- sc.connect(new InetSocketAddress(LOCAL_ADDR, port));
+ sc.connect(new InetSocketAddress(LOCAL_ADDR, ss.getLocalPort()));
assertEquals(0, selectionKey.readyOps());
assertFalse(selectionKey.isConnectable());
selector.select();
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectorTest.java
index 3617230..0eb51b6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectorTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.ServerSocket;
@@ -206,9 +206,6 @@ public class SelectorTest extends TestCase {
assert_select_SelectorClosed(SelectType.NOW, 0);
}
- /**
- * @test java.nio.channels.Selector#selectNow()
- */
public void test_selectNow_Timeout() throws IOException {
// make sure selectNow doesn't block
selector.selectNow();
@@ -266,17 +263,11 @@ public class SelectorTest extends TestCase {
}
}
- /**
- * @test java.nio.channels.Selector#select(long)
- */
public void test_selectJ_Timeout() throws IOException {
// make sure select(timeout) doesn't block
selector.select(WAIT_TIME);
}
- /**
- * @test java.nio.channels.Selector#select(long)
- */
public void test_selectJ_Empty_Keys() throws IOException {
// regression test, see HARMONY-3888.
// make sure select(long) does wait for specified amount of
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java
index fdbbc48..be40d0b 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.io.InputStream;
@@ -32,9 +32,7 @@ import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/*
* test for ServerSocketChannel
@@ -47,17 +45,12 @@ public class ServerSocketChannelTest extends TestCase {
private static final int TIME_UNIT = 200;
- private InetSocketAddress localAddr1;
-
private ServerSocketChannel serverChannel;
private SocketChannel clientChannel;
protected void setUp() throws Exception {
super.setUp();
- this.localAddr1 = new InetSocketAddress(
- "127.0.0.1", Support_PortManager
- .getNextPort());
this.serverChannel = ServerSocketChannel.open();
this.clientChannel = SocketChannel.open();
}
@@ -115,6 +108,140 @@ public class ServerSocketChannelTest extends TestCase {
}
// -------------------------------------------------------------------
+ // Tests for bind()
+ // -------------------------------------------------------------------
+
+ public void test_bind_null() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ try {
+ assertNull(ssc.socket().getLocalSocketAddress());
+
+ ssc.socket().bind(null);
+
+ InetSocketAddress localAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertTrue(localAddress.getAddress().isAnyLocalAddress());
+ assertTrue(localAddress.getPort() > 0);
+ } finally {
+ ssc.close();
+ }
+ }
+
+ public void test_bind_failure() throws Exception {
+ ServerSocketChannel portHog = ServerSocketChannel.open();
+ portHog.socket().bind(null);
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ try {
+ // Bind to a local address that is in use
+ ssc.socket().bind(portHog.socket().getLocalSocketAddress());
+ fail();
+ } catch (IOException expected) {
+ } finally {
+ ssc.close();
+ portHog.close();
+ }
+ }
+
+ public void test_bind_closed() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.close();
+
+ try {
+ ssc.socket().bind(null);
+ fail();
+ } catch (IOException expected) {
+ } finally {
+ ssc.close();
+ }
+ }
+
+ public void test_bind_explicitPort() throws Exception {
+ ServerSocketChannel portPickingChannel = ServerSocketChannel.open();
+ // Have the OS find a free port.
+ portPickingChannel.socket().bind(null);
+
+ InetSocketAddress address = (InetSocketAddress) portPickingChannel.socket().getLocalSocketAddress();
+ assertTrue(address.getPort() > 0);
+ portPickingChannel.close();
+
+ // There is a risk of flakiness here if the port is allocated to something else between
+ // close() and bind().
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ InetSocketAddress bindAddress = new InetSocketAddress("localhost", address.getPort());
+ ssc.socket().bind(bindAddress);
+
+ InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertEquals(bindAddress.getHostName(), boundAddress.getHostName());
+ assertEquals(bindAddress.getPort(), boundAddress.getPort());
+
+ ssc.close();
+ }
+
+ public void test_bind_socketSync() throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ assertNull(ssc.socket().getLocalSocketAddress());
+
+ ServerSocket socket = ssc.socket();
+ assertNull(socket.getLocalSocketAddress());
+ assertFalse(socket.isBound());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ ssc.socket().bind(bindAddr);
+
+ InetSocketAddress actualAddr = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isClosed());
+
+ ssc.close();
+
+ assertFalse(ssc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ public void test_bind_socketSyncAfterBind() throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ assertNull(ssc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ ssc.socket().bind(bindAddr);
+
+ // Socket creation after bind().
+ ServerSocket socket = ssc.socket();
+ InetSocketAddress actualAddr = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isClosed());
+
+ ssc.close();
+
+ assertFalse(ssc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ // -------------------------------------------------------------------
+ // Test for getLocalSocketAddress()
+ // -------------------------------------------------------------------
+
+ public void test_getLocalSocketAddress_afterClose() throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ assertNull(ssc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ ssc.socket().bind(bindAddr);
+
+ assertNotNull(ssc.socket().getLocalSocketAddress());
+
+ ssc.close();
+
+ assertFalse(ssc.isOpen());
+
+ ssc.socket().getLocalSocketAddress();
+ }
+
+ // -------------------------------------------------------------------
// Test for socket()
// -------------------------------------------------------------------
@@ -242,8 +369,7 @@ public class ServerSocketChannelTest extends TestCase {
public void testAccept_Block_NoConnect() throws IOException {
assertTrue(this.serverChannel.isBlocking());
- ServerSocket gotSocket = this.serverChannel.socket();
- gotSocket.bind(localAddr1);
+ serverChannel.socket().bind(null);
// blocking mode , will block and wait for ever...
// so must close the server channel with another thread.
new Thread() {
@@ -266,8 +392,7 @@ public class ServerSocketChannelTest extends TestCase {
}
public void testAccept_NonBlock_NoConnect() throws IOException {
- ServerSocket gotSocket = this.serverChannel.socket();
- gotSocket.bind(localAddr1);
+ this.serverChannel.socket().bind(null);
this.serverChannel.configureBlocking(false);
// non-blocking mode , will immediately return
assertNull(this.serverChannel.accept());
@@ -277,13 +402,13 @@ public class ServerSocketChannelTest extends TestCase {
* @tests ServerSocketChannel#accept().socket()
*/
public void test_read_Blocking_RealData() throws IOException {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
for (int i = 0; i < CAPACITY_NORMAL; i++) {
buf.put((byte) i);
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket serverSocket = serverChannel.accept().socket();
InputStream in = serverSocket.getInputStream();
buf.flip();
@@ -316,13 +441,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_read_NonBlocking_RealData() throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
for (int i = 0; i < CAPACITY_NORMAL; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket serverSocket = serverChannel.accept().socket();
InputStream in = serverSocket.getInputStream();
clientChannel.write(buf);
@@ -335,14 +460,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_write_Blocking_RealData() throws IOException {
assertTrue(serverChannel.isBlocking());
- ServerSocket serverSocket = serverChannel.socket();
- serverSocket.bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_NORMAL];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
OutputStream out = socket.getOutputStream();
out.write(writeContent);
@@ -357,14 +481,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_write_NonBlocking_RealData() throws Exception {
serverChannel.configureBlocking(false);
- ServerSocket serverSocket = serverChannel.socket();
- serverSocket.bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_NORMAL];
for (int i = 0; i < CAPACITY_NORMAL; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket clientSocket = serverChannel.accept().socket();
OutputStream out = clientSocket.getOutputStream();
out.write(writeContent);
@@ -378,13 +501,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_read_LByteBuffer_Blocking_ReadWriteRealLargeData()
throws IOException, InterruptedException {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
for (int i = 0; i < CAPACITY_64KB; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
writeThread.start();
Socket socket = serverChannel.accept().socket();
@@ -423,13 +546,13 @@ public class ServerSocketChannelTest extends TestCase {
public void test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
for (int i = 0; i < CAPACITY_64KB; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
writeThread.start();
Socket socket = serverChannel.accept().socket();
@@ -448,12 +571,12 @@ public class ServerSocketChannelTest extends TestCase {
public void test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_64KB];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
writeThread.start();
@@ -491,12 +614,12 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_write_LByteBuffer_Blocking_ReadWriteRealLargeData()
throws Exception {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_64KB];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
writeThread.start();
@@ -534,20 +657,35 @@ public class ServerSocketChannelTest extends TestCase {
* @tests ServerSocketChannel#socket().getSoTimeout()
*/
public void test_accept_SOTIMEOUT() throws IOException {
- // regression test for Harmony-707
- final int SO_TIMEOUT = 10;
+ // Regression test for Harmony-707
+ // The timeout actually used may be different from the one set due to
+ // rounding by the Linux Kernel (see sock_set_timeout() in net/core/sock.c).
+ // getSoTimeout() can return a different value from the one set with
+ // setSoTimeout(). Consequently we do not check for equality with what was
+ // set.
+
ServerSocketChannel sc = ServerSocketChannel.open();
try {
- ServerSocket ss = sc.socket();
- ss.bind(localAddr1);
+ sc.socket().bind(null);
+
+ // Non blocking mode, accept() will return NULL since there are no pending connections.
sc.configureBlocking(false);
+
+ ServerSocket ss = sc.socket();
+
+ int defaultTimeout = ss.getSoTimeout();
+ assertEquals(0, defaultTimeout);
+ // The timeout value is unimportant, providing it is large enough to be accepted
+ // by the Kernel as distinct from the default.
+ final int SO_TIMEOUT = 200;
ss.setSoTimeout(SO_TIMEOUT);
+ int nonDefaultTimeout = ss.getSoTimeout();
+ assertTrue(nonDefaultTimeout != defaultTimeout);
+
SocketChannel client = sc.accept();
- // non blocking mode, returns null since there are no pending connections.
assertNull(client);
- int soTimeout = ss.getSoTimeout();
- // Harmony fails here.
- assertEquals(SO_TIMEOUT, soTimeout);
+ // Confirm the timeout was unchanged.
+ assertEquals(nonDefaultTimeout, ss.getSoTimeout());
} finally {
sc.close();
}
@@ -563,15 +701,13 @@ public class ServerSocketChannelTest extends TestCase {
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
+ } catch (IllegalBlockingModeException expected) {
}
serverChannel.close();
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
+ } catch (IllegalBlockingModeException expected) {
}
}
@@ -585,15 +721,13 @@ public class ServerSocketChannelTest extends TestCase {
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
+ } catch (IllegalBlockingModeException expected) {
}
serverChannel.close();
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
+ } catch (IllegalBlockingModeException expected) {
}
}
@@ -603,20 +737,18 @@ public class ServerSocketChannelTest extends TestCase {
public void test_socket_accept_Nonblocking_Bound() throws IOException {
// regression test for Harmony-748
serverChannel.configureBlocking(false);
+ serverChannel.socket().bind(null);
ServerSocket gotSocket = serverChannel.socket();
- gotSocket.bind(localAddr1);
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
+ } catch (IllegalBlockingModeException expected) {
}
serverChannel.close();
try {
gotSocket.accept();
fail("Should throw a ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
+ } catch (ClosedChannelException expected) {
}
}
@@ -626,25 +758,23 @@ public class ServerSocketChannelTest extends TestCase {
public void test_socket_accept_Blocking_Bound() throws IOException {
// regression test for Harmony-748
serverChannel.configureBlocking(true);
- ServerSocket gotSocket = serverChannel.socket();
- gotSocket.bind(localAddr1);
+ serverChannel.socket().bind(null);
serverChannel.close();
try {
- gotSocket.accept();
+ serverChannel.socket().accept();
fail("Should throw a ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
+ } catch (ClosedChannelException expected) {
}
}
/**
* Regression test for HARMONY-4961
*/
public void test_socket_getLocalPort() throws IOException {
- serverChannel.socket().bind(localAddr1);
- clientChannel.connect(localAddr1);
+ serverChannel.socket().bind(null);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
SocketChannel myChannel = serverChannel.accept();
int port = myChannel.socket().getLocalPort();
- assertEquals(localAddr1.getPort(), port);
+ assertEquals(serverChannel.socket().getLocalPort(), port);
myChannel.close();
clientChannel.close();
serverChannel.close();
@@ -674,8 +804,7 @@ public class ServerSocketChannelTest extends TestCase {
try {
serverChannel.accept();
fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // expected
+ } catch (AsynchronousCloseException expected) {
}
serverChannel.close();
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SinkChannelTest.java
index 9e96fad..32f59c5 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SinkChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.InetAddress;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java
index 7325ba1..51a8cff 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.io.InputStream;
@@ -41,9 +41,7 @@ import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException;
import java.nio.channels.spi.SelectorProvider;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/**
* Tests for SocketChannel and its default implementation.
@@ -53,7 +51,6 @@ public class SocketChannelTest extends TestCase {
private static final int CAPACITY_NORMAL = 200;
private InetSocketAddress localAddr1;
-
private InetSocketAddress localAddr2;
private SocketChannel channel1;
@@ -70,13 +67,13 @@ public class SocketChannelTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
- this.localAddr1 = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
- this.localAddr2 = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
this.channel1 = SocketChannel.open();
this.channel2 = SocketChannel.open();
- this.server1 = new ServerSocket(localAddr1.getPort());
+ this.server1 = new ServerSocket(0);
+ this.localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+
+ this.server2 = new ServerSocket(0);
+ this.localAddr2 = new InetSocketAddress("127.0.0.1", server2.getLocalPort());
}
protected void tearDown() throws Exception {
@@ -148,14 +145,79 @@ public class SocketChannelTest extends TestCase {
* Test method for 'java.nio.channels.SocketChannel.open(SocketAddress)'
*/
public void testOpenSocketAddress_Null() throws IOException {
- SocketChannel channel1IP = null;
try {
- channel1IP = SocketChannel.open(null);
+ SocketChannel.open(null);
fail("Should throw an IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
}
- assertNull(channel1IP);
+ }
+
+ public void testBind_Null() throws Exception {
+ assertNull(channel1.socket().getLocalSocketAddress());
+
+ channel1.socket().bind(null);
+
+ InetSocketAddress localAddress = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
+ assertTrue(localAddress.getAddress().isAnyLocalAddress());
+ assertTrue(localAddress.getPort() > 0);
+ }
+
+ public void testBind_Failure() throws Exception {
+ assertNull(channel1.socket().getLocalSocketAddress());
+
+ try {
+ // Bind to a local address that is in use
+ channel1.socket().bind(localAddr1);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testBind_Closed() throws Exception {
+ channel1.close();
+
+ try {
+ channel1.socket().bind(null);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testBind_explicitPort() throws Exception {
+ ServerSocketChannel portPickingChannel = ServerSocketChannel.open();
+ // Have the OS find a free port.
+ portPickingChannel.socket().bind(null);
+ InetSocketAddress address = (InetSocketAddress) portPickingChannel.socket().getLocalSocketAddress();
+ assertTrue(address.getPort() > 0);
+ portPickingChannel.close();
+
+ // There is a risk of flakiness here if the port is allocated to something else between
+ // close() and bind().
+ InetSocketAddress bindAddress = new InetSocketAddress("localhost", address.getPort());
+ // Allow the socket to bind to a port we know is already in use.
+ channel1.socket().setReuseAddress(true);
+ channel1.socket().bind(bindAddress);
+
+ InetSocketAddress boundAddress = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
+ assertEquals(bindAddress.getHostName(), boundAddress.getHostName());
+ assertEquals(bindAddress.getPort(), boundAddress.getPort());
+ }
+
+ public void test_getLocalSocketAddress_afterClose() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ assertNull(sc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ sc.socket().bind(bindAddr);
+
+ assertNotNull(sc.socket().getLocalSocketAddress());
+
+ sc.close();
+
+ assertFalse(sc.isOpen());
+
+ sc.socket().getLocalSocketAddress();
}
/*
@@ -166,8 +228,7 @@ public class SocketChannelTest extends TestCase {
MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
MockSocketChannel testMSChannel = new MockSocketChannel(
SelectorProvider.provider());
- ServerSocket testServer = new ServerSocket(Support_PortManager
- .getNextPort());
+ ServerSocket testServer = new ServerSocket(0);
try {
try {
this.channel1.read(byteBuf);
@@ -182,8 +243,7 @@ public class SocketChannelTest extends TestCase {
} catch (NotYetConnectedException e) {
// correct
}
- long readNum = CAPACITY_NORMAL;
- readNum = testMSChannel.read(byteBuf);
+ long readNum = testMSChannel.read(byteBuf);
assertEquals(0, readNum);
readNum = CAPACITY_NORMAL;
readNum = testMSChannelnull.read(byteBuf);
@@ -277,6 +337,7 @@ public class SocketChannelTest extends TestCase {
public void testSocket_BasicStatusBeforeConnect() throws IOException {
assertFalse(this.channel1.isConnected());// not connected
Socket s1 = this.channel1.socket();
+ assertSocketBeforeBind(s1);
assertSocketBeforeConnect(s1);
Socket s2 = this.channel1.socket();
// same
@@ -300,12 +361,15 @@ public class SocketChannelTest extends TestCase {
assertFalse(this.channel1.isConnected());// not connected
this.channel1.configureBlocking(false);
boolean connected = channel1.connect(localAddr1);
- Socket s1 = null;
- Socket s2 = null;
+ Socket s1;
+ Socket s2;
if (!connected) {
assertFalse(this.channel1.isConnected());
assertTrue(this.channel1.isConnectionPending());
s1 = this.channel1.socket();
+ // A connect() causes an implicit bind()
+ assertSocketAfterImplicitBind(s1);
+
// status of not connected
assertSocketBeforeConnect(s1);
s2 = this.channel1.socket();
@@ -400,11 +464,10 @@ public class SocketChannelTest extends TestCase {
public void testSocket_getLocalAddress() throws Exception {
Socket socket = channel1.socket();
- assertNotNull(socket.getLocalAddress());
channel1.connect(localAddr1);
- assertNotNull(socket.getLocalAddress());
+ assertNotNull(socket.getLocalSocketAddress());
}
public void testSocket_getLocalSocketAddress() throws Exception {
@@ -433,8 +496,26 @@ public class SocketChannelTest extends TestCase {
assertTrue(socket.getLocalPort() != -1);
}
- private void assertSocketBeforeConnect(Socket s) throws IOException {
+ private void assertSocketBeforeBind(Socket s) {
assertFalse(s.isBound());
+ assertTrue(s.getLocalAddress().isAnyLocalAddress());
+ // RI fails here. RI returns 0 while spec says unbound socket should
+ // return -1.
+ assertEquals(-1, s.getLocalPort());
+ assertNull(s.getLocalSocketAddress());
+ }
+
+ private void assertSocketAfterImplicitBind(Socket s) throws IOException {
+ assertTrue(s.isBound());
+ assertTrue(s.getLocalAddress().isLoopbackAddress());
+ assertTrue(s.getLocalPort() > 0);
+
+ InetSocketAddress localSocketAddress = (InetSocketAddress) s.getLocalSocketAddress();
+ assertTrue(localSocketAddress.getAddress().isLoopbackAddress());
+ assertEquals(s.getLocalPort(), localSocketAddress.getPort());
+ }
+
+ private void assertSocketBeforeConnect(Socket s) throws IOException {
assertFalse(s.isClosed());
assertFalse(s.isConnected());
assertFalse(s.getKeepAlive());
@@ -458,12 +539,7 @@ public class SocketChannelTest extends TestCase {
assertFalse(s.isOutputShutdown());
assertNull(s.getInetAddress());
- assertEquals(s.getLocalAddress().getHostAddress(), "0.0.0.0");
- // RI fails here. RI returns 0 while spec says unbound socket should
- // return -1.
- assertEquals(-1, s.getLocalPort());
assertFalse(s.getReuseAddress());
- assertNull(s.getLocalSocketAddress());
// not connected
assertEquals(0, s.getPort());
@@ -508,7 +584,6 @@ public class SocketChannelTest extends TestCase {
private void assertSocketAction_Block_BeforeConnect(Socket s)
throws IOException {
assertFalse(this.channel1.isConnected());
- this.server2 = new ServerSocket(localAddr2.getPort());
s.connect(localAddr2);
assertTrue(this.channel1.isConnected());
assertTrue(s.isConnected());
@@ -530,7 +605,6 @@ public class SocketChannelTest extends TestCase {
private void assertSocketAction_NonBlock_BeforeConnect(Socket s)
throws IOException {
assertFalse(this.channel1.isConnected());
- this.server2 = new ServerSocket(localAddr2.getPort());
try {
s.connect(localAddr2);
fail("Should throw IllegalBlockingModeException");
@@ -1419,8 +1493,10 @@ public class SocketChannelTest extends TestCase {
private void ensureServerOpen() throws IOException {
ensureServerClosed();
- this.server1 = new ServerSocket(localAddr1.getPort());
- this.server2 = new ServerSocket(localAddr2.getPort());
+ this.server1 = new ServerSocket(0);
+ this.localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+ this.server2 = new ServerSocket(0);
+ this.localAddr2 = new InetSocketAddress("127.0.0.1", server2.getLocalPort());
assertTrue(this.server1.isBound());
assertTrue(this.server2.isBound());
}
@@ -1624,8 +1700,6 @@ public class SocketChannelTest extends TestCase {
public void testCFII_Data_FinishConnect_AddrSetServerStartLater()
throws IOException, InterruptedException {
ensureServerClosed();
- java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
- writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
this.channel1.configureBlocking(false);
try {
SocketChannel.open(localAddr1);
@@ -1694,8 +1768,6 @@ public class SocketChannelTest extends TestCase {
public void testCFII_Data_FinishConnect_ServerStartLater()
throws IOException {
ensureServerClosed();
- java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
- writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
this.channel1.configureBlocking(true);
try {
this.channel1.finishConnect();
@@ -1794,7 +1866,7 @@ public class SocketChannelTest extends TestCase {
ServerSocket serversocket = theServerChannel.socket();
serversocket.setReuseAddress(true);
// Bind the socket
- serversocket.bind(address);
+ theServerChannel.socket().bind(address);
boolean doneNonBlockingConnect = false;
// Loop so that we make sure we're definitely testing finishConnect()
@@ -1846,7 +1918,7 @@ public class SocketChannelTest extends TestCase {
ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
int totalCount = 0;
- int count = 0;
+ int count;
long startTime = System.currentTimeMillis();
// use SocketChannel.read to read data
while (totalCount <= CAPACITY_NORMAL) {
@@ -1890,7 +1962,7 @@ public class SocketChannelTest extends TestCase {
channel1.configureBlocking(false);
ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
int totalCount = 0;
- int count = 0;
+ int count;
long startTime = System.currentTimeMillis();
// use SocketChannel.read to read data
while (totalCount <= CAPACITY_NORMAL) {
@@ -2115,8 +2187,7 @@ public class SocketChannelTest extends TestCase {
ByteBuffer buffer = ByteBuffer.allocateDirect(128);
ServerSocketChannel server = ServerSocketChannel.open();
- server.socket().bind(
- new InetSocketAddress(InetAddress.getLocalHost(), 0), 5);
+ server.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), 0), 5);
Socket client = new Socket(InetAddress.getLocalHost(), server.socket()
.getLocalPort());
client.setTcpNoDelay(false);
@@ -2270,7 +2341,7 @@ public class SocketChannelTest extends TestCase {
// note: blocking-mode will make the read process endless!
this.channel1.configureBlocking(false);
try {
- channel1.read(null, 0, 0);
+ channel1.read(null, 0, 1);
fail("Should throw NPE");
} catch (NullPointerException e) {
// correct
@@ -2279,7 +2350,7 @@ public class SocketChannelTest extends TestCase {
if (tryFinish()) {
try {
- channel1.read(null, 0, 0);
+ channel1.read(null, 0, 1);
fail("Should throw NPE");
} catch (NullPointerException e) {
// correct
@@ -2610,7 +2681,7 @@ public class SocketChannelTest extends TestCase {
channel1.configureBlocking(isBlocking);
long startTime = System.currentTimeMillis();
long totalRead = 0;
- long countRead = 0;
+ long countRead;
while (totalRead <= CAPACITY_NORMAL * 2) {
countRead = channel1.read(readContents, 0, 2);
@@ -2690,7 +2761,7 @@ public class SocketChannelTest extends TestCase {
InputStream in = acceptedSocket.getInputStream();
byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1];
int totalCount = 0;
- int count = 0;
+ int count;
// if the channel could not finish reading in TIMEOUT ms, the test
// fails. It is used to guarantee the test never hangs even if there
// are bugs of SocketChannel implementation.
@@ -2734,9 +2805,9 @@ public class SocketChannelTest extends TestCase {
*/
public void test_writev() throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer[] buf = { ByteBuffer.allocate(10), ByteBuffer.allocateDirect(20) };
@@ -2851,7 +2922,7 @@ public class SocketChannelTest extends TestCase {
client.write(buffers);
client.close();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
- while (EOF != worker.read(readBuffer)) {};
+ while (EOF != worker.read(readBuffer)) {}
readBuffer.flip();
Buffer expected = ByteBuffer.allocate(1024).put(data).put(data).flip();
assertEquals(expected, readBuffer);
@@ -2894,7 +2965,7 @@ public class SocketChannelTest extends TestCase {
client.write(buffers);
client.close();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
- while (EOF != worker.read(readBuffer)) {};
+ while (EOF != worker.read(readBuffer)) {}
readBuffer.flip();
assertEquals(ByteBuffer.wrap(data), readBuffer);
@@ -2936,7 +3007,7 @@ public class SocketChannelTest extends TestCase {
// Read what we wrote and check it
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
- while (EOF != worker.read(readBuffer)) {};
+ while (EOF != worker.read(readBuffer)) {}
readBuffer.flip();
assertEquals(ByteBuffer.wrap(data), readBuffer);
@@ -2962,32 +3033,27 @@ public class SocketChannelTest extends TestCase {
try {
client.write((ByteBuffer[]) null);
fail("Should throw a NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
try {
client.write((ByteBuffer[]) null, 0, 0);
fail("Should throw a NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
try {
client.write((ByteBuffer[]) null, 1, 0);
fail("Should throw a NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
try {
client.write((ByteBuffer[]) null, 0, 1);
fail("Should throw a NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
try {
client.write((ByteBuffer[]) null, 1, 1);
fail("Should throw a NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
ByteBuffer[] buffers = new ByteBuffer[1];
@@ -3059,9 +3125,9 @@ public class SocketChannelTest extends TestCase {
throws Exception {
// regression 1 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
ssc.accept().close();
ByteBuffer[] buf = { ByteBuffer.allocate(10) };
assertEquals(-1, sc.read(buf, 0, 1));
@@ -3075,16 +3141,15 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_write_ByteBufferII() throws Exception {
// regression 2 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer[] buf = { ByteBuffer.allocate(10), null };
try {
sc.write(buf, 0, 2);
fail("should throw NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
ssc.close();
sc.close();
@@ -3098,9 +3163,9 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
// regression 3 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
ssc.accept();
ByteBuffer[] buf = new ByteBuffer[2];
buf[0] = ByteBuffer.allocate(1);
@@ -3108,8 +3173,7 @@ public class SocketChannelTest extends TestCase {
try {
sc.read(buf, 0, 2);
fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
ssc.close();
sc.close();
@@ -3121,9 +3185,9 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_write_close() throws Exception {
// regression 4 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer buf = null;
ssc.close();
@@ -3131,8 +3195,7 @@ public class SocketChannelTest extends TestCase {
try {
sc.write(buf);
fail("should throw NPE");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
sock.close();
}
@@ -3147,9 +3210,9 @@ public class SocketChannelTest extends TestCase {
ByteBuffer readBuf = ByteBuffer.allocate(11);
ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes());
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
buf.position(2);
ssc.accept().write(buf);
assertEquals(9, sc.read(readBuf));
@@ -3201,35 +3264,59 @@ public class SocketChannelTest extends TestCase {
fail();
} catch (IllegalBlockingModeException expected) {
}
+
try {
is.read(null);
fail();
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, -1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 0, -1);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 0, 2);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 2, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(null, 0, 0);
fail();
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
}
is.close();
@@ -3238,36 +3325,75 @@ public class SocketChannelTest extends TestCase {
is.read();
fail();
} catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(null);
fail();
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, -1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 0, -1);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 0, 2);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(buf, 2, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
+
try {
is.read(null, 0, 0);
fail();
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
+ } catch (IOException expected) {
+ // Any of these exceptions are possible.
}
}
@@ -3296,12 +3422,12 @@ public class SocketChannelTest extends TestCase {
} catch (IndexOutOfBoundsException expected) {
}
try {
- is.read(buf, 2, 0);
+ is.read(buf, 2, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
try {
- is.read(null, 0, 0);
+ is.read(null, 0, 1);
fail();
} catch (NullPointerException expected) {
}
@@ -3329,12 +3455,12 @@ public class SocketChannelTest extends TestCase {
} catch (IndexOutOfBoundsException expected) {
}
try {
- is.read(buf, 2, 0);
+ is.read(buf, 2, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
try {
- is.read(null, 0, 0);
+ is.read(null, 0, 1);
fail();
} catch (NullPointerException expected) {
}
@@ -3354,32 +3480,55 @@ public class SocketChannelTest extends TestCase {
try {
os.write(null);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, -1, 1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, 0, -1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, 0, 2);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
- os.write(buf, 2, 0);
+ os.write(buf, 2, 1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
- os.write(null, 0, 0);
+ os.write(null, 0, 1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
}
os.close();
@@ -3389,35 +3538,59 @@ public class SocketChannelTest extends TestCase {
fail();
} catch (IllegalBlockingModeException expected) {
}
+
try {
os.write(null);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, -1, 1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, 0, -1);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, 0, 2);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(buf, 2, 0);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (IndexOutOfBoundsException expected) {
+ // Any of these exceptions are possible.
}
+
try {
os.write(null, 0, 0);
fail();
+ } catch (IllegalBlockingModeException expected) {
+ // Any of these exceptions are possible.
} catch (NullPointerException expected) {
+ // Any of these exceptions are possible.
}
}
@@ -3558,40 +3731,47 @@ public class SocketChannelTest extends TestCase {
channel1.write(buffer);
}
- class MockSocketChannel extends SocketChannel{
+ class MockSocketChannel extends SocketChannel {
private boolean isWriteCalled = false;
private boolean isReadCalled = false;
- public MockSocketChannel(SelectorProvider provider){
+ public MockSocketChannel(SelectorProvider provider) {
super(provider);
}
+ @Override
public Socket socket() {
return null;
}
+ @Override
public boolean isConnected() {
return false;
}
+ @Override
public boolean isConnectionPending() {
return false;
}
+ @Override
public boolean connect(SocketAddress address) throws IOException {
return false;
}
+ @Override
public boolean finishConnect() throws IOException {
return false;
}
+ @Override
public int read(ByteBuffer target) throws IOException {
return 0;
}
+ @Override
public long read(ByteBuffer[] targets, int offset, int length) throws IOException {
// Verify that calling read(ByteBuffer[]) leads to the method
// read(ByteBuffer[], int, int) being called with a 0 for the
@@ -3602,10 +3782,12 @@ public class SocketChannelTest extends TestCase {
return 0;
}
+ @Override
public int write(ByteBuffer source) throws IOException {
return 0;
}
+ @Override
public long write(ByteBuffer[] sources, int offset, int length) throws IOException {
// Verify that calling write(ByteBuffer[]) leads to the method
// write(ByteBuffer[], int, int) being called with a 0 for the
@@ -3616,10 +3798,12 @@ public class SocketChannelTest extends TestCase {
return 0;
}
+ @Override
protected void implCloseSelectableChannel() throws IOException {
// empty
}
+ @Override
protected void implConfigureBlocking(boolean blockingMode) throws IOException {
// empty
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SourceChannelTest.java
index 53fdae4..2d45e61 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SourceChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnixSelectorTest.java
index 8995394..59d8ed8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnixSelectorTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
index 827dcd7..cb89964 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.UnresolvedAddressException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
index e032ea4..3b47cd4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels;
+package org.apache.harmony.tests.java.nio.channels;
import java.nio.channels.UnsupportedAddressTypeException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
index 5072dc9..d6eb228 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels.spi;
+package org.apache.harmony.tests.java.nio.channels.spi;
import java.io.IOException;
import java.nio.channels.AsynchronousCloseException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
index b396264..31124ce 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels.spi;
+package org.apache.harmony.tests.java.nio.channels.spi;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
index 1404fc1..e0abf8b 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels.spi;
+package org.apache.harmony.tests.java.nio.channels.spi;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectorTest.java
index 4b39001..6f10b11 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/AbstractSelectorTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels.spi;
+package org.apache.harmony.tests.java.nio.channels.spi;
import java.io.IOException;
import java.nio.channels.IllegalBlockingModeException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/MockAbstractSelector.java
index 6e016b0..aa173d8 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/spi/MockAbstractSelector.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.tests.java.nio.channels.spi;
+package org.apache.harmony.tests.java.nio.channels.spi;
import java.io.IOException;
import java.nio.channels.SelectionKey;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetDecoderTest.java
index a349b9c..989443a 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetTest.java
index f46321e..afd95ee 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCCharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
/**
* Test charset US-ASCII.
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCIICharsetEncoderTest.java
index a85576c..ccaee57 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ASCIICharsetEncoderTest.java
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
+import junit.framework.TestCase;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
@@ -26,78 +27,83 @@ import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
-import junit.framework.TestCase;
-
public class ASCIICharsetEncoderTest extends TestCase {
- // charset for ascii
- private static final Charset cs = Charset.forName("ascii");
- private static final CharsetEncoder encoder = cs.newEncoder();
+ // charset for ascii
+ private final Charset cs = Charset.forName("ascii");
+ private final CharsetEncoder encoder = cs.newEncoder();
private static final int MAXCODEPOINT = 0x7F;
- /*
- * @see CharsetEncoderTest#setUp()
- */
- protected void setUp() throws Exception {
+
+ /*
+ * @see CharsetEncoderTest#setUp()
+ */
+ protected void setUp() throws Exception {
+ }
+
+ /*
+ * @see CharsetEncoderTest#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ }
+
+ public void testCanEncodeCharSequence() {
+ // normal case for ascCS
+ assertTrue(encoder.canEncode("\u0077"));
+ assertFalse(encoder.canEncode("\uc2a3"));
+ assertFalse(encoder.canEncode("\ud800\udc00"));
+ try {
+ encoder.canEncode(null);
+ } catch (NullPointerException e) {
+ }
+ assertTrue(encoder.canEncode(""));
+ }
+
+ public void testCanEncodeSurrogate() {
+ assertFalse(encoder.canEncode('\ud800'));
+ assertFalse(encoder.canEncode("\udc00"));
}
- /*
- * @see CharsetEncoderTest#tearDown()
- */
- protected void tearDown() throws Exception {
+ public void testCanEncodechar() throws CharacterCodingException {
+ assertTrue(encoder.canEncode('\u0077'));
+ assertFalse(encoder.canEncode('\uc2a3'));
}
- public void testCanEncodeCharSequence() {
- // normal case for ascCS
- assertTrue(encoder.canEncode("\u0077"));
- assertFalse(encoder.canEncode("\uc2a3"));
- assertFalse(encoder.canEncode("\ud800\udc00"));
- try {
- encoder.canEncode(null);
- } catch (NullPointerException e) {
- }
- assertTrue(encoder.canEncode(""));
- }
-
- public void testCanEncodeSurrogate () {
- assertFalse(encoder.canEncode('\ud800'));
- assertFalse(encoder.canEncode("\udc00"));
- }
-
- public void testCanEncodechar() throws CharacterCodingException {
- assertTrue(encoder.canEncode('\u0077'));
- assertFalse(encoder.canEncode('\uc2a3'));
- }
-
- public void testSpecificDefaultValue() {
- assertEquals(1.0, encoder.averageBytesPerChar(), 0.0);
- assertEquals(1.0, encoder.maxBytesPerChar(), 0.0);
- }
-
- public void testMultiStepEncode() throws CharacterCodingException {
- encoder.onMalformedInput(CodingErrorAction.REPORT);
- encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- try {
- encoder.encode(CharBuffer.wrap("\ud800\udc00"));
- fail("should unmappable");
- } catch (UnmappableCharacterException e) {
- }
- encoder.reset();
- ByteBuffer out = ByteBuffer.allocate(10);
- assertTrue(encoder.encode(CharBuffer.wrap("\ud800"), out, true)
- .isMalformed());
- encoder.flush(out);
- encoder.reset();
- out = ByteBuffer.allocate(10);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(CharBuffer
- .wrap("\ud800"), out, false));
- assertTrue(encoder.encode(CharBuffer.wrap("\udc00"), out, true)
- .isMalformed());
- }
+ public void testSpecificDefaultValue() {
+ assertEquals(1.0, encoder.averageBytesPerChar(), 0.0);
+ assertEquals(1.0, encoder.maxBytesPerChar(), 0.0);
+ }
+
+ public void testMultiStepEncode() throws CharacterCodingException {
+ encoder.onMalformedInput(CodingErrorAction.REPORT);
+ encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
+ try {
+ encoder.encode(CharBuffer.wrap("\ud800\udc00"));
+ fail("should unmappable");
+ } catch (UnmappableCharacterException e) {
+ }
+ encoder.reset();
+ ByteBuffer out = ByteBuffer.allocate(10);
+ assertEquals(CoderResult.UNDERFLOW,
+ encoder.encode(CharBuffer.wrap("\ud800"), out, true));
+ assertTrue(encoder.flush(out).isMalformed());
+ encoder.reset();
+
+ out = ByteBuffer.allocate(10);
+ CharBuffer buffer1 = CharBuffer.wrap("\ud800");
+ CharBuffer buffer2 = CharBuffer.wrap("\udc00");
+ assertSame(CoderResult.UNDERFLOW, encoder.encode(buffer1, out, false));
+ // We consume the entire input buffer because we're in an underflow
+ // state. We can't make a decision on whether the char in this buffer
+ // is unmappable or malformed without looking at the next input buffer.
+ assertEquals(1, buffer1.position());
+ assertTrue(encoder.encode(buffer2, out, true).isUnmappable());
+ assertEquals(0, buffer2.position());
+ }
public void testEncodeMapping() throws CharacterCodingException {
encoder.reset();
- for (int i =0; i <= MAXCODEPOINT; i++) {
+ for (int i = 0; i <= MAXCODEPOINT; i++) {
char[] chars = Character.toChars(i);
CharBuffer cb = CharBuffer.wrap(chars);
ByteBuffer bb = encoder.encode(cb);
@@ -123,7 +129,7 @@ public class ASCIICharsetEncoderTest extends TestCase {
encoder.reset();
encoder.encode(cb, bb, false);
try {
- encoder.encode(cb);
+ encoder.encode(cb);
} catch (IllegalStateException e) {
//expected
}
@@ -291,16 +297,16 @@ public class ASCIICharsetEncoderTest extends TestCase {
CharsetEncoder newEncoder = cs.newEncoder();
// init -> flushed
- {
- ByteBuffer out = ByteBuffer.allocate(0x10);
- try {
- newEncoder.flush(out);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- //expected
- }
+ {
+ ByteBuffer out = ByteBuffer.allocate(0x10);
+ try {
+ newEncoder.flush(out);
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ //expected
+ }
- }
+ }
// reset - > flushed
{
@@ -311,7 +317,7 @@ public class ASCIICharsetEncoderTest extends TestCase {
newEncoder.reset();
try {
newEncoder.flush(out);
- fail("Should throw IllegalStateException");
+ fail("Should throw IllegalStateException");
} catch (IllegalStateException e) {
//expected
}
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/AbstractCharsetTestCase.java
index 0ebf922..536cbce 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/AbstractCharsetTestCase.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharacterCodingExceptionTest.java
index a45938f..aa69959 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharacterCodingExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoder2Test.java
index 1a7b984..1fd61df 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoder2Test.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.IOException;
import java.nio.BufferOverflowException;
@@ -32,7 +32,7 @@ import java.util.Arrays;
import junit.framework.TestCase;
-public class CharsetDecoderTest extends TestCase {
+public class CharsetDecoder2Test extends TestCase {
/**
* @tests java.nio.charset.CharsetDecoder.CharsetDecoder(Charset, float,
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoderTest.java
index 7fbe9e7..e64b2b9 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetDecoderTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoder2Test.java
index c3f1a8d..9884625 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoder2Test.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.IOException;
import java.nio.BufferOverflowException;
@@ -28,7 +28,7 @@ import java.nio.charset.CoderResult;
import junit.framework.TestCase;
-public class CharsetEncoderTest extends TestCase {
+public class CharsetEncoder2Test extends TestCase {
/**
* @tests java.nio.charset.CharsetEncoder.CharsetEncoder(
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoderTest.java
index b63f4d9..5226ed6 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetEncoderTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
@@ -534,16 +534,6 @@ public class CharsetEncoderTest extends TestCase {
assertTrue(encoder.canEncode("\ud800\udb00"));
}
- public void test_canEncode_char_ICUBug() {
- // The RI doesn't allow this, but icu4c does.
- assertTrue(encoder.canEncode('\ud800'));
- }
-
- public void test_canEncode_CharSequence_ICUBug() {
- // The RI doesn't allow this, but icu4c does.
- assertTrue(encoder.canEncode("\ud800"));
- }
-
public void test_canEncode_empty() throws Exception {
assertTrue(encoder.canEncode(""));
}
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetTest.java
index 92f230e..01cf40e 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderMalfunctionErrorTest.java
index 8e6318f..1b343ad 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderMalfunctionErrorTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.charset.CoderMalfunctionError;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderResultTest.java
index 469fc98..dafd21d 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CoderResultTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CodingErrorActionTest.java
index da293bb..7e408de 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/CodingErrorActionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.charset.CodingErrorAction;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetDecoderTest.java
index e129c54..3f19877 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetEncoderTest.java
index ab4eeea..02b9062 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/GBCharsetEncoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetDecoderTest.java
index 82ba9b3..3c8bad4 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetEncoderTest.java
index 8a84938..1c0bb48 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetEncoderTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetTest.java
index 689dbf3..73f6ffd 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/ISOCharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
/**
* Test ISO-8859-1.
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java
index a514aef..f5ba3d1 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.Serializable;
import java.nio.charset.IllegalCharsetNameException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/MalformedInputExceptionTest.java
index f482d9d..d288a4a 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/MalformedInputExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.Serializable;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetDecoderTest.java
index a8e1343..800353d 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetEncoderTest.java
index 68bd2f5..66970de 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetEncoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetTest.java
index 52cee90..e951943 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16BECharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
/**
* Test UTF-16BE.
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetDecoderTest.java
index c5bb408..d47a5c9 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetEncoderTest.java
index 6a42d41..a0f2ac3 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetEncoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetTest.java
index 61dcf49..7ec7d62 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16CharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
/**
* Test UTF-16.
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetDecoderTest.java
index e9a8e56..5caacae 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetEncoderTest.java
index 1e9187d..425dc13 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetEncoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetTest.java
index d795773..a173d06 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF16LECharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
/**
* Test UTF-16LE.
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF8CharsetTest.java
index 8ab8b5c..e6e328e 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTF8CharsetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetDecoderTest.java
index b8ed9fd..80c9dfc 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetDecoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetEncoderTest.java
index d483fcb..1662ae3 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UTFCharsetEncoderTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnmappableCharacterExceptionTest.java
index a6cf6a6..d9de0d4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnmappableCharacterExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.Serializable;
import java.nio.charset.CharacterCodingException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java
index 57ea31c..be52a84 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio_char.tests.java.nio.charset;
+package org.apache.harmony.tests.java.nio.charset;
import java.io.Serializable;
import java.nio.charset.UnsupportedCharsetException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AnnotationTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AnnotationTest.java
new file mode 100644
index 0000000..61b1c17
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AnnotationTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.Annotation;
+
+import junit.framework.TestCase;
+
+public class AnnotationTest extends TestCase {
+
+ public void testAnnotation() {
+ assertNotNull(new Annotation(null));
+ assertNotNull(new Annotation("value"));
+ }
+
+ public void testGetValue() {
+ Annotation a = new Annotation(null);
+ assertNull(a.getValue());
+ a = new Annotation("value");
+ assertEquals("value", a.getValue());
+ }
+
+ public void testToString() {
+ Annotation ant = new Annotation("HelloWorld");
+ assertEquals("toString error.",
+ "java.text.Annotation[value=HelloWorld]",ant.toString());
+ assertNotNull(new Annotation(null).toString());
+ assertNotNull(new Annotation("value").toString());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorAttributeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorAttributeTest.java
new file mode 100644
index 0000000..0cc224a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorAttributeTest.java
@@ -0,0 +1,147 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.text.AttributedCharacterIterator.Attribute;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.NotSerializableException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Locale;
+import java.text.Annotation;
+
+public class AttributedCharacterIteratorAttributeTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.AttributedCharacterIterator$Attribute()
+ */
+ public void test_constructor() {
+ MyAttribute attribute = new MyAttribute("attribute");
+
+ assertEquals("Attribute has wrong name", "attribute", attribute.getExposedName());
+
+ attribute = new MyAttribute(null);
+ assertEquals("Attribute has wrong name", null, attribute.getExposedName());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator.Attribute#equals(Object)
+ */
+ public void test_equals() {
+
+ assertTrue(Attribute.LANGUAGE.equals(Attribute.LANGUAGE));
+
+ assertFalse(Attribute.LANGUAGE.equals(Attribute.READING));
+
+ MyAttribute attribute = new MyAttribute("test");
+
+ assertTrue(attribute.equals(attribute));
+
+ /* this implementation of equals should only return true
+ * if the same objects */
+ assertFalse(attribute.equals(new MyAttribute("test")));
+
+ attribute = new MyAttribute(null);
+ assertFalse(attribute.equals(new MyAttribute(null)));
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator$Attribute#readResolve()
+ */
+ public void test_readResolve() {
+ // test for method java.lang.Object readResolve()
+
+ ObjectOutputStream out = null;
+ ObjectInputStream in = null;
+ try {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ out = new ObjectOutputStream(bytes);
+
+ AttributedCharacterIterator.Attribute dattribute, dattribute2;
+ MyAttribute attribute;
+
+ // a regular instance of DateFormat.Field
+ dattribute = AttributedCharacterIterator.Attribute.LANGUAGE;
+
+ // a subclass instance with null name
+ attribute = new MyAttribute(null);
+
+ out.writeObject(dattribute);
+ try {
+ out.writeObject(attribute);
+ } catch (NotSerializableException e) {
+ }
+
+ in = new ObjectInputStream(new ByteArrayInputStream(bytes
+ .toByteArray()));
+
+ try {
+ dattribute2 = (AttributedCharacterIterator.Attribute) in.readObject();
+ assertSame("resolved incorrectly", dattribute, dattribute2);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException: " + e);
+ }
+
+ } catch (IOException e) {
+ fail("unexpected IOException" + e);
+ } catch (ClassNotFoundException e) {
+ fail("unexpected ClassNotFoundException" + e);
+ } finally {
+ try {
+ if (out != null)
+ out.close();
+ if (in != null)
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator$Attribute#LANGUAGE
+ * java.text.AttributedCharacterIterator$Attribute#READING
+ * java.text.AttributedCharacterIterator$Attribute#INPUT_METHOD_SEGMENT
+ */
+ public void test_fields() {
+
+ // Just check that the fields are accessible as all
+ // methods are protected
+ Attribute language = Attribute.LANGUAGE;
+ Attribute reading = Attribute.READING;
+ Attribute inputMethodSegment = Attribute.INPUT_METHOD_SEGMENT;
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+
+ class MyAttribute extends AttributedCharacterIterator.Attribute {
+ protected MyAttribute(String name) {
+ super(name);
+ }
+
+ public Object getExposedName() {
+ return this.getName();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorTest.java
new file mode 100644
index 0000000..12164bc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedCharacterIteratorTest.java
@@ -0,0 +1,178 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.text.AttributedString;
+import java.text.CharacterIterator;
+
+public class AttributedCharacterIteratorTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#current()
+ */
+ public void test_current() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ assertEquals("Wrong first", 'T', it.current());
+ it.next();
+ assertEquals("Wrong second", 'e', it.current());
+ for (int i = 0; i < 9; i++)
+ it.next();
+ assertEquals("Wrong last", 'g', it.current());
+ it.next();
+ assertTrue("Wrong final", it.current() == CharacterIterator.DONE);
+
+ it = attrString.getIterator(null, 2, 8);
+ assertEquals("Wrong first2", 's', it.current());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#first()
+ */
+ public void test_first() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ assertEquals("Wrong first1", 'T', it.first());
+ it = attrString.getIterator(null, 0, 3);
+ assertEquals("Wrong first2", 'T', it.first());
+ it = attrString.getIterator(null, 2, 8);
+ assertEquals("Wrong first3", 's', it.first());
+ it = attrString.getIterator(null, 11, 11);
+ assertTrue("Wrong first4", it.first() == CharacterIterator.DONE);
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#getBeginIndex()
+ */
+ public void test_getBeginIndex() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator(null, 2, 6);
+ assertEquals("Wrong begin index", 2, it.getBeginIndex());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#getEndIndex()
+ */
+ public void test_getEndIndex() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator(null, 2, 6);
+ assertEquals("Wrong begin index", 6, it.getEndIndex());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#getIndex()
+ */
+ public void test_getIndex() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ assertEquals("Wrong first", 0, it.getIndex());
+ it.next();
+ assertEquals("Wrong second", 1, it.getIndex());
+ for (int i = 0; i < 9; i++)
+ it.next();
+ assertEquals("Wrong last", 10, it.getIndex());
+ it.next();
+ assertEquals("Wrong final", 11, it.getIndex());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#last()
+ */
+ public void test_last() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ assertEquals("Wrong last1", 'g', it.last());
+ it = attrString.getIterator(null, 0, 3);
+ assertEquals("Wrong last2", 's', it.last());
+ it = attrString.getIterator(null, 2, 8);
+ assertEquals("Wrong last3", 'r', it.last());
+ it = attrString.getIterator(null, 0, 0);
+ assertTrue("Wrong last4", it.last() == CharacterIterator.DONE);
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#next()
+ */
+ public void test_next() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ assertEquals("Wrong first", 'e', it.next());
+ for (int i = 0; i < 8; i++)
+ it.next();
+ assertEquals("Wrong last", 'g', it.next());
+ assertTrue("Wrong final", it.next() == CharacterIterator.DONE);
+
+ it = attrString.getIterator(null, 2, 8);
+ assertEquals("Wrong first2", 't', it.next());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#previous()
+ */
+ public void test_previous() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ it.setIndex(11);
+ assertEquals("Wrong first", 'g', it.previous());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#setIndex(int)
+ */
+ public void test_setIndexI() {
+ String test = "Test 23ring";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ it.setIndex(5);
+ assertEquals("Wrong first", '2', it.current());
+ }
+
+ /**
+ * @tests java.text.AttributedCharacterIterator#getRunLimit(java.text.AttributedCharacterIterator$Attribute)
+ */
+ public void test_getRunLimitLjava_text_AttributedCharacterIterator$Attribute() {
+ AttributedString as = new AttributedString("test");
+ as.addAttribute(AttributedCharacterIterator.Attribute.LANGUAGE, "a", 2,
+ 3);
+ AttributedCharacterIterator it = as.getIterator();
+ assertEquals("non-null value limit",
+ 2, it.getRunLimit(AttributedCharacterIterator.Attribute.LANGUAGE));
+
+ as = new AttributedString("test");
+ as.addAttribute(AttributedCharacterIterator.Attribute.LANGUAGE, null,
+ 2, 3);
+ it = as.getIterator();
+ assertEquals("null value limit",
+ 4, it.getRunLimit(AttributedCharacterIterator.Attribute.LANGUAGE));
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedStringTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedStringTest.java
new file mode 100644
index 0000000..a0a4e16
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/AttributedStringTest.java
@@ -0,0 +1,179 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.text.AttributedString;
+import java.text.CharacterIterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.WeakHashMap;
+
+public class AttributedStringTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.AttributedString#AttributedString(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ String test = "Test string";
+ AttributedString attrString = new AttributedString(test);
+ AttributedCharacterIterator it = attrString.getIterator();
+ StringBuffer buf = new StringBuffer();
+ buf.append(it.first());
+ char ch;
+ while ((ch = it.next()) != CharacterIterator.DONE)
+ buf.append(ch);
+ assertTrue("Wrong string: " + buf, buf.toString().equals(test));
+ }
+
+ /**
+ * @tests java.text.AttributedString#AttributedString(AttributedCharacterIterator)
+ */
+ public void test_ConstructorLAttributedCharacterIterator() {
+ //Regression for HARMONY-1354
+ assertNotNull(new AttributedString(new testAttributedCharacterIterator()));
+ }
+ /**
+ * @tests java.text.AttributedString#AttributedString(AttributedCharacterIterator, int, int)
+ */
+ public void test_ConstructorLAttributedCharacterIteratorII() {
+ //Regression for HARMONY-1355
+ assertNotNull(new AttributedString(new testAttributedCharacterIterator(), 0, 0));
+ }
+
+ private class testAttributedCharacterIterator implements AttributedCharacterIterator {
+ public Set getAllAttributeKeys() {
+ return null;
+ }
+ public Object getAttribute(AttributedCharacterIterator.Attribute p) {
+ return null;
+ }
+ public Map getAttributes() {
+ return null;
+ }
+ public int getRunLimit(Set p) {
+ return 0;
+ }
+ public int getRunLimit(AttributedCharacterIterator.Attribute p) {
+ return 0;
+ }
+ public int getRunLimit() {
+ return 0;
+ }
+ public int getRunStart(Set p) {
+ return 0;
+ }
+ public int getRunStart(AttributedCharacterIterator.Attribute p) {
+ return 0;
+ }
+ public int getRunStart() {
+ return 0;
+ }
+ public Object clone() {
+ return null;
+ }
+ public int getIndex() {
+ return 0;
+ }
+ public int getEndIndex() {
+ return 0;
+ }
+ public int getBeginIndex() {
+ return 0;
+ }
+ public char setIndex(int p) {
+ return 'a';
+ }
+ public char previous() {
+ return 'a';
+ }
+ public char next() {
+ return 'a';
+ }
+ public char current() {
+ return 'a';
+ }
+ public char last() {
+ return 'a';
+ }
+ public char first() {
+ return 'a';
+ }
+ }
+
+ public void test_addAttributeLjava_text_AttributedCharacterIterator$AttributeLjava_lang_ObjectII() {
+ AttributedString as = new AttributedString("test");
+ as.addAttribute(AttributedCharacterIterator.Attribute.LANGUAGE, "a", 2,
+ 3);
+ AttributedCharacterIterator it = as.getIterator();
+ assertEquals("non-null value limit", 2, it
+ .getRunLimit(AttributedCharacterIterator.Attribute.LANGUAGE));
+
+ as = new AttributedString("test");
+ as.addAttribute(AttributedCharacterIterator.Attribute.LANGUAGE, null,
+ 2, 3);
+ it = as.getIterator();
+ assertEquals("null value limit", 4, it
+ .getRunLimit(AttributedCharacterIterator.Attribute.LANGUAGE));
+
+ try {
+ as = new AttributedString("test");
+ as.addAttribute(AttributedCharacterIterator.Attribute.LANGUAGE,
+ null, -1, 3);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // regression for Harmony-1244
+ as = new AttributedString("123", new WeakHashMap());
+ try {
+ as.addAttribute(null, new TreeSet(), 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ as.addAttribute(null, new TreeSet(), -1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.AttributedString.addAttribute(AttributedCharacterIterator, Object)
+ */
+ public void test_addAttributeLjava_text_AttributedCharacterIterator$AttributeLjava_lang_Object() {
+ //regression for Harmony-1244
+ AttributedString as = new AttributedString("123", new WeakHashMap());
+ try {
+ as.addAttribute(null, new TreeSet());
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ as.addAttribute(null, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BidiTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BidiTest.java
new file mode 100644
index 0000000..52a29a2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BidiTest.java
@@ -0,0 +1,964 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.AttributedString;
+import java.text.Bidi;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+public class BidiTest extends TestCase {
+
+ Bidi bd;
+
+ public static void assertRunArrayEquals(int[][] expected, Bidi bidi) {
+ assertEquals("different length", expected.length, bidi.getRunCount());
+
+ FORRUN: for (int i = 0; i < bidi.getRunCount(); i++) {
+ int[] butWas = new int[] { bidi.getRunStart(i),
+ bidi.getRunLimit(i), bidi.getRunLevel(i) };
+
+ for (int j = 0; j < expected.length; j++) {
+ if (expected[j][0] == butWas[0] && expected[j][1] == butWas[1]
+ && expected[j][2] == butWas[2]) {
+ continue FORRUN;
+ }
+ }
+ fail("expected [" + i + "] " + " start: " + butWas[0] + " limit: "
+ + butWas[1] + " level: " + butWas[2]);
+ }
+ }
+
+ public void testNullPointerConstructor() {
+ try {
+ bd = new Bidi(null, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(null, 0, new byte[] { 0 }, 0, 0,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(null);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+
+ bd = new Bidi("a".toCharArray(), 0, null, 0, 1,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ }
+
+ public void testBadLength() {
+ try {
+ bd = new Bidi("1".toCharArray(), 0, new byte[] { 0 }, 0, 20,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi("1234567".toCharArray(), 0, new byte[] { 0 }, 0, 4,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi("1234567".toCharArray(), 4, new byte[] { 0, 1, 2, 3,
+ 4 }, 0, 5, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi("1234567".toCharArray(), 0, new byte[] { 0, 1, 2, 3,
+ 4 }, 4, 5, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ //regression for HARMONY-1031
+ try {
+ bd = new Bidi(new char[] { 't','t','t'}, -1, new byte[] { 2, 2 }, 1, 1, 1);
+ fail("should be IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(new char[] { 't','t','t'}, 1, new byte[] { 2, 2 }, -1, 1, 1);
+ fail("should be IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(new char[] { 't','t','t'}, 1, new byte[] { 2, 2 }, 1, -1, 1);
+ fail("should be IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(new char[] {}, 5, new byte[] { 2, 2, 2, 2, 2, 2 }, 8, Integer.MAX_VALUE, 5);
+ fail("should be IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ bd = new Bidi(null, 5, null, 8, Integer.MAX_VALUE, 5);
+ fail("should be IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ bd = new Bidi(new char[] {'o'}, 0, new byte[] { 2, 2}, 2, 0, 2 );
+ }
+
+ public void testEmptyParagraph() {
+ bd = new Bidi("", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(0, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 0, 0 } }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(0, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 0, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+
+ bd = new Bidi("", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(0, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 0, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(0, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 0, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+ }
+
+ public void testSpaceParagraph() {
+ bd = new Bidi(" ", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(" ", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+
+ bd = new Bidi(" ", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(" ", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+ }
+
+ public void testSimpleParagraph() {
+ bd = new Bidi("t", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("t", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("t", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testBadFlags() {
+ bd = new Bidi("", 173);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(0, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 0, 0 }, }, bd);
+ assertTrue(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testBadEmbeddings() {
+ try {
+ bd = new Bidi("".toCharArray(), 0, new byte[] {}, 0, 1,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void testOverrideEmbeddings() {
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -7,
+ (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(7, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 7 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -1,
+ (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -1,
+ (byte) -2, (byte) -3 }, 0, 3, Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -1,
+ (byte) -2, (byte) -3 }, 0, 3, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testDefaultEmbeddings() {
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) 0,
+ (byte) 0, (byte) 0 }, 0, 3, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(2, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 3, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testRelativeEmbeddings() {
+ bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) 1,
+ (byte) 2, (byte) 3 }, 0, 3, Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(4, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 2, 2 }, { 2, 3, 4 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testSimpleHebrewParagraph() {
+ bd = new Bidi("\u05D0", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+
+ bd = new Bidi("\u05D0", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+
+ bd = new Bidi("\u05D0", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertFalse(bd.isMixed());
+ assertTrue(bd.isRightToLeft());
+ }
+
+ public void testSimpleBidiParagraph_1() {
+ bd = new Bidi("\u05D0a", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("\u05D0a", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("\u05D0a", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 0 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("\u05D0a", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testSimpleBidiParagraph_2() {
+ bd = new Bidi("a\u05D0", Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, { 1, 2, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("a\u05D0", Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, { 1, 2, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("a\u05D0", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(0, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 0 }, { 1, 2, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi("a\u05D0", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(2, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(2, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 2 }, { 1, 2, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ /*
+ * spec reads: public static final int DIRECTION_RIGHT_TO_LEFT Constant
+ * indicating base direction is right-to-left. according to that, the method
+ * baseIsLeftToRight() here should return false. however, RI doesn't act so.
+ */
+ public void testRIBug_1() {
+ bd = new Bidi("t", Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ // the base level it the essential cause
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ // this is essentially the same bug as Bug_1
+ public void testRIBug_2() {
+ bd = new Bidi("\u05D0", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(1, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(1, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testComplicatedBidi() {
+ bd = new Bidi("a\u05D0a\"a\u05D0\"\u05D0a",
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(9, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(2, bd.getLevelAt(2));
+ assertEquals(2, bd.getLevelAt(3));
+ assertEquals(2, bd.getLevelAt(4));
+ assertEquals(1, bd.getLevelAt(5));
+ assertEquals(1, bd.getLevelAt(6));
+ assertEquals(1, bd.getLevelAt(7));
+ assertEquals(2, bd.getLevelAt(8));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(5, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 2 }, { 1, 2, 1 },
+ { 2, 5, 2 }, { 5, 8, 1 }, { 8, 9, 2 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testComplicatedOverrideBidi() {
+ bd = new Bidi("a\u05D0a\"a\u05D0\"\u05D0a".toCharArray(), 0,
+ new byte[] { 0, 0, 0, -3, -3, 2, 2, 0, 3 }, 0, 9,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(9, bd.getLength());
+ assertEquals(2, bd.getLevelAt(0));
+ assertEquals(1, bd.getLevelAt(1));
+ assertEquals(2, bd.getLevelAt(2));
+ assertEquals(3, bd.getLevelAt(3));
+ assertEquals(3, bd.getLevelAt(4));
+ assertEquals(3, bd.getLevelAt(5));
+ assertEquals(2, bd.getLevelAt(6));
+ assertEquals(1, bd.getLevelAt(7));
+ assertEquals(4, bd.getLevelAt(8));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(7, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 2 }, { 1, 2, 1 },
+ { 2, 3, 2 }, { 3, 6, 3 }, { 6, 7, 2 }, { 7, 8, 1 },
+ { 8, 9, 4 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testRequiresBidi() {
+ try{
+ Bidi.requiresBidi(null, 0, 0);
+ fail("should throw NullPointerException");
+ }catch (NullPointerException e){
+ // expected
+ }
+
+ try {
+ assertFalse(Bidi.requiresBidi(null, 0, 1));
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("".toCharArray(), 0, 1));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), -1, 1));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 1, -1));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("\u05D0".toCharArray(), 1, -1));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 1, 0));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 7, 7));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 1, Integer.MAX_VALUE));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), Integer.MAX_VALUE, 1));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ assertFalse(Bidi.requiresBidi("".toCharArray(), 0, 0));
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 1, 1));
+ assertFalse(Bidi.requiresBidi("aaa".toCharArray(), 0, 2));
+ assertFalse(Bidi.requiresBidi("\u05D0".toCharArray(), 1, 1));
+ assertTrue(Bidi.requiresBidi("\u05D0".toCharArray(), 0, 1));
+ assertFalse(Bidi.requiresBidi("aa\u05D0a".toCharArray(), 0, 2));
+ assertTrue(Bidi.requiresBidi("aa\u05D0a".toCharArray(), 1, 3));
+ }
+
+ public void testHebrewOverrideEmbeddings() {
+ bd = new Bidi(new char[] { '\u05D0', '\u05D0', '\u05D0' }, 0,
+ new byte[] { (byte) -1, (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { '\u05D0', '\u05D0', '\u05D0' }, 0,
+ new byte[] { (byte) -1, (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { '\u05D0', '\u05D0', '\u05D0' }, 0,
+ new byte[] { (byte) -1, (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_LEFT_TO_RIGHT);
+ assertTrue(bd.baseIsLeftToRight());
+ assertEquals(0, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(0, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+
+ bd = new Bidi(new char[] { '\u05D0', '\u05D0', '\u05D0' }, 0,
+ new byte[] { (byte) -1, (byte) -2, (byte) -3 }, 0, 3,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ assertFalse(bd.baseIsLeftToRight());
+ assertEquals(1, bd.getBaseLevel());
+ assertEquals(3, bd.getLength());
+ assertEquals(1, bd.getLevelAt(0));
+ assertEquals(2, bd.getLevelAt(1));
+ assertEquals(3, bd.getLevelAt(2));
+ assertEquals(1, bd.getLevelAt(1000));
+ assertEquals(3, bd.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 1 }, { 1, 2, 2 },
+ { 2, 3, 3 }, }, bd);
+ assertFalse(bd.isLeftToRight());
+ assertTrue(bd.isMixed());
+ assertFalse(bd.isRightToLeft());
+ }
+
+ public void testCreateLineBidi() {
+ bd = new Bidi("a\u05D0a\u05D0a\u05D0\"\u05D0a".toCharArray(), 0,
+ new byte[] { 0, 0, 0, -3, -3, 2, 2, 0, 3 }, 0, 9,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ Bidi line = bd.createLineBidi(2, 7);
+ assertFalse(line.baseIsLeftToRight());
+ assertEquals(1, line.getBaseLevel());
+ assertEquals(5, line.getLength());
+ assertEquals(2, line.getLevelAt(0));
+ assertEquals(3, line.getLevelAt(1));
+ assertEquals(3, line.getLevelAt(2));
+ assertEquals(3, line.getLevelAt(3));
+ assertEquals(2, line.getLevelAt(4));
+ assertEquals(1, line.getLevelAt(1000));
+ assertEquals(3, line.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 1, 2 }, { 1, 4, 3 },
+ { 4, 5, 2 }, }, line);
+ assertFalse(line.isLeftToRight());
+ assertTrue(line.isMixed());
+ assertFalse(line.isRightToLeft());
+ }
+
+ public void testCreateLineBidiInvalid() {
+ //regression for HARMONY-1050
+ Bidi bidi = new Bidi("str", 1);
+ try {
+ bidi.createLineBidi(-1, 1);
+ fail("Expected IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ bidi.createLineBidi(1, -1);
+ fail("Expected IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ bidi.createLineBidi(-1, -1);
+ fail("Expected IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ bidi.createLineBidi(2, 1);
+ fail("Expected IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ bidi.createLineBidi(2, 2);
+ }catch (IllegalArgumentException e){
+ // Expected
+ }
+
+ try {
+ bidi.createLineBidi(2, 4);
+ fail("Expected IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testIncompatibleLineAlgorithm() {
+ // ICU treat a new line as in the same run, however RI does not
+ bd = new Bidi("aaaaa".toCharArray(), 0,
+ new byte[] { -2, -1, -3, -3, -2 }, 0, 5,
+ Bidi.DIRECTION_RIGHT_TO_LEFT);
+ Bidi line = bd.createLineBidi(1, 4);
+ assertFalse(line.baseIsLeftToRight());
+ assertEquals(1, line.getBaseLevel());
+ assertEquals(3, line.getLength());
+ assertEquals(1, line.getLevelAt(0));
+ assertEquals(1, line.getLevelAt(1));
+ assertEquals(1, line.getLevelAt(2));
+ assertEquals(1, line.getLevelAt(1000));
+ assertEquals(1, line.getRunCount());
+ assertRunArrayEquals(new int[][] { { 0, 3, 1 }, }, line);
+ assertFalse(line.isLeftToRight());
+ assertFalse(line.isMixed());
+ assertTrue(line.isRightToLeft());
+ }
+
+ public void testReorderVisually() {
+ String[] init = new String[] { "a", "b", "c", "d" };
+ String[] s = new String[4];
+
+ System.arraycopy(init, 0, s, 0, s.length);
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 0, s, 0, 4);
+ assertEquals("[c, b, a, d]", Arrays.asList(s).toString());
+
+ System.arraycopy(init, 0, s, 0, s.length);
+ Bidi.reorderVisually(new byte[] { 1, 3 }, 0, s, 1, 2);
+ assertEquals("[a, c, b, d]", Arrays.asList(s).toString());
+
+ System.arraycopy(init, 0, s, 0, s.length);
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 1, s, 1, 2);
+ assertEquals("[a, c, b, d]", Arrays.asList(s).toString());
+
+ System.arraycopy(init, 0, s, 0, s.length);
+ Bidi.reorderVisually(new byte[] { 2, 1, 2, 1 }, 1, s, 0, 3);
+ assertEquals("[c, b, a, d]", Arrays.asList(s).toString());
+
+ System.arraycopy(init, 0, s, 0, s.length);
+ Bidi.reorderVisually(new byte[] { 2, 1, 0, 1 }, 1, s, 0, 3);
+ assertEquals("[a, b, c, d]", Arrays.asList(s).toString());
+ }
+
+ public void testBadReorderVisually() {
+ String[] s = new String[] { "a", "b", "c", "d" };
+
+ try {
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 0, s, 0, 5);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 0, s, -1, 1);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, -1, s, 0, 1);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ Bidi.reorderVisually(null, 0, s, 0, 1);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 0, null, 0, 1);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ Bidi.reorderVisually(new byte[] { 2, 1, 3, 0 }, 1, s, 0, -1);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ }
+
+ public void testGetRuns() {
+ //Regression test for Harmony-1028
+
+ String LTR = "\u0061\u0062";
+ String RTL = "\u05DC\u05DD";
+ String newLine = "\n";
+ String defText = LTR + newLine + RTL + LTR + RTL;
+
+ int[][] expectedRuns = {
+ {0, 3},
+ {3, 5},
+ {5, 7},
+ {7, 9},
+ };
+
+ Bidi bi = new Bidi(defText, 0);
+ final int count = bi.getRunCount();
+ for (int i = 0; i < count; i++) {
+ assertEquals(expectedRuns[i][0], bi.getRunStart(i));
+ assertEquals(expectedRuns[i][1], bi.getRunLimit(i));
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BreakIteratorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BreakIteratorTest.java
new file mode 100644
index 0000000..d12f9ac
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/BreakIteratorTest.java
@@ -0,0 +1,317 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.BreakIterator;
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+public class BreakIteratorTest extends TestCase {
+
+ private static final String TEXT = "a\u0308abc def, gh-12i?jkl.mno?";
+
+ BreakIterator iterator;
+
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ iterator = BreakIterator.getCharacterInstance(Locale.US);
+ }
+
+ public void testConsts() {
+ assertEquals(-1, BreakIterator.DONE);
+ }
+
+ public void testCache() {
+ BreakIterator newOne = BreakIterator.getCharacterInstance(Locale.US);
+ assertNotSame(newOne, iterator);
+ assertEquals(newOne, iterator);
+
+ newOne = BreakIterator.getCharacterInstance();
+ assertEquals(newOne, iterator);
+
+ newOne = BreakIterator.getCharacterInstance(Locale.CHINA);
+ assertEquals(newOne, iterator);
+
+ BreakIterator wordIterator = BreakIterator.getWordInstance();
+ assertFalse(wordIterator.equals(iterator));
+
+ BreakIterator lineIterator = BreakIterator.getLineInstance();
+ assertFalse(lineIterator.equals(iterator));
+
+ BreakIterator senteIterator = BreakIterator.getSentenceInstance();
+ assertFalse(senteIterator.equals(iterator));
+ }
+
+ public void testClone() {
+ BreakIterator cloned = (BreakIterator) iterator.clone();
+ assertNotSame(cloned, iterator);
+ assertEquals(cloned, iterator);
+ }
+
+ public void testCurrent() {
+ assertEquals(0, iterator.current());
+ iterator.setText(TEXT);
+ assertEquals(iterator.first(), iterator.current());
+ }
+
+ public void testFirst() {
+ assertEquals(0, iterator.first());
+ iterator.setText(TEXT);
+ assertEquals(0, iterator.first());
+ }
+
+ public void testFollowing() {
+ try {
+ iterator.following(1);
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ iterator.setText(TEXT);
+ assertEquals(2, iterator.following(1));
+ try {
+ assertEquals(0, iterator.following(-1));
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ assertEquals(BreakIterator.DONE, iterator.following(TEXT.length()));
+ }
+
+ public void testIsBoundary() {
+ try {
+ iterator.isBoundary(2);
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ iterator.setText(TEXT);
+ assertTrue(iterator.isBoundary(2));
+ assertFalse(iterator.isBoundary(1));
+ assertTrue(iterator.isBoundary(0));
+ try {
+ iterator.isBoundary(-1);
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ assertTrue(iterator.isBoundary(TEXT.length()));
+ }
+
+ public void testLast() {
+ assertEquals(0, iterator.last());
+ iterator.setText(TEXT);
+ assertEquals(TEXT.length(), iterator.last());
+ }
+
+ /*
+ * Class under test for int next(int)
+ */
+ public void testNextint() {
+ assertEquals(BreakIterator.DONE, iterator.next(3));
+ iterator.setText(TEXT);
+ assertEquals(4, iterator.next(3));
+ assertEquals(24, iterator.next(20));
+ assertEquals(23, iterator.next(-1));
+ assertEquals(-1, iterator.next(TEXT.length()));
+ }
+
+ public void testPreceding() {
+ try {
+ iterator.preceding(2);
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ iterator.setText(TEXT);
+ assertEquals(0, iterator.preceding(2));
+ assertEquals(2, iterator.preceding(3));
+ assertEquals(16, iterator.preceding(17));
+ assertEquals(17, iterator.preceding(18));
+ assertEquals(18, iterator.preceding(19));
+ try {
+ iterator.preceding(-1);
+ fail("should throw illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ }
+ assertEquals(TEXT.length() - 1, iterator.preceding(TEXT.length()));
+ assertEquals(BreakIterator.DONE, iterator.preceding(0));
+ }
+
+ public void testPrevious() {
+ assertEquals(-1, iterator.previous());
+ iterator.setText(TEXT);
+ assertEquals(-1, iterator.previous());
+ iterator.last();
+ assertEquals(TEXT.length() - 1, iterator.previous());
+ }
+
+ public void testGetAvailableLocales() {
+ Locale[] locales = BreakIterator.getAvailableLocales();
+ assertTrue(locales.length > 0);
+ }
+
+ /*
+ * Class under test for BreakIterator getCharacterInstance()
+ */
+ public void testGetCharacterInstance() {
+ BreakIterator.getCharacterInstance();
+ }
+
+ /*
+ * Class under test for BreakIterator getCharacterInstance(Locale)
+ */
+ public void testGetCharacterInstanceLocale() {
+ BreakIterator it = BreakIterator.getCharacterInstance(Locale.US);
+ BreakIterator it2 = BreakIterator.getCharacterInstance(Locale.CHINA);
+ assertEquals(it, it2);
+ }
+
+ /*
+ * Class under test for BreakIterator getLineInstance()
+ */
+ public void testGetLineInstance() {
+ BreakIterator it = BreakIterator.getLineInstance();
+ assertNotNull(it);
+ }
+
+ /*
+ * Class under test for BreakIterator getLineInstance(Locale)
+ */
+ public void testGetLineInstanceLocale() {
+ BreakIterator it = BreakIterator.getLineInstance(Locale.US);
+ assertNotNull(it);
+ BreakIterator.getLineInstance(new Locale("bad locale"));
+ }
+
+ /*
+ * Class under test for BreakIterator getSentenceInstance()
+ */
+ public void testGetSentenceInstance() {
+ BreakIterator it = BreakIterator.getSentenceInstance();
+ assertNotNull(it);
+ }
+
+ /*
+ * Class under test for BreakIterator getSentenceInstance(Locale)
+ */
+ public void testGetSentenceInstanceLocale() {
+ BreakIterator it = BreakIterator.getSentenceInstance(Locale.US);
+ assertNotNull(it);
+ }
+
+ public void testGetText() {
+ assertEquals(new StringCharacterIterator(""), iterator.getText());
+ iterator.setText(TEXT);
+ assertEquals(new StringCharacterIterator(TEXT), iterator.getText());
+ }
+
+ /*
+ * Class under test for BreakIterator getWordInstance()
+ */
+ public void testGetWordInstance() {
+ BreakIterator it = BreakIterator.getWordInstance();
+ assertNotNull(it);
+ }
+
+ /*
+ * Class under test for BreakIterator getWordInstance(Locale)
+ */
+ public void testGetWordInstanceLocale() {
+ BreakIterator it = BreakIterator.getWordInstance(Locale.US);
+ assertNotNull(it);
+ }
+
+ /*
+ * Class under test for void setText(CharacterIterator)
+ */
+ public void testSetTextCharacterIterator() {
+ try {
+ iterator.setText((CharacterIterator) null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ CharacterIterator it = new StringCharacterIterator("abc");
+ iterator.setText(it);
+ assertSame(it, iterator.getText());
+ }
+
+ /*
+ * Class under test for void setText(String)
+ */
+ public void testSetTextString() {
+ try {
+ iterator.setText((String) null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ iterator.setText("abc");
+ CharacterIterator it = new StringCharacterIterator("abc");
+ assertEquals(it, iterator.getText());
+ }
+
+ public void test_next() {
+ // Regression test for HARMONY-30
+ BreakIterator bi = BreakIterator.getWordInstance(Locale.US);
+ bi.setText("This is the test, WordInstance");
+ int n = bi.first();
+ n = bi.next();
+ assertEquals("Assert 0: next() returns incorrect value ", 4, n);
+
+ assertEquals(BreakIterator.DONE, iterator.next());
+ iterator.setText(TEXT);
+ assertEquals(2, iterator.next());
+ }
+
+ /**
+ * @tests java.text.BreakIterator#getCharacterInstance(Locale)
+ */
+ public void testGetCharacterInstanceLocale_NPE() {
+ // Regression for HARMONY-265
+ try {
+ BreakIterator.getCharacterInstance(null);
+ fail("BreakIterator.getCharacterInstance(null); should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testGetLineInstanceLocale_NPE() {
+ try {
+ BreakIterator.getLineInstance(null);
+ fail("BreakIterator.getLineInstance(null); should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testGetSentenceInstanceLocale_NPE() {
+ try {
+ BreakIterator.getSentenceInstance(null);
+ fail("BreakIterator.getSentenceInstance(null); should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testGetWordInstanceLocale_NPE() {
+ try {
+ BreakIterator.getWordInstance(null);
+ fail("BreakIterator.getWordInstance(null); should throw NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ChoiceFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ChoiceFormatTest.java
new file mode 100644
index 0000000..e4d6bd8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ChoiceFormatTest.java
@@ -0,0 +1,469 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.ChoiceFormat;
+import java.text.FieldPosition;
+import java.text.MessageFormat;
+import java.text.ParsePosition;
+
+import junit.framework.TestCase;
+
+public class ChoiceFormatTest extends TestCase {
+
+ double[] limits = new double[] { 0, 1, ChoiceFormat.nextDouble(1),
+ ChoiceFormat.nextDouble(2) };
+
+ String[] formats = new String[] { "Less than one", "one",
+ "Between one and two", "Greater than two" };
+
+ ChoiceFormat f1 = new ChoiceFormat(limits, formats);
+
+ /**
+ * @tests java.text.ChoiceFormat#ChoiceFormat(double[], java.lang.String[])
+ */
+ public void test_Constructor$D$Ljava_lang_String() {
+ // Test for method java.text.ChoiceFormat(double [], java.lang.String
+ // [])
+ String formattedString;
+ double[] appleLimits = { 1, 2, 3, 4, 5 };
+ String[] appleFormats = { "Tiny Apple", "Small Apple", "Medium Apple",
+ "Large Apple", "Huge Apple" };
+ ChoiceFormat cf = new ChoiceFormat(appleLimits, appleFormats);
+
+ formattedString = cf.format(Double.NEGATIVE_INFINITY);
+ assertTrue("a) Incorrect format returned: " + formattedString,
+ formattedString.equals("Tiny Apple"));
+ formattedString = cf.format(0.5d);
+ assertTrue("b) Incorrect format returned: " + formattedString,
+ formattedString.equals("Tiny Apple"));
+ formattedString = cf.format(1d);
+ assertTrue("c) Incorrect format returned: " + formattedString,
+ formattedString.equals("Tiny Apple"));
+ formattedString = cf.format(1.5d);
+ assertTrue("d) Incorrect format returned: " + formattedString,
+ formattedString.equals("Tiny Apple"));
+ formattedString = cf.format(2d);
+ assertTrue("e) Incorrect format returned: " + formattedString,
+ formattedString.equals("Small Apple"));
+ formattedString = cf.format(2.5d);
+ assertTrue("f) Incorrect format returned: " + formattedString,
+ formattedString.equals("Small Apple"));
+ formattedString = cf.format(3d);
+ assertTrue("g) Incorrect format returned: " + formattedString,
+ formattedString.equals("Medium Apple"));
+ formattedString = cf.format(4d);
+ assertTrue("h) Incorrect format returned: " + formattedString,
+ formattedString.equals("Large Apple"));
+ formattedString = cf.format(5d);
+ assertTrue("i) Incorrect format returned: " + formattedString,
+ formattedString.equals("Huge Apple"));
+ formattedString = cf.format(5.5d);
+ assertTrue("j) Incorrect format returned: " + formattedString,
+ formattedString.equals("Huge Apple"));
+ formattedString = cf.format(6.0d);
+ assertTrue("k) Incorrect format returned: " + formattedString,
+ formattedString.equals("Huge Apple"));
+ formattedString = cf.format(Double.POSITIVE_INFINITY);
+ assertTrue("l) Incorrect format returned: " + formattedString,
+ formattedString.equals("Huge Apple"));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#ChoiceFormat(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.text.ChoiceFormat(java.lang.String)
+ String formattedString;
+ String patternString = "-2#Inverted Orange| 0#No Orange| 0<Almost No Orange| 1#Normal Orange| 2#Expensive Orange";
+ ChoiceFormat cf = new ChoiceFormat(patternString);
+
+ formattedString = cf.format(Double.NEGATIVE_INFINITY);
+ assertTrue("a) Incorrect format returned: " + formattedString,
+ formattedString.equals("Inverted Orange"));
+ formattedString = cf.format(-3);
+ assertTrue("b) Incorrect format returned: " + formattedString,
+ formattedString.equals("Inverted Orange"));
+ formattedString = cf.format(-2);
+ assertTrue("c) Incorrect format returned: " + formattedString,
+ formattedString.equals("Inverted Orange"));
+ formattedString = cf.format(-1);
+ assertTrue("d) Incorrect format returned: " + formattedString,
+ formattedString.equals("Inverted Orange"));
+ formattedString = cf.format(-0);
+ assertTrue("e) Incorrect format returned: " + formattedString,
+ formattedString.equals("No Orange"));
+ formattedString = cf.format(0);
+ assertTrue("f) Incorrect format returned: " + formattedString,
+ formattedString.equals("No Orange"));
+ formattedString = cf.format(0.1);
+ assertTrue("g) Incorrect format returned: " + formattedString,
+ formattedString.equals("Almost No Orange"));
+ formattedString = cf.format(1);
+ assertTrue("h) Incorrect format returned: " + formattedString,
+ formattedString.equals("Normal Orange"));
+ formattedString = cf.format(1.5);
+ assertTrue("i) Incorrect format returned: " + formattedString,
+ formattedString.equals("Normal Orange"));
+ formattedString = cf.format(2);
+ assertTrue("j) Incorrect format returned: " + formattedString,
+ formattedString.equals("Expensive Orange"));
+ formattedString = cf.format(3);
+ assertTrue("k) Incorrect format returned: " + formattedString,
+ formattedString.equals("Expensive Orange"));
+ formattedString = cf.format(Double.POSITIVE_INFINITY);
+ assertTrue("l) Incorrect format returned: " + formattedString,
+ formattedString.equals("Expensive Orange"));
+
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#applyPattern(java.lang.String)
+ */
+ public void test_applyPatternLjava_lang_String() {
+ // Test for method void
+ // java.text.ChoiceFormat.applyPattern(java.lang.String)
+ ChoiceFormat f = (ChoiceFormat) f1.clone();
+ f.applyPattern("0#0|1#1");
+ assertTrue("Incorrect limits", java.util.Arrays.equals(f.getLimits(),
+ new double[] { 0, 1 }));
+ assertTrue("Incorrect formats", java.util.Arrays.equals(f.getFormats(),
+ new String[] { "0", "1" }));
+
+ //Regression for Harmony 540
+ double[] choiceLimits = { -1, 0, 1, ChoiceFormat.nextDouble(1) };
+ String[] choiceFormats = { "is negative", "is zero or fraction",
+ "is one", "is more than 1" };
+
+ f = new ChoiceFormat("");
+ f.applyPattern("-1#is negative|0#is zero or fraction|1#is one|1<is more than 1");
+ assertTrue("Incorrect limits", java.util.Arrays.equals(f.getLimits(),
+ choiceLimits));
+ assertTrue("Incorrect formats", java.util.Arrays.equals(f.getFormats(),
+ choiceFormats));
+
+ f = new ChoiceFormat("");
+ try {
+ f.applyPattern("-1#is negative|0#is zero or fraction|-1#is one|1<is more than 1");
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ f = new ChoiceFormat("");
+ try {
+ f.applyPattern("-1is negative|0#is zero or fraction|1#is one|1<is more than 1");
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ f = new ChoiceFormat("");
+ f.applyPattern("-1<is negative|0#is zero or fraction|1#is one|1<is more than 1");
+ choiceLimits[0] = ChoiceFormat.nextDouble(-1);
+ assertTrue("Incorrect limits", java.util.Arrays.equals(f.getLimits(),
+ choiceLimits));
+ assertTrue("Incorrect formats", java.util.Arrays.equals(f.getFormats(),
+ choiceFormats));
+
+ f = new ChoiceFormat("");
+ f.applyPattern("-1#is negative|0#is zero or fraction|1#is one|1<is more than 1");
+ String str = "org.apache.harmony.tests.java.text.ChoiceFormat";
+ f.applyPattern(str);
+ String ptrn = f.toPattern();
+ assertEquals("Return value should be empty string for invalid pattern",
+ 0, ptrn.length());
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.text.ChoiceFormat.clone()
+ ChoiceFormat f = (ChoiceFormat) f1.clone();
+ assertTrue("Not equal", f.equals(f1));
+ f.setChoices(new double[] { 0, 1, 2 }, new String[] { "0", "1", "2" });
+ assertTrue("Equal", !f.equals(f1));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.text.ChoiceFormat.equals(java.lang.Object)
+
+ String patternString = "-2#Inverted Orange| 0#No Orange| 0<Almost No Orange| 1#Normal Orange| 2#Expensive Orange";
+ double[] appleLimits = { 1, 2, 3, 4, 5 };
+ String[] appleFormats = { "Tiny Apple", "Small Apple", "Medium Apple",
+ "Large Apple", "Huge Apple" };
+ double[] orangeLimits = { -2, 0, ChoiceFormat.nextDouble(0), 1, 2 };
+ String[] orangeFormats = { "Inverted Orange", "No Orange",
+ "Almost No Orange", "Normal Orange", "Expensive Orange" };
+
+ ChoiceFormat appleChoiceFormat = new ChoiceFormat(appleLimits,
+ appleFormats);
+ ChoiceFormat orangeChoiceFormat = new ChoiceFormat(orangeLimits,
+ orangeFormats);
+ ChoiceFormat orangeChoiceFormat2 = new ChoiceFormat(patternString);
+ ChoiceFormat hybridChoiceFormat = new ChoiceFormat(appleLimits,
+ orangeFormats);
+
+ assertTrue("Apples should not equal oranges", !appleChoiceFormat
+ .equals(orangeChoiceFormat));
+ assertTrue("Different limit list--should not appear as equal",
+ !orangeChoiceFormat.equals(hybridChoiceFormat));
+ assertTrue("Different format list--should not appear as equal",
+ !appleChoiceFormat.equals(hybridChoiceFormat));
+ assertTrue("Should be equal--identical format", appleChoiceFormat
+ .equals(appleChoiceFormat));
+ assertTrue("Should be equals--same limits, same formats",
+ orangeChoiceFormat.equals(orangeChoiceFormat2));
+
+ ChoiceFormat f2 = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ assertTrue("Not equal", f1.equals(f2));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#format(double, java.lang.StringBuffer,
+ * java.text.FieldPosition)
+ */
+ public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() {
+ // Test for method java.lang.StringBuffer
+ // java.text.ChoiceFormat.format(double, java.lang.StringBuffer,
+ // java.text.FieldPosition)
+ FieldPosition field = new FieldPosition(0);
+ StringBuffer buf = new StringBuffer();
+ String r = f1.format(-1, buf, field).toString();
+ assertEquals("Wrong choice for -1", "Less than one", r);
+ buf.setLength(0);
+ r = f1.format(0, buf, field).toString();
+ assertEquals("Wrong choice for 0", "Less than one", r);
+ buf.setLength(0);
+ r = f1.format(1, buf, field).toString();
+ assertEquals("Wrong choice for 1", "one", r);
+ buf.setLength(0);
+ r = f1.format(2, buf, field).toString();
+ assertEquals("Wrong choice for 2", "Between one and two", r);
+ buf.setLength(0);
+ r = f1.format(3, buf, field).toString();
+ assertEquals("Wrong choice for 3", "Greater than two", r);
+
+ // Regression test for HARMONY-1081
+ assertEquals(0, new ChoiceFormat("|").format(Double.NaN, new StringBuffer(), new FieldPosition(6)).length());
+ assertEquals(0, new ChoiceFormat("|").format(1, new StringBuffer(), new FieldPosition(6)).length());
+ assertEquals("Less than one", f1.format(Double.NaN, new StringBuffer(), field).toString());
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#format(long, java.lang.StringBuffer,
+ * java.text.FieldPosition)
+ */
+ public void test_formatJLjava_lang_StringBufferLjava_text_FieldPosition() {
+ // Test for method java.lang.StringBuffer
+ // java.text.ChoiceFormat.format(long, java.lang.StringBuffer,
+ // java.text.FieldPosition)
+ FieldPosition field = new FieldPosition(0);
+ StringBuffer buf = new StringBuffer();
+ String r = f1.format(0.5, buf, field).toString();
+ assertEquals("Wrong choice for 0.5", "Less than one", r);
+ buf.setLength(0);
+ r = f1.format(1.5, buf, field).toString();
+ assertEquals("Wrong choice for 1.5", "Between one and two", r);
+ buf.setLength(0);
+ r = f1.format(2.5, buf, field).toString();
+ assertEquals("Wrong choice for 2.5", "Greater than two", r);
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#getFormats()
+ */
+ public void test_getFormats() {
+ // Test for method java.lang.Object []
+ // java.text.ChoiceFormat.getFormats()
+ String[] orgFormats = (String[]) formats.clone();
+ String[] f = (String[]) f1.getFormats();
+ assertTrue("Wrong formats", f.equals(formats));
+ f[0] = "Modified";
+ assertTrue("Formats copied", !f.equals(orgFormats));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#getLimits()
+ */
+ public void test_getLimits() {
+ // Test for method double [] java.text.ChoiceFormat.getLimits()
+ double[] orgLimits = (double[]) limits.clone();
+ double[] l = f1.getLimits();
+ assertTrue("Wrong limits", l.equals(limits));
+ l[0] = 3.14527;
+ assertTrue("Limits copied", !l.equals(orgLimits));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.text.ChoiceFormat.hashCode()
+ ChoiceFormat f2 = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ assertTrue("Different hash", f1.hashCode() == f2.hashCode());
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#nextDouble(double)
+ */
+ public void test_nextDoubleD() {
+ // Test for method double java.text.ChoiceFormat.nextDouble(double)
+ assertTrue("Not greater 5", ChoiceFormat.nextDouble(5) > 5);
+ assertTrue("Not greater 0", ChoiceFormat.nextDouble(0) > 0);
+ assertTrue("Not greater -5", ChoiceFormat.nextDouble(-5) > -5);
+ assertTrue("Not NaN", Double.isNaN(ChoiceFormat.nextDouble(Double.NaN)));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#nextDouble(double, boolean)
+ */
+ public void test_nextDoubleDZ() {
+ // Test for method double java.text.ChoiceFormat.nextDouble(double,
+ // boolean)
+ assertTrue("Not greater 0", ChoiceFormat.nextDouble(0, true) > 0);
+ assertTrue("Not less 0", ChoiceFormat.nextDouble(0, false) < 0);
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#parse(java.lang.String,
+ * java.text.ParsePosition)
+ */
+ public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
+ // Test for method java.lang.Number
+ // java.text.ChoiceFormat.parse(java.lang.String,
+ // java.text.ParsePosition)
+ ChoiceFormat format = new ChoiceFormat("1#one|2#two|3#three");
+ assertEquals("Case insensitive", 0, format
+ .parse("One", new ParsePosition(0)).intValue());
+
+ ParsePosition pos = new ParsePosition(0);
+ Number result = f1.parse("Greater than two", pos);
+ assertTrue("Not a Double1", result instanceof Double);
+ assertTrue("Wrong value ~>2", result.doubleValue() == ChoiceFormat
+ .nextDouble(2));
+ assertEquals("Wrong position ~16", 16, pos.getIndex());
+ pos = new ParsePosition(0);
+ assertTrue("Incorrect result", Double.isNaN(f1.parse("12one", pos)
+ .doubleValue()));
+ assertEquals("Wrong position ~0", 0, pos.getIndex());
+ pos = new ParsePosition(2);
+ result = f1.parse("12one and two", pos);
+ assertTrue("Not a Double2", result instanceof Double);
+ assertEquals("Ignored parse position", 1.0D, result.doubleValue(), 0.0D);
+ assertEquals("Wrong position ~5", 5, pos.getIndex());
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#previousDouble(double)
+ */
+ public void test_previousDoubleD() {
+ // Test for method double java.text.ChoiceFormat.previousDouble(double)
+ assertTrue("Not less 5", ChoiceFormat.previousDouble(5) < 5);
+ assertTrue("Not less 0", ChoiceFormat.previousDouble(0) < 0);
+ assertTrue("Not less -5", ChoiceFormat.previousDouble(-5) < -5);
+ assertTrue("Not NaN", Double.isNaN(ChoiceFormat
+ .previousDouble(Double.NaN)));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#setChoices(double[], java.lang.String[])
+ */
+ public void test_setChoices$D$Ljava_lang_String() {
+ // Test for method void java.text.ChoiceFormat.setChoices(double [],
+ // java.lang.String [])
+ ChoiceFormat f = (ChoiceFormat) f1.clone();
+ double[] l = new double[] { 0, 1 };
+ String[] fs = new String[] { "0", "1" };
+ f.setChoices(l, fs);
+ assertTrue("Limits copied", f.getLimits() == l);
+ assertTrue("Formats copied", f.getFormats() == fs);
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#toPattern()
+ */
+ public void test_toPattern() {
+ // Regression for HARMONY-59
+ ChoiceFormat cf = new ChoiceFormat("");
+ assertEquals("", cf.toPattern());
+
+ cf = new ChoiceFormat("-1#NEGATIVE_ONE|0#ZERO|1#ONE|1<GREATER_THAN_ONE");
+ assertEquals("-1.0#NEGATIVE_ONE|0.0#ZERO|1.0#ONE|1.0<GREATER_THAN_ONE",
+ cf.toPattern());
+
+ MessageFormat mf = new MessageFormat("CHOICE {1,choice}");
+ String ptrn = mf.toPattern();
+ assertEquals("Unused message format returning incorrect pattern", "CHOICE {1,choice,}", ptrn
+ );
+
+ String pattern = f1.toPattern();
+ assertTrue(
+ "Wrong pattern: " + pattern,
+ pattern
+ .equals("0.0#Less than one|1.0#one|1.0<Between one and two|2.0<Greater than two"));
+
+ cf = new ChoiceFormat(
+ "-1#is negative| 0#is zero or fraction | 1#is one |1.0<is 1+|2#is two |2<is more than 2.");
+ String str = "org.apache.harmony.tests.java.lang.share.MyResources2";
+ cf.applyPattern(str);
+ ptrn = cf.toPattern();
+ assertEquals("Return value should be empty string for invalid pattern",
+ 0, ptrn.length());
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#format(long)
+ */
+ public void test_formatL() {
+ ChoiceFormat fmt = new ChoiceFormat(
+ "-1#NEGATIVE_ONE|0#ZERO|1#ONE|1<GREATER_THAN_ONE");
+
+ assertEquals("NEGATIVE_ONE", fmt.format(Long.MIN_VALUE));
+ assertEquals("NEGATIVE_ONE", fmt.format(-1));
+ assertEquals("ZERO", fmt.format(0));
+ assertEquals("ONE", fmt.format(1));
+ assertEquals("GREATER_THAN_ONE", fmt.format(Long.MAX_VALUE));
+ }
+
+ /**
+ * @tests java.text.ChoiceFormat#format(double)
+ */
+ public void test_formatD() {
+ ChoiceFormat fmt = new ChoiceFormat(
+ "-1#NEGATIVE_ONE|0#ZERO|1#ONE|1<GREATER_THAN_ONE");
+ assertEquals("NEGATIVE_ONE", fmt.format(Double.NEGATIVE_INFINITY));
+ assertEquals("NEGATIVE_ONE", fmt.format(-999999999D));
+ assertEquals("NEGATIVE_ONE", fmt.format(-1.1));
+ assertEquals("NEGATIVE_ONE", fmt.format(-1.0));
+ assertEquals("NEGATIVE_ONE", fmt.format(-0.9));
+ assertEquals("ZERO", fmt.format(0.0));
+ assertEquals("ZERO", fmt.format(0.9));
+ assertEquals("ONE", fmt.format(1.0));
+ assertEquals("GREATER_THAN_ONE", fmt.format(1.1));
+ assertEquals("GREATER_THAN_ONE", fmt.format(999999999D));
+ assertEquals("GREATER_THAN_ONE", fmt.format(Double.POSITIVE_INFINITY));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationElementIteratorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationElementIteratorTest.java
new file mode 100644
index 0000000..081b446
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationElementIteratorTest.java
@@ -0,0 +1,224 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.CollationElementIterator;
+import java.text.Collator;
+import java.text.RuleBasedCollator;
+import java.text.StringCharacterIterator;
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+/**
+ * Test CollationElementIterator
+ *
+ * Only test normal condition.
+ *
+ */
+public class CollationElementIteratorTest extends TestCase {
+
+ private RuleBasedCollator coll;
+
+ protected void setUp() {
+ coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
+ }
+
+ public void testGetOffset() {
+ String text = "abc";
+ CollationElementIterator iterator = coll.getCollationElementIterator(text);
+ int[] offsets = { 0, 1, 2, 3 };
+ int offset = iterator.getOffset();
+ int i = 0;
+ assertEquals(offsets[i++], offset);
+ while (offset != text.length()) {
+ iterator.next();
+ offset = iterator.getOffset();
+ assertEquals(offsets[i++], offset);
+ }
+ }
+
+ public void testNext() {
+ String text = "abc";
+ CollationElementIterator iterator = coll.getCollationElementIterator(text);
+ int[] orders = new int[text.length()];
+ int order = iterator.next();
+ int i = 0;
+ while (order != CollationElementIterator.NULLORDER) {
+ orders[i++] = order;
+ order = iterator.next();
+ }
+
+ int offset = iterator.getOffset();
+ assertEquals(text.length(), offset);
+
+ iterator.reset();
+ order = iterator.previous();
+
+ while (order != CollationElementIterator.NULLORDER) {
+ assertEquals(orders[--i], order);
+ order = iterator.previous();
+ }
+
+ assertEquals(0, iterator.getOffset());
+ }
+
+ public void testPrevious() {
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
+ String text = "abc";
+ CollationElementIterator iterator = coll
+ .getCollationElementIterator(text);
+ int[] orders = new int[text.length()];
+ int order = iterator.next();
+ int i = 0;
+ while (order != CollationElementIterator.NULLORDER) {
+ orders[i++] = order;
+ order = iterator.next();
+ }
+
+ int offset = iterator.getOffset();
+ assertEquals(text.length(), offset);
+
+ iterator.reset();
+ order = iterator.previous();
+
+ while (order != CollationElementIterator.NULLORDER) {
+ assertEquals(orders[--i], order);
+ order = iterator.previous();
+ }
+
+ assertEquals(0, iterator.getOffset());
+ }
+
+ public void testReset() {
+ String text = "abc";
+ CollationElementIterator iterator = coll.getCollationElementIterator(text);
+ int[] orders = new int[text.length()];
+ int order = iterator.next();
+ int i = 0;
+ while (order != CollationElementIterator.NULLORDER) {
+ orders[i++] = order;
+ order = iterator.next();
+ }
+
+ int offset = iterator.getOffset();
+ assertEquals(text.length(), offset);
+
+ iterator.reset();
+ assertEquals(0, iterator.getOffset());
+ }
+
+ public void testGetMaxExpansion() {
+ String text = "cha";
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(
+ Locale.forLanguageTag("es-u-co-trad"));
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ int order = iterator.next();
+ while (order != CollationElementIterator.NULLORDER) {
+ assertEquals(1, iterator.getMaxExpansion(order));
+ order = iterator.next();
+ }
+ }
+
+ public void testPrimaryOrder() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(new Locale("de", "DE"));
+ String text = "\u00e6";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ int order = iterator.next();
+ int pOrder = CollationElementIterator.primaryOrder(order);
+ CollationElementIterator iterator2 = rbColl.getCollationElementIterator("ae");
+ int order2 = iterator2.next();
+ int pOrder2 = CollationElementIterator.primaryOrder(order2);
+ assertEquals(pOrder, pOrder2);
+ }
+
+ public void testSecondaryOrder() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(new Locale("fr", "FR"));
+ String text = "a\u00e0";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ int order = iterator.next();
+ int sOrder1 = CollationElementIterator.secondaryOrder(order);
+
+ order = iterator.next();
+ int sOrder2 = CollationElementIterator.secondaryOrder(order);
+
+ assertEquals(sOrder1, sOrder2);
+ }
+
+ public void testTertiaryOrder() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(new Locale("fr", "FR"));
+ String text = "abAB";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ int order = iterator.next();
+ int tOrder1 = CollationElementIterator.tertiaryOrder(order);
+ order = iterator.next();
+ int tOrder2 = CollationElementIterator.tertiaryOrder(order);
+ assertEquals(tOrder1, tOrder2);
+
+ order = iterator.next();
+ tOrder1 = CollationElementIterator.tertiaryOrder(order);
+ order = iterator.next();
+ tOrder2 = CollationElementIterator.tertiaryOrder(order);
+ assertEquals(tOrder1, tOrder2);
+ }
+
+ public void testSetOffset() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(
+ Locale.forLanguageTag("es-u-co-trad"));
+ String text = "cha";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ iterator.setOffset(0);
+ assertEquals(0, iterator.getOffset());
+ iterator.setOffset(1);
+ assertEquals(0, iterator.getOffset());
+ iterator.setOffset(2);
+ assertEquals(2, iterator.getOffset());
+ }
+
+ public void testSetTextString() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(
+ Locale.forLanguageTag("es-u-co-trad"));
+ String text = "caa";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ iterator.setOffset(0);
+ assertEquals(0, iterator.getOffset());
+ iterator.setOffset(1);
+ assertEquals(1, iterator.getOffset());
+ iterator.setOffset(2);
+ assertEquals(2, iterator.getOffset());
+ iterator.setText("cha");
+ iterator.setOffset(0);
+ assertEquals(0, iterator.getOffset());
+ iterator.setOffset(1);
+ assertEquals(0, iterator.getOffset());
+ iterator.setOffset(2);
+ assertEquals(2, iterator.getOffset());
+ }
+
+ public void testSetTextCharacterIterator() {
+ RuleBasedCollator rbColl = (RuleBasedCollator) Collator.getInstance(
+ Locale.forLanguageTag("es-u-co-trad"));
+ String text = "caa";
+ CollationElementIterator iterator = rbColl.getCollationElementIterator(text);
+ iterator.setOffset(1);
+ assertEquals(1, iterator.getOffset());
+ iterator.setText(new StringCharacterIterator("cha"));
+ iterator.setOffset(1);
+ assertEquals(1, iterator.getOffset());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationKeyTest.java
new file mode 100644
index 0000000..345c25d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollationKeyTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.CollationKey;
+import java.text.Collator;
+import java.text.ParseException;
+import java.text.RuleBasedCollator;
+import java.util.Arrays;
+
+public class CollationKeyTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.CollationKey#compareTo(java.text.CollationKey)
+ */
+ public void test_compareToLjava_text_CollationKey() {
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ CollationKey key1 = collator.getCollationKey("abc");
+ CollationKey key2 = collator.getCollationKey("ABC");
+ assertEquals("Should be equal", 0, key1.compareTo(key2));
+ }
+
+ /**
+ * @tests java.text.CollationKey#compareTo(java.lang.Object)
+ */
+ public void test_compareToLjava_lang_Object() {
+ // Test for method int
+ // java.text.CollationKey.compareTo(java.lang.Object)
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ CollationKey key1 = collator.getCollationKey("abc");
+ CollationKey key2 = collator.getCollationKey("ABC");
+ assertEquals("Should be equal", 0, key1.compareTo(key2));
+ }
+
+ /**
+ * @tests java.text.CollationKey#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ CollationKey key1 = collator.getCollationKey("abc");
+ CollationKey key2 = collator.getCollationKey("ABC");
+ assertTrue("Should be equal", key1.equals(key2));
+ }
+
+ /**
+ * @tests java.text.CollationKey#getSourceString()
+ */
+ public void test_getSourceString() {
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ assertTrue("Wrong source string1", collator.getCollationKey("abc")
+ .getSourceString() == "abc");
+ assertTrue("Wrong source string2", collator.getCollationKey("ABC")
+ .getSourceString() == "ABC");
+ }
+
+ /**
+ * @tests java.text.CollationKey#hashCode()
+ */
+ public void test_hashCode() {
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ CollationKey key1 = collator.getCollationKey("abc");
+ CollationKey key2 = collator.getCollationKey("ABC");
+ assertTrue("Should be equal", key1.hashCode() == key2.hashCode());
+ }
+
+ /**
+ * @tests java.text.CollationKey#toByteArray()
+ */
+ //FIXME This test fails on Harmony ClassLibrary
+ public void failing_test_toByteArray() {
+ // Test for method byte [] java.text.CollationKey.toByteArray()
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.PRIMARY);
+ CollationKey key1 = collator.getCollationKey("abc");
+ byte[] bytes = key1.toByteArray();
+ assertTrue("Not enough bytes", bytes.length >= 3);
+
+ try {
+ collator = new RuleBasedCollator("= 1 , 2 ; 3 , 4 < 5 ; 6 , 7");
+ } catch (ParseException e) {
+ fail("ParseException");
+ return;
+ }
+ bytes = collator.getCollationKey("1234567").toByteArray();
+ /*
+ * CollationElementIterator it =
+ * ((RuleBasedCollator)collator).getCollationElementIterator("1234567");
+ * int order; while ((order = it.next()) !=
+ * CollationElementIterator.NULLORDER) {
+ * System.out.println(Integer.toHexString(order)); } for (int i=0; i<bytes.length;
+ * i+=2) { System.out.print(Integer.toHexString(bytes[i]) +
+ * Integer.toHexString(bytes[i+1]) + " "); } System.out.println();
+ */
+ byte[] result = new byte[] { 0, 2, 0, 2, 0, 2, 0, 0, 0, 3, 0, 3, 0, 1,
+ 0, 2, 0, 2, 0, 0, 0, 4, 0, 4, 0, 1, 0, 1, 0, 2 };
+ assertTrue("Wrong bytes", Arrays.equals(bytes, result));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollatorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollatorTest.java
new file mode 100644
index 0000000..9f5d141
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/CollatorTest.java
@@ -0,0 +1,234 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.Collator;
+import java.text.ParseException;
+import java.text.RuleBasedCollator;
+import java.util.Locale;
+
+public class CollatorTest extends junit.framework.TestCase {
+
+ public void test_clone() {
+ Collator c = Collator.getInstance(Locale.GERMAN);
+ Collator c2 = (Collator) c.clone();
+ assertTrue("Clones answered false to equals", c.equals(c2));
+ assertTrue("Clones were equivalent", c != c2);
+ }
+
+ public void test_compareLjava_lang_ObjectLjava_lang_Object() {
+ Collator c = Collator.getInstance(Locale.FRENCH);
+ Object o, o2;
+
+ c.setStrength(Collator.IDENTICAL);
+ o = "E";
+ o2 = "F";
+ assertTrue("a) Failed on primary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "\u00e9";
+ assertTrue("a) Failed on secondary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "E";
+ assertTrue("a) Failed on tertiary difference", c.compare(o, o2) < 0);
+ o = "\u0001";
+ o2 = "\u0002";
+ assertTrue("a) Failed on identical", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "e";
+ assertEquals("a) Failed on equivalence", 0, c.compare(o, o2));
+ assertTrue("a) Failed on primary expansion",
+ c.compare("\u01db", "v") < 0);
+
+ c.setStrength(Collator.TERTIARY);
+ o = "E";
+ o2 = "F";
+ assertTrue("b) Failed on primary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "\u00e9";
+ assertTrue("b) Failed on secondary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "E";
+ assertTrue("b) Failed on tertiary difference", c.compare(o, o2) < 0);
+ o = "\u0001";
+ o2 = "\u0002";
+ assertEquals("b) Failed on identical", 0, c.compare(o, o2));
+ o = "e";
+ o2 = "e";
+ assertEquals("b) Failed on equivalence", 0, c.compare(o, o2));
+
+ c.setStrength(Collator.SECONDARY);
+ o = "E";
+ o2 = "F";
+ assertTrue("c) Failed on primary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "\u00e9";
+ assertTrue("c) Failed on secondary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "E";
+ assertEquals("c) Failed on tertiary difference", 0, c.compare(o, o2));
+ o = "\u0001";
+ o2 = "\u0002";
+ assertEquals("c) Failed on identical", 0, c.compare(o, o2));
+ o = "e";
+ o2 = "e";
+ assertEquals("c) Failed on equivalence", 0, c.compare(o, o2));
+
+ c.setStrength(Collator.PRIMARY);
+ o = "E";
+ o2 = "F";
+ assertTrue("d) Failed on primary difference", c.compare(o, o2) < 0);
+ o = "e";
+ o2 = "\u00e9";
+ assertEquals("d) Failed on secondary difference", 0, c.compare(o, o2));
+ o = "e";
+ o2 = "E";
+ assertEquals("d) Failed on tertiary difference", 0, c.compare(o, o2));
+ o = "\u0001";
+ o2 = "\u0002";
+ assertEquals("d) Failed on identical", 0, c.compare(o, o2));
+ o = "e";
+ o2 = "e";
+ assertEquals("d) Failed on equivalence", 0, c.compare(o, o2));
+
+ try {
+ c.compare("e", new StringBuffer("Blah"));
+ } catch (ClassCastException e) {
+ // correct
+ return;
+ }
+ fail("Failed to throw ClassCastException");
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ Collator c = Collator.getInstance(Locale.ENGLISH);
+ Collator c2 = (Collator) c.clone();
+ assertTrue("Cloned collators not equal", c.equals(c2));
+ c2.setStrength(Collator.SECONDARY);
+ assertTrue("Collators with different strengths equal", !c.equals(c2));
+ }
+
+ public void test_equalsLjava_lang_StringLjava_lang_String() {
+ Collator c = Collator.getInstance(Locale.FRENCH);
+
+ c.setStrength(Collator.IDENTICAL);
+ assertTrue("a) Failed on primary difference", !c.equals("E", "F"));
+ assertTrue("a) Failed on secondary difference", !c
+ .equals("e", "\u00e9"));
+ assertTrue("a) Failed on tertiary difference", !c.equals("e", "E"));
+ assertTrue("a) Failed on identical", !c.equals("\u0001", "\u0002"));
+ assertTrue("a) Failed on equivalence", c.equals("e", "e"));
+
+ c.setStrength(Collator.TERTIARY);
+ assertTrue("b) Failed on primary difference", !c.equals("E", "F"));
+ assertTrue("b) Failed on secondary difference", !c
+ .equals("e", "\u00e9"));
+ assertTrue("b) Failed on tertiary difference", !c.equals("e", "E"));
+ assertTrue("b) Failed on identical", c.equals("\u0001", "\u0002"));
+ assertTrue("b) Failed on equivalence", c.equals("e", "e"));
+
+ c.setStrength(Collator.SECONDARY);
+ assertTrue("c) Failed on primary difference", !c.equals("E", "F"));
+ assertTrue("c) Failed on secondary difference", !c
+ .equals("e", "\u00e9"));
+ assertTrue("c) Failed on tertiary difference", c.equals("e", "E"));
+ assertTrue("c) Failed on identical", c.equals("\u0001", "\u0002"));
+ assertTrue("c) Failed on equivalence", c.equals("e", "e"));
+
+ c.setStrength(Collator.PRIMARY);
+ assertTrue("d) Failed on primary difference", !c.equals("E", "F"));
+ assertTrue("d) Failed on secondary difference", c.equals("e", "\u00e9"));
+ assertTrue("d) Failed on tertiary difference", c.equals("e", "E"));
+ assertTrue("d) Failed on identical", c.equals("\u0001", "\u0002"));
+ assertTrue("d) Failed on equivalence", c.equals("e", "e"));
+ }
+
+ public void failing_test_getAvailableLocales() {
+ Locale[] locales = Collator.getAvailableLocales();
+ assertTrue("No locales", locales.length > 0);
+ boolean english = false, german = false;
+ for (int i = locales.length; --i >= 0;) {
+ if (locales[i].equals(Locale.ENGLISH))
+ english = true;
+ if (locales[i].equals(Locale.GERMAN))
+ german = true;
+ // Output the working locale to help diagnose a hang
+ Collator c1 = Collator.getInstance(locales[i]);
+ assertTrue("Doesn't work", c1.compare("a", "b") < 0);
+ assertTrue("Wrong decomposition",
+ c1.getDecomposition() == Collator.NO_DECOMPOSITION);
+ assertTrue("Wrong strength", c1.getStrength() == Collator.TERTIARY);
+ if (c1 instanceof RuleBasedCollator) {
+ try {
+ new RuleBasedCollator(((RuleBasedCollator) c1).getRules());
+ } catch (ParseException e) {
+ fail("ParseException");
+ }
+ // assertTrue("Can't recreate: " + locales[i], temp.equals(c1));
+ }
+ }
+ assertTrue("Missing locales", english && german);
+ }
+
+ public void failing_test_getDecomposition() {
+ RuleBasedCollator collator;
+ try {
+ collator = new RuleBasedCollator("; \u0300 < a, A < b < c < d");
+ } catch (ParseException e) {
+ fail("ParseException");
+ return;
+ }
+ assertTrue("Wrong default",
+ collator.getDecomposition() == Collator.CANONICAL_DECOMPOSITION);
+ }
+
+ public void test_getInstance() {
+ Collator c1 = Collator.getInstance();
+ Collator c2 = Collator.getInstance(Locale.getDefault());
+ assertTrue("Wrong locale", c1.equals(c2));
+ }
+
+ public void test_getInstanceLjava_util_Locale() {
+ assertTrue("Used to test", true);
+ }
+
+ public void test_getStrength() throws ParseException {
+ RuleBasedCollator collator = new RuleBasedCollator("&9 ; \u0300 < a, A < b < c < d");
+ assertTrue("Wrong default", collator.getStrength() == Collator.TERTIARY);
+ }
+
+ public void failing_test_setDecompositionI() {
+ Collator c = Collator.getInstance(Locale.FRENCH);
+ c.setStrength(Collator.IDENTICAL);
+ c.setDecomposition(Collator.NO_DECOMPOSITION);
+ assertTrue("Collator should not be using decomposition", !c.equals(
+ "\u212B", "\u00C5")); // "ANGSTROM SIGN" and "LATIN CAPITAL
+ // LETTER A WITH RING ABOVE"
+ c.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
+ assertTrue("Collator should be using decomposition", c.equals("\u212B",
+ "\u00C5")); // "ANGSTROM SIGN" and "LATIN CAPITAL LETTER A WITH
+ // RING ABOVE"
+ assertTrue("Should not be equal under canonical decomposition", !c
+ .equals("\u2163", "IV")); // roman number "IV"
+ c.setDecomposition(Collator.FULL_DECOMPOSITION);
+ assertTrue("Should be equal under full decomposition", c.equals(
+ "\u2163", "IV")); // roman number "IV"
+ }
+
+ public void test_setStrengthI() {
+ assertTrue("Used to test", true);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DataFormatFieldTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DataFormatFieldTest.java
new file mode 100644
index 0000000..390dff8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DataFormatFieldTest.java
@@ -0,0 +1,223 @@
+/*
+ * 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.tests.java.text;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InvalidObjectException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import java.text.DateFormat;
+import java.text.DateFormat.Field;
+import java.util.Calendar;
+
+import junit.framework.TestCase;
+
+public class DataFormatFieldTest extends TestCase{
+
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() {
+ // Regression for HARMONY-178
+ MyField field = new MyField("day of month", Calendar.ERA);
+
+ assertEquals("field has wrong name", "day of month", field.getName());
+ assertEquals("field has wrong Calendar field number", Calendar.ERA,
+ field.getCalendarField());
+
+ DateFormat.Field realField = DateFormat.Field
+ .ofCalendarField(Calendar.ERA);
+ assertSame("Modified calendar field with the same field number",
+ DateFormat.Field.ERA, realField);
+
+ DateFormat.Field realField2 = DateFormat.Field
+ .ofCalendarField(Calendar.DAY_OF_MONTH);
+ assertSame("Modified calendar field with the same field number",
+ DateFormat.Field.DAY_OF_MONTH, realField2);
+ }
+
+ static class MyField extends DateFormat.Field {
+ private static final long serialVersionUID = 1L;
+
+ protected MyField(String fieldName, int calendarField) {
+ super(fieldName, calendarField);
+ }
+
+ protected String getName() {
+ return super.getName();
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat$Field#Field(java.lang.String, int)
+ */
+ public void test_ConstructorLjava_lang_StringI() {
+ MyField field = new MyField("a field", Calendar.DAY_OF_WEEK);
+
+ assertEquals("field has wrong name", "a field", field.getName());
+ assertEquals("field has wrong Calendar field number",
+ Calendar.DAY_OF_WEEK, field.getCalendarField());
+
+ DateFormat.Field realField = DateFormat.Field
+ .ofCalendarField(Calendar.DAY_OF_WEEK);
+ assertSame("Modified calendar field with the same field number",
+ DateFormat.Field.DAY_OF_WEEK, realField);
+ }
+
+ /**
+ * @tests java.text.DateFormat$Field#Field(java.lang.String, int)
+ */
+ public void test_Constructor2() {
+ MyField field = new MyField("day of month", Calendar.ERA);
+
+ assertEquals("field has wrong name", "day of month", field.getName());
+ assertEquals("field has wrong Calendar field number", Calendar.ERA,
+ field.getCalendarField());
+
+ DateFormat.Field realField = DateFormat.Field
+ .ofCalendarField(Calendar.ERA);
+ assertSame("Modified calendar field with the same field number",
+ DateFormat.Field.ERA, realField);
+
+ DateFormat.Field realField2 = DateFormat.Field
+ .ofCalendarField(Calendar.DAY_OF_MONTH);
+ assertSame("Modified calendar field with the same field number",
+ DateFormat.Field.DAY_OF_MONTH, realField2);
+ }
+
+ /**
+ * @tests java.text.DateFormat$Field#getCalendarField()
+ */
+ public void test_getCalendarField() {
+ // Test for method int getCalendarField()
+ assertEquals("Field.AM_PM.getCalendarField() returned the wrong value",
+ Calendar.AM_PM, Field.AM_PM.getCalendarField());
+
+ // test special cases
+ assertEquals(
+ "Field.TIME_ZONE.getCalendarField() returned the wrong value",
+ -1, Field.TIME_ZONE.getCalendarField());
+ assertEquals("Field.HOUR0.getCalendarField() returned the wrong value",
+ Calendar.HOUR, Field.HOUR0.getCalendarField());
+ assertEquals("Field.HOUR1.getCalendarField() returned the wrong value",
+ -1, Field.HOUR1.getCalendarField());
+ assertEquals(
+ "Field.HOUR_OF_DAY0.getCalendarField() returned the wrong value",
+ Calendar.HOUR_OF_DAY, Field.HOUR_OF_DAY0.getCalendarField());
+ assertEquals(
+ "Field.HOUR_OF_DAY1.getCalendarField() returned the wrong value",
+ -1, Field.HOUR_OF_DAY1.getCalendarField());
+ }
+
+ /**
+ * @tests java.text.DateFormat$Field#ofCalendarField(int)
+ */
+ public void test_ofCalendarFieldI() {
+ // Test for method static java.text.DateFormat.Field
+ // ofCalendarField(int)
+ assertSame("ofCalendarField(Calendar.AM_PM) returned the wrong value",
+ Field.AM_PM, Field.ofCalendarField(Calendar.AM_PM));
+
+ // test special cases
+ assertSame("ofCalendarField(Calendar.HOUR) returned the wrong value",
+ Field.HOUR0, Field.ofCalendarField(Calendar.HOUR));
+ assertSame(
+ "ofCalendarField(Calendar.HOUR_OF_DAY) returned the wrong value",
+ Field.HOUR_OF_DAY0, Field.ofCalendarField(Calendar.HOUR_OF_DAY));
+
+ // test illegal args
+ try {
+ DateFormat.Field.ofCalendarField(-1);
+ fail("Expected IllegalArgumentException for ofCalendarField(-1)");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ DateFormat.Field.ofCalendarField(Calendar.FIELD_COUNT);
+ fail("Expected IllegalArgumentException for ofCalendarField(Calendar.FIELD_COUNT)");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // test Calendar fields that do not have corresponding DateFormat Fields
+ assertNull(
+ "ofCalendarField(Calendar.DST_OFFSET) returned the wrong value",
+ DateFormat.Field.ofCalendarField(Calendar.DST_OFFSET));
+ assertNull(
+ "ofCalendarField(Calendar.ZONE_OFFSET) returned the wrong value",
+ DateFormat.Field.ofCalendarField(Calendar.ZONE_OFFSET));
+ }
+
+ /**
+ * @tests java.text.DateFormat$Field#readResolve()
+ */
+ public void test_readResolve() {
+ // test for method java.lang.Object readResolve()
+
+ // see serialization stress tests:
+ // implemented in
+ // SerializationStressTest4.test_writeObject_NumberFormat_Field()
+
+ ObjectOutputStream out = null;
+ ObjectInputStream in = null;
+ try {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ out = new ObjectOutputStream(bytes);
+
+ DateFormat.Field dfield, dfield2;
+ MyField field;
+
+ // a regular instance of DateFormat.Field
+ dfield = DateFormat.Field.MILLISECOND;
+
+ // a subclass instance with null name
+ field = new MyField(null, Calendar.AM_PM);
+
+ out.writeObject(dfield);
+ out.writeObject(field);
+
+ in = new ObjectInputStream(new ByteArrayInputStream(bytes
+ .toByteArray()));
+
+ try {
+ dfield2 = (Field) in.readObject();
+ assertSame("resolved incorrectly", dfield, dfield2);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException: " + e);
+ }
+
+ try {
+ in.readObject();
+ fail("Expected InvalidObjectException for subclass instance with null name");
+ } catch (InvalidObjectException e) {
+ }
+
+ } catch (IOException e) {
+ fail("unexpected IOException" + e);
+ } catch (ClassNotFoundException e) {
+ fail("unexpected ClassNotFoundException" + e);
+ } finally {
+ try {
+ if (out != null)
+ out.close();
+ if (in != null)
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatSymbolsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatSymbolsTest.java
new file mode 100644
index 0000000..1a6a25e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatSymbolsTest.java
@@ -0,0 +1,423 @@
+/*
+ * 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.tests.java.text;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.text.DateFormatSymbols;
+import java.util.Arrays;
+import java.util.Locale;
+
+public class DateFormatSymbolsTest extends junit.framework.TestCase {
+
+ private DateFormatSymbols dfs;
+
+ /**
+ * @tests java.text.DateFormatSymbols#DateFormatSymbols()
+ */
+ public void test_Constructor() {
+ // Test for method java.text.DateFormatSymbols()
+ // Used in tests
+ new DateFormatSymbols();
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#DateFormatSymbols(java.util.Locale)
+ */
+ public void test_ConstructorLjava_util_Locale() {
+ // Test for method java.text.DateFormatSymbols(java.util.Locale)
+ new DateFormatSymbols(new Locale("en", "us"));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getAvailableLocales()
+ */
+ public void test_getAvailableLocales_no_provider() throws Exception {
+ Locale[] locales = DateFormatSymbols.getAvailableLocales();
+ assertNotNull(locales);
+ // must contain Locale.US
+ boolean flag = false;
+ for (Locale locale : locales) {
+ if (locale.equals(Locale.US)) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue(flag);
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getInstance()
+ */
+ public void test_getInstance() {
+ DateFormatSymbols.getInstance();
+ assertEquals(new DateFormatSymbols(), DateFormatSymbols.getInstance());
+ assertEquals(new DateFormatSymbols(Locale.getDefault()),
+ DateFormatSymbols.getInstance());
+
+ assertNotSame(DateFormatSymbols.getInstance(), DateFormatSymbols.getInstance());
+ }
+
+ public void test_getInstanceLjava_util_Locale() {
+ try {
+ DateFormatSymbols.getInstance(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ assertEquals(new DateFormatSymbols(Locale.GERMANY), DateFormatSymbols.getInstance(Locale.GERMANY));
+
+ Locale locale = new Locale("not exist language", "not exist country");
+ DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
+ assertEquals(DateFormatSymbols.getInstance(Locale.ROOT), symbols);
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.text.DateFormatSymbols.clone()
+ DateFormatSymbols symbols = new DateFormatSymbols();
+ DateFormatSymbols clone = (DateFormatSymbols) symbols.clone();
+ assertTrue("Not equal", symbols.equals(clone));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.text.DateFormatSymbols.equals(java.lang.Object)
+ assertTrue("Equal object returned true", dfs.equals(dfs.clone()));
+ dfs.setLocalPatternChars("KKKKKKKKK");
+ assertTrue("Un-Equal objects returned false", !dfs
+ .equals(new DateFormatSymbols()));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getAmPmStrings()
+ */
+ public void test_getAmPmStrings() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getAmPmStrings()
+ String[] retVal = dfs.getAmPmStrings();
+ String[] val = { "AM", "PM" };
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getEras()
+ */
+ public void test_getEras() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getEras()
+ String[] retVal = dfs.getEras();
+ String[] val = { "BC", "AD" };
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getMonths()
+ */
+ public void test_getMonths() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getMonths()
+ String[] retVal = dfs.getMonths();
+ String[] val = { "January", "February", "March", "April", "May",
+ "June", "July", "August", "September", "October", "November",
+ "December"};
+ assertEquals("Returned wrong array: ", val.length, retVal.length);
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getShortMonths()
+ */
+ public void test_getShortMonths() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getShortMonths()
+ String[] retVal = dfs.getShortMonths();
+ String[] val = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
+ "Aug", "Sep", "Oct", "Nov", "Dec"};
+ assertEquals("Returned wrong array: ", val.length, retVal.length);
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getShortWeekdays()
+ */
+ public void test_getShortWeekdays() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getShortWeekdays()
+ String[] retVal = dfs.getShortWeekdays();
+ String[] val = { "", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getWeekdays()
+ */
+ public void test_getWeekdays() {
+ // Test for method java.lang.String []
+ // java.text.DateFormatSymbols.getWeekdays()
+ String[] retVal = dfs.getWeekdays();
+ String[] val = { "", "Sunday", "Monday", "Tuesday", "Wednesday",
+ "Thursday", "Friday", "Saturday" };
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Array values do not match", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#getZoneStrings()
+ */
+ public void test_getZoneStrings() {
+ // Test for method java.lang.String [][]
+ // java.text.DateFormatSymbols.getZoneStrings()
+ String[][] val = { { "XX", "XX", "XX", "XX", "XX" },
+ { "YY", "YY", "YY", "YY", "YY" } };
+ dfs.setZoneStrings(val);
+ String[][] retVal = dfs.getZoneStrings();
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", Arrays
+ .equals(retVal[i], val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.text.DateFormatSymbols.hashCode()
+ int hc1 = dfs.hashCode();
+ int hc2 = dfs.hashCode();
+ assertTrue("hashCode() returned inconsistent number : " + hc1 + " - " + hc2, hc1 == hc2);
+
+ assertTrue("hashCode() returns different values for equal() objects",
+ dfs.hashCode() == dfs.clone().hashCode());
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setAmPmStrings(java.lang.String[])
+ */
+ public void test_setAmPmStrings$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setAmPmStrings(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setAmPmStrings(val);
+ String[] retVal = dfs.getAmPmStrings();
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setEras(java.lang.String[])
+ */
+ public void test_setEras$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setEras(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setEras(val);
+ String[] retVal = dfs.getEras();
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ public void test_setLocalPatternCharsLjava_lang_String() {
+ String patternChars = "GyMZZkHmsSEHHFwWahKz";
+ dfs.setLocalPatternChars(patternChars);
+ assertEquals(patternChars, dfs.getLocalPatternChars());
+
+ try {
+ // Regression for HARMONY-466
+ new DateFormatSymbols().setLocalPatternChars(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setMonths(java.lang.String[])
+ */
+ public void test_setMonths$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setMonths(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setMonths(val);
+ String[] retVal = dfs.getMonths();
+ assertTrue("Return is identical", retVal != dfs.getMonths());
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setShortMonths(java.lang.String[])
+ */
+ public void test_setShortMonths$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setShortMonths(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setShortMonths(val);
+ String[] retVal = dfs.getShortMonths();
+ assertTrue("Return is identical", retVal != dfs.getShortMonths());
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setShortWeekdays(java.lang.String[])
+ */
+ public void test_setShortWeekdays$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setShortWeekdays(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setShortWeekdays(val);
+ String[] retVal = dfs.getShortWeekdays();
+ assertTrue("Return is identical", retVal != dfs.getShortWeekdays());
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setWeekdays(java.lang.String[])
+ */
+ public void test_setWeekdays$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setWeekdays(java.lang.String [])
+ String[] val = { "XX", "YY" };
+ dfs.setWeekdays(val);
+ String[] retVal = dfs.getWeekdays();
+ assertTrue("Return is identical", retVal != dfs.getWeekdays());
+ if (retVal.length != val.length)
+ fail("Returned wrong array");
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings", retVal[i].equals(val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setZoneStrings(java.lang.String[][])
+ */
+ public void test_setZoneStrings$$Ljava_lang_String() {
+ // Test for method void
+ // java.text.DateFormatSymbols.setZoneStrings(java.lang.String [][])
+ String[][] val = { { "XX", "XX", "XX", "XX", "XX" },
+ { "YY", "YY", "YY", "YY", "YY" } };
+ dfs.setZoneStrings(val);
+ String[][] retVal = dfs.getZoneStrings();
+ assertTrue("get returns identical", retVal != dfs.getZoneStrings());
+ assertTrue("get[0] returns identical", retVal[0] != dfs
+ .getZoneStrings()[0]);
+ assertTrue("get returned identical", retVal != val);
+ assertEquals("Returned wrong array", val.length, retVal.length);
+ for (int i = 0; i < val.length; i++)
+ assertTrue("Failed to set strings: " + retVal[i], Arrays.equals(
+ retVal[i], val[i]));
+ }
+
+ /**
+ * @tests java.text.DateFormatSymbols#setZoneStrings(java.lang.String[][])
+ *
+ * Tests setting zone strings to invalid values
+ * Regression for HARMONY-6337
+ */
+ public void test_setZoneStrings_invalid() {
+ // failing cases
+ String[][] val1 = null;
+ try {
+ dfs.setZoneStrings(val1);
+ fail("Attempt to set zone strings a null array should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ String[][] val2 = { { "XX", "XX" }, { "YY", "YY" } };
+ try {
+ dfs.setZoneStrings(val2);
+ fail("Attempt to set zone strings to a 2D array that contains one or more "
+ + "rows of length less than 5 should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected because each subarray has length < 5
+ }
+
+ String[][] val3 = { { "a", "b", "c", "d", "e" },
+ { "a", "b", "c", "d", "e" },
+ { "a", "b", "c", "d" },
+ { "a", "b", "c", "d", "e" } };
+ try {
+ dfs.setZoneStrings(val3);
+ fail("Attempt to set zone strings to a 2D array that contains one or more "
+ + "rows of length less than 5 should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected because each subarray has length < 5
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ dfs = new DateFormatSymbols(new Locale("en", "us"));
+ }
+
+ // Test serialization mechanism of DateFormatSymbols
+ public void test_serialization() throws Exception {
+ DateFormatSymbols symbols = new DateFormatSymbols(Locale.FRANCE);
+ String[][] zoneStrings = symbols.getZoneStrings();
+ assertNotNull(zoneStrings);
+
+ // serialize
+ ByteArrayOutputStream byteOStream = new ByteArrayOutputStream();
+ ObjectOutputStream objectOStream = new ObjectOutputStream(byteOStream);
+ objectOStream.writeObject(symbols);
+
+ // and deserialize
+ ObjectInputStream objectIStream = new ObjectInputStream(
+ new ByteArrayInputStream(byteOStream.toByteArray()));
+ DateFormatSymbols symbolsD = (DateFormatSymbols) objectIStream
+ .readObject();
+
+ String[][] zoneStringsD = symbolsD.getZoneStrings();
+ assertNotNull(zoneStringsD);
+ assertEquals(symbols, symbolsD);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatTest.java
new file mode 100644
index 0000000..072d133
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DateFormatTest.java
@@ -0,0 +1,475 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.DateFormatSymbols;
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+public class DateFormatTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.DateFormat#clone()
+ */
+ public void test_clone() {
+ DateFormat format = DateFormat.getInstance();
+ DateFormat clone = (DateFormat) format.clone();
+ assertTrue("Clone not equal", format.equals(clone));
+ clone.getNumberFormat().setMinimumFractionDigits(123);
+ assertTrue("Clone shares NumberFormat", !format.equals(clone));
+ }
+
+ /**
+ * @tests java.text.DateFormat#getAvailableLocales()
+ */
+ public void test_getAvailableLocales() {
+ Locale[] locales = DateFormat.getAvailableLocales();
+ assertTrue("No locales", locales.length > 0);
+ boolean english = false, german = false;
+ for (int i = locales.length; --i >= 0;) {
+ if (locales[i].equals(Locale.ENGLISH))
+ english = true;
+ if (locales[i].equals(Locale.GERMAN))
+ german = true;
+ DateFormat f1 = DateFormat.getDateTimeInstance(DateFormat.SHORT,
+ DateFormat.SHORT, locales[i]);
+ assertTrue("Doesn't work",
+ f1.format(new Date()).getClass() == String.class);
+ }
+ assertTrue("Missing locales", english && german);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getCalendar()
+ */
+ public void test_getCalendar() {
+ DateFormat format = DateFormat.getInstance();
+ Calendar cal1 = format.getCalendar();
+ Calendar cal2 = format.getCalendar();
+ assertTrue("Calendars not identical", cal1 == cal2);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateInstance()
+ */
+ public void test_getDateInstance() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getDateInstance();
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default", f2.equals(DateFormat.getDateInstance(
+ DateFormat.DEFAULT, Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateInstance(int)
+ */
+ public void test_getDateInstanceI() {
+ assertTrue("Default not medium",
+ DateFormat.DEFAULT == DateFormat.MEDIUM);
+
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat
+ .getDateInstance(DateFormat.SHORT);
+ assertTrue("Wrong class1", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default1", f2.equals(DateFormat.getDateInstance(
+ DateFormat.SHORT, Locale.getDefault())));
+ assertTrue("Wrong symbols1", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work1",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.MEDIUM);
+ assertTrue("Wrong class2", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default2", f2.equals(DateFormat.getDateInstance(
+ DateFormat.MEDIUM, Locale.getDefault())));
+ assertTrue("Wrong symbols2", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work2",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.LONG);
+ assertTrue("Wrong class3", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default3", f2.equals(DateFormat.getDateInstance(
+ DateFormat.LONG, Locale.getDefault())));
+ assertTrue("Wrong symbols3", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work3",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL);
+ assertTrue("Wrong class4", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default4", f2.equals(DateFormat.getDateInstance(
+ DateFormat.FULL, Locale.getDefault())));
+ assertTrue("Wrong symbols4", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work4",
+ f2.format(new Date()).getClass() == String.class);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getDateInstance(77);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateInstance(int, java.util.Locale)
+ */
+ public void test_getDateInstanceILjava_util_Locale() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getDateInstance(
+ DateFormat.SHORT, Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.MEDIUM,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.LONG,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getDateInstance(77, Locale.GERMAN);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateTimeInstance()
+ */
+ public void test_getDateTimeInstance() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat
+ .getDateTimeInstance();
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default", f2.equals(DateFormat.getDateTimeInstance(
+ DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ private void testDateTime(int dStyle, int tStyle) {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat
+ .getDateTimeInstance(dStyle, tStyle);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ SimpleDateFormat date = (SimpleDateFormat) DateFormat.getDateInstance(
+ dStyle, Locale.getDefault());
+ SimpleDateFormat time = (SimpleDateFormat) DateFormat.getTimeInstance(
+ tStyle, Locale.getDefault());
+ assertTrue("Wrong default", f2.toPattern().equals(
+ date.toPattern() + " " + time.toPattern()));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateTimeInstance(int, int)
+ */
+ public void test_getDateTimeInstanceII() {
+ testDateTime(DateFormat.SHORT, DateFormat.SHORT);
+ testDateTime(DateFormat.SHORT, DateFormat.MEDIUM);
+ testDateTime(DateFormat.SHORT, DateFormat.LONG);
+ testDateTime(DateFormat.SHORT, DateFormat.FULL);
+
+ testDateTime(DateFormat.MEDIUM, DateFormat.SHORT);
+ testDateTime(DateFormat.MEDIUM, DateFormat.MEDIUM);
+ testDateTime(DateFormat.MEDIUM, DateFormat.LONG);
+ testDateTime(DateFormat.MEDIUM, DateFormat.FULL);
+
+ testDateTime(DateFormat.LONG, DateFormat.SHORT);
+ testDateTime(DateFormat.LONG, DateFormat.MEDIUM);
+ testDateTime(DateFormat.LONG, DateFormat.LONG);
+ testDateTime(DateFormat.LONG, DateFormat.FULL);
+
+ testDateTime(DateFormat.FULL, DateFormat.SHORT);
+ testDateTime(DateFormat.FULL, DateFormat.MEDIUM);
+ testDateTime(DateFormat.FULL, DateFormat.LONG);
+ testDateTime(DateFormat.FULL, DateFormat.FULL);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getDateTimeInstance(77, 66);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ private void testDateTimeLocale(int dStyle, int tStyle) {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat
+ .getDateTimeInstance(dStyle, tStyle, Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ SimpleDateFormat date = (SimpleDateFormat) DateFormat.getDateInstance(
+ dStyle, Locale.GERMAN);
+ SimpleDateFormat time = (SimpleDateFormat) DateFormat.getTimeInstance(
+ tStyle, Locale.GERMAN);
+ assertTrue("Wrong default", f2.toPattern().equals(
+ date.toPattern() + " " + time.toPattern()));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getDateTimeInstance(int, int,
+ * java.util.Locale)
+ */
+ public void test_getDateTimeInstanceIILjava_util_Locale() {
+ testDateTimeLocale(DateFormat.SHORT, DateFormat.SHORT);
+ testDateTimeLocale(DateFormat.SHORT, DateFormat.MEDIUM);
+ testDateTimeLocale(DateFormat.SHORT, DateFormat.LONG);
+ testDateTimeLocale(DateFormat.SHORT, DateFormat.FULL);
+
+ testDateTimeLocale(DateFormat.MEDIUM, DateFormat.SHORT);
+ testDateTimeLocale(DateFormat.MEDIUM, DateFormat.MEDIUM);
+ testDateTimeLocale(DateFormat.MEDIUM, DateFormat.LONG);
+ testDateTimeLocale(DateFormat.MEDIUM, DateFormat.FULL);
+
+ testDateTimeLocale(DateFormat.LONG, DateFormat.SHORT);
+ testDateTimeLocale(DateFormat.LONG, DateFormat.MEDIUM);
+ testDateTimeLocale(DateFormat.LONG, DateFormat.LONG);
+ testDateTimeLocale(DateFormat.LONG, DateFormat.FULL);
+
+ testDateTimeLocale(DateFormat.FULL, DateFormat.SHORT);
+ testDateTimeLocale(DateFormat.FULL, DateFormat.MEDIUM);
+ testDateTimeLocale(DateFormat.FULL, DateFormat.LONG);
+ testDateTimeLocale(DateFormat.FULL, DateFormat.FULL);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getDateTimeInstance(77, 66, Locale.GERMAN);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#getInstance()
+ */
+ public void test_getInstance() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getInstance();
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default", f2.equals(DateFormat.getDateTimeInstance(
+ DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getNumberFormat()
+ */
+ public void test_getNumberFormat() {
+ DateFormat format = DateFormat.getInstance();
+ NumberFormat nf1 = format.getNumberFormat();
+ NumberFormat nf2 = format.getNumberFormat();
+ assertTrue("NumberFormats not identical", nf1 == nf2);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getTimeInstance()
+ */
+ public void test_getTimeInstance() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getTimeInstance();
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default", f2.equals(DateFormat.getTimeInstance(
+ DateFormat.DEFAULT, Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+ }
+
+ /**
+ * @tests java.text.DateFormat#getTimeInstance(int)
+ */
+ public void test_getTimeInstanceI() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat
+ .getTimeInstance(DateFormat.SHORT);
+ assertTrue("Wrong class1", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default1", f2.equals(DateFormat.getTimeInstance(
+ DateFormat.SHORT, Locale.getDefault())));
+ assertTrue("Wrong symbols1", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work1",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.MEDIUM);
+ assertTrue("Wrong class2", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default2", f2.equals(DateFormat.getTimeInstance(
+ DateFormat.MEDIUM, Locale.getDefault())));
+ assertTrue("Wrong symbols2", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work2",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.LONG);
+ assertTrue("Wrong class3", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default3", f2.equals(DateFormat.getTimeInstance(
+ DateFormat.LONG, Locale.getDefault())));
+ assertTrue("Wrong symbols3", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work3",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.FULL);
+ assertTrue("Wrong class4", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default4", f2.equals(DateFormat.getTimeInstance(
+ DateFormat.FULL, Locale.getDefault())));
+ assertTrue("Wrong symbols4", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols()));
+ assertTrue("Doesn't work4",
+ f2.format(new Date()).getClass() == String.class);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getTimeInstance(77);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#getTimeInstance(int, java.util.Locale)
+ */
+ public void test_getTimeInstanceILjava_util_Locale() {
+ SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getTimeInstance(
+ DateFormat.SHORT, Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.MEDIUM,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.LONG,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ f2 = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.FULL,
+ Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work",
+ f2.format(new Date()).getClass() == String.class);
+
+ // regression test for HARMONY-940
+ try {
+ DateFormat.getTimeInstance(77, Locale.GERMAN);
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#setCalendar(java.util.Calendar)
+ */
+ public void test_setCalendarLjava_util_Calendar() {
+ DateFormat format = DateFormat.getInstance();
+ Calendar cal = Calendar.getInstance();
+ format.setCalendar(cal);
+ assertTrue("Not identical Calendar", cal == format.getCalendar());
+ }
+
+ /**
+ * @tests java.text.DateFormat#setNumberFormat(java.text.NumberFormat)
+ */
+ public void test_setNumberFormatLjava_text_NumberFormat() {
+ DateFormat format = DateFormat.getInstance();
+ NumberFormat f1 = NumberFormat.getInstance();
+ format.setNumberFormat(f1);
+ assertTrue("Not identical NumberFormat", f1 == format.getNumberFormat());
+ }
+
+ /**
+ * @tests java.text.DateFormat#parse(String)
+ */
+ public void test_parse_LString() {
+ DateFormat format = DateFormat.getInstance();
+ try {
+ format.parse("not a Date");
+ fail("should throw ParseException first");
+ } catch (ParseException e) {
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.text.DateFormat#setLenient(boolean)
+ */
+ public void test_setLenient() {
+ Date d = null;
+ DateFormat output = new SimpleDateFormat("MM/dd/yy");
+ output.setLenient(false);
+ try {
+ d = output.parse("01/01/-1");
+ fail("Should throw ParseException here.");
+ } catch (ParseException e) {}
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatSymbolsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatSymbolsTest.java
new file mode 100644
index 0000000..c6eace0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatSymbolsTest.java
@@ -0,0 +1,552 @@
+/*
+ * 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.tests.java.text;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.URL;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.NumberFormat;
+import java.util.Currency;
+import java.util.Locale;
+import java.util.ServiceConfigurationError;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class DecimalFormatSymbolsTest extends TestCase {
+
+ DecimalFormatSymbols dfs;
+
+ DecimalFormatSymbols dfsUS;
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#DecimalFormatSymbols()
+ */
+ public void test_Constructor() {
+ // Test for method java.text.DecimalFormatSymbols()
+ // Used in tests
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#DecimalFormatSymbols(java.util.Locale)
+ */
+ public void test_ConstructorLjava_util_Locale() {
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols(new Locale("en",
+ "us"));
+ assertEquals("Returned incorrect symbols", '%', dfs.getPercent());
+ }
+
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getAvailableLocales()
+ */
+ public void test_getAvailableLocales_no_provider() throws Exception {
+ Locale[] locales = DecimalFormatSymbols.getAvailableLocales();
+ assertNotNull(locales);
+ // must contain Locale.US
+ boolean flag = false;
+ for (Locale locale : locales) {
+ if (locale.equals(Locale.US)) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue(flag);
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getInstance()
+ */
+ public void test_getInstance() {
+ assertEquals(new DecimalFormatSymbols(), DecimalFormatSymbols.getInstance());
+ assertEquals(new DecimalFormatSymbols(Locale.getDefault()),
+ DecimalFormatSymbols.getInstance());
+
+ assertNotSame(DecimalFormatSymbols.getInstance(), DecimalFormatSymbols.getInstance());
+ }
+
+ public void test_getInstanceLjava_util_Locale() {
+ try {
+ DecimalFormatSymbols.getInstance(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ assertEquals(new DecimalFormatSymbols(Locale.GERMANY), DecimalFormatSymbols.getInstance(Locale.GERMANY));
+
+ Locale locale = new Locale("not exist language", "not exist country");
+ DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
+ assertNotNull(symbols);
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertTrue("Equal objects returned false", dfs.equals(dfs.clone()));
+ dfs.setDigit('B');
+ assertTrue("Un-Equal objects returned true", !dfs
+ .equals(new DecimalFormatSymbols()));
+
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getCurrency()
+ */
+ public void test_getCurrency() {
+ Currency currency = Currency.getInstance("USD");
+ assertEquals("Returned incorrect currency",
+ dfsUS.getCurrency(), currency);
+
+ Currency currK = Currency.getInstance("KRW");
+ Currency currX = Currency.getInstance("XXX");
+ Currency currE = Currency.getInstance("EUR");
+ // Currency currF = Currency.getInstance("FRF");
+
+ DecimalFormatSymbols dfs1 = new DecimalFormatSymbols(new Locale("ko",
+ "KR"));
+ assertTrue("Test1: Returned incorrect currency",
+ dfs1.getCurrency() == currK);
+ assertEquals("Test1: Returned incorrect currencySymbol", "\u20a9", dfs1
+ .getCurrencySymbol());
+ assertEquals("Test1: Returned incorrect intlCurrencySymbol", "KRW",
+ dfs1.getInternationalCurrencySymbol());
+
+ dfs1 = new DecimalFormatSymbols(new Locale("", "KR"));
+ assertTrue("Test2: Returned incorrect currency",
+ dfs1.getCurrency() == currK);
+ assertEquals("Test2: Returned incorrect currencySymbol", "\u20a9", dfs1
+ .getCurrencySymbol());
+ assertEquals("Test2: Returned incorrect intlCurrencySymbol", "KRW",
+ dfs1.getInternationalCurrencySymbol());
+
+ dfs1 = new DecimalFormatSymbols(new Locale("ko", ""));
+ assertTrue("Test3: Returned incorrect currency",
+ dfs1.getCurrency() == currX);
+ assertEquals("Test3: Returned incorrect currencySymbol", "\u00a4", dfs1
+ .getCurrencySymbol());
+ assertEquals("Test3: Returned incorrect intlCurrencySymbol", "XXX",
+ dfs1.getInternationalCurrencySymbol());
+
+ dfs1 = new DecimalFormatSymbols(new Locale("fr", "FR"));
+ assertTrue("Test4: Returned incorrect currency",
+ dfs1.getCurrency() == currE);
+ assertEquals("Test4: Returned incorrect currencySymbol", "\u20ac", dfs1
+ .getCurrencySymbol());
+ assertEquals("Test4: Returned incorrect intlCurrencySymbol", "EUR",
+ dfs1.getInternationalCurrencySymbol());
+
+ // RI fails these tests since it doesn't have the PREEURO variant
+ // dfs1 = new DecimalFormatSymbols(new Locale("fr", "FR","PREEURO"));
+ // assertTrue("Test5: Returned incorrect currency", dfs1.getCurrency()
+ // == currF);
+ // assertTrue("Test5: Returned incorrect currencySymbol",
+ // dfs1.getCurrencySymbol().equals("F"));
+ // assertTrue("Test5: Returned incorrect intlCurrencySymbol",
+ // dfs1.getInternationalCurrencySymbol().equals("FRF"));
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getCurrencySymbol()
+ */
+ public void test_getCurrencySymbol() {
+ assertEquals("Returned incorrect currencySymbol", "$", dfsUS
+ .getCurrencySymbol());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getDecimalSeparator()
+ */
+ public void test_getDecimalSeparator() {
+ dfs.setDecimalSeparator('*');
+ assertEquals("Returned incorrect DecimalSeparator symbol", '*', dfs
+ .getDecimalSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getDigit()
+ */
+ public void test_getDigit() {
+ dfs.setDigit('*');
+ assertEquals("Returned incorrect Digit symbol", '*', dfs.getDigit());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getExponentSeparator()
+ */
+ public void test_getExponentSeparator() {
+ dfs.setExponentSeparator("EE");
+ assertEquals("Returned incorrect Exponent Separator symbol", "EE", dfs
+ .getExponentSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getGroupingSeparator()
+ */
+ public void test_getGroupingSeparator() {
+ dfs.setGroupingSeparator('*');
+ assertEquals("Returned incorrect GroupingSeparator symbol", '*', dfs
+ .getGroupingSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getInfinity()
+ */
+ public void test_getInfinity() {
+ dfs.setInfinity("&");
+ assertTrue("Returned incorrect Infinity symbol",
+ dfs.getInfinity() == "&");
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getInternationalCurrencySymbol()
+ */
+ public void test_getInternationalCurrencySymbol() {
+ assertEquals("Returned incorrect InternationalCurrencySymbol", "USD",
+ dfsUS.getInternationalCurrencySymbol());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getMinusSign()
+ */
+ public void test_getMinusSign() {
+ dfs.setMinusSign('&');
+ assertEquals("Returned incorrect MinusSign symbol", '&', dfs
+ .getMinusSign());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getNaN()
+ */
+ public void test_getNaN() {
+ dfs.setNaN("NAN!!");
+ assertEquals("Returned incorrect nan symbol", "NAN!!", dfs.getNaN());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getPatternSeparator()
+ */
+ public void test_getPatternSeparator() {
+ dfs.setPatternSeparator('X');
+ assertEquals("Returned incorrect PatternSeparator symbol", 'X', dfs
+ .getPatternSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getPercent()
+ */
+ public void test_getPercent() {
+ dfs.setPercent('*');
+ assertEquals("Returned incorrect Percent symbol", '*', dfs.getPercent());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getPerMill()
+ */
+ public void test_getPerMill() {
+ dfs.setPerMill('#');
+ assertEquals("Returned incorrect PerMill symbol", '#', dfs.getPerMill());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#getZeroDigit()
+ */
+ public void test_getZeroDigit() {
+ dfs.setZeroDigit('*');
+ assertEquals("Returned incorrect ZeroDigit symbol", '*', dfs
+ .getZeroDigit());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setCurrency(java.util.Currency)
+ */
+ public void test_setCurrencyLjava_util_Currency() {
+ Locale locale = Locale.CANADA;
+ DecimalFormatSymbols dfs = ((DecimalFormat) NumberFormat
+ .getCurrencyInstance(locale)).getDecimalFormatSymbols();
+
+ try {
+ dfs.setCurrency(null);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ }
+
+ Currency currency = Currency.getInstance("JPY");
+ dfs.setCurrency(currency);
+
+ assertTrue("Returned incorrect currency", currency == dfs.getCurrency());
+ assertEquals("Returned incorrect currency symbol", currency.getSymbol(
+ locale), dfs.getCurrencySymbol());
+ assertTrue("Returned incorrect international currency symbol", currency
+ .getCurrencyCode().equals(dfs.getInternationalCurrencySymbol()));
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setDecimalSeparator(char)
+ */
+ public void test_setDecimalSeparatorC() {
+ dfs.setDecimalSeparator('*');
+ assertEquals("Returned incorrect DecimalSeparator symbol", '*', dfs
+ .getDecimalSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setDigit(char)
+ */
+ public void test_setDigitC() {
+ dfs.setDigit('*');
+ assertEquals("Returned incorrect Digit symbol", '*', dfs.getDigit());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setExponentSeparator(String)
+ */
+ public void test_setExponentSeparator() {
+ try {
+ dfs.setExponentSeparator(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ dfs.setExponentSeparator("");
+ assertEquals("Returned incorrect Exponent Separator symbol", "", dfs
+ .getExponentSeparator());
+
+ dfs.setExponentSeparator("what ever you want");
+ assertEquals("Returned incorrect Exponent Separator symbol",
+ "what ever you want", dfs.getExponentSeparator());
+
+ dfs.setExponentSeparator(" E ");
+ assertEquals("Returned incorrect Exponent Separator symbol", " E ", dfs
+ .getExponentSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setGroupingSeparator(char)
+ */
+ public void test_setGroupingSeparatorC() {
+ dfs.setGroupingSeparator('*');
+ assertEquals("Returned incorrect GroupingSeparator symbol", '*', dfs
+ .getGroupingSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setInfinity(java.lang.String)
+ */
+ public void test_setInfinityLjava_lang_String() {
+ dfs.setInfinity("&");
+ assertTrue("Returned incorrect Infinity symbol",
+ dfs.getInfinity() == "&");
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setInternationalCurrencySymbol(java.lang.String)
+ */
+ public void test_setInternationalCurrencySymbolLjava_lang_String() {
+ Locale locale = Locale.CANADA;
+ DecimalFormatSymbols dfs = ((DecimalFormat) NumberFormat
+ .getCurrencyInstance(locale)).getDecimalFormatSymbols();
+ Currency currency = Currency.getInstance("JPY");
+ dfs.setInternationalCurrencySymbol(currency.getCurrencyCode());
+
+ assertTrue("Test1: Returned incorrect currency", currency == dfs
+ .getCurrency());
+ assertEquals("Test1: Returned incorrect currency symbol", currency
+ .getSymbol(locale), dfs.getCurrencySymbol());
+ assertTrue("Test1: Returned incorrect international currency symbol",
+ currency.getCurrencyCode().equals(
+ dfs.getInternationalCurrencySymbol()));
+
+ dfs.setInternationalCurrencySymbol("bogus");
+ // RI support this legacy country code
+ // assertNotNull("Test2: Returned incorrect currency", dfs.getCurrency());
+ assertEquals("Test2: Returned incorrect international currency symbol",
+ "bogus", dfs.getInternationalCurrencySymbol());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setMinusSign(char)
+ */
+ public void test_setMinusSignC() {
+ dfs.setMinusSign('&');
+ assertEquals("Returned incorrect MinusSign symbol", '&', dfs
+ .getMinusSign());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setNaN(java.lang.String)
+ */
+ public void test_setNaNLjava_lang_String() {
+ dfs.setNaN("NAN!!");
+ assertEquals("Returned incorrect nan symbol", "NAN!!", dfs.getNaN());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setPatternSeparator(char)
+ */
+ public void test_setPatternSeparatorC() {
+ dfs.setPatternSeparator('X');
+ assertEquals("Returned incorrect PatternSeparator symbol", 'X', dfs
+ .getPatternSeparator());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setPercent(char)
+ */
+ public void test_setPercentC() {
+ dfs.setPercent('*');
+ assertEquals("Returned incorrect Percent symbol", '*', dfs.getPercent());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setPerMill(char)
+ */
+ public void test_setPerMillC() {
+ dfs.setPerMill('#');
+ assertEquals("Returned incorrect PerMill symbol", '#', dfs.getPerMill());
+ }
+
+ /**
+ * @tests java.text.DecimalFormatSymbols#setZeroDigit(char)
+ */
+ public void test_setZeroDigitC() {
+ dfs.setZeroDigit('*');
+ assertEquals("Set incorrect ZeroDigit symbol", '*', dfs.getZeroDigit());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ dfs = new DecimalFormatSymbols();
+ dfsUS = new DecimalFormatSymbols(new Locale("en", "us"));
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+
+ // Test serialization mechanism of DecimalFormatSymbols
+ public void test_serialization() throws Exception {
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRANCE);
+ Currency currency = symbols.getCurrency();
+ assertNotNull(currency);
+
+ // serialize
+ ByteArrayOutputStream byteOStream = new ByteArrayOutputStream();
+ ObjectOutputStream objectOStream = new ObjectOutputStream(byteOStream);
+ objectOStream.writeObject(symbols);
+
+ // and deserialize
+ ObjectInputStream objectIStream = new ObjectInputStream(
+ new ByteArrayInputStream(byteOStream.toByteArray()));
+ DecimalFormatSymbols symbolsD = (DecimalFormatSymbols) objectIStream
+ .readObject();
+
+ // The associated currency will not persist
+ currency = symbolsD.getCurrency();
+ assertNotNull(currency);
+ }
+
+ /**
+ * Assert that Harmony can correct read an instance that was created by
+ * the Java 1.5 RI. The actual values may differ on Harmony and other JREs,
+ * so we only assert the values that are known to be in the serialized data.
+ */
+ public void test_RIHarmony_compatible() throws Exception {
+ DecimalFormatSymbols dfs;
+ ObjectInputStream i = null;
+ try {
+ i = new ObjectInputStream(getClass().getClassLoader().getResourceAsStream(
+ "serialization/org/apache/harmony/tests/java/text/DecimalFormatSymbols.ser"));
+ dfs = (DecimalFormatSymbols) i.readObject();
+ } finally {
+ try {
+ if (i != null) {
+ i.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+ assertDecimalFormatSymbolsRIFrance(dfs);
+ }
+
+ static void assertDecimalFormatSymbolsRIFrance(DecimalFormatSymbols dfs) {
+ // Values based on Java 1.5 RI DecimalFormatSymbols for Locale.FRANCE
+ /*
+ * currency = [EUR]
+ * currencySymbol = [€][U+20ac]
+ * decimalSeparator = [,][U+002c]
+ * digit = [#][U+0023]
+ * groupingSeparator = [ ][U+00a0]
+ * infinity = [∞][U+221e]
+ * internationalCurrencySymbol = [EUR]
+ * minusSign = [-][U+002d]
+ * monetaryDecimalSeparator = [,][U+002c]
+ * naN = [�][U+fffd]
+ * patternSeparator = [;][U+003b]
+ * perMill = [‰][U+2030]
+ * percent = [%][U+0025]
+ * zeroDigit = [0][U+0030]
+ */
+ assertEquals("EUR", dfs.getCurrency().getCurrencyCode());
+ assertEquals("\u20AC", dfs.getCurrencySymbol());
+ assertEquals(',', dfs.getDecimalSeparator());
+ assertEquals('#', dfs.getDigit());
+ assertEquals('\u00a0', dfs.getGroupingSeparator());
+ assertEquals("\u221e", dfs.getInfinity());
+ assertEquals("EUR", dfs.getInternationalCurrencySymbol());
+ assertEquals('-', dfs.getMinusSign());
+ assertEquals(',', dfs.getMonetaryDecimalSeparator());
+ // RI's default NaN is U+FFFD, Harmony's is based on ICU
+ assertEquals("\uFFFD", dfs.getNaN());
+ assertEquals('\u003b', dfs.getPatternSeparator());
+ assertEquals('\u2030', dfs.getPerMill());
+ assertEquals('%', dfs.getPercent());
+ assertEquals('0', dfs.getZeroDigit());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI6.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
+ symbols.setExponentSeparator("EE");
+ symbols.setNaN("NaN");
+ SerializationTest.verifyGolden(this, symbols);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ITALIAN);
+ SerializationTest.verifySelf(symbols);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatTest.java
new file mode 100644
index 0000000..e0e04e8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/DecimalFormatTest.java
@@ -0,0 +1,2594 @@
+/*
+ * 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.tests.java.text;
+
+import java.io.ObjectInputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.RoundingMode;
+import java.text.AttributedCharacterIterator;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.FieldPosition;
+import java.text.NumberFormat;
+import java.text.ParsePosition;
+import java.util.ArrayList;
+import java.util.Currency;
+import java.util.List;
+import java.util.Locale;
+
+import junit.framework.Assert;
+import junit.framework.AssertionFailedError;
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+
+public class DecimalFormatTest extends TestCase {
+
+ // https://code.google.com/p/android/issues/detail?id=59600
+ public void test_setNan_emptyString() throws Exception {
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+ dfs.setNaN("");
+ DecimalFormat df = new DecimalFormat();
+ df.setDecimalFormatSymbols(dfs);
+ df.format(Double.NaN);
+ }
+
+ public void testAttributedCharacterIterator() throws Exception {
+ // Regression for http://issues.apache.org/jira/browse/HARMONY-333
+ AttributedCharacterIterator iterator = new DecimalFormat().formatToCharacterIterator(
+ new Integer(1));
+ assertNotNull(iterator);
+ assertFalse("attributes should exist", iterator.getAttributes().isEmpty());
+ }
+
+ public void test_parse_bigDecimal() throws Exception {
+ // parseBigDecimal default to false
+ DecimalFormat form = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ assertFalse(form.isParseBigDecimal());
+ form.setParseBigDecimal(true);
+ assertTrue(form.isParseBigDecimal());
+
+ Number result = form.parse("123.123");
+ assertEquals(new BigDecimal("123.123"), result);
+
+ form.setParseBigDecimal(false);
+ assertFalse(form.isParseBigDecimal());
+
+ result = form.parse("123.123");
+ assertFalse(result instanceof BigDecimal);
+ }
+
+ public void test_parse_integerOnly() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+ assertFalse("Default value of isParseIntegerOnly is true", format.isParseIntegerOnly());
+
+ format.setParseIntegerOnly(true);
+ assertTrue(format.isParseIntegerOnly());
+ Number result = format.parse("123.123");
+ assertEquals(new Long("123"), result);
+
+ format.setParseIntegerOnly(false);
+ assertFalse(format.isParseIntegerOnly());
+ result = format.parse("123.123");
+ assertEquals(new Double("123.123"), result);
+ }
+
+ // Test the type of the returned object
+ public void test_parse_returnType() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ Number number = form.parse("23.1", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ // Test parsed object of type double when
+ // parseBigDecimal is set to true
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ number = form.parse("23.1", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ form.setParseBigDecimal(true);
+ number = form.parse("23.1", new ParsePosition(0));
+
+ assertTrue(number instanceof BigDecimal);
+ assertEquals(new BigDecimal("23.1"), number);
+
+ // When parseIntegerOnly set to true, all numbers will be parsed
+ // into Long unless the value is out of the bound of Long or
+ // some special values such as NaN or Infinity.
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ form.setParseIntegerOnly(true);
+ number = form.parse("23.1f", new ParsePosition(0));
+
+ assertTrue(number instanceof Long);
+
+ number = form.parse("23.0", new ParsePosition(0));
+ assertTrue(number instanceof Long);
+
+ number = form.parse("-0.0", new ParsePosition(0));
+ assertTrue(number instanceof Long);
+ assertTrue(new Long(0).equals(number));
+
+ // The last integers representable by long.
+ number = form.parse("9223372036854775807.00", new ParsePosition(0));
+ assertEquals(Long.class, number.getClass());
+ number = form.parse("9223372036854775808.00", new ParsePosition(0));
+ assertEquals(Double.class, number.getClass());
+ // The first integers that need to be represented by double.
+ number = form.parse("-9223372036854775808.00", new ParsePosition(0));
+ assertEquals(Long.class, number.getClass());
+ number = form.parse("-9223372036854775809.00", new ParsePosition(0));
+ assertEquals(Double.class, number.getClass());
+
+ // Even if parseIntegerOnly is set to true, NaN will be parsed to Double
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ form.setParseIntegerOnly(true);
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ number = form.parse(symbols.getNaN(), new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ // Even if parseIntegerOnly is set to true, Infinity will still be
+ // parsed to Double
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ form.setParseIntegerOnly(true);
+ symbols = new DecimalFormatSymbols();
+ number = form.parse(symbols.getInfinity(), new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ // ParseBigDecimal take precedence of parseBigInteger
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ form.setParseIntegerOnly(true);
+ form.setParseBigDecimal(true);
+
+ number = form.parse("23.1f", new ParsePosition(0));
+
+ assertTrue(number instanceof BigDecimal);
+
+ number = form.parse("23.0", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ number = form.parse("-92,233,720,368,547,758,080.00", new ParsePosition(0));
+ assertFalse(number instanceof BigInteger);
+ assertTrue(number instanceof BigDecimal);
+
+ // Test whether the parsed object is of type float. (To be specific,
+ // they are of type Double)
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ number = form.parse("23.1f", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ form.setParseBigDecimal(true);
+ number = form.parse("23.1f", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+ assertEquals(new BigDecimal("23.1"), number);
+
+ // Integer will be parsed to Long, unless parseBigDecimal is set to true
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ number = form.parse("123", new ParsePosition(0));
+ assertTrue(number instanceof Long);
+
+ form.setParseBigDecimal(true);
+ number = form.parse("123", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+ assertEquals(new BigDecimal("123"), number);
+
+ // NaN will be parsed to Double, no matter parseBigDecimal set or not.
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ symbols = new DecimalFormatSymbols();
+ number = form.parse(symbols.getNaN() + "", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ form.setParseBigDecimal(true);
+ number = form.parse(symbols.getNaN() + "", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ // Infinity will be parsed to Double, no matter parseBigDecimal set or
+ // not.
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ symbols = new DecimalFormatSymbols();
+
+ number = form.parse(symbols.getInfinity(), new ParsePosition(0));
+
+ assertTrue(number instanceof Double);
+ assertEquals("Infinity", number.toString());
+ // When set bigDecimal to true, the result of parsing infinity
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ symbols = new DecimalFormatSymbols();
+ form.setParseBigDecimal(true);
+
+ number = form.parse(symbols.getInfinity(), new ParsePosition(0));
+ assertTrue(number instanceof Double);
+ assertEquals("Infinity", number.toString());
+
+ // Negative infinity will be parsed to double no matter parseBigDecimal
+ // set or not
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ symbols = new DecimalFormatSymbols();
+
+ number = form.parse("-" + symbols.getInfinity(), new ParsePosition(0));
+
+ assertTrue(number instanceof Double);
+ assertEquals("-Infinity", number.toString());
+
+ // When set bigDecimal to true, the result of parsing minus infinity
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ symbols = new DecimalFormatSymbols();
+ form.setParseBigDecimal(true);
+
+ number = form.parse("-" + symbols.getInfinity(), new ParsePosition(0));
+
+ assertTrue(number instanceof Double);
+ assertEquals("-Infinity", number.toString());
+
+ // -0.0 will be parsed to different type according to the combination of
+ // parseBigDecimal and parseIntegerOnly
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ // parseBigDecimal == true;
+ // parseIntegerOnly == false;
+ form.setParseBigDecimal(true);
+ number = form.parse("-0", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ number = form.parse("-0.0", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ // parseBigDecimal == false;
+ // parseIntegerOnly == true;
+ form.setParseBigDecimal(false);
+ form.setParseIntegerOnly(true);
+ number = form.parse("-0", new ParsePosition(0));
+
+ assertTrue(number instanceof Long);
+
+ number = form.parse("-0.0", new ParsePosition(0));
+ assertTrue(number instanceof Long);
+
+ // parseBigDecimal == false;
+ // parseIntegerOnly == false;
+ form.setParseBigDecimal(false);
+ form.setParseIntegerOnly(false);
+ number = form.parse("-0", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ number = form.parse("-0.0", new ParsePosition(0));
+ assertTrue(number instanceof Double);
+
+ // parseBigDecimal == true;
+ // parseIntegerOnly == true;
+ // parseBigDecimal take precedence of parseBigInteger
+ form.setParseBigDecimal(true);
+ form.setParseIntegerOnly(true);
+ number = form.parse("-0", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ number = form.parse("-0.0", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ number = form.parse("12.4", new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+
+ // When parseBigDecimal is set to false, no matter how massive the
+ // mantissa part of a number is, the number will be parsed into Double
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ number = form.parse("9,223,372,036,854,775,808.00",
+ new ParsePosition(0));
+
+ assertTrue(number instanceof Double);
+ assertEquals("9.223372036854776E18", number.toString());
+
+ number = form.parse("-92,233,720,368,547,758,080.00",
+ new ParsePosition(0));
+ assertTrue(number instanceof Double);
+ assertEquals("-9.223372036854776E19", number.toString());
+
+ // When parseBigDecimal is set to true, if mantissa part of number
+ // exceeds Long.MAX_VALUE, the number will be parsed into BigDecimal
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ form.setParseBigDecimal(true);
+ number = form.parse("9,223,372,036,854,775,808.00",
+ new ParsePosition(0));
+
+ assertTrue(number instanceof BigDecimal);
+
+ assertEquals(9.223372036854776E18, number.doubleValue(), 0);
+
+ number = form.parse("-92,233,720,368,547,758,080.00", new ParsePosition(0));
+
+ assertTrue(number instanceof BigDecimal);
+ assertEquals(-9.223372036854776E19, number.doubleValue(), 0);
+
+ // The minimum value of Long will be parsed to Long when parseBigDecimal
+ // is not set
+
+ ParsePosition pos = new ParsePosition(0);
+ DecimalFormat df = new DecimalFormat();
+ pos = new ParsePosition(0);
+ Number nb = df.parse("" + Long.MIN_VALUE, pos);
+ assertTrue(nb instanceof Long);
+
+ // The maximum value of Long will be parsed to Long when parseBigDecimal
+ // is set
+ pos = new ParsePosition(0);
+ df = new DecimalFormat();
+ pos = new ParsePosition(0);
+ nb = df.parse("" + Long.MAX_VALUE, pos);
+ assertTrue(nb instanceof Long);
+
+ // When parsing invalid string( which is neither consist of digits nor
+ // NaN/Infinity), a null will be returned.
+
+ pos = new ParsePosition(0);
+ df = new DecimalFormat();
+ try {
+ nb = df.parse("invalid", pos);
+ assertNull(nb);
+ } catch (NullPointerException e) {
+ fail("Should not throw NPE");
+ }
+ }
+
+ public void test_parse_largeBigDecimal() {
+ DecimalFormat form = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ form.setParseIntegerOnly(true);
+ form.setParseBigDecimal(true);
+
+ final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408,"
+ + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077,"
+ + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653,"
+ + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152,"
+ + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806,"
+ + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476,"
+ + "354,361,838,599,762,500,808,052,368,249,716,736";
+ Number number = form.parse(doubleMax2, new ParsePosition(0));
+ assertTrue(number instanceof BigDecimal);
+ BigDecimal result = (BigDecimal) number;
+ assertEquals(new BigDecimal(Double.MAX_VALUE).add(new BigDecimal(Double.MAX_VALUE)),
+ result);
+ }
+
+ public void testMaximumFractionDigits_getAndSet() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ // getMaximumFractionDigits of DecimalFormat defaults to 3
+ assertEquals(3, form.getMaximumFractionDigits());
+
+ form.setMaximumFractionDigits(310);
+ assertEquals(310, form.getMaximumFractionDigits());
+
+ // Deliberately > 340. The API docs mention 340 and suggest that you can set the value
+ // higher but it will use 340 as a ceiling.
+ form.setMaximumFractionDigits(500);
+ assertEquals(500, form.getMaximumFractionDigits());
+
+ form.setMaximumFractionDigits(500);
+ assertEquals(500, form.getMaximumFractionDigits());
+ form.format(12.3);
+ assertEquals(500, form.getMaximumFractionDigits());
+
+ form.setMaximumFractionDigits(-2);
+ assertEquals(0, form.getMaximumFractionDigits());
+ }
+
+ public void testMinimumFractionDigits_getAndSet() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ // getMinimumFractionDigits from NumberFormat (default to 0)
+ // getMinimumFractionDigits from DecimalFormat (default to 0)
+ assertEquals(0, form.getMinimumFractionDigits());
+
+ form.setMinimumFractionDigits(310);
+ assertEquals(310, form.getMinimumFractionDigits());
+
+ // Deliberately > 340. The API docs mention 340 and suggest that you can set the value
+ // higher but it will use 340 as a ceiling.
+ form.setMinimumFractionDigits(500);
+ assertEquals(500, form.getMinimumFractionDigits());
+
+ form.setMaximumFractionDigits(400);
+ assertEquals(400, form.getMinimumFractionDigits());
+
+ form.setMinimumFractionDigits(-3);
+ assertEquals(0, form.getMinimumFractionDigits());
+ }
+
+ public void testMaximumIntegerDigits_getAndSet() {
+ // When use default locale, in this case zh_CN
+ // the returned instance of NumberFormat is a DecimalFormat
+ DecimalFormat form = new DecimalFormat("00.###E0");
+ assertEquals(2, form.getMaximumIntegerDigits());
+
+ form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ form.setMaximumIntegerDigits(300);
+ assertEquals(300, form.getMaximumIntegerDigits());
+
+ // Deliberately > 309. The API docs mention 309 and suggest that you can set the value
+ // higher but it will use 309 as a ceiling.
+ form.setMaximumIntegerDigits(500);
+ assertEquals(500, form.getMaximumIntegerDigits());
+
+ form = new DecimalFormat("00.###E0");
+ assertEquals(2, form.getMaximumIntegerDigits());
+
+ form.setMaximumIntegerDigits(500);
+ assertEquals(500, form.getMaximumIntegerDigits());
+ form.format(12.3);
+ assertEquals(500, form.getMaximumIntegerDigits());
+
+ form.setMaximumIntegerDigits(-3);
+ assertEquals(0, form.getMaximumIntegerDigits());
+
+ // regression test for HARMONY-878
+ assertTrue(new DecimalFormat("0\t'0'").getMaximumIntegerDigits() > 0);
+ }
+
+ public void testMinimumIntegerDigits_getAndSet() {
+ final int minIntDigit = 1;
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ // getMaximumIntegerDigits from DecimalFormat (default to 1)
+ assertEquals(minIntDigit, form.getMinimumIntegerDigits());
+
+ form.setMinimumIntegerDigits(300);
+ assertEquals(300, form.getMinimumIntegerDigits());
+
+ // Deliberately > 309. The API docs mention 309 and suggest that you can set the value
+ // higher but it will use 309 as a ceiling.
+ form.setMinimumIntegerDigits(500);
+ assertEquals(500, form.getMinimumIntegerDigits());
+
+ form.setMaximumIntegerDigits(400);
+ assertEquals(400, form.getMinimumIntegerDigits());
+
+ form.setMinimumIntegerDigits(-3);
+ assertEquals(0, form.getMinimumIntegerDigits());
+ }
+
+ // When MaxFractionDigits is set first and less than MinFractionDigits, max
+ // will be changed to min value
+ public void testMinimumFactionDigits_minChangesMax() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ form.setMaximumFractionDigits(100);
+ form.setMinimumFractionDigits(200);
+
+ assertEquals(200, form.getMaximumFractionDigits());
+ assertEquals(200, form.getMinimumFractionDigits());
+
+ form.setMaximumIntegerDigits(100);
+ form.setMinimumIntegerDigits(200);
+
+ assertEquals(200, form.getMaximumIntegerDigits());
+ assertEquals(200, form.getMinimumIntegerDigits());
+ }
+
+ // When MinFractionDigits is set first and less than MaxFractionDigits, min
+ // will be changed to max value
+ public void testMaximumFactionDigits_maxChangesMin() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ form.setMinimumFractionDigits(200);
+ form.setMaximumFractionDigits(100);
+
+ assertEquals(100, form.getMaximumFractionDigits());
+ assertEquals(100, form.getMinimumFractionDigits());
+
+ form.setMinimumIntegerDigits(200);
+ form.setMaximumIntegerDigits(100);
+
+ assertEquals(100, form.getMaximumIntegerDigits());
+ assertEquals(100, form.getMinimumIntegerDigits());
+ }
+
+ public void test_formatObject_errorCases() {
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ // If Object(including null) is not of type Number,
+ // IllegalArgumentException will be thrown out
+ try {
+ form.format(new Object(), new StringBuffer(), new FieldPosition(0));
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ form.format(null, new StringBuffer(), new FieldPosition(0));
+ fail("Should throw IAE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ // When StringBuffer == null || FieldPosition == null
+ // NullPointerException will be thrown out.
+ try {
+ form.format(new Double(1.9), null, new FieldPosition(0));
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ form.format(new Double(1.3), new StringBuffer(), null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ form.format(new Object(), new StringBuffer(), new FieldPosition(0));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_formatObject() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+
+ // format maxLong
+ FieldPosition pos = new FieldPosition(0);
+ StringBuffer out = format.format(new Long(Long.MAX_VALUE), new StringBuffer(), pos);
+ assertTrue("Wrong result L1: " + out, out.toString().equals("9,223,372,036,854,775,807"));
+
+ // format minLong
+ pos = new FieldPosition(0);
+ out = format.format(new Long(Long.MIN_VALUE), new StringBuffer(), pos);
+ assertTrue("Wrong result L2: " + out, out.toString().equals("-9,223,372,036,854,775,808"));
+
+ // format maxLong of type BigInteger
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigInteger(String.valueOf(Long.MAX_VALUE)),
+ new StringBuffer(), pos);
+ assertTrue("Wrong result BI1: " + out, out.toString().equals("9,223,372,036,854,775,807"));
+
+ // format minLong of type BigInteger
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigInteger(String.valueOf(Long.MIN_VALUE)),
+ new StringBuffer(), pos);
+ assertTrue("Wrong result BI2: " + out, out.toString().equals("-9,223,372,036,854,775,808"));
+
+ // format maxLong + 1
+ java.math.BigInteger big;
+ pos = new FieldPosition(0);
+ big = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE))
+ .add(new java.math.BigInteger("1"));
+ out = format.format(big, new StringBuffer(), pos);
+ assertTrue("Wrong result BI3: " + out, out.toString().equals("9,223,372,036,854,775,808"));
+
+ // format minLong - 1
+ pos = new FieldPosition(0);
+ big = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE))
+ .add(new java.math.BigInteger("-1"));
+ out = format.format(big, new StringBuffer(), pos);
+ assertTrue("Wrong result BI4: " + out, out.toString().equals("-9,223,372,036,854,775,809"));
+
+ // format big decimal
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigDecimal("51.348"), new StringBuffer(), pos);
+ assertTrue("Wrong result BD1: " + out, out.toString().equals("51.348"));
+
+ // format big decimal
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigDecimal("51"), new StringBuffer(), pos);
+ assertTrue("Wrong result BD2: " + out, out.toString().equals("51"));
+
+ // format big decimal Double.MAX_VALUE * 2
+ java.math.BigDecimal bigDecimal;
+ pos = new FieldPosition(0);
+ final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408,"
+ + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077,"
+ + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653,"
+ + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152,"
+ + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806,"
+ + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476,"
+ + "354,361,838,599,762,500,808,052,368,249,716,736";
+ bigDecimal = new BigDecimal(Double.MAX_VALUE).add(new BigDecimal(Double.MAX_VALUE));
+ out = format.format(bigDecimal, new StringBuffer(), pos);
+ assertTrue("Wrong result BDmax2: " + out, out.toString().equals(doubleMax2));
+
+ // format big decimal Double.MIN_VALUE + Double.MIN_VALUE
+ // and Double.MIN_VALUE - Double.MIN_VALUE
+ pos = new FieldPosition(0);
+
+ bigDecimal = new BigDecimal(Double.MIN_VALUE).add(new BigDecimal(Double.MIN_VALUE));
+ out = format.format(bigDecimal, new StringBuffer(), pos);
+
+ bigDecimal = new BigDecimal(Float.MAX_VALUE).add(new BigDecimal(Float.MAX_VALUE));
+ out = format.format(bigDecimal, new StringBuffer(), pos);
+ final String BDFloatMax2 = "680,564,693,277,057,719,623,408,366,969,033,850,880";
+ assertTrue("Wrong result BDFloatMax2: " + out, out.toString().equals(BDFloatMax2));
+ // format big decimal Float.MIN_VALUE + Float.MIN_VALUE
+ // and Float.MIN_VALUE - Float.MIN_VALUE
+ bigDecimal = new BigDecimal(Float.MIN_VALUE).add(new BigDecimal(Float.MIN_VALUE));
+ out = format.format(bigDecimal, new StringBuffer(), pos);
+ final String BDFloatMin2 = "0";
+
+ bigDecimal = new BigDecimal(Float.MIN_VALUE).subtract(new BigDecimal(Float.MIN_VALUE));
+ out = format.format(bigDecimal, new StringBuffer(), pos);
+
+ assertTrue("Wrong result BDFloatMax2: " + out, out.toString().equals(BDFloatMin2));
+ }
+
+ public void test_equals() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ DecimalFormat cloned = (DecimalFormat) format.clone();
+ cloned.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
+ assertEquals(format, cloned);
+
+ Currency c = Currency.getInstance(Locale.US);
+ cloned.setCurrency(c);
+
+ assertEquals(format, cloned);
+ }
+
+ public void test_getNegativePrefix() {
+ DecimalFormat df = new DecimalFormat();
+ df.setNegativePrefix("--");
+ assertTrue("Incorrect negative prefix", df.getNegativePrefix().equals("--"));
+ }
+
+ public void test_getNegativeSuffix() {
+ DecimalFormat df = new DecimalFormat();
+ df.setNegativeSuffix("&");
+ assertTrue("Incorrect negative suffix", df.getNegativeSuffix().equals("&"));
+ }
+
+ public void test_getPositivePrefix() {
+ DecimalFormat df = new DecimalFormat();
+ df.setPositivePrefix("++");
+ assertTrue("Incorrect positive prefix", df.getPositivePrefix().equals("++"));
+ }
+
+ public void test_getPositiveSuffix() {
+ DecimalFormat df = new DecimalFormat();
+ df.setPositiveSuffix("%");
+ assertTrue("Incorrect positive prefix", df.getPositiveSuffix().equals("%"));
+ }
+
+ public void test_setPositivePrefix() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+ assertEquals("", format.getPositivePrefix());
+
+ format.setPositivePrefix("PosPrf");
+ assertEquals("PosPrf", format.getPositivePrefix());
+ assertTrue(format.parse("PosPrf123.45").doubleValue() == 123.45);
+
+ format.setPositivePrefix("");
+ assertEquals("", format.getPositivePrefix());
+
+ format.setPositivePrefix(null);
+ assertNull(format.getPositivePrefix());
+ }
+
+ public void test_setPositiveSuffix() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+ assertEquals("", format.getPositiveSuffix());
+
+ format.setPositiveSuffix("PosSfx");
+ assertEquals("PosSfx", format.getPositiveSuffix());
+ assertTrue(format.parse("123.45PosSfx").doubleValue() == 123.45);
+
+ format.setPositiveSuffix("");
+ assertEquals("", format.getPositiveSuffix());
+
+ format.setPositiveSuffix(null);
+ assertNull(format.getPositiveSuffix());
+ }
+
+ public void test_setNegativePrefix() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+ assertEquals("-", format.getNegativePrefix());
+
+ format.setNegativePrefix("NegPrf");
+ assertEquals("NegPrf", format.getNegativePrefix());
+ assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45);
+ format.setNegativePrefix("");
+ assertEquals("", format.getNegativePrefix());
+
+ format.setNegativePrefix(null);
+ assertNull(format.getNegativePrefix());
+ }
+
+ public void test_setNegativeSuffix() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+ assertEquals("", format.getNegativeSuffix());
+
+ format.setNegativeSuffix("NegSfx");
+ assertEquals("NegSfx", format.getNegativeSuffix());
+ assertTrue(format.parse("123.45NegPfx").doubleValue() == 123.45);
+
+ format.setNegativeSuffix("");
+ assertEquals("", format.getNegativeSuffix());
+
+ format.setNegativeSuffix(null);
+ assertNull(format.getNegativeSuffix());
+ }
+
+ public void test_setGroupingUsed() {
+ DecimalFormat format = new DecimalFormat();
+
+ StringBuffer buf = new StringBuffer();
+ format.setGroupingUsed(false);
+ format.format(new Long(1970), buf, new FieldPosition(0));
+ assertEquals("1970", buf.toString());
+ assertFalse(format.isGroupingUsed());
+ format.format(new Long(1970), buf, new FieldPosition(0));
+ assertEquals("19701970", buf.toString());
+ assertFalse(format.isGroupingUsed());
+
+ format.setGroupingUsed(true);
+ format.format(new Long(1970), buf, new FieldPosition(0));
+ assertEquals("197019701,970", buf.toString());
+ assertTrue(format.isGroupingUsed());
+ }
+
+ public void test_isGroupingUsed() {
+ assertFalse(new DecimalFormat("####.##").isGroupingUsed());
+ assertFalse(new DecimalFormat("######.######").isGroupingUsed());
+ assertFalse(new DecimalFormat("000000.000000").isGroupingUsed());
+ assertFalse(new DecimalFormat("######.000000").isGroupingUsed());
+ assertFalse(new DecimalFormat("000000.######").isGroupingUsed());
+ assertFalse(new DecimalFormat(" ###.###").isGroupingUsed());
+ assertFalse(new DecimalFormat("$#####.######").isGroupingUsed());
+ assertFalse(new DecimalFormat("$$####.######").isGroupingUsed());
+
+ assertTrue(new DecimalFormat("###,####").isGroupingUsed());
+ }
+
+ public void testConstructor_noArg() {
+ // Test for method java.text.DecimalFormat()
+ // the constructor form that specifies a pattern is equal to the form
+ // constructed with no pattern and applying that pattern using the
+ // applyPattern call
+ DecimalFormat format1 = new DecimalFormat();
+ format1.applyPattern("'$'1000.0000");
+ DecimalFormat format2 = new DecimalFormat();
+ format2.applyPattern("'$'1000.0000");
+ assertTrue("Constructed format did not match applied format object",
+ format2.equals(format1));
+ DecimalFormat format3 = new DecimalFormat("'$'1000.0000");
+ assertTrue("Constructed format did not match applied format object",
+ format3.equals(format1));
+ DecimalFormat format4 = new DecimalFormat("'$'8000.0000");
+ assertTrue("Constructed format did not match applied format object",
+ !format4.equals(format1));
+ }
+
+ public void testConstructor_string() {
+ // Test for method java.text.DecimalFormat(java.lang.String)
+ // the constructor form that specifies a pattern is equal to the form
+ // constructed with no pattern and applying that pattern using the
+ // applyPattern call
+ DecimalFormat format = new DecimalFormat("'$'0000.0000");
+ DecimalFormat format1 = new DecimalFormat();
+ format1.applyPattern("'$'0000.0000");
+ assertTrue("Constructed format did not match applied format object",
+ format.equals(format1));
+
+ new DecimalFormat("####.##");
+ new DecimalFormat("######.######");
+ new DecimalFormat("000000.000000");
+ new DecimalFormat("######.000000");
+ new DecimalFormat("000000.######");
+ new DecimalFormat(" ###.###");
+ new DecimalFormat("$#####.######");
+ new DecimalFormat("$$####.######");
+ new DecimalFormat("%#,##,###,####");
+ new DecimalFormat("#,##0.00;(#,##0.00)");
+
+ try {
+ new DecimalFormat(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ new DecimalFormat("%#,##,###,####'");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ new DecimalFormat("#.##0.00");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testConstructor_stringAndSymbols() {
+ // case 1: Try to construct object using correct pattern and format
+ // symbols.
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.CANADA);
+ DecimalFormat format1 = new DecimalFormat("'$'1000.0000", dfs);
+ DecimalFormat format2 = new DecimalFormat();
+ format2.applyPattern("'$'1000.0000");
+ format2.setDecimalFormatSymbols(dfs);
+ assertTrue("Constructed format did not match applied format object",
+ format2.equals(format1));
+ assertTrue("Constructed format did not match applied format object",
+ !format1.equals(
+ new DecimalFormat("'$'1000.0000", new DecimalFormatSymbols(Locale.CHINA))));
+
+ // case 2: Try to construct object using null arguments.
+ try {
+ new DecimalFormat("'$'1000.0000", (DecimalFormatSymbols) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ new DecimalFormat(null, new DecimalFormatSymbols());
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ new DecimalFormat(null, (DecimalFormatSymbols) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // case 3: Try to construct object using incorrect pattern.
+ try {
+ new DecimalFormat("$'", new DecimalFormatSymbols());
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_applyPattern() {
+ DecimalFormat format = new DecimalFormat("#.#");
+ assertEquals("Wrong pattern 1", "#0.#", format.toPattern());
+ format = new DecimalFormat("#.");
+ assertEquals("Wrong pattern 2", "#0.", format.toPattern());
+ format = new DecimalFormat("#");
+ assertEquals("Wrong pattern 3", "#", format.toPattern());
+ format = new DecimalFormat(".#");
+ assertEquals("Wrong pattern 4", "#.0", format.toPattern());
+
+ // Regression for HARMONY-6485
+ format = new DecimalFormat();
+ format.setMinimumIntegerDigits(0);
+ format.setMinimumFractionDigits(0);
+ format.setMaximumFractionDigits(0);
+ format.applyPattern("00.0#");
+ assertEquals("Minimum integer digits not set", 2, format.getMinimumIntegerDigits());
+ assertEquals("Minimum fraction digits not set", 1, format.getMinimumFractionDigits());
+ assertEquals("Maximum fraction digits not set", 2, format.getMaximumFractionDigits());
+
+ try {
+ format.applyPattern(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ format.applyPattern("%#,##,###,####'");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ format.applyPattern("#.##0.00");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ // AndroidOnly: icu supports 2 grouping sizes
+ public void test_applyPattern_icu2GroupingSizes() {
+ DecimalFormat decFormat = new DecimalFormat("#.#");
+ String[] patterns = {
+ "####.##", "######.######", "000000.000000",
+ "######.000000", "000000.######", " ###.###", "$#####.######",
+ "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)",
+ "##.##-E"
+ };
+
+ String[] expResult = {
+ "#0.##", "#0.######", "#000000.000000",
+ "#.000000", "#000000.######", " #0.###", "$#0.######",
+ "$$#0.######",
+ "%#,###,####", // icu only. icu supports two grouping sizes
+ "#,##0.00;(#,##0.00)",
+ "#0.##-'E'"
+ // icu only. E in the suffix does not need to be quoted. This is done automatically.
+ };
+
+ for (int i = 0; i < patterns.length; i++) {
+ decFormat.applyPattern(patterns[i]);
+ String result = decFormat.toPattern();
+ assertEquals("Failed to apply following pattern: " + patterns[i] +
+ "\n expected: " + expResult[i] +
+ "\n returned: " + result, expResult[i], result);
+ }
+ }
+
+ public void test_applyLocalizedPattern() throws Exception {
+ DecimalFormat format = new DecimalFormat();
+
+ // case 1: Try to apply correct variants of pattern.
+ format.applyLocalizedPattern("#.#");
+ assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern());
+ format.applyLocalizedPattern("#.");
+ assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern());
+ format.applyLocalizedPattern("#");
+ assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern());
+ format.applyLocalizedPattern(".#");
+ assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern());
+
+ // case 2: Try to apply malformed patten.
+ try {
+ format.applyLocalizedPattern("'#,#:#0.0#;(#)");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ // case 3: Try to apply null pattern.
+ try {
+ format.applyLocalizedPattern((String) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_toPattern() {
+ DecimalFormat format = new DecimalFormat();
+ format.applyPattern("#.#");
+ assertEquals("Wrong pattern 1", "#0.#", format.toPattern());
+ format.applyPattern("#.");
+ assertEquals("Wrong pattern 2", "#0.", format.toPattern());
+ format.applyPattern("#");
+ assertEquals("Wrong pattern 3", "#", format.toPattern());
+ format.applyPattern(".#");
+ assertEquals("Wrong pattern 4", "#.0", format.toPattern());
+ }
+
+ public void test_toLocalizedPattern() {
+ DecimalFormat format = new DecimalFormat();
+ format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
+ format.applyLocalizedPattern("#.#");
+ assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern());
+ format.applyLocalizedPattern("#.");
+ assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern());
+ format.applyLocalizedPattern("#");
+ assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern());
+ format.applyLocalizedPattern(".#");
+ assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern());
+ }
+
+ public void test_hashCode() {
+ DecimalFormat df1 = new DecimalFormat();
+ DecimalFormat df2 = (DecimalFormat) df1.clone();
+ assertTrue("Hash codes of equals object are not equal", df2.hashCode() == df1.hashCode());
+ }
+
+ public void test_clone() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ DecimalFormat cloned = (DecimalFormat) format.clone();
+ assertEquals(cloned.getDecimalFormatSymbols(), format.getDecimalFormatSymbols());
+
+ format = new DecimalFormat("'$'0000.0000");
+ DecimalFormat format1 = (DecimalFormat) (format.clone());
+ // make sure the objects are equal
+ assertTrue("Object's clone isn't equal!", format.equals(format1));
+ // change the content of the clone and make sure it's not equal anymore
+ // verifies that it's data is now distinct from the original
+ format1.applyPattern("'$'0000.####");
+ assertTrue("Object's changed clone should not be equal!", !format.equals(format1));
+ }
+
+ public void test_formatDouble_maximumFractionDigits() {
+ DecimalFormat df = new DecimalFormat("###0.##", new DecimalFormatSymbols(Locale.US));
+ df.setMaximumFractionDigits(3);
+ assertEquals(3, df.getMaximumFractionDigits());
+ assertEquals("1.235", df.format(1.23456));
+ df.setMinimumFractionDigits(4);
+ assertEquals(4, df.getMaximumFractionDigits());
+ assertEquals("456.0000", df.format(456));
+
+ df = new DecimalFormat("##0.#");
+ df.setMaximumFractionDigits(30);
+ assertEquals("0", df.format(0.0));
+ assertEquals("-0", df.format(-0.0));
+ assertEquals("1", df.format(1.0));
+ assertEquals("-1", df.format(-1.0));
+ }
+
+ public void test_formatDouble_minimumFractionDigits() {
+ DecimalFormat df = new DecimalFormat("###0.##", new DecimalFormatSymbols(Locale.US));
+ df.setMinimumFractionDigits(4);
+ assertEquals(4, df.getMinimumFractionDigits());
+ assertEquals("1.2300", df.format(1.23));
+ df.setMaximumFractionDigits(2);
+ assertEquals(2, df.getMinimumFractionDigits());
+ assertEquals("456.00", df.format(456));
+
+ df = new DecimalFormat("##0.#", new DecimalFormatSymbols(Locale.US));
+ df.setMinimumFractionDigits(30);
+ assertEquals("0.000000000000000000000000000000", df.format(0.0));
+ assertEquals("-0.000000000000000000000000000000", df.format(-0.0));
+ assertEquals("1.000000000000000000000000000000", df.format(1.0));
+ assertEquals("-1.000000000000000000000000000000", df.format(-1.0));
+ }
+
+ public void test_formatDouble_withFieldPosition() {
+ new Support_DecimalFormat(
+ "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition")
+ .t_format_with_FieldPosition();
+ }
+
+ // This test serves as a regression test for Android's behavior.
+ // There are many patterns that produce different output from the RI but are sometimes the
+ // consequence of Android following the ICU DecimalFormat rules.
+ public void test_formatDouble_scientificNotation() {
+ FormatTester formatTester = new FormatTester();
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+
+ DecimalFormat df = new DecimalFormat("00.0#E0", dfs);
+ // ["00.0#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=2,
+ // maxFractionDigits=2,minIntegerDigits=2,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (2) + "max fractional digits (2) == 4
+ formatTester.format(df, "00.0E0", 0.0);
+ formatTester.format(df, "10.0E-1", 1.0);
+ formatTester.format(df, "12.0E0", 12.0);
+ formatTester.format(df, "12.3E1", 123.0);
+ formatTester.format(df, "12.34E2", 1234.0);
+ formatTester.format(df, "12.35E3", 12346.0);
+ formatTester.format(df, "10.0E4", 99999.0);
+ formatTester.format(df, "12.0E-1", 1.2);
+ formatTester.format(df, "12.3E0", 12.3);
+ formatTester.format(df, "12.34E1", 123.4);
+ formatTester.format(df, "12.35E2", 1234.6);
+ formatTester.format(df, "10.0E3", 9999.9);
+ formatTester.format(df, "10.0E-2", 0.1);
+ formatTester.format(df, "12.0E-2", 0.12);
+ formatTester.format(df, "12.3E-2", 0.123);
+ formatTester.format(df, "12.34E-2", 0.1234);
+ formatTester.format(df, "12.35E-2", 0.12346);
+ formatTester.format(df, "10.0E-1", 0.99999);
+ formatTester.format(df, "-10.0E-1", -1.0);
+ formatTester.format(df, "-12.0E0", -12.0);
+ formatTester.format(df, "-12.3E1", -123.0);
+ formatTester.format(df, "-12.34E2", -1234.0);
+ formatTester.format(df, "-12.35E3", -12346.0);
+ formatTester.format(df, "-10.0E4", -99999.0);
+
+ df = new DecimalFormat("#00.0##E0", dfs);
+ // ["#00.0##E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=3,minIntegerDigits=2,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (2) + "max fractional digits (3) == 5
+ formatTester.format(df, "100E-3", 0.1);
+ formatTester.format(df, "120E-3", 0.12);
+ formatTester.format(df, "123E-3", 0.123);
+ formatTester.format(df, "123.4E-3", 0.1234);
+ formatTester.format(df, "123.46E-3", 0.1234567);
+ formatTester.format(df, "10E-3", 0.01);
+ formatTester.format(df, "12E-3", 0.012);
+ formatTester.format(df, "12.3E-3", 0.0123);
+ formatTester.format(df, "12.34E-3", 0.01234);
+ formatTester.format(df, "12.346E-3", 0.01234567);
+ formatTester.format(df, "1.0E-3", 0.001);
+ formatTester.format(df, "1.2E-3", 0.0012);
+ formatTester.format(df, "1.23E-3", 0.00123);
+ formatTester.format(df, "1.234E-3", 0.001234);
+ formatTester.format(df, "1.2346E-3", 0.001234567);
+ formatTester.format(df, "100E-6", 0.0001);
+ formatTester.format(df, "120E-6", 0.00012);
+ formatTester.format(df, "123E-6", 0.000123);
+ formatTester.format(df, "123.4E-6", 0.0001234);
+ formatTester.format(df, "123.46E-6", 0.0001234567);
+ formatTester.format(df, "0.0E0", 0.0);
+ formatTester.format(df, "1.0E0", 1.0);
+ formatTester.format(df, "12E0", 12.0);
+ formatTester.format(df, "123E0", 123.0);
+ formatTester.format(df, "1.234E3", 1234.0);
+ formatTester.format(df, "12.345E3", 12345.0);
+ formatTester.format(df, "123.46E3", 123456.0);
+ formatTester.format(df, "1.2346E6", 1234567.0);
+ formatTester.format(df, "12.346E6", 12345678.0);
+ formatTester.format(df, "100E6", 99999999.0);
+
+ df = new DecimalFormat("#.0E0", dfs);
+ // ["#.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (1).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 1
+ formatTester.format(df, "0.0E0", 0.0);
+ formatTester.format(df, "1.0E0", 1.0);
+ formatTester.format(df, "1.0E1", 12.0);
+ formatTester.format(df, "1.0E2", 123.0);
+ formatTester.format(df, "1.0E3", 1234.0);
+ formatTester.format(df, "1.0E4", 9999.0);
+
+ df = new DecimalFormat("0.E0", dfs);
+ // ["0.E0",isDecimalSeparatorAlwaysShown=true,groupingSize=0,multiplier=1,negativePrefix=-,
+ // negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,maxFractionDigits=0,
+ // minIntegerDigits=1,minFractionDigits=0,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (0) == 1
+ formatTester.format(df, "0E0", 0.0);
+ formatTester.format(df, "1E0", 1.0);
+ formatTester.format(df, "1E1", 12.0);
+ formatTester.format(df, "1E2", 123.0);
+ formatTester.format(df, "1E3", 1234.0);
+ formatTester.format(df, "1E4", 9999.0);
+
+ df = new DecimalFormat("##0.00#E0", dfs);
+ // ["##0.00#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=3,minIntegerDigits=1,minFractionDigits=2,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (3) == 4
+ formatTester.format(df, "100E-3", 0.1);
+ formatTester.format(df, "123.5E-3", 0.1234567);
+ formatTester.format(df, "1.00E0", 0.9999999);
+ formatTester.format(df, "10.0E-3", 0.01);
+ formatTester.format(df, "12.35E-3", 0.01234567);
+ formatTester.format(df, "100E-3", 0.09999999);
+ formatTester.format(df, "1.00E-3", 0.001);
+ formatTester.format(df, "1.235E-3", 0.001234567);
+ formatTester.format(df, "10.0E-3", 0.009999999);
+ formatTester.format(df, "100E-6", 0.0001);
+ formatTester.format(df, "123.5E-6", 0.0001234567);
+ formatTester.format(df, "1.00E-3", 0.0009999999);
+
+ df = new DecimalFormat("###0.00#E0", dfs);
+ // ["###0.00#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=4,
+ // maxFractionDigits=3,minIntegerDigits=1,minFractionDigits=2,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (4).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (3) == 4
+ formatTester.format(df, "1000E-4", 0.1);
+ formatTester.format(df, "1235E-4", 0.12345678);
+ formatTester.format(df, "1.00E0", 0.99999999);
+ formatTester.format(df, "100E-4", 0.01);
+ formatTester.format(df, "123.5E-4", 0.012345678);
+ formatTester.format(df, "1000E-4", 0.099999999);
+ formatTester.format(df, "10.0E-4", 0.001);
+ formatTester.format(df, "12.35E-4", 0.0012345678);
+ formatTester.format(df, "100E-4", 0.0099999999);
+ formatTester.format(df, "1.00E-4", 0.0001);
+ formatTester.format(df, "1.235E-4", 0.00012345678);
+ formatTester.format(df, "10.0E-4", 0.00099999999);
+ formatTester.format(df, "1000E-8", 0.00001);
+ formatTester.format(df, "1235E-8", 0.000012345678);
+ formatTester.format(df, "1.00E-4", 0.000099999999);
+
+ df = new DecimalFormat("###0.0#E0", dfs);
+ // ["###0.0#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=4,
+ // maxFractionDigits=2,minIntegerDigits=1,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (4).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (2) == 3
+ formatTester.format(df, "1000E-4", 0.1);
+ formatTester.format(df, "1230E-4", 0.1234567);
+ formatTester.format(df, "1.0E0", 0.9999999);
+ formatTester.format(df, "100E-4", 0.01);
+ formatTester.format(df, "123E-4", 0.01234567);
+ formatTester.format(df, "1000E-4", 0.09999999);
+ formatTester.format(df, "10E-4", 0.001);
+ formatTester.format(df, "12.3E-4", 0.001234567);
+ formatTester.format(df, "100E-4", 0.009999999);
+ formatTester.format(df, "1.0E-4", 0.0001);
+ formatTester.format(df, "1.23E-4", 0.0001234567);
+ formatTester.format(df, "10E-4", 0.0009999999);
+ formatTester.format(df, "1000E-8", 0.00001);
+ formatTester.format(df, "1230E-8", 0.00001234567);
+ formatTester.format(df, "1.0E-4", 0.00009999999);
+
+ df = new DecimalFormat("##0.0E0", dfs);
+ // ["##0.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "0.0E0", 0.0);
+ formatTester.format(df, "1.0E0", 1.0);
+ formatTester.format(df, "12E0", 12.0);
+ formatTester.format(df, "120E0", 123.0);
+ formatTester.format(df, "1.2E3", 1234.0);
+ formatTester.format(df, "12E3", 12346.0);
+ formatTester.format(df, "100E3", 99999.0);
+ formatTester.format(df, "1.0E6", 999999.0);
+
+ df = new DecimalFormat("0.#E0", dfs);
+ // ["0.#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=0,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "0E0", 0.0);
+ formatTester.format(df, "1E0", 1.0);
+ formatTester.format(df, "1.2E1", 12.0);
+ formatTester.format(df, "1.2E2", 123.0);
+ formatTester.format(df, "1.2E3", 1234.0);
+ formatTester.format(df, "1E4", 9999.0);
+
+ df = new DecimalFormat(".0E0", dfs);
+ // [".0E0",isDecimalSeparatorAlwaysShown=true,groupingSize=0,multiplier=1,negativePrefix=-,
+ // negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=0,maxFractionDigits=1,
+ // minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 2
+ formatTester.format(df, ".0E0", 0.0);
+ formatTester.format(df, ".1E1", 1.0);
+ formatTester.format(df, ".1E2", 12.0);
+ formatTester.format(df, ".1E3", 123.0);
+ formatTester.format(df, ".1E4", 1234.0);
+ formatTester.format(df, ".1E5", 9999.0);
+
+ formatTester.throwFailures();
+ }
+
+ public void test_formatDouble_scientificNotationMinusZero() throws Exception {
+ FormatTester formatTester = new FormatTester();
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+
+ DecimalFormat df = new DecimalFormat("00.0#E0", dfs);
+ // ["00.0#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=2,
+ // maxFractionDigits=2,minIntegerDigits=2,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (2) + "max fractional digits (2) == 4
+ formatTester.format(df, "-00.0E0", -0.0);
+
+ df = new DecimalFormat("##0.0E0", dfs);
+ // ["##0.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "-0.0E0", -0.0);
+
+ df = new DecimalFormat("#.0E0", dfs);
+ // ["#.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (1).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 2
+ formatTester.format(df, "-0.0E0", -0.0);
+
+ df = new DecimalFormat("0.#E0", dfs);
+ // ["0.#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=0,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "-0E0", -0.0);
+
+ df = new DecimalFormat(".0E0", dfs);
+ // [".0E0",isDecimalSeparatorAlwaysShown=true,groupingSize=0,multiplier=1,negativePrefix=-,
+ // negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=0,maxFractionDigits=1,
+ // minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 1
+ formatTester.format(df, "-.0E0", -0.0);
+
+ formatTester.throwFailures();
+ }
+
+ public void test_formatLong_maximumIntegerDigits() {
+ DecimalFormat df = new DecimalFormat("###0.##");
+ df.setMaximumIntegerDigits(2);
+ assertEquals(2, df.getMaximumIntegerDigits());
+ assertEquals("34", df.format(1234));
+ df.setMinimumIntegerDigits(4);
+ assertEquals(4, df.getMaximumIntegerDigits());
+ assertEquals("0026", df.format(26));
+ }
+
+ public void test_formatLong_minimumIntegerDigits() {
+ DecimalFormat df = new DecimalFormat("###0.##", new DecimalFormatSymbols(Locale.US));
+ df.setMinimumIntegerDigits(3);
+ assertEquals(3, df.getMinimumIntegerDigits());
+ assertEquals("012", df.format(12));
+ df.setMaximumIntegerDigits(2);
+ assertEquals(2, df.getMinimumIntegerDigits());
+ assertEquals("00.7", df.format(0.7));
+ }
+
+ // See also the _formatDouble tests. This tests a subset of patterns / values.
+ public void test_formatLong_scientificNotation() {
+ FormatTester formatTester = new FormatTester();
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+
+ DecimalFormat df = new DecimalFormat("00.0#E0", dfs);
+ // ["00.0#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=2,
+ // maxFractionDigits=2,minIntegerDigits=2,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (2) + "max fractional digits (2) == 4
+ formatTester.format(df, "00.0E0", 0);
+ formatTester.format(df, "10.0E-1", 1);
+ formatTester.format(df, "12.0E0", 12);
+ formatTester.format(df, "12.3E1", 123);
+ formatTester.format(df, "12.34E2", 1234);
+ formatTester.format(df, "12.35E3", 12346);
+ formatTester.format(df, "10.0E4", 99999);
+ formatTester.format(df, "-10.0E-1", -1);
+ formatTester.format(df, "-12.0E0", -12);
+ formatTester.format(df, "-12.3E1", -123);
+ formatTester.format(df, "-12.34E2", -1234);
+ formatTester.format(df, "-12.35E3", -12346);
+ formatTester.format(df, "-10.0E4", -99999);
+
+ df = new DecimalFormat("##0.0E0", dfs);
+ // ["##0.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "0.0E0", 0);
+ formatTester.format(df, "1.0E0", 1);
+ formatTester.format(df, "12E0", 12);
+ formatTester.format(df, "120E0", 123);
+ formatTester.format(df, "1.2E3", 1234);
+ formatTester.format(df, "12E3", 12346);
+ formatTester.format(df, "100E3", 99999);
+ formatTester.format(df, "1.0E6", 999999);
+
+ df = new DecimalFormat("#00.0##E0", dfs);
+ // ["##0.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=3,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (3).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (2) + "max fractional digits (3) == 5
+ formatTester.format(df, "0.0E0", 0);
+ formatTester.format(df, "1.0E0", 1);
+ formatTester.format(df, "12E0", 12);
+ formatTester.format(df, "123E0", 123);
+ formatTester.format(df, "1.234E3", 1234);
+ formatTester.format(df, "12.345E3", 12345);
+ formatTester.format(df, "123.46E3", 123456);
+ formatTester.format(df, "1.2346E6", 1234567);
+ formatTester.format(df, "12.346E6", 12345678);
+ formatTester.format(df, "100E6", 99999999);
+
+ df = new DecimalFormat("#.0E0", dfs);
+ // ["#.0E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit count is set: The exponent must be a multiple of it (1).
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 1
+ formatTester.format(df, "0.0E0", 0);
+ formatTester.format(df, "1.0E0", 1);
+ formatTester.format(df, "1.0E1", 12);
+ formatTester.format(df, "1.0E2", 123);
+ formatTester.format(df, "1.0E3", 1234);
+ formatTester.format(df, "1.0E4", 9999);
+
+ df = new DecimalFormat("0.#E0", dfs);
+ // ["0.#E0",isDecimalSeparatorAlwaysShown=false,groupingSize=0,multiplier=1,
+ // negativePrefix=-,negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=1,
+ // maxFractionDigits=1,minIntegerDigits=1,minFractionDigits=0,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (1) + "max fractional digits (1) == 2
+ formatTester.format(df, "0E0", 0);
+ formatTester.format(df, "1E0", 1);
+ formatTester.format(df, "1.2E1", 12);
+ formatTester.format(df, "1.2E2", 123);
+ formatTester.format(df, "1.2E3", 1234);
+ formatTester.format(df, "1E4", 9999);
+
+ df = new DecimalFormat(".0E0", dfs);
+ // [".0E0",isDecimalSeparatorAlwaysShown=true,groupingSize=0,multiplier=1,negativePrefix=-,
+ // negativeSuffix=,positivePrefix=,positiveSuffix=,maxIntegerDigits=0,maxFractionDigits=1,
+ // minIntegerDigits=0,minFractionDigits=1,grouping=false]
+ // Because maximum integer digit was not explicitly set: The exponent can be any integer.
+ // Scientific notation => use significant digit logic
+ // '@' not present: Significant digits: Min: 1,
+ // Max: "min integer digits" (0) + "max fractional digits (1) == 1
+ formatTester.format(df, ".0E0", 0);
+ formatTester.format(df, ".1E1", 1);
+ formatTester.format(df, ".1E2", 12);
+ formatTester.format(df, ".1E3", 123);
+ formatTester.format(df, ".1E4", 1234);
+ formatTester.format(df, ".1E5", 9999);
+
+ formatTester.throwFailures();
+ }
+
+ // Demonstrates that fraction digit rounding occurs as expected with 1, 10 and 14 fraction
+ // digits, using numbers that are well within the precision of IEEE 754.
+ public void test_formatDouble_maxFractionDigits() {
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat format = new DecimalFormat("#0.#", dfs);
+ format.setGroupingUsed(false);
+ format.setMaximumIntegerDigits(400);
+ format.setMaximumFractionDigits(1);
+
+ assertEquals("1", format.format(0.99));
+ assertEquals("1", format.format(0.95));
+ assertEquals("0.9", format.format(0.94));
+ assertEquals("0.9", format.format(0.90));
+
+ assertEquals("0.2", format.format(0.19));
+ assertEquals("0.2", format.format(0.15));
+ assertEquals("0.1", format.format(0.14));
+ assertEquals("0.1", format.format(0.10));
+
+ format.setMaximumFractionDigits(10);
+ assertEquals("1", format.format(0.99999999999));
+ assertEquals("1", format.format(0.99999999995));
+ assertEquals("0.9999999999", format.format(0.99999999994));
+ assertEquals("0.9999999999", format.format(0.99999999990));
+
+ assertEquals("0.1111111112", format.format(0.11111111119));
+ assertEquals("0.1111111112", format.format(0.11111111115));
+ assertEquals("0.1111111111", format.format(0.11111111114));
+ assertEquals("0.1111111111", format.format(0.11111111110));
+
+ format.setMaximumFractionDigits(14);
+ assertEquals("1", format.format(0.999999999999999));
+ assertEquals("1", format.format(0.999999999999995));
+ assertEquals("0.99999999999999", format.format(0.999999999999994));
+ assertEquals("0.99999999999999", format.format(0.999999999999990));
+
+ assertEquals("0.11111111111112", format.format(0.111111111111119));
+ assertEquals("0.11111111111112", format.format(0.111111111111115));
+ assertEquals("0.11111111111111", format.format(0.111111111111114));
+ assertEquals("0.11111111111111", format.format(0.111111111111110));
+ }
+
+ // This demonstrates rounding at the 15th decimal digit. By setting the maximum fraction digits
+ // we force rounding at a point just below the full IEEE 754 precision. IEEE 754 should be
+ // precise to just above 15 decimal digits.
+ // df.format() with no limits always emits up to 16 decimal digits, slightly above what IEEE 754
+ // can store precisely.
+ public void test_formatDouble_roundingTo15Digits() throws Exception {
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat df = new DecimalFormat("#.#", dfs);
+ df.setMaximumIntegerDigits(400);
+ df.setGroupingUsed(false);
+
+ df.setMaximumFractionDigits(0);
+ assertEquals("1000000000000000", df.format(999999999999999.9));
+ df.setMaximumFractionDigits(1);
+ assertEquals("100000000000000", df.format(99999999999999.99));
+ df.setMaximumFractionDigits(2);
+ assertEquals("10000000000000", df.format(9999999999999.999));
+ df.setMaximumFractionDigits(3);
+ assertEquals("1000000000000", df.format(999999999999.9999));
+ df.setMaximumFractionDigits(4);
+ assertEquals("100000000000", df.format(99999999999.99999));
+ df.setMaximumFractionDigits(5);
+ assertEquals("10000000000", df.format(9999999999.999999));
+ df.setMaximumFractionDigits(6);
+ assertEquals("1000000000", df.format(999999999.9999999));
+ df.setMaximumFractionDigits(7);
+ assertEquals("100000000", df.format(99999999.99999999));
+ df.setMaximumFractionDigits(8);
+ assertEquals("10000000", df.format(9999999.999999999));
+ df.setMaximumFractionDigits(9);
+ assertEquals("1000000", df.format(999999.9999999999));
+ df.setMaximumFractionDigits(10);
+ assertEquals("100000", df.format(99999.99999999999));
+ df.setMaximumFractionDigits(11);
+ assertEquals("10000", df.format(9999.999999999999));
+ df.setMaximumFractionDigits(12);
+ assertEquals("1000", df.format(999.9999999999999));
+ df.setMaximumFractionDigits(13);
+ assertEquals("100", df.format(99.99999999999999));
+ df.setMaximumFractionDigits(14);
+ assertEquals("10", df.format(9.999999999999999));
+ df.setMaximumFractionDigits(15);
+ assertEquals("1", df.format(0.9999999999999999));
+ }
+
+ // This checks formatting over most of the representable IEEE 754 range using a formatter that
+ // should be performing no lossy rounding.
+ // It checks that the formatted double can be parsed to get the original double.
+ // IEEE 754 can represent values from (decimal) ~2.22507E−308 to ~1.79769E308 to full precision.
+ // Close to zero it can go down to 4.94066E-324 with a loss of precision.
+ // At the extremes of the double range this test will not be testing doubles that exactly
+ // represent powers of 10. The test is only interested in whether the doubles closest
+ // to powers of 10 that can be represented can each be turned into a string and read back again
+ // to arrive at the original double.
+ public void test_formatDouble_wideRange() throws Exception {
+ for (int i = -324; i < 309; i++) {
+ // Generate a decimal number we are interested in: 1 * 10^i
+ String stringForm = "1e" + i;
+ BigDecimal bigDecimal = new BigDecimal(stringForm);
+
+ // Obtain the nearest double representation of the decimal number.
+ // This is lossy because going from BigDecimal -> double is inexact, but we should
+ // arrive at a number that is as close as possible to the decimal value. We assume that
+ // BigDecimal is capable of this, but it is not critical to this test if it gets it a
+ // little wrong, though it may mean we are testing a double value different from the one
+ // we thought we were.
+ double d = bigDecimal.doubleValue();
+
+ assertDecimalFormatIsLossless(d);
+ }
+ }
+
+ // This test is a regression test for http://b/17656132.
+ // It checks hand-picked values can be formatted and parsed to get the original double.
+ // The formatter as configured should perform no rounding.
+ public void test_formatDouble_roundingProblemCases() throws Exception {
+ // Most of the double literals below are not exactly representable in IEEE 754 but
+ // it should not matter to this test.
+ assertDecimalFormatIsLossless(999999999999999.9);
+ assertDecimalFormatIsLossless(99999999999999.99);
+ assertDecimalFormatIsLossless(9999999999999.999);
+ assertDecimalFormatIsLossless(999999999999.9999);
+ assertDecimalFormatIsLossless(99999999999.99999);
+ assertDecimalFormatIsLossless(9999999999.999999);
+ assertDecimalFormatIsLossless(999999999.9999999);
+ assertDecimalFormatIsLossless(99999999.99999999);
+ assertDecimalFormatIsLossless(9999999.999999999);
+ assertDecimalFormatIsLossless(999999.9999999999);
+ assertDecimalFormatIsLossless(99999.99999999999);
+ assertDecimalFormatIsLossless(9999.999999999999);
+ assertDecimalFormatIsLossless(999.9999999999999);
+ assertDecimalFormatIsLossless(99.99999999999999);
+ assertDecimalFormatIsLossless(9.999999999999999);
+ assertDecimalFormatIsLossless(0.9999999999999999);
+ }
+
+ // This test checks hand-picked values can be formatted and parsed to get the original double.
+ // The formatter as configured should perform no rounding.
+ // These numbers are not affected by http://b/17656132.
+ public void test_formatDouble_varyingScale() throws Exception {
+ // Most of the double literals below are not exactly representable in IEEE 754 but
+ // it should not matter to this test.
+
+ assertDecimalFormatIsLossless(999999999999999.);
+
+ assertDecimalFormatIsLossless(123456789012345.);
+ assertDecimalFormatIsLossless(12345678901234.5);
+ assertDecimalFormatIsLossless(1234567890123.25);
+ assertDecimalFormatIsLossless(999999999999.375);
+ assertDecimalFormatIsLossless(99999999999.0625);
+ assertDecimalFormatIsLossless(9999999999.03125);
+ assertDecimalFormatIsLossless(999999999.015625);
+ assertDecimalFormatIsLossless(99999999.0078125);
+ assertDecimalFormatIsLossless(9999999.00390625);
+ assertDecimalFormatIsLossless(999999.001953125);
+ assertDecimalFormatIsLossless(9999.00048828125);
+ assertDecimalFormatIsLossless(999.000244140625);
+ assertDecimalFormatIsLossless(99.0001220703125);
+ assertDecimalFormatIsLossless(9.00006103515625);
+ assertDecimalFormatIsLossless(0.000030517578125);
+ }
+
+ private static void assertDecimalFormatIsLossless(double d) throws Exception {
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat format = new DecimalFormat("#0.#", dfs);
+ format.setGroupingUsed(false);
+ format.setMaximumIntegerDigits(400);
+ format.setMaximumFractionDigits(400);
+
+ // Every floating point binary can be represented exactly in decimal if you have enough
+ // digits. This shows the value actually being tested.
+ String testId = "decimalValue: " + new BigDecimal(d);
+
+ // As a sanity check we try out parseDouble() with the string generated by
+ // Double.toString(). Strictly speaking Double.toString() is probably not guaranteed to be
+ // lossless, but in reality it probably is, or at least is close enough.
+ assertDoubleEqual(
+ testId + " failed parseDouble(toString()) sanity check",
+ d, Double.parseDouble(Double.toString(d)));
+
+ // Format the number: If this is lossy it is a problem. We are trying to check that it
+ // doesn't lose any unnecessary precision.
+ String result = format.format(d);
+
+ // Here we use Double.parseDouble() which should able to parse a number we know was
+ // representable as a double into the original double. If parseDouble() is not implemented
+ // correctly the test is invalid.
+ double doubleParsed = Double.parseDouble(result);
+ assertDoubleEqual(testId + " (format() produced " + result + ")",
+ d, doubleParsed);
+
+ // For completeness we try to parse using the formatter too. If this fails but the format
+ // above didn't it may be a problem with parse(), or with format() that we didn't spot.
+ assertDoubleEqual(testId + " failed parse(format()) check",
+ d, format.parse(result).doubleValue());
+ }
+
+ private static void assertDoubleEqual(String message, double d, double doubleParsed) {
+ assertEquals(message,
+ createPrintableDouble(d),createPrintableDouble(doubleParsed));
+ }
+
+ private static String createPrintableDouble(double d) {
+ return Double.toString(d) + "(" + Long.toHexString(Double.doubleToRawLongBits(d)) + ")";
+ }
+
+ // Concise demonstration of http://b/17656132 using hard-coded expected values.
+ public void test_formatDouble_bug17656132() {
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat df = new DecimalFormat("#0.#", dfs);
+ df.setGroupingUsed(false);
+ df.setMaximumIntegerDigits(400);
+ df.setMaximumFractionDigits(400);
+
+ // The expected values below come from the RI and are correct 16 decimal digit
+ // representations of the formatted value. Android does something different.
+ // The decimal value given in each comment is the actual double value as represented by
+ // IEEE 754. See new BigDecimal(double).
+
+ // double: 999999999999999.9 is decimal 999999999999999.875
+ assertEquals("999999999999999.9", df.format(999999999999999.9));
+ // double: 99999999999999.98 is decimal 99999999999999.984375
+ assertEquals("99999999999999.98", df.format(99999999999999.98));
+ // double 9999999999999.998 is decimal 9999999999999.998046875
+ assertEquals("9999999999999.998", df.format(9999999999999.998));
+ // double 999999999999.9999 is decimal 999999999999.9998779296875
+ assertEquals("999999999999.9999", df.format(999999999999.9999));
+ // double 99999999999.99998 is decimal 99999999999.9999847412109375
+ assertEquals("99999999999.99998", df.format(99999999999.99998));
+ // double 9999999999.999998 is decimal 9999999999.9999980926513671875
+ assertEquals("9999999999.999998", df.format(9999999999.999998));
+ // double 1E23 is decimal 99999999999999991611392
+ assertEquals("9999999999999999", df.format(1E23));
+ }
+
+ public void test_getDecimalFormatSymbols() {
+ DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
+ DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
+ assertNotSame(dfs, df.getDecimalFormatSymbols());
+ }
+
+ public void test_getCurrency() {
+ Currency currK = Currency.getInstance("KRW");
+ Currency currX = Currency.getInstance("XXX");
+ Currency currE = Currency.getInstance("EUR");
+
+ DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("ko", "KR"));
+ assertTrue("Test1: Returned incorrect currency", df.getCurrency() == currK);
+
+ df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("", "KR"));
+ assertTrue("Test2: Returned incorrect currency", df.getCurrency() == currK);
+
+ df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("ko", ""));
+ assertTrue("Test3: Returned incorrect currency", df.getCurrency() == currX);
+
+ df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("fr", "FR"));
+ assertTrue("Test4: Returned incorrect currency", df.getCurrency() == currE);
+
+ // Regression for HARMONY-1351
+ df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("QWERTY"));
+ assertTrue("Test5: Returned incorrect currency", df.getCurrency() == currX);
+
+ // JDK fails these tests since it doesn't have the PREEURO variant
+ // df = (DecimalFormat)NumberFormat.getCurrencyInstance(new Locale("fr",
+ // "FR","PREEURO"));
+ // assertTrue("Test5: Returned incorrect currency", df.getCurrency() ==
+ // currF);
+ }
+
+ public void test_getGroupingSize() {
+ DecimalFormat df = new DecimalFormat("###0.##");
+ assertEquals("Wrong unset size", 0, df.getGroupingSize());
+ df = new DecimalFormat("#,##0.##");
+ assertEquals("Wrong set size", 3, df.getGroupingSize());
+ df = new DecimalFormat("#,###,###0.##");
+ assertEquals("Wrong multiple set size", 4, df.getGroupingSize());
+ }
+
+ public void test_getMultiplier() {
+ final int defaultMultiplier = 1;
+ DecimalFormat form = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ assertEquals(defaultMultiplier, form.getMultiplier());
+
+ DecimalFormat df = new DecimalFormat("###0.##");
+ assertEquals("Wrong unset multiplier", 1, df.getMultiplier());
+ df = new DecimalFormat("###0.##%");
+ assertEquals("Wrong percent multiplier", 100, df.getMultiplier());
+ df = new DecimalFormat("###0.##\u2030");
+ assertEquals("Wrong mille multiplier", 1000, df.getMultiplier());
+ }
+
+ public void test_isDecimalSeparatorAlwaysShown() {
+ DecimalFormat df = new DecimalFormat("###0.##");
+ assertTrue("Wrong unset value", !df.isDecimalSeparatorAlwaysShown());
+ df = new DecimalFormat("###0.00");
+ assertTrue("Wrong unset2 value", !df.isDecimalSeparatorAlwaysShown());
+ df = new DecimalFormat("###0.");
+ assertTrue("Wrong set value", df.isDecimalSeparatorAlwaysShown());
+ }
+
+ public void test_parse_withParsePosition() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
+ ParsePosition pos = new ParsePosition(0);
+ Number result = format.parse("9223372036854775807", pos);
+ assertTrue("Wrong result type for Long.MAX_VALUE", result.getClass() == Long.class);
+ assertTrue("Wrong result Long.MAX_VALUE", result.longValue() == Long.MAX_VALUE);
+ pos = new ParsePosition(0);
+ result = format.parse("-9223372036854775808", pos);
+ assertTrue("Wrong result type for Long.MIN_VALUE", result.getClass() == Long.class);
+ assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(),
+ result.longValue() == Long.MIN_VALUE);
+ pos = new ParsePosition(0);
+ result = format.parse("9223372036854775808", pos);
+ assertTrue("Wrong result type for Long.MAX_VALUE+1", result.getClass() == Double.class);
+ assertTrue("Wrong result Long.MAX_VALUE + 1",
+ result.doubleValue() == (double) Long.MAX_VALUE + 1);
+ pos = new ParsePosition(0);
+ result = format.parse("-9223372036854775809", pos);
+ assertTrue("Wrong result type for Long.MIN_VALUE+1", result.getClass() == Double.class);
+ assertTrue("Wrong result Long.MIN_VALUE - 1",
+ result.doubleValue() == (double) Long.MIN_VALUE - 1);
+
+ pos = new ParsePosition(0);
+ result = format.parse("18446744073709551629", pos);
+ assertTrue("Wrong result type for overflow", result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow", result.doubleValue() == 18446744073709551629d);
+
+ pos = new ParsePosition(0);
+ result = format.parse("42325917317067571199", pos);
+ assertTrue("Wrong result type for overflow a: " + result,
+ result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow a: " + result,
+ result.doubleValue() == 42325917317067571199d);
+ pos = new ParsePosition(0);
+ result = format.parse("4232591731706757119E1", pos);
+ assertTrue("Wrong result type for overflow b: " + result,
+ result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow b: " + result,
+ result.doubleValue() == 42325917317067571190d);
+ pos = new ParsePosition(0);
+ result = format.parse(".42325917317067571199E20", pos);
+ assertTrue("Wrong result type for overflow c: " + result,
+ result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow c: " + result,
+ result.doubleValue() == 42325917317067571199d);
+ pos = new ParsePosition(0);
+ result = format.parse("922337203685477580.9E1", pos);
+ assertTrue("Wrong result type for overflow d: " + result,
+ result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow d: " + result,
+ result.doubleValue() == 9223372036854775809d);
+ pos = new ParsePosition(0);
+ result = format.parse("9.223372036854775809E18", pos);
+ assertTrue("Wrong result type for overflow e: " + result,
+ result.getClass() == Double.class);
+ assertTrue("Wrong result for overflow e: " + result,
+ result.doubleValue() == 9223372036854775809d);
+ }
+
+ public void test_parse_withMultiplier() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
+ Number result;
+
+ format.setMultiplier(100);
+ result = format.parse("9223372036854775807", new ParsePosition(0));
+ assertEquals("Wrong result type multiplier 100: " + result, Double.class,
+ result.getClass());
+ assertEquals("Wrong result for multiplier 100: " + result,
+ 92233720368547758.07d, result.doubleValue());
+
+ format.setMultiplier(1000);
+ result = format.parse("9223372036854775807", new ParsePosition(0));
+ assertEquals("Wrong result type multiplier 1000: " + result, Double.class,
+ result.getClass());
+ assertEquals("Wrong result for multiplier 1000: " + result,
+ 9223372036854775.807d, result.doubleValue());
+
+ format.setMultiplier(10000);
+ result = format.parse("9223372036854775807", new ParsePosition(0));
+ assertEquals("Wrong result type multiplier 10000: " + result,
+ Double.class, result.getClass());
+ assertEquals("Wrong result for multiplier 10000: " + result,
+ 922337203685477.5807d, result.doubleValue());
+ }
+
+ public void test_setDecimalFormatSymbols() {
+ DecimalFormat df = new DecimalFormat("###0.##");
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+ dfs.setDecimalSeparator('@');
+ df.setDecimalFormatSymbols(dfs);
+ assertTrue("Not set", df.getDecimalFormatSymbols().equals(dfs));
+ assertEquals("Symbols not used", "1@2", df.format(1.2));
+
+ // The returned symbols may be cloned in two spots
+ // 1. When set
+ // 2. When returned
+ DecimalFormat format = new DecimalFormat();
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ format.setDecimalFormatSymbols(symbols);
+ DecimalFormatSymbols symbolsOut = format.getDecimalFormatSymbols();
+ assertNotSame(symbols, symbolsOut);
+ }
+
+ public void test_setDecimalSeparatorAlwaysShown() {
+ DecimalFormat df = new DecimalFormat("###0.##", new DecimalFormatSymbols(Locale.US));
+ assertEquals("Wrong default result", "5", df.format(5));
+ df.setDecimalSeparatorAlwaysShown(true);
+ assertTrue("Not set", df.isDecimalSeparatorAlwaysShown());
+ assertEquals("Wrong set result", "7.", df.format(7));
+ }
+
+ public void test_setCurrency() {
+ Locale locale = Locale.CANADA;
+ DecimalFormat df = ((DecimalFormat) NumberFormat.getCurrencyInstance(locale));
+
+ try {
+ df.setCurrency(null);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ }
+
+ Currency currency = Currency.getInstance("AED");
+ df.setCurrency(currency);
+ assertTrue("Returned incorrect currency", currency == df.getCurrency());
+ assertEquals("Returned incorrect currency symbol", currency.getSymbol(locale),
+ df.getDecimalFormatSymbols().getCurrencySymbol());
+ assertEquals("Returned incorrect international currency symbol", currency.getCurrencyCode(),
+ df.getDecimalFormatSymbols().getInternationalCurrencySymbol());
+ }
+
+ public void test_setGroupingSize() {
+ DecimalFormat df = new DecimalFormat("###0.##", new DecimalFormatSymbols(Locale.ENGLISH));
+ df.setGroupingUsed(true);
+ df.setGroupingSize(2);
+ assertEquals("Value not set", 2, df.getGroupingSize());
+ String result = df.format(123);
+ assertTrue("Invalid format:" + result, result.equals("1,23"));
+ }
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new DecimalFormat());
+ }
+
+ public void testSerializationHarmonyRICompatible() throws Exception {
+ NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
+
+ DecimalFormat df = null;
+ if (!(nf instanceof DecimalFormat)) {
+ throw new Error("This NumberFormat is not a DecimalFormat");
+
+ }
+ df = (DecimalFormat) nf;
+
+ ObjectInputStream oinput = null;
+
+ DecimalFormat deserializedDF = null;
+
+ try {
+ oinput = new ObjectInputStream(getClass().getResource(
+ "/serialization/org/apache/harmony/tests/java/text/DecimalFormat.ser")
+ .openStream());
+ deserializedDF = (DecimalFormat) oinput.readObject();
+ } finally {
+ try {
+ if (null != oinput) {
+ oinput.close();
+ }
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+
+ assertEquals(df.getNegativePrefix(), deserializedDF.getNegativePrefix());
+ assertEquals(df.getNegativeSuffix(), deserializedDF.getNegativeSuffix());
+ assertEquals(df.getPositivePrefix(), deserializedDF.getPositivePrefix());
+ assertEquals(df.getPositiveSuffix(), deserializedDF.getPositiveSuffix());
+ assertEquals(df.getCurrency(), deserializedDF.getCurrency());
+
+ DecimalFormatSymbolsTest.assertDecimalFormatSymbolsRIFrance(
+ deserializedDF.getDecimalFormatSymbols());
+
+ assertEquals(df.getGroupingSize(), df.getGroupingSize());
+ assertEquals(df.getMaximumFractionDigits(), deserializedDF
+ .getMaximumFractionDigits());
+
+ assertEquals(df.getMaximumIntegerDigits(), deserializedDF
+ .getMaximumIntegerDigits());
+
+ assertEquals(df.getMinimumFractionDigits(), deserializedDF
+ .getMinimumFractionDigits());
+ assertEquals(df.getMinimumIntegerDigits(), deserializedDF
+ .getMinimumIntegerDigits());
+ assertEquals(df.getMultiplier(), deserializedDF.getMultiplier());
+
+ // Deliberately omitted this assertion. Since different data resource
+ // will cause the assertion fail.
+ // assertEquals(df, deserializedDF);
+
+ }
+
+ public void test_parse_infinityBigDecimalFalse() {
+ // Regression test for HARMONY-106
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ Number number = format.parse(symbols.getInfinity(),
+ new ParsePosition(0));
+ assertTrue(number instanceof Double);
+ assertTrue(Double.isInfinite(number.doubleValue()));
+ }
+
+ public void test_parse_minusInfinityBigDecimalFalse() {
+ // Regression test for HARMONY-106
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ Number number = format.parse("-" + symbols.getInfinity(),
+ new ParsePosition(0));
+ assertTrue(number instanceof Double);
+ assertTrue(Double.isInfinite(number.doubleValue()));
+ }
+
+ public void test_setDecimalFormatSymbolsAsNull() {
+ // Regression for HARMONY-1070
+ DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
+ format.setDecimalFormatSymbols(null);
+ }
+
+ public void test_formatToCharacterIterator_null() {
+ try {
+ // Regression for HARMONY-466
+ new DecimalFormat().formatToCharacterIterator(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_formatToCharacterIterator_original() {
+ new Support_DecimalFormat(
+ "test_formatToCharacterIteratorLjava_lang_Object")
+ .t_formatToCharacterIterator();
+ }
+
+ public void test_formatToCharacterIterator() throws Exception {
+ AttributedCharacterIterator iterator;
+ int[] runStarts;
+ int[] runLimits;
+ String result;
+ char current;
+
+ // BigInteger.
+ iterator = new DecimalFormat().formatToCharacterIterator(new BigInteger("123456789"));
+ runStarts = new int[] { 0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8 };
+ runLimits = new int[] { 3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11 };
+ result = "123,456,789";
+ current = iterator.current();
+ for (int i = 0; i < runStarts.length; i++) {
+ assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
+ assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+ assertEquals(0, iterator.getBeginIndex());
+ assertEquals(11, iterator.getEndIndex());
+
+ // For BigDecimal with multiplier test.
+ DecimalFormat df = new DecimalFormat();
+ df.setMultiplier(10);
+ iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890"));
+ result = "123,456,789,012,345,678,900";
+ current = iterator.current();
+ for (int i = 0; i < result.length(); i++) {
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+
+ // For BigDecimal with multiplier test.
+ df = new DecimalFormat();
+ df.setMultiplier(-1);
+ df.setMaximumFractionDigits(20);
+ iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901"));
+ result = "-1.23456789012345678901";
+ current = iterator.current();
+ for (int i = 0; i < result.length(); i++) {
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+
+ iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.23456789E301"));
+ runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
+ runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
+ result = "12,345,678,900,"; // 000,000,000,000....
+ current = iterator.current();
+ for (int i = 0; i < runStarts.length; i++) {
+ assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
+ assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+ assertEquals(0, iterator.getBeginIndex());
+ assertEquals(402, iterator.getEndIndex());
+
+ iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.2345678E4"));
+ runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7 };
+ runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10 };
+ result = "12,345.678";
+ current = iterator.current();
+ for (int i = 0; i < runStarts.length; i++) {
+ assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
+ assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+ assertEquals(0, iterator.getBeginIndex());
+ assertEquals(10, iterator.getEndIndex());
+ }
+
+ public void test_formatToCharacterIterator_veryLarge() throws Exception {
+ AttributedCharacterIterator iterator;
+ int[] runStarts;
+ int[] runLimits;
+ String result;
+ char current;
+
+ Number number = new BigDecimal("1.23456789E1234");
+ assertEquals("1.23456789E+1234", number.toString());
+ iterator = new DecimalFormat().formatToCharacterIterator(number);
+ runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
+ runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
+ result = "12,345,678,900,"; // 000,000,000,000....
+ current = iterator.current();
+ for (int i = 0; i < runStarts.length; i++) {
+ assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
+ assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
+ assertEquals("wrong char @" + i, result.charAt(i), current);
+ current = iterator.next();
+ }
+ assertEquals(0, iterator.getBeginIndex());
+ assertEquals(1646, iterator.getEndIndex());
+ }
+
+ public void test_formatToCharacterIterator_roundingUnnecessaryArithmeticException() {
+ DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+ decimalFormat.setMaximumFractionDigits(0);
+ try {
+ // when rounding is needed, but RoundingMode is set to RoundingMode.UNNECESSARY,
+ // throw ArithmeticException
+ decimalFormat.formatToCharacterIterator(new Double(1.5));
+ fail("ArithmeticException expected");
+ } catch (ArithmeticException e) {
+ // expected
+ }
+ }
+
+ public void test_formatDouble_roundingUnnecessaryArithmeticException() {
+ DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ decimalFormat.setMaximumFractionDigits(0);
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+
+ try {
+ // when rounding is needed, but RoundingMode is set to RoundingMode.UNNECESSARY,
+ // throw ArithmeticException
+ decimalFormat.format(11.5, new StringBuffer(), new FieldPosition(0));
+ fail("ArithmeticException expected");
+ } catch (ArithmeticException e) {
+ // expected
+ }
+ }
+
+ public void test_format_roundingUnnecessaryArithmeticException() {
+ final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat decimalFormat = new DecimalFormat("00.0#E0", dfs);
+
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+ try {
+ // when rounding is needed, but RoundingMode is set to RoundingMode.UNNECESSARY,
+ // throw ArithmeticException
+ decimalFormat.format(99999, new StringBuffer(), new FieldPosition(0));
+ fail("ArithmeticException expected");
+ } catch (ArithmeticException e) {
+ // expected
+ }
+ }
+
+ public void test_getRoundingMode() {
+ // get the default RoundingMode of this DecimalFormat
+ DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+
+ // the default RoundingMode is HALF_EVEN
+ assertEquals("Incorrect default RoundingMode",
+ decimalFormat.getRoundingMode(), RoundingMode.HALF_EVEN);
+
+ // set RoundingMode.HALF_DOWN of this DecimalFormat
+ decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
+ assertEquals("Returned incorrect RoundingMode",
+ decimalFormat.getRoundingMode(), RoundingMode.HALF_DOWN);
+
+ }
+
+ public void test_setRoundingMode_null() {
+ DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ try {
+ // when the given RoundingMode is null, throw NullPointerException
+ decimalFormat.setRoundingMode(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_format_withRoundingMode() {
+ DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
+ // ignore the fraction part of a given value
+ decimalFormat.setMaximumFractionDigits(0);
+
+ // set RoundingMode.HALF_DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
+ String result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result);
+
+ result = decimalFormat.format(11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result);
+
+ result = decimalFormat.format(11.6);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "12", result);
+
+ // set RoundingMode.CEILING of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.CEILING);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "12", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11", result);
+
+ // set RoundingMode.DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.DOWN);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result);
+
+ // set RoundingMode.FLOOR of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.FLOOR);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-12", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result);
+
+ // set RoundingMode.HALF_EVEN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "0", result);
+
+ // set RoundingMode.HALF_UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "0", result);
+
+ result = decimalFormat.format(-0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-0", result);
+
+ // set RoundingMode.UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UP);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "1", result);
+
+ result = decimalFormat.format(-0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-1", result);
+
+ // set RoundingMode.UNNECESSARY of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+
+ try {
+ // when rounding is needed but RoundingMode is set to RoundingMode.UNNECESSARY,
+ // throw ArithmeticException
+ result = decimalFormat.format(5.5);
+ fail("ArithmeticException expected: RoundingMode.UNNECESSARY");
+ } catch (ArithmeticException e) {
+ // expected
+ }
+
+ result = decimalFormat.format(1.0);
+ assertEquals(
+ "Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "1", result);
+
+ result = decimalFormat.format(-1.0);
+ assertEquals(
+ "Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "-1", result);
+
+ // set MaxFractionDigits to 3, test different DecimalFormat format
+ // function with differnt RoundingMode
+ decimalFormat.setMaximumFractionDigits(3);
+
+ // set RoundingMode.HALF_DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.565", result);
+
+ result = decimalFormat.format(11.5655);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.565", result);
+
+ result = decimalFormat.format(11.5656);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.566", result);
+
+ // set RoundingMode.CEILING of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.CEILING);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "11.566", result);
+
+ result = decimalFormat.format(-11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11.565", result);
+
+ // set RoundingMode.DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.DOWN);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11.565", result);
+
+ result = decimalFormat.format(-11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11.565", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result);
+
+ // set RoundingMode.FLOOR of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.FLOOR);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11.565", result);
+
+ result = decimalFormat.format(-11.5655);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-11.566", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result);
+
+ // set RoundingMode.HALF_EVEN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "11.565", result);
+
+ result = decimalFormat.format(-11.5655);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-11.566", result);
+
+ result = decimalFormat.format(11.5656);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "11.566", result);
+
+ // set RoundingMode.HALF_UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "11.565", result);
+
+ result = decimalFormat.format(-11.5655);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-11.566", result);
+
+ result = decimalFormat.format(11.5656);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "11.566", result);
+
+ // set RoundingMode.UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UP);
+ result = decimalFormat.format(11.5653);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "11.566", result);
+
+ result = decimalFormat.format(-11.5655);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-11.566", result);
+
+ // set RoundingMode.UNNECESSARY of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+ result = decimalFormat.format(-11.565);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY",
+ "-11.565", result);
+
+ result = decimalFormat.format(11.565);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY",
+ "11.565", result);
+
+ // when setting MaxFractionDigits to negative value -2, default it as
+ // zero, test different DecimalFormat format
+ // function with differnt RoundingMode
+ decimalFormat.setMaximumFractionDigits(-2);
+
+ // set RoundingMode.HALF_DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result);
+
+ result = decimalFormat.format(11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result);
+
+ result = decimalFormat.format(11.6);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "12", result);
+
+ // set RoundingMode.CEILING of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.CEILING);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "12", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11", result);
+
+ // set RoundingMode.DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.DOWN);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result);
+
+ // set RoundingMode.FLOOR of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.FLOOR);
+ result = decimalFormat.format(11.3);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11", result);
+
+ result = decimalFormat.format(-11.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-12", result);
+
+ result = decimalFormat.format(0);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result);
+
+ // set RoundingMode.HALF_EVEN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "0", result);
+
+ // set RoundingMode.HALF_UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "0", result);
+
+ result = decimalFormat.format(-0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-0", result);
+
+ // set RoundingMode.UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UP);
+ result = decimalFormat.format(5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "6", result);
+
+ result = decimalFormat.format(-5.5);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-6", result);
+
+ result = decimalFormat.format(0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "1", result);
+
+ result = decimalFormat.format(-0.2);
+ assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-1", result);
+
+ // set RoundingMode.UNNECESSARY of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);
+
+ result = decimalFormat.format(1.0);
+ assertEquals(
+ "Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "1", result);
+
+ result = decimalFormat.format(-1.0);
+ assertEquals(
+ "Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "-1", result);
+
+ // Regression for HARMONY-6485
+ // Test with applyPattern call after setRoundingMode
+
+ // set RoundingMode.HALF_UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
+ decimalFormat.applyPattern(".##");
+ result = decimalFormat.format(0.125);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".13", result);
+ result = decimalFormat.format(0.255);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".26", result);
+ result = decimalFormat.format(0.732);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".73", result);
+ result = decimalFormat.format(0.467);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".47", result);
+
+ // set RoundingMode.HALF_DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
+ decimalFormat.applyPattern(".##");
+ result = decimalFormat.format(0.125);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".12", result);
+ result = decimalFormat.format(0.255);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".25", result);
+ result = decimalFormat.format(0.732);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".73", result);
+ result = decimalFormat.format(0.467);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".47", result);
+
+ // set RoundingMode.UP of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.UP);
+ decimalFormat.applyPattern(".##");
+ result = decimalFormat.format(0.125);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".13", result);
+ result = decimalFormat.format(0.255);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".26", result);
+ result = decimalFormat.format(0.732);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".74", result);
+ result = decimalFormat.format(0.467);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".47", result);
+
+ // set RoundingMode.DOWN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.DOWN);
+ decimalFormat.applyPattern(".##");
+ result = decimalFormat.format(0.125);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".12", result);
+ result = decimalFormat.format(0.255);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".25", result);
+ result = decimalFormat.format(0.732);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".73", result);
+ result = decimalFormat.format(0.467);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".46", result);
+
+ // set RoundingMode.HALF_EVEN of this DecimalFormat and test its
+ // behavior
+ decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
+ decimalFormat.applyPattern(".##");
+ result = decimalFormat.format(0.125);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".12", result);
+ result = decimalFormat.format(0.255);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".26", result);
+ result = decimalFormat.format(0.732);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".73", result);
+ result = decimalFormat.format(0.467);
+ assertEquals("Incorrect RoundingMode behavior after applyPattern", ".47", result);
+ }
+
+ private static class FormatTester {
+ private List<AssertionFailedError> failures = new ArrayList<AssertionFailedError>();
+
+ public void format(DecimalFormat format, String expected, double value) {
+ try {
+ Assert.assertEquals(format.toPattern() + ": " + value, expected,
+ format.format(value));
+ } catch (AssertionFailedError e) {
+ failures.add(e);
+ }
+ }
+
+ public void format(DecimalFormat format, String expected, int value) {
+ try {
+ Assert.assertEquals(format.toPattern() + ": " + value, expected,
+ format.format(value));
+ } catch (AssertionFailedError e) {
+ failures.add(e);
+ }
+ }
+
+ public void throwFailures() throws AssertionFailedError {
+ if (failures.isEmpty()) {
+ return;
+ }
+ if (failures.size() == 1) {
+ throw failures.get(0);
+ }
+ AssertionFailedError combined = new AssertionFailedError("Multiple format failures");
+ for (AssertionFailedError failure : failures) {
+ combined.addSuppressed(failure);
+ }
+ throw combined;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/FieldPositionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/FieldPositionTest.java
new file mode 100644
index 0000000..8fdc334
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/FieldPositionTest.java
@@ -0,0 +1,249 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.FieldPosition;
+
+public class FieldPositionTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.FieldPosition#FieldPosition(int)
+ */
+ public void test_ConstructorI() {
+ // Test for constructor java.text.FieldPosition(int)
+ FieldPosition fpos = new FieldPosition(DateFormat.MONTH_FIELD);
+ assertEquals("Test1: Constructor failed to set field identifier!",
+ DateFormat.MONTH_FIELD, fpos.getField());
+ assertNull("Constructor failed to set field attribute!", fpos
+ .getFieldAttribute());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#FieldPosition(java.text.Format$Field)
+ */
+ public void test_ConstructorLjava_text_Format$Field() {
+ // Test for constructor java.text.FieldPosition(Format.Field)
+ FieldPosition fpos = new FieldPosition(DateFormat.Field.MONTH);
+ assertSame("Constructor failed to set field attribute!",
+ DateFormat.Field.MONTH, fpos.getFieldAttribute());
+ assertEquals("Test1: Constructor failed to set field identifier!", -1,
+ fpos.getField());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#FieldPosition(java.text.Format$Field, int)
+ */
+ public void test_ConstructorLjava_text_Format$FieldI() {
+ // Test for constructor java.text.FieldPosition(Format.Field, int)
+ FieldPosition fpos = new FieldPosition(DateFormat.Field.MONTH,
+ DateFormat.MONTH_FIELD);
+ assertSame("Constructor failed to set field attribute!",
+ DateFormat.Field.MONTH, fpos.getFieldAttribute());
+ assertEquals("Test1: Constructor failed to set field identifier!",
+ DateFormat.MONTH_FIELD, fpos.getField());
+
+ // test special cases
+ FieldPosition fpos2 = new FieldPosition(DateFormat.Field.HOUR1,
+ DateFormat.HOUR1_FIELD);
+ assertSame("Constructor failed to set field attribute!",
+ DateFormat.Field.HOUR1, fpos2.getFieldAttribute());
+ assertEquals("Test2: Constructor failed to set field identifier!",
+ DateFormat.HOUR1_FIELD, fpos2.getField());
+
+ FieldPosition fpos3 = new FieldPosition(DateFormat.Field.TIME_ZONE,
+ DateFormat.MONTH_FIELD);
+ assertSame("Constructor failed to set field attribute!",
+ DateFormat.Field.TIME_ZONE, fpos3.getFieldAttribute());
+ assertEquals("Test3: Constructor failed to set field identifier!",
+ DateFormat.MONTH_FIELD, fpos3.getField());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.text.FieldPosition.equals(java.lang.Object)
+ FieldPosition fpos = new FieldPosition(1);
+ FieldPosition fpos1 = new FieldPosition(1);
+ assertTrue("Identical objects were not equal!", fpos.equals(fpos1));
+
+ FieldPosition fpos2 = new FieldPosition(2);
+ assertTrue("Objects with a different ID should not be equal!", !fpos
+ .equals(fpos2));
+
+ fpos.setBeginIndex(1);
+ fpos1.setBeginIndex(2);
+ assertTrue("Objects with a different beginIndex were still equal!",
+ !fpos.equals(fpos1));
+ fpos1.setBeginIndex(1);
+ fpos1.setEndIndex(2);
+ assertTrue("Objects with a different endIndex were still equal!", !fpos
+ .equals(fpos1));
+
+ FieldPosition fpos3 = new FieldPosition(DateFormat.Field.ERA, 1);
+ assertTrue("Objects with a different attribute should not be equal!",
+ !fpos.equals(fpos3));
+ FieldPosition fpos4 = new FieldPosition(DateFormat.Field.AM_PM, 1);
+ assertTrue("Objects with a different attribute should not be equal!",
+ !fpos3.equals(fpos4));
+ }
+
+ /**
+ * @tests java.text.FieldPosition#getBeginIndex()
+ */
+ public void test_getBeginIndex() {
+ // Test for method int java.text.FieldPosition.getBeginIndex()
+ FieldPosition fpos = new FieldPosition(1);
+ fpos.setEndIndex(3);
+ fpos.setBeginIndex(2);
+ assertEquals("getBeginIndex should have returned 2",
+ 2, fpos.getBeginIndex());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#getEndIndex()
+ */
+ public void test_getEndIndex() {
+ // Test for method int java.text.FieldPosition.getEndIndex()
+ FieldPosition fpos = new FieldPosition(1);
+ fpos.setBeginIndex(2);
+ fpos.setEndIndex(3);
+ assertEquals("getEndIndex should have returned 3",
+ 3, fpos.getEndIndex());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#getField()
+ */
+ public void test_getField() {
+ // Test for method int java.text.FieldPosition.getField()
+ FieldPosition fpos = new FieldPosition(65);
+ assertEquals("FieldPosition(65) should have caused getField to return 65",
+ 65, fpos.getField());
+ FieldPosition fpos2 = new FieldPosition(DateFormat.Field.MINUTE);
+ assertEquals("FieldPosition(DateFormat.Field.MINUTE) should have caused getField to return -1",
+ -1, fpos2.getField());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#getFieldAttribute()
+ */
+ public void test_getFieldAttribute() {
+ // Test for method int java.text.FieldPosition.getFieldAttribute()
+ FieldPosition fpos = new FieldPosition(DateFormat.Field.TIME_ZONE);
+ assertTrue(
+ "FieldPosition(DateFormat.Field.TIME_ZONE) should have caused getFieldAttribute to return DateFormat.Field.TIME_ZONE",
+ fpos.getFieldAttribute() == DateFormat.Field.TIME_ZONE);
+
+ FieldPosition fpos2 = new FieldPosition(DateFormat.TIMEZONE_FIELD);
+ assertNull(
+ "FieldPosition(DateFormat.TIMEZONE_FIELD) should have caused getFieldAttribute to return null",
+ fpos2.getFieldAttribute());
+ }
+
+ public void test_hashCode() {
+ // Test for method int java.text.FieldPosition.hashCode()
+ FieldPosition fpos1 = new FieldPosition(1);
+ FieldPosition fpos2 = new FieldPosition(1);
+ assertTrue("test 1: hash codes are not equal for equal objects.",
+ fpos1.hashCode() == fpos2.hashCode());
+ fpos1.setBeginIndex(5);
+ fpos1.setEndIndex(110);
+ assertTrue("test 2: hash codes are equal for non equal objects.",
+ fpos1.hashCode() != fpos2.hashCode());
+ fpos2.setBeginIndex(5);
+ fpos2.setEndIndex(110);
+ assertTrue("test 3: hash codes are not equal for equal objects.",
+ fpos1.hashCode() == fpos2.hashCode());
+
+ FieldPosition fpos3 = new FieldPosition(
+ DateFormat.Field.DAY_OF_WEEK_IN_MONTH);
+
+ assertTrue("test 4: hash codes are equal for non equal objects.",
+ fpos2.hashCode() != fpos3.hashCode());
+ }
+
+ public void test_setBeginIndexI() {
+ FieldPosition fpos = new FieldPosition(1);
+ fpos.setBeginIndex(2);
+ fpos.setEndIndex(3);
+ assertEquals("beginIndex should have been set to 2", 2, fpos
+ .getBeginIndex());
+
+ fpos.setBeginIndex(Integer.MAX_VALUE);
+ assertEquals("beginIndex should have been set to Integer.MAX_VALUE",
+ Integer.MAX_VALUE, fpos.getBeginIndex());
+
+ fpos.setBeginIndex(-1);
+ assertEquals("beginIndex should have been set to -1",
+ -1, fpos.getBeginIndex());
+ }
+
+ public void test_setEndIndexI() {
+ FieldPosition fpos = new FieldPosition(1);
+ fpos.setEndIndex(3);
+ fpos.setBeginIndex(2);
+ assertEquals("EndIndex should have been set to 3", 3, fpos
+ .getEndIndex());
+
+ fpos.setEndIndex(Integer.MAX_VALUE);
+ assertEquals("endIndex should have been set to Integer.MAX_VALUE",
+ Integer.MAX_VALUE, fpos.getEndIndex());
+
+ fpos.setEndIndex(-1);
+ assertEquals("endIndex should have been set to -1",
+ -1, fpos.getEndIndex());
+ }
+
+ /**
+ * @tests java.text.FieldPosition#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.text.FieldPosition.toString()
+ FieldPosition fpos = new FieldPosition(1);
+ fpos.setBeginIndex(2);
+ fpos.setEndIndex(3);
+ assertEquals(
+ "ToString returned the wrong value:",
+ "java.text.FieldPosition[attribute=null,field=1,beginIndex=2,endIndex=3]",
+ fpos.toString());
+
+ FieldPosition fpos2 = new FieldPosition(DateFormat.Field.ERA);
+ fpos2.setBeginIndex(4);
+ fpos2.setEndIndex(5);
+ assertEquals("ToString returned the wrong value:",
+ "java.text.FieldPosition[attribute=" + DateFormat.Field.ERA
+ + ",field=-1,beginIndex=4,endIndex=5]", fpos2
+ .toString());
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/LoadLocaleProviderTestHelper.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/LoadLocaleProviderTestHelper.java
new file mode 100644
index 0000000..b898061
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/LoadLocaleProviderTestHelper.java
@@ -0,0 +1,48 @@
+/*
+ * 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.tests.java.text;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+
+public abstract class LoadLocaleProviderTestHelper implements Runnable {
+ private Throwable throwable;
+
+ public LoadLocaleProviderTestHelper(URL[] classpathes)
+ throws InterruptedException {
+ URLClassLoader loader = new URLClassLoader(classpathes);
+ Thread thread = new Thread(this);
+ thread.setContextClassLoader(loader);
+ thread.start();
+ thread.join();
+ }
+
+ public Throwable getThrowable() {
+ return throwable;
+ }
+
+ public void run() {
+ try {
+ test();
+ } catch (Throwable t) {
+ throwable = t;
+ }
+ }
+
+ public abstract void test();
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatFieldTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatFieldTest.java
new file mode 100644
index 0000000..91eb9e3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatFieldTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.tests.java.text;
+
+public class MessageFormatFieldTest extends junit.framework.TestCase {
+ /**
+ * @tests java.text.MessageFormat$Field#Field(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // protected constructor
+ }
+
+ /**
+ * @tests java.text.MessageFormat$Field#readResolve()
+ */
+ public void test_readResolve() {
+ // test for method java.lang.Object readResolve()
+
+ // see serialization stress tests:
+ // implemented in
+ // SerializationStressTest4.test_writeObject_MessageFormat_Field()
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+
+ protected void doneSuite() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatTest.java
new file mode 100644
index 0000000..171f247
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/MessageFormatTest.java
@@ -0,0 +1,953 @@
+/*
+ * 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.tests.java.text;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.text.ChoiceFormat;
+import java.text.DateFormat;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.FieldPosition;
+import java.text.Format;
+import java.text.MessageFormat;
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import junit.framework.TestCase;
+
+public class MessageFormatTest extends TestCase {
+
+ private MessageFormat format1, format2, format3;
+
+ private Locale defaultLocale;
+
+ private void checkSerialization(MessageFormat format) {
+ try {
+ ByteArrayOutputStream ba = new ByteArrayOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream(ba);
+ out.writeObject(format);
+ out.close();
+ ObjectInputStream in = new ObjectInputStream(
+ new ByteArrayInputStream(ba.toByteArray()));
+ MessageFormat read = (MessageFormat) in.readObject();
+ assertTrue("Not equal: " + format.toPattern(), format.equals(read));
+ } catch (IOException e) {
+ fail("Format: " + format.toPattern()
+ + " caused IOException: " + e);
+ } catch (ClassNotFoundException e) {
+ fail("Format: " + format.toPattern()
+ + " caused ClassNotFoundException: " + e);
+ }
+ }
+
+ public void test_formatToCharacterIteratorLjava_lang_Object() {
+ new Support_MessageFormat("test_formatToCharacterIteratorLjava_lang_Object").t_formatToCharacterIterator();
+
+ try {
+ new MessageFormat("{1, number}").formatToCharacterIterator(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ new MessageFormat("{0, time}").formatToCharacterIterator(new Object[]{""});
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+
+ public void test_getLocale() throws Exception {
+ Locale[] l = {
+ Locale.FRANCE,
+ Locale.KOREA,
+ new Locale("FR", "fr"), // Deliberately backwards.
+ new Locale("mk"),
+ new Locale("mk", "MK"),
+ Locale.US,
+ new Locale("#ru", "@31230") // Deliberately nonsense.
+ };
+
+ String pattern = "getLocale test {0,number,#,####}";
+
+ for (int i = 0; i < 0; i++) {
+ MessageFormat mf = new MessageFormat(pattern, l[i]);
+ Locale result = mf.getLocale();
+ assertEquals(l[i], result);
+ assertEquals(l[i].getLanguage(), result.getLanguage());
+ assertEquals(l[i].getCountry(), result.getCountry());
+ }
+
+ MessageFormat mf = new MessageFormat(pattern);
+ mf.setLocale(null);
+ Locale result = mf.getLocale();
+ assertEquals(null, result);
+ }
+
+ public void test_setFormatILjava_text_Format() throws Exception {
+ // case 1: Compare getFormats() results after calls to setFormat()
+ MessageFormat f1 = (MessageFormat) format1.clone();
+ f1.setFormat(0, DateFormat.getTimeInstance());
+ f1.setFormat(1, DateFormat.getTimeInstance());
+ f1.setFormat(2, NumberFormat.getInstance());
+ f1.setFormat(3, new ChoiceFormat("0#off|1#on"));
+ f1.setFormat(4, new ChoiceFormat("1#few|2#ok|3#a lot"));
+ f1.setFormat(5, DateFormat.getTimeInstance());
+
+ Format[] formats = f1.getFormats();
+ formats = f1.getFormats();
+
+ Format[] correctFormats = new Format[] {
+ DateFormat.getTimeInstance(),
+ DateFormat.getTimeInstance(),
+ NumberFormat.getInstance(),
+ new ChoiceFormat("0#off|1#on"),
+ new ChoiceFormat("1#few|2#ok|3#a lot"),
+ DateFormat.getTimeInstance()
+ };
+
+ assertEquals(correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1B:wrong format for pattern index " + i + ":", correctFormats[i], formats[i]);
+ }
+
+ // case 2: Try to setFormat using incorrect index
+ try {
+ f1.setFormat(-1, DateFormat.getDateInstance());
+ fail();
+ } catch (ArrayIndexOutOfBoundsException expected) {
+ }
+ try {
+ f1.setFormat(f1.getFormats().length, DateFormat.getDateInstance());
+ fail();
+ } catch (ArrayIndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_parseObjectLjava_lang_StringLjavajava_text_ParsePosition() throws Exception {
+ MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
+ // case 1: Try to parse correct data string.
+ Object[] objs = { new Double(3.1415) };
+ String result = mf.format(objs);
+ // result now equals "3.14, 3.1"
+ Object[] res = null;
+ ParsePosition pp = new ParsePosition(0);
+ int parseIndex = pp.getIndex();
+ res = (Object[]) mf.parseObject(result, pp);
+ assertTrue("Parse operation return null", res != null);
+ assertTrue("parse operation return array with incorrect length", 1 == res.length);
+ assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex);
+ assertTrue("Result object is incorrect", new Double(3.1).equals(res[0]));
+
+ // case 2: Try to parse partially correct data string.
+ pp.setIndex(0);
+ char[] cur = result.toCharArray();
+ cur[cur.length / 2] = 'Z';
+ String partialCorrect = new String(cur);
+ res = (Object[]) mf.parseObject(partialCorrect, pp);
+ assertTrue("Parse operation return null", res == null);
+ assertTrue("ParseIndex is incorrect", pp.getIndex() == 0);
+ assertTrue("ParseErrorIndex is incorrect", pp.getErrorIndex() == cur.length / 2);
+
+ // case 3: Try to use argument ParsePosition as null.
+ try {
+ mf.parseObject(result, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_parseLjava_lang_String() throws ParseException {
+ String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}";
+ MessageFormat mf = new MessageFormat(pattern);
+ String sToParse = "A $12,345.00 B 9:56:07 AM C 3,200% D 1/15/70 9:56 AM E on F Jan 1, 1970";
+ Object[] result = mf.parse(sToParse);
+
+ assertTrue("No result: " + result.length, result.length == 5);
+ assertTrue("Object 0 is not date", result[0] instanceof Date);
+ assertEquals("Object 1 is not stringr", result[1].toString(), "1.0");
+ assertTrue("Object 2 is not date", result[2] instanceof Date);
+ assertEquals("Object 3 is not number", result[3].toString(), "12345");
+ assertEquals("Object 4 is not string", result[4].toString(), "1/15/70 9:56 AM");
+
+ sToParse = "xxdate is Feb 28, 1999";
+ try {
+ result = format1.parse(sToParse);
+ fail();
+ } catch (java.text.ParseException expected) {
+ }
+
+ sToParse = "vm=Test, @3 4 6, 3 ";
+ mf = new MessageFormat("vm={0},{1},{2}");
+ result = mf.parse(sToParse);
+ assertTrue("No result: " + result.length, result.length == 3);
+ assertEquals("Object 0 is not string", result[0].toString(), "Test");
+ assertEquals("Object 1 is not string", result[1].toString(), " @3 4 6");
+ assertEquals("Object 2 is not string", result[2].toString(), " 3 ");
+
+ try {
+ result = mf.parse(null);
+ fail();
+ } catch (java.text.ParseException expected) {
+ }
+ }
+
+ public void test_setFormats$Ljava_text_Format() throws Exception {
+ MessageFormat f1 = (MessageFormat) format1.clone();
+
+ // case 1: Test with repeating formats and max argument index < max
+ // offset
+ // compare getFormats() results after calls to setFormats(Format[])
+ Format[] correctFormats = new Format[] {
+ DateFormat.getTimeInstance(),
+ new ChoiceFormat("0#off|1#on"),
+ DateFormat.getTimeInstance(),
+ NumberFormat.getCurrencyInstance(),
+ new ChoiceFormat("1#few|2#ok|3#a lot")
+ };
+
+ f1.setFormats(correctFormats);
+ Format[] formats = f1.getFormats();
+
+ assertTrue("Test1A:Returned wrong number of formats:", correctFormats.length <= formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1B:wrong format for argument index " + i + ":", correctFormats[i], formats[i]);
+ }
+
+ // case 2: Try to pass null argument to setFormats().
+ try {
+ f1.setFormats(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_formatLjava_lang_StringLjava_lang_Object() {
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ int iCurrency = 123;
+ int iInteger = Integer.MIN_VALUE;
+
+ Date date = new Date(12345678);
+ Object[] args = { date, iCurrency, iInteger };
+ String resStr = "Date: Jan 1, 1970 Currency: $" + iCurrency + ".00 Integer: -2,147,483,648";
+ String pattern = "Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}";
+ String sFormat = MessageFormat.format(pattern, (Object[]) args);
+ assertEquals(
+ "format(String, Object[]) with valid parameters returns incorrect string: case 1",
+ sFormat, resStr);
+
+ pattern = "abc {4, number, integer} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}";
+ resStr = "abc -2,147,483,648 def Jan 1, 1970 ghi -2,147,483,648 jkl high mnop -2,147,483,648";
+ Object[] args_ = { iInteger, 1, iInteger, date, iInteger };
+ sFormat = MessageFormat.format(pattern, args_);
+ assertEquals(
+ "format(String, Object[]) with valid parameters returns incorrect string: case 1",
+ sFormat, resStr);
+
+ try {
+ args = null;
+ MessageFormat.format(null, args);
+ fail();
+ } catch (Exception expected) {
+ }
+
+ try {
+ MessageFormat.format("Invalid {1,foobar} format descriptor!", new Object[] {iInteger} );
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ MessageFormat.format("Invalid {1,date,invalid-spec} format descriptor!", new Object[]{""});
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ MessageFormat.format("{0,number,integer", new Object[] {iInteger});
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ MessageFormat.format("Valid {1, date} format {0, number} descriptor!", new Object[]{ "" } );
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_ConstructorLjava_lang_StringLjava_util_Locale() {
+ Locale mk = new Locale("mk", "MK");
+ MessageFormat format = new MessageFormat("Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}", mk);
+ assertEquals(format.getLocale(), mk);
+ assertEquals(format.getFormats()[0], DateFormat.getDateInstance(DateFormat.DEFAULT, mk));
+ assertEquals(format.getFormats()[1], NumberFormat.getCurrencyInstance(mk));
+ assertEquals(format.getFormats()[2], NumberFormat.getIntegerInstance(mk));
+ }
+
+ public void test_ConstructorLjava_lang_String() {
+ MessageFormat format = new MessageFormat(
+ "abc {4,time} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}");
+ assertTrue("Not a MessageFormat",
+ format.getClass() == MessageFormat.class);
+ Format[] formats = format.getFormats();
+ assertNotNull("null formats", formats);
+ assertTrue("Wrong format count: " + formats.length, formats.length >= 5);
+ assertTrue("Wrong time format", formats[0].equals(DateFormat
+ .getTimeInstance()));
+ assertTrue("Wrong date format", formats[1].equals(DateFormat
+ .getDateInstance()));
+ assertTrue("Wrong number format", formats[2].equals(NumberFormat
+ .getInstance()));
+ assertTrue("Wrong choice format", formats[3].equals(new ChoiceFormat(
+ "0.0#low|1.0#high")));
+ assertNull("Wrong string format", formats[4]);
+
+ Date date = new Date();
+ FieldPosition pos = new FieldPosition(-1);
+ StringBuffer buffer = new StringBuffer();
+ format.format(new Object[] { "123", new Double(1.6), new Double(7.2),
+ date, date }, buffer, pos);
+ String result = buffer.toString();
+ buffer.setLength(0);
+ buffer.append("abc ");
+ buffer.append(DateFormat.getTimeInstance().format(date));
+ buffer.append(" def ");
+ buffer.append(DateFormat.getDateInstance().format(date));
+ buffer.append(" ghi ");
+ buffer.append(NumberFormat.getInstance().format(new Double(7.2)));
+ buffer.append(" jkl high mnop 123");
+ assertTrue("Wrong answer:\n" + result + "\n" + buffer, result
+ .equals(buffer.toString()));
+
+ assertEquals("Simple string", "Test message", new MessageFormat("Test message").format(
+ new Object[0]));
+
+ result = new MessageFormat("Don't").format(new Object[0]);
+ assertTrue("Should not throw IllegalArgumentException: " + result,
+ "Dont".equals(result));
+
+ try {
+ new MessageFormat("Invalid {1,foobar} format descriptor!");
+ fail("Expected test_ConstructorLjava_lang_String to throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+
+ try {
+ new MessageFormat(
+ "Invalid {1,date,invalid-spec} format descriptor!");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+
+ checkSerialization(new MessageFormat(""));
+ checkSerialization(new MessageFormat("noargs"));
+ checkSerialization(new MessageFormat("{0}"));
+ checkSerialization(new MessageFormat("a{0}"));
+ checkSerialization(new MessageFormat("{0}b"));
+ checkSerialization(new MessageFormat("a{0}b"));
+
+ // Regression for HARMONY-65
+ try {
+ new MessageFormat("{0,number,integer");
+ fail("Assert 0: Failed to detect unmatched brackets.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void test_applyPatternLjava_lang_String() {
+ MessageFormat format = new MessageFormat("test");
+ format.applyPattern("xx {0}");
+ assertEquals("Invalid number", "xx 46", format.format(
+ new Object[] { new Integer(46) }));
+ Date date = new Date();
+ String result = format.format(new Object[] { date });
+ String expected = "xx " + DateFormat.getInstance().format(date);
+ assertTrue("Invalid date:\n" + result + "\n" + expected, result
+ .equals(expected));
+ format = new MessageFormat("{0,date}{1,time}{2,number,integer}");
+ format.applyPattern("nothing");
+ assertEquals("Found formats", "nothing", format.toPattern());
+
+ format.applyPattern("{0}");
+ assertNull("Wrong format", format.getFormats()[0]);
+ assertEquals("Wrong pattern", "{0}", format.toPattern());
+
+ format.applyPattern("{0, \t\u001ftime }");
+ assertTrue("Wrong time format", format.getFormats()[0]
+ .equals(DateFormat.getTimeInstance()));
+ assertEquals("Wrong time pattern", "{0,time}", format.toPattern());
+ format.applyPattern("{0,Time, Short\n}");
+ assertTrue("Wrong short time format", format.getFormats()[0]
+ .equals(DateFormat.getTimeInstance(DateFormat.SHORT)));
+ assertEquals("Wrong short time pattern",
+ "{0,time,short}", format.toPattern());
+ format.applyPattern("{0,TIME,\nmedium }");
+ assertTrue("Wrong medium time format", format.getFormats()[0]
+ .equals(DateFormat.getTimeInstance(DateFormat.MEDIUM)));
+ assertEquals("Wrong medium time pattern",
+ "{0,time}", format.toPattern());
+ format.applyPattern("{0,time,LONG}");
+ assertTrue("Wrong long time format", format.getFormats()[0]
+ .equals(DateFormat.getTimeInstance(DateFormat.LONG)));
+ assertEquals("Wrong long time pattern",
+ "{0,time,long}", format.toPattern());
+ format.setLocale(Locale.FRENCH); // use French since English has the
+ // same LONG and FULL time patterns
+ format.applyPattern("{0,time, Full}");
+ assertTrue("Wrong full time format", format.getFormats()[0]
+ .equals(DateFormat.getTimeInstance(DateFormat.FULL,
+ Locale.FRENCH)));
+ assertEquals("Wrong full time pattern",
+ "{0,time,full}", format.toPattern());
+ format.setLocale(Locale.getDefault());
+
+ format.applyPattern("{0, date}");
+ assertTrue("Wrong date format", format.getFormats()[0]
+ .equals(DateFormat.getDateInstance()));
+ assertEquals("Wrong date pattern", "{0,date}", format.toPattern());
+ format.applyPattern("{0, date, short}");
+ assertTrue("Wrong short date format", format.getFormats()[0]
+ .equals(DateFormat.getDateInstance(DateFormat.SHORT)));
+ assertEquals("Wrong short date pattern",
+ "{0,date,short}", format.toPattern());
+ format.applyPattern("{0, date, medium}");
+ assertTrue("Wrong medium date format", format.getFormats()[0]
+ .equals(DateFormat.getDateInstance(DateFormat.MEDIUM)));
+ assertEquals("Wrong medium date pattern",
+ "{0,date}", format.toPattern());
+ format.applyPattern("{0, date, long}");
+ assertTrue("Wrong long date format", format.getFormats()[0]
+ .equals(DateFormat.getDateInstance(DateFormat.LONG)));
+ assertEquals("Wrong long date pattern",
+ "{0,date,long}", format.toPattern());
+ format.applyPattern("{0, date, full}");
+ assertTrue("Wrong full date format", format.getFormats()[0]
+ .equals(DateFormat.getDateInstance(DateFormat.FULL)));
+ assertEquals("Wrong full date pattern",
+ "{0,date,full}", format.toPattern());
+
+ format.applyPattern("{0, date, MMM d {hh:mm:ss}}");
+ assertEquals("Wrong time/date format", " MMM d {hh:mm:ss}", ((SimpleDateFormat) (format
+ .getFormats()[0])).toPattern());
+ assertEquals("Wrong time/date pattern",
+ "{0,date, MMM d {hh:mm:ss}}", format.toPattern());
+
+ format.applyPattern("{0, number}");
+ assertTrue("Wrong number format", format.getFormats()[0]
+ .equals(NumberFormat.getNumberInstance()));
+ assertEquals("Wrong number pattern",
+ "{0,number}", format.toPattern());
+ format.applyPattern("{0, number, currency}");
+ assertTrue("Wrong currency number format", format.getFormats()[0]
+ .equals(NumberFormat.getCurrencyInstance()));
+ assertEquals("Wrong currency number pattern",
+ "{0,number,currency}", format.toPattern());
+ format.applyPattern("{0, number, percent}");
+ assertTrue("Wrong percent number format", format.getFormats()[0]
+ .equals(NumberFormat.getPercentInstance()));
+ assertEquals("Wrong percent number pattern",
+ "{0,number,percent}", format.toPattern());
+ format.applyPattern("{0, number, integer}");
+
+ DecimalFormat expectedNumberFormat = (DecimalFormat) NumberFormat.getIntegerInstance();
+ DecimalFormat actualNumberFormat = (DecimalFormat) format.getFormats()[0];
+ assertEquals(expectedNumberFormat.getDecimalFormatSymbols(), actualNumberFormat.getDecimalFormatSymbols());
+ assertEquals(expectedNumberFormat.isParseIntegerOnly(), actualNumberFormat.isParseIntegerOnly());
+ assertEquals("Wrong integer number pattern", "{0,number,integer}", format.toPattern());
+ assertEquals(expectedNumberFormat, format.getFormats()[0]);
+
+ format.applyPattern("{0, number, {'#'}##0.0E0}");
+
+ /*
+ * TODO validate these assertions
+ * String actual = ((DecimalFormat)(format.getFormats()[0])).toPattern();
+ * assertEquals("Wrong pattern number format", "' {#}'##0.0E0", actual);
+ * assertEquals("Wrong pattern number pattern", "{0,number,' {#}'##0.0E0}", format.toPattern());
+ *
+ */
+
+ format.applyPattern("{0, choice,0#no|1#one|2#{1,number}}");
+ assertEquals("Wrong choice format",
+
+ "0.0#no|1.0#one|2.0#{1,number}", ((ChoiceFormat) format.getFormats()[0]).toPattern());
+ assertEquals("Wrong choice pattern",
+ "{0,choice,0.0#no|1.0#one|2.0#{1,number}}", format.toPattern());
+ assertEquals("Wrong formatted choice", "3.6", format.format(
+ new Object[] { new Integer(2), new Float(3.6) }));
+
+ try {
+ format.applyPattern("WRONG MESSAGE FORMAT {0,number,{}");
+ fail("Expected IllegalArgumentException for invalid pattern");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // Regression for HARMONY-65
+ MessageFormat mf = new MessageFormat("{0,number,integer}");
+ String badpattern = "{0,number,#";
+ try {
+ mf.applyPattern(badpattern);
+ fail("Assert 0: Failed to detect unmatched brackets.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void test_clone() {
+ MessageFormat format = new MessageFormat("'{'choice'}'{0}");
+ MessageFormat clone = (MessageFormat) format.clone();
+ assertTrue("Clone not equal", format.equals(clone));
+ assertEquals("Wrong answer",
+ "{choice}{0}", format.format(new Object[] {}));
+ clone.setFormat(0, DateFormat.getInstance());
+ assertTrue("Clone shares format data", !format.equals(clone));
+ format = (MessageFormat) clone.clone();
+ Format[] formats = clone.getFormats();
+ ((SimpleDateFormat) formats[0]).applyPattern("adk123");
+ assertTrue("Clone shares format data", !format.equals(clone));
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ MessageFormat format1 = new MessageFormat("{0}");
+ MessageFormat format2 = new MessageFormat("{1}");
+ assertTrue("Should not be equal", !format1.equals(format2));
+ format2.applyPattern("{0}");
+ assertTrue("Should be equal", format1.equals(format2));
+ SimpleDateFormat date = (SimpleDateFormat) DateFormat.getTimeInstance();
+ format1.setFormat(0, DateFormat.getTimeInstance());
+ format2.setFormat(0, new SimpleDateFormat(date.toPattern()));
+ assertTrue("Should be equal2", format1.equals(format2));
+ }
+
+ public void test_hashCode() {
+ assertEquals("Should be equal", 3648, new MessageFormat("rr", null).hashCode());
+ }
+
+ public void test_format$Ljava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
+ MessageFormat format = new MessageFormat("{1,number,integer}");
+ StringBuffer buffer = new StringBuffer();
+ format.format(new Object[] { "0", new Double(53.863) }, buffer,
+ new FieldPosition(0));
+ assertEquals("Wrong result", "54", buffer.toString());
+
+ format.format(new Object[] { "0", new Double(53.863) }, buffer,
+ new FieldPosition(MessageFormat.Field.ARGUMENT));
+ assertEquals("Wrong result", "5454", buffer.toString());
+
+ buffer = new StringBuffer();
+ format.applyPattern("{0,choice,0#zero|1#one '{1,choice,2#two {2,time}}'}");
+ Date date = new Date();
+ String expectedText = "one two " + DateFormat.getTimeInstance().format(date);
+ format.format(new Object[] { new Double(1.6), new Integer(3), date }, buffer, new FieldPosition(MessageFormat.Field.ARGUMENT));
+ assertEquals("Choice not recursive:\n" + expectedText + "\n" + buffer, expectedText, buffer.toString());
+
+ StringBuffer str = format.format(new Object[] { new Double(0.6),
+ new Integer(3)}, buffer, null);
+ assertEquals(expectedText + "zero", str.toString());
+ assertEquals(expectedText + "zero", buffer.toString());
+
+ try {
+ format.format(new Object[] { "0", new Double(1), "" }, buffer,
+ new FieldPosition(MessageFormat.Field.ARGUMENT));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ format.format(new Object[] { "", new Integer(3)}, buffer,
+ new FieldPosition(MessageFormat.Field.ARGUMENT));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
+ new Support_MessageFormat(
+ "test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition")
+ .t_format_with_FieldPosition();
+
+ String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} hamburger{2,choice,1#|1<s}.";
+ MessageFormat format = new MessageFormat(pattern, Locale.US);
+ Object[] objects = new Object[] { "", new Integer(3), 8, ""};
+ try {
+ format.format(objects, new StringBuffer(), new FieldPosition(DateFormat.Field.AM_PM));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_getFormats() {
+ // test with repeating formats and max argument index < max offset
+ Format[] formats = format1.getFormats();
+ Format[] correctFormats = new Format[] {
+ NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(),
+ NumberFormat.getPercentInstance(), null,
+ new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance(), };
+
+ assertEquals("Test1:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test with max argument index > max offset
+ formats = format2.getFormats();
+ correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(),
+ NumberFormat.getPercentInstance(), null,
+ new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance() };
+
+ assertEquals("Test2:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test with argument number being zero
+ formats = format3.getFormats();
+ assertEquals("Test3: Returned wrong number of formats:", 0,
+ formats.length);
+ }
+
+ public void test_getFormatsByArgumentIndex() {
+ // test with repeating formats and max argument index < max offset
+ Format[] formats = format1.getFormatsByArgumentIndex();
+ Format[] correctFormats = new Format[] { DateFormat.getDateInstance(),
+ new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
+ NumberFormat.getCurrencyInstance(), null };
+
+ assertEquals("Test1:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test with max argument index > max offset
+ formats = format2.getFormatsByArgumentIndex();
+ correctFormats = new Format[] { DateFormat.getDateInstance(),
+ new ChoiceFormat("0#off|1#on"), null,
+ NumberFormat.getCurrencyInstance(), null, null, null, null,
+ DateFormat.getTimeInstance() };
+
+ assertEquals("Test2:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test with argument number being zero
+ formats = format3.getFormatsByArgumentIndex();
+ assertEquals("Test3: Returned wrong number of formats:", 0,
+ formats.length);
+ }
+
+ public void test_setFormatByArgumentIndexILjava_text_Format() {
+ // test for method setFormatByArgumentIndex(int, Format)
+ MessageFormat f1 = (MessageFormat) format1.clone();
+ f1.setFormatByArgumentIndex(0, DateFormat.getTimeInstance());
+ f1.setFormatByArgumentIndex(4, new ChoiceFormat("1#few|2#ok|3#a lot"));
+
+ // test with repeating formats and max argument index < max offset
+ // compare getFormatsByArgumentIndex() results after calls to
+ // setFormatByArgumentIndex()
+ Format[] formats = f1.getFormatsByArgumentIndex();
+
+ Format[] correctFormats = new Format[] { DateFormat.getTimeInstance(),
+ new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
+ NumberFormat.getCurrencyInstance(),
+ new ChoiceFormat("1#few|2#ok|3#a lot") };
+
+ assertEquals("Test1A:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1B:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // compare getFormats() results after calls to
+ // setFormatByArgumentIndex()
+ formats = f1.getFormats();
+
+ correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
+ new ChoiceFormat("1#few|2#ok|3#a lot"),
+ new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(), };
+
+ assertEquals("Test1C:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1D:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test setting argumentIndexes that are not used
+ MessageFormat f2 = (MessageFormat) format2.clone();
+ f2.setFormatByArgumentIndex(2, NumberFormat.getPercentInstance());
+ f2.setFormatByArgumentIndex(4, DateFormat.getTimeInstance());
+
+ formats = f2.getFormatsByArgumentIndex();
+ correctFormats = format2.getFormatsByArgumentIndex();
+
+ assertEquals("Test2A:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2B:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ formats = f2.getFormats();
+ correctFormats = format2.getFormats();
+
+ assertEquals("Test2C:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2D:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test exceeding the argumentIndex number
+ MessageFormat f3 = (MessageFormat) format3.clone();
+ f3.setFormatByArgumentIndex(1, NumberFormat.getCurrencyInstance());
+
+ formats = f3.getFormatsByArgumentIndex();
+ assertEquals("Test3A:Returned wrong number of formats:", 0,
+ formats.length);
+
+ formats = f3.getFormats();
+ assertEquals("Test3B:Returned wrong number of formats:", 0,
+ formats.length);
+ }
+
+ public void test_setFormatsByArgumentIndex$Ljava_text_Format() {
+ MessageFormat f1 = (MessageFormat) format1.clone();
+
+ // test with repeating formats and max argument index < max offset
+ // compare getFormatsByArgumentIndex() results after calls to
+ // setFormatsByArgumentIndex(Format[])
+ Format[] correctFormats = new Format[] { DateFormat.getTimeInstance(),
+ new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
+ NumberFormat.getCurrencyInstance(),
+ new ChoiceFormat("1#few|2#ok|3#a lot") };
+
+ f1.setFormatsByArgumentIndex(correctFormats);
+ Format[] formats = f1.getFormatsByArgumentIndex();
+
+ assertEquals("Test1A:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1B:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // compare getFormats() results after calls to
+ // setFormatByArgumentIndex()
+ formats = f1.getFormats();
+ correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
+ new ChoiceFormat("1#few|2#ok|3#a lot"),
+ new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(), };
+
+ assertEquals("Test1C:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test1D:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test setting argumentIndexes that are not used
+ MessageFormat f2 = (MessageFormat) format2.clone();
+ Format[] inputFormats = new Format[] { DateFormat.getDateInstance(),
+ new ChoiceFormat("0#off|1#on"),
+ NumberFormat.getPercentInstance(),
+ NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(), null, null, null,
+ DateFormat.getTimeInstance() };
+ f2.setFormatsByArgumentIndex(inputFormats);
+
+ formats = f2.getFormatsByArgumentIndex();
+ correctFormats = format2.getFormatsByArgumentIndex();
+
+ assertEquals("Test2A:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2B:wrong format for argument index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ formats = f2.getFormats();
+ correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
+ DateFormat.getTimeInstance(), DateFormat.getDateInstance(),
+ null, new ChoiceFormat("0#off|1#on"),
+ DateFormat.getDateInstance() };
+
+ assertEquals("Test2C:Returned wrong number of formats:",
+ correctFormats.length, formats.length);
+ for (int i = 0; i < correctFormats.length; i++) {
+ assertEquals("Test2D:wrong format for pattern index " + i + ":",
+ correctFormats[i], formats[i]);
+ }
+
+ // test exceeding the argumentIndex number
+ MessageFormat f3 = (MessageFormat) format3.clone();
+ f3.setFormatsByArgumentIndex(inputFormats);
+
+ formats = f3.getFormatsByArgumentIndex();
+ assertEquals("Test3A:Returned wrong number of formats:", 0,
+ formats.length);
+
+ formats = f3.getFormats();
+ assertEquals("Test3B:Returned wrong number of formats:", 0,
+ formats.length);
+
+ }
+
+ public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
+ MessageFormat format = new MessageFormat("date is {0,date,MMM d, yyyy}");
+ ParsePosition pos = new ParsePosition(2);
+ Object[] result = (Object[]) format
+ .parse("xxdate is Feb 28, 1999", pos);
+ assertTrue("No result: " + result.length, result.length >= 1);
+ assertTrue("Wrong answer", ((Date) result[0])
+ .equals(new GregorianCalendar(1999, Calendar.FEBRUARY, 28)
+ .getTime()));
+
+ MessageFormat mf = new MessageFormat("vm={0},{1},{2}");
+ result = mf.parse("vm=win,foo,bar", new ParsePosition(0));
+ assertTrue("Invalid parse", result[0].equals("win")
+ && result[1].equals("foo") && result[2].equals("bar"));
+
+ mf = new MessageFormat("{0}; {0}; {0}");
+ String parse = "a; b; c";
+ result = mf.parse(parse, new ParsePosition(0));
+ assertEquals("Wrong variable result", "c", result[0]);
+
+ mf = new MessageFormat("before {0}, after {1,number}");
+ parse = "before you, after 42";
+ pos.setIndex(0);
+ pos.setErrorIndex(8);
+ result = mf.parse(parse, pos);
+ assertEquals(2, result.length);
+
+ try {
+ mf.parse(parse, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // This should _not_ throw.
+ mf.parse(null, pos);
+ }
+
+ public void test_setLocaleLjava_util_Locale() {
+ MessageFormat format = new MessageFormat("date {0,date}");
+ format.setLocale(Locale.CHINA);
+ assertEquals("Wrong locale1", Locale.CHINA, format.getLocale());
+ format.applyPattern("{1,date}");
+ assertEquals("Wrong locale3", DateFormat.getDateInstance(DateFormat.DEFAULT,
+ Locale.CHINA), format.getFormats()[0]);
+ }
+
+ public void test_toPattern() {
+ String pattern = "[{0}]";
+ MessageFormat mf = new MessageFormat(pattern);
+ assertTrue("Wrong pattern", mf.toPattern().equals(pattern));
+
+ // Regression for HARMONY-59
+ new MessageFormat("CHOICE {1,choice}").toPattern();
+ }
+
+ protected void setUp() {
+ defaultLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+
+ // test with repeating formats and max argument index < max offset
+ String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}";
+ format1 = new MessageFormat(pattern);
+
+ // test with max argument index > max offset
+ pattern = "A {3, number, currency} B {8, time} C {0, number, percent} D {6} E {1,choice,0#off|1#on} F {0, date}";
+ format2 = new MessageFormat(pattern);
+
+ // test with argument number being zero
+ pattern = "A B C D E F";
+ format3 = new MessageFormat(pattern);
+ }
+
+ protected void tearDown() {
+ Locale.setDefault(defaultLocale);
+ }
+
+ public void test_ConstructorLjava_util_Locale() {
+ // Regression for HARMONY-65
+ try {
+ new MessageFormat("{0,number,integer", Locale.US);
+ fail("Assert 0: Failed to detect unmatched brackets.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void test_parse() throws ParseException {
+ // Regression for HARMONY-63
+ MessageFormat mf = new MessageFormat("{0,number,#,##}", Locale.US);
+ Object[] res = mf.parse("1,00,00");
+ assertEquals("Assert 0: incorrect size of parsed data ", 1, res.length);
+ assertEquals("Assert 1: parsed value incorrectly", new Long(10000), (Long)res[0]);
+ }
+
+ public void test_format_Object() {
+ // Regression for HARMONY-1875
+ Locale.setDefault(Locale.CANADA);
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ String pat="text here {0, date, yyyyyyyyy } and here";
+ String etalon="text here 000002007 and here";
+ MessageFormat obj = new MessageFormat(pat);
+ assertEquals(etalon, obj.format(new Object[]{new Date(1198141737640L)}));
+
+ assertEquals("{0}", MessageFormat.format("{0}", (Object[]) null));
+ assertEquals("nullABC", MessageFormat.format("{0}{1}", (Object[]) new String[]{null, "ABC"}));
+ }
+
+ public void testHARMONY5323() {
+ Object[] messageArgs = new Object[11];
+ for (int i = 0; i < messageArgs.length; i++) {
+ messageArgs[i] = "example" + i;
+ }
+
+ String res = MessageFormat.format("bgcolor=\"{10}\"", messageArgs);
+ assertEquals(res, "bgcolor=\"example10\"");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NormalizerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NormalizerTest.java
new file mode 100644
index 0000000..50aa096
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NormalizerTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.Normalizer;
+import java.text.Normalizer.Form;
+
+import junit.framework.TestCase;
+
+public class NormalizerTest extends TestCase {
+ /**
+ * @tests java.text.Normalizer.Form#values()
+ */
+ public void test_form_values() throws Exception {
+ Form[] forms = Form.values();
+ assertEquals(4, forms.length);
+ assertEquals(Form.NFD, forms[0]);
+ assertEquals(Form.NFC, forms[1]);
+ assertEquals(Form.NFKD, forms[2]);
+ assertEquals(Form.NFKC, forms[3]);
+ }
+
+ /**
+ * @tests java.text.Normalizer.Form#valueOf(String)
+ */
+ public void test_form_valueOfLjava_lang_String() {
+ try {
+ Form.valueOf(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ assertEquals(Form.NFC, Form.valueOf("NFC"));
+ assertEquals(Form.NFD, Form.valueOf("NFD"));
+ assertEquals(Form.NFKC, Form.valueOf("NFKC"));
+ assertEquals(Form.NFKD, Form.valueOf("NFKD"));
+
+ try {
+ Form.valueOf("not exist");
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ Form.valueOf("nfc");
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ Form.valueOf("NFC ");
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.Normalizer#isNormalized(CharSequence, Form)
+ */
+ public void test_isNormalized() throws Exception {
+ String src = "\u00c1";
+ assertTrue(Normalizer.isNormalized(src, Form.NFC));
+ assertFalse(Normalizer.isNormalized(src, Form.NFD));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKC));
+ assertFalse(Normalizer.isNormalized(src, Form.NFKD));
+
+ src = "\u0041\u0301";
+ assertFalse(Normalizer.isNormalized(src, Form.NFC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFD));
+ assertFalse(Normalizer.isNormalized(src, Form.NFKC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKD));
+
+ src = "\ufb03";
+ assertTrue(Normalizer.isNormalized(src, Form.NFC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFD));
+ assertFalse(Normalizer.isNormalized(src, Form.NFKC));
+ assertFalse(Normalizer.isNormalized(src, Form.NFKD));
+
+ src = "\u0066\u0066\u0069";
+ assertTrue(Normalizer.isNormalized(src, Form.NFC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFD));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKD));
+
+ src = "";
+ assertTrue(Normalizer.isNormalized(src, Form.NFC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFD));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKC));
+ assertTrue(Normalizer.isNormalized(src, Form.NFKD));
+ }
+
+ /**
+ * @tests java.text.Normalizer#isNormalized(CharSequence, Form)
+ */
+ public void test_isNormalized_exception() throws Exception {
+ try {
+ Normalizer.isNormalized(null, Form.NFC);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ Normalizer.isNormalized("chars", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.Normalizer#normalize(CharSequence, Form)
+ */
+ public void test_normalize() throws Exception {
+ String src = "\u00c1";
+ assertEquals("\u00c1", Normalizer.normalize(src, Form.NFC));
+ assertEquals("\u0041\u0301", Normalizer.normalize(src, Form.NFD));
+ assertEquals("\u00c1", Normalizer.normalize(src, Form.NFKC));
+ assertEquals("\u0041\u0301", Normalizer.normalize(src, Form.NFKD));
+
+ src = "\u0041\u0301";
+ assertEquals("\u00c1", Normalizer.normalize(src, Form.NFC));
+ assertEquals("\u0041\u0301", Normalizer.normalize(src, Form.NFD));
+ assertEquals("\u00c1", Normalizer.normalize(src, Form.NFKC));
+ assertEquals("\u0041\u0301", Normalizer.normalize(src, Form.NFKD));
+
+ src = "\ufb03";
+ assertEquals("\ufb03", Normalizer.normalize(src, Form.NFC));
+ assertEquals("\ufb03", Normalizer.normalize(src, Form.NFD));
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFKC));
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFKD));
+
+ src = "\u0066\u0066\u0069";
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFC));
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFD));
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFKC));
+ assertEquals("\u0066\u0066\u0069", Normalizer.normalize(src, Form.NFKD));
+
+ src = "";
+ assertEquals("", Normalizer.normalize(src, Form.NFC));
+ assertEquals("", Normalizer.normalize(src, Form.NFD));
+ assertEquals("", Normalizer.normalize(src, Form.NFKC));
+ assertEquals("", Normalizer.normalize(src, Form.NFKD));
+ }
+
+ /**
+ * @tests java.text.Normalizer#normalize(CharSequence, Form)
+ */
+ public void test_normalize_exception() throws Exception {
+ try {
+ Normalizer.normalize(null, Form.NFC);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ Normalizer.normalize("chars", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatFieldTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatFieldTest.java
new file mode 100644
index 0000000..8d64d8a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatFieldTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.tests.java.text;
+
+public class NumberFormatFieldTest extends junit.framework.TestCase {
+ /**
+ * @tests java.text.NumberFormat$Field#Field(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // protected constructor
+ }
+
+ /**
+ * @tests java.text.NumberFormat$Field#readResolve()
+ */
+ public void test_readResolve() {
+ // test for method java.lang.Object readResolve()
+
+ // see serialization stress tests:
+ // implemented in
+ // SerializationStressTest4.test_writeObject_NumberFormat_Field()
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+
+ protected void doneSuite() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatTest.java
new file mode 100644
index 0000000..49e3d9e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/NumberFormatTest.java
@@ -0,0 +1,295 @@
+/*
+ * 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.tests.java.text;
+
+import java.math.RoundingMode;
+import java.text.ChoiceFormat;
+import java.text.DecimalFormat;
+import java.text.FieldPosition;
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.Currency;
+import java.util.Locale;
+
+public class NumberFormatTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.NumberFormat#format(java.lang.Object,
+ * java.lang.StringBuffer, java.text.FieldPosition)
+ */
+ public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
+ FieldPosition pos;
+ StringBuffer out;
+ DecimalFormat format = (DecimalFormat) NumberFormat
+ .getInstance(Locale.US);
+
+ pos = new FieldPosition(0);
+ out = format.format(new Long(Long.MAX_VALUE), new StringBuffer(), pos);
+ assertEquals("Wrong result L1: " + out, "9,223,372,036,854,775,807",
+ out.toString());
+
+ pos = new FieldPosition(0);
+ out = format.format(new Long(Long.MIN_VALUE), new StringBuffer(), pos);
+ assertEquals("Wrong result L2: " + out, "-9,223,372,036,854,775,808",
+ out.toString());
+
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigInteger(String
+ .valueOf(Long.MAX_VALUE)), new StringBuffer(), pos);
+ assertEquals("Wrong result BI1: " + out, "9,223,372,036,854,775,807",
+ out.toString());
+
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigInteger(String
+ .valueOf(Long.MIN_VALUE)), new StringBuffer(), pos);
+ assertEquals("Wrong result BI2: " + out, "-9,223,372,036,854,775,808",
+ out.toString());
+
+ java.math.BigInteger big;
+ pos = new FieldPosition(0);
+ big = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE))
+ .add(new java.math.BigInteger("1"));
+ out = format.format(big, new StringBuffer(), pos);
+ assertEquals("Wrong result BI3: " + out, "9,223,372,036,854,775,808",
+ out.toString());
+
+ pos = new FieldPosition(0);
+ big = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE))
+ .add(new java.math.BigInteger("-1"));
+ out = format.format(big, new StringBuffer(), pos);
+ assertEquals("Wrong result BI4: " + out, "-9,223,372,036,854,775,809",
+ out.toString());
+
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigDecimal("51.348"),
+ new StringBuffer(), pos);
+ assertEquals("Wrong result BD1: " + out, "51.348", out.toString());
+
+ pos = new FieldPosition(0);
+ out = format.format(new java.math.BigDecimal("51"), new StringBuffer(),
+ pos);
+ assertEquals("Wrong result BD2: " + out, "51", out.toString());
+
+ try {
+ format.format(this, new StringBuffer(), pos);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ format.format(null, new StringBuffer(), pos);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ format.format(new Long(0), null, pos);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ format.format(new Long(0), new StringBuffer(), null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * @tests java.text.NumberFormat#getIntegerInstance()
+ */
+ public void test_getIntegerInstance() throws ParseException {
+ // Test for method java.text.NumberFormat getIntegerInstance()
+ Locale origLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+
+ DecimalFormat format = (DecimalFormat) NumberFormat
+ .getIntegerInstance();
+
+ assertEquals(
+ "Test1: NumberFormat.getIntegerInstance().toPattern() returned wrong pattern",
+ "#,##0", format.toPattern());
+ assertEquals(
+ "Test2: NumberFormat.getIntegerInstance().format(35.76) returned wrong value",
+ "36", format.format(35.76));
+ assertEquals(
+ "Test3: NumberFormat.getIntegerInstance().parse(\"35.76\") returned wrong number",
+ new Long(35), format.parse("35.76"));
+ assertEquals(
+ "Test4: NumberFormat.getIntegerInstance().parseObject(\"35.76\") returned wrong number",
+ new Long(35), format.parseObject("35.76"));
+ Locale.setDefault(origLocale);
+ }
+
+ /**
+ * @tests java.text.NumberFormat#getIntegerInstance(java.util.Locale)
+ */
+ public void test_getIntegerInstanceLjava_util_Locale()
+ throws ParseException {
+ // Test for method java.text.NumberFormat
+ // getIntegerInstance(java.util.Locale)
+ Locale usLocale = Locale.US;
+ Locale arLocale = new Locale("ar", "AE");
+
+ DecimalFormat format = (DecimalFormat) NumberFormat
+ .getIntegerInstance(usLocale);
+ assertEquals(
+ "Test1: NumberFormat.getIntegerInstance().toPattern() returned wrong pattern",
+ "#,##0", format.toPattern());
+ assertEquals(
+ "Test2: NumberFormat.getIntegerInstance().format(-35.76) returned wrong value",
+ "-36", format.format(-35.76));
+ assertEquals(
+ "Test3: NumberFormat.getIntegerInstance().parse(\"-36\") returned wrong number",
+ new Long(-36), format.parse("-36"));
+ assertEquals(
+ "Test4: NumberFormat.getIntegerInstance().parseObject(\"-36\") returned wrong number",
+ new Long(-36), format.parseObject("-36"));
+ assertEquals(
+ "Test5: NumberFormat.getIntegerInstance().getMaximumFractionDigits() returned wrong value",
+ 0, format.getMaximumFractionDigits());
+ assertTrue("Test6: NumberFormat.getIntegerInstance().isParseIntegerOnly() returned wrong value",
+ format.isParseIntegerOnly());
+
+ // try with a locale that has a different integer pattern
+ format = (DecimalFormat) NumberFormat.getIntegerInstance(arLocale);
+ assertEquals(
+ "Test7: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).toPattern() returned wrong pattern",
+ "#,##0", format.toPattern());
+ assertEquals(
+ "Test8: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).format(-35.76) returned wrong value",
+ "\u200f-\u0666", format.format(-6));
+ assertEquals(
+ "Test9: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).parse(\"-36-\") returned wrong number",
+ new Long(36), format.parse("36-"));
+ assertEquals(
+ "Test10: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).parseObject(\"36-\") returned wrong number",
+ new Long(36), format.parseObject("36-"));
+
+ assertEquals(
+ "Test11: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).getMaximumFractionDigits() returned wrong value",
+ 0, format.getMaximumFractionDigits());
+ assertTrue(
+ "Test12: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).isParseIntegerOnly() returned wrong value",
+ format.isParseIntegerOnly());
+ }
+
+ /**
+ * @tests java.text.NumberFormat#getCurrency()
+ */
+ public void test_getCurrency() {
+ // Test for method java.util.Currency getCurrency()
+
+ // a subclass that supports currency formatting
+ Currency currH = Currency.getInstance("HUF");
+ NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
+ assertSame("Returned incorrect currency", currH, format.getCurrency());
+
+ // a subclass that doesn't support currency formatting
+ ChoiceFormat cformat = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ try {
+ ((NumberFormat) cformat).getCurrency();
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ /**
+ * @tests java.text.NumberFormat#getMaximumIntegerDigits()
+ */
+ public void test_getMaximumIntegerDigits() {
+ NumberFormat format = NumberFormat.getInstance();
+ format.setMaximumIntegerDigits(2);
+ assertEquals("Wrong result", "23", format.format(123));
+ }
+
+ /**
+ * @tests java.text.NumberFormat#setCurrency(java.util.Currency)
+ */
+ public void test_setCurrencyLjava_util_Currency() {
+ // Test for method void setCurrency(java.util.Currency)
+ // a subclass that supports currency formatting
+ Currency currA = Currency.getInstance("ARS");
+ NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
+ format.setCurrency(currA);
+ assertSame("Returned incorrect currency", currA, format.getCurrency());
+
+ // a subclass that doesn't support currency formatting
+ ChoiceFormat cformat = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ try {
+ ((NumberFormat) cformat).setCurrency(currA);
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+ /**
+ * @tests java.text.NumberFormat#parseObject(java.lang.String, java.text.ParsePosition)
+ */
+ public void test_parseObjectLjava_lang_StringLjava_text_ParsePosition() {
+ // regression test for HARMONY-1003
+ assertNull(NumberFormat.getInstance().parseObject("0", new ParsePosition(-1)));
+
+ // Regression for HARMONY-1685
+ try {
+ NumberFormat.getInstance().parseObject("test", null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+
+ public void test_setRoundingMode_NullRoundingMode() {
+ try {
+ // Create a subclass ChoiceFormat which doesn't support
+ // RoundingMode
+ ChoiceFormat choiceFormat = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ ((NumberFormat) choiceFormat).setRoundingMode(null);
+ // Follow the behavior of RI
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ public void test_setRoundingMode_Normal() {
+ try {
+ // Create a subclass ChoiceFormat which doesn't support
+ // RoundingMode
+ ChoiceFormat choiceFormat = new ChoiceFormat(
+ "0#Less than one|1#one|1<Between one and two|2<Greater than two");
+ ((NumberFormat) choiceFormat).setRoundingMode(RoundingMode.CEILING);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParseExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParseExceptionTest.java
new file mode 100644
index 0000000..c73d8e3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParseExceptionTest.java
@@ -0,0 +1,49 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+
+@SuppressWarnings("nls")
+public class ParseExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * @tests java.text.ParseException#ParseException(java.lang.String, int)
+ */
+ public void test_ConstructorLjava_lang_StringI() {
+ try {
+ DateFormat df = DateFormat.getInstance();
+ df.parse("HelloWorld");
+ fail("ParseException not created/thrown.");
+ } catch (ParseException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.ParseException#getErrorOffset()
+ */
+ public void test_getErrorOffset() {
+ try {
+ DateFormat df = DateFormat.getInstance();
+ df.parse("1999HelloWorld");
+ } catch (ParseException e) {
+ assertEquals("getErrorOffsetFailed.", 4, e.getErrorOffset());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParsePositionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParsePositionTest.java
new file mode 100644
index 0000000..994a8d3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/ParsePositionTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.ParsePosition;
+
+public class ParsePositionTest extends junit.framework.TestCase {
+
+ ParsePosition pp;
+
+ /**
+ * @tests java.text.ParsePosition#ParsePosition(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.text.ParsePosition(int)
+ ParsePosition pp1 = new ParsePosition(Integer.MIN_VALUE);
+ assertTrue("Initialization failed.", pp1.getIndex() == Integer.MIN_VALUE);
+ assertEquals("Initialization failed.", -1, pp1.getErrorIndex());
+ }
+
+ /**
+ * @tests java.text.ParsePosition#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.text.ParsePosition.equals(java.lang.Object)
+ ParsePosition pp2 = new ParsePosition(43);
+ pp2.setErrorIndex(56);
+ assertTrue("equals failed.", !pp.equals(pp2));
+ pp.setErrorIndex(56);
+ pp.setIndex(43);
+ assertTrue("equals failed.", pp.equals(pp2));
+ }
+
+ /**
+ * @tests java.text.ParsePosition#getErrorIndex()
+ */
+ public void test_getErrorIndex() {
+ // Test for method int java.text.ParsePosition.getErrorIndex()
+ pp.setErrorIndex(56);
+ assertEquals("getErrorIndex failed.", 56, pp.getErrorIndex());
+ }
+
+ /**
+ * @tests java.text.ParsePosition#getIndex()
+ */
+ public void test_getIndex() {
+ // Test for method int java.text.ParsePosition.getIndex()
+ assertTrue("getIndex failed.", pp.getIndex() == Integer.MAX_VALUE);
+ }
+
+ /**
+ * @tests java.text.ParsePosition#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.text.ParsePosition.hashCode()
+ assertTrue("Wrong hashCode returned", (pp.hashCode() == pp.getIndex()
+ + pp.getErrorIndex()));
+ }
+
+ /**
+ * @tests java.text.ParsePosition#setErrorIndex(int)
+ */
+ public void test_setErrorIndexI() {
+ // Test for method void java.text.ParsePosition.setErrorIndex(int)
+ pp.setErrorIndex(4564);
+ assertEquals("setErrorIndex failed.", 4564, pp.getErrorIndex());
+ }
+
+ /**
+ * @tests java.text.ParsePosition#setIndex(int)
+ */
+ public void test_setIndexI() {
+ // Test for method void java.text.ParsePosition.setIndex(int)
+ pp.setIndex(4564);
+ assertEquals("setErrorIndex failed.", 4564, pp.getIndex());
+ }
+
+ /**
+ * @tests java.text.ParsePosition#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.text.ParsePosition.toString()
+ assertEquals("toString failed.",
+ "java.text.ParsePosition[index=2147483647, errorIndex=-1]", pp.toString());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+
+ pp = new ParsePosition(Integer.MAX_VALUE);
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/RuleBasedCollatorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/RuleBasedCollatorTest.java
new file mode 100644
index 0000000..906857b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/RuleBasedCollatorTest.java
@@ -0,0 +1,258 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.CharacterIterator;
+import java.text.CollationElementIterator;
+import java.text.CollationKey;
+import java.text.Collator;
+import java.text.ParseException;
+import java.text.RuleBasedCollator;
+import java.text.StringCharacterIterator;
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+public class RuleBasedCollatorTest extends TestCase {
+
+ public void test_getCollationKeyLjava_lang_String() throws Exception {
+ // Regression test for HARMONY-28
+ String source = null;
+ String Simple = "&9 < a< b< c< d";
+ RuleBasedCollator rbc = new RuleBasedCollator(Simple);
+ CollationKey ck = rbc.getCollationKey(source);
+ assertNull("Assert 1: getCollationKey (null) does not return null", ck);
+ }
+
+ public void testHashCode() throws ParseException {
+ {
+ String rule = "&9 < a < b < c < d";
+ RuleBasedCollator coll = new RuleBasedCollator(rule);
+ assertEquals(rule.hashCode(), coll.hashCode());
+ }
+
+ {
+ String rule = "&9 < a < b < c < d < e";
+ RuleBasedCollator coll = new RuleBasedCollator(rule);
+ assertEquals(rule.hashCode(), coll.hashCode());
+ }
+ }
+
+ public void testClone() throws ParseException {
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
+ RuleBasedCollator clone = (RuleBasedCollator) coll.clone();
+ assertNotSame(coll, clone);
+ assertEquals(coll.getRules(), clone.getRules());
+ assertEquals(coll.getDecomposition(), clone.getDecomposition());
+ assertEquals(coll.getStrength(), clone.getStrength());
+ }
+
+ public void testEqualsObject() throws ParseException {
+ String rule = "&9 < a < b < c < d < e";
+ RuleBasedCollator coll = new RuleBasedCollator(rule);
+
+ assertEquals(Collator.TERTIARY, coll.getStrength());
+ assertEquals(Collator.NO_DECOMPOSITION, coll.getDecomposition());
+ RuleBasedCollator other = new RuleBasedCollator(rule);
+ assertTrue(coll.equals(other));
+
+ coll.setStrength(Collator.PRIMARY);
+ assertFalse(coll.equals(other));
+
+ coll.setStrength(Collator.TERTIARY);
+ coll.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
+ assertFalse(coll.equals(other));
+ }
+
+ public void testCompareStringString() throws ParseException {
+ String rule = "&9 < c < b < a";
+ RuleBasedCollator coll = new RuleBasedCollator(rule);
+ assertEquals(-1, coll.compare("c", "a"));
+ }
+
+ public void testGetCollationKey() {
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.GERMAN);
+ String source = "abc";
+ CollationKey key1 = coll.getCollationKey(source);
+ assertEquals(source, key1.getSourceString());
+ String source2 = "abb";
+ CollationKey key2 = coll.getCollationKey(source2);
+ assertEquals(source2, key2.getSourceString());
+ assertTrue(key1.compareTo(key2) > 0);
+ assertTrue(coll.compare(source, source2) > 0);
+ }
+
+ public void testGetRules() throws ParseException {
+ String rule = "&9 < a = b < c";
+ RuleBasedCollator coll = new RuleBasedCollator(rule);
+ assertEquals(rule, coll.getRules());
+ }
+
+ public void testGetCollationElementIteratorString() throws Exception {
+ {
+ Locale locale = Locale.forLanguageTag("es-u-co-trad");
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(locale);
+ String source = "cha";
+ CollationElementIterator iterator = coll.getCollationElementIterator(source);
+ int[] e_offset = { 0, 2, 3 };
+ int offset = iterator.getOffset();
+ int i = 0;
+ assertEquals(e_offset[i++], offset);
+ while (offset != source.length()) {
+ iterator.next();
+ offset = iterator.getOffset();
+ assertEquals(e_offset[i++], offset);
+ }
+ assertEquals(CollationElementIterator.NULLORDER, iterator.next());
+ }
+
+ {
+ Locale locale = new Locale("de", "DE");
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(locale);
+ String source = "\u00fcb";
+ CollationElementIterator iterator = coll.getCollationElementIterator(source);
+ int[] e_offset = { 0, 1, 1, 2 };
+ int offset = iterator.getOffset();
+ int i = 0;
+ assertEquals(e_offset[i++], offset);
+ while (offset != source.length()) {
+ iterator.next();
+ offset = iterator.getOffset();
+ assertEquals(e_offset[i++], offset);
+ }
+ assertEquals(CollationElementIterator.NULLORDER, iterator.next());
+ }
+ //Regression for HARMONY-1352
+ try {
+ new RuleBasedCollator("&9 < a< b< c< d").getCollationElementIterator((String)null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testGetCollationElementIteratorCharacterIterator() throws Exception {
+ {
+ Locale locale = Locale.forLanguageTag("es-u-co-trad");
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(locale);
+ String text = "cha";
+ StringCharacterIterator source = new StringCharacterIterator(text);
+ CollationElementIterator iterator = coll.getCollationElementIterator(source);
+ int[] e_offset = { 0, 2, 3 };
+ int offset = iterator.getOffset();
+ int i = 0;
+ assertEquals(e_offset[i++], offset);
+ while (offset != text.length()) {
+ iterator.next();
+ offset = iterator.getOffset();
+ // System.out.println(offset);
+ assertEquals(e_offset[i++], offset);
+ }
+ assertEquals(CollationElementIterator.NULLORDER, iterator.next());
+ }
+
+ {
+ Locale locale = new Locale("de", "DE");
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(locale);
+ String text = "\u00fcb";
+ StringCharacterIterator source = new StringCharacterIterator(text);
+ CollationElementIterator iterator = coll.getCollationElementIterator(source);
+ int[] e_offset = { 0, 1, 1, 2 };
+ int offset = iterator.getOffset();
+ int i = 0;
+ assertEquals(e_offset[i++], offset);
+ while (offset != text.length()) {
+ iterator.next();
+ offset = iterator.getOffset();
+ assertEquals(e_offset[i++], offset);
+ }
+ assertEquals(CollationElementIterator.NULLORDER, iterator.next());
+ }
+ //Regression for HARMONY-1352
+ try {
+ new RuleBasedCollator("&9 < a< b< c< d").getCollationElementIterator((CharacterIterator)null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testStrength() {
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
+ for (int i = 0; i < 4; i++) {
+ coll.setStrength(i);
+ assertEquals(i, coll.getStrength());
+ }
+ }
+
+ public void testDecomposition() {
+ RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
+ for (int i = 0; i < 2; i++) {
+ coll.setDecomposition(i);
+ assertEquals(i, coll.getDecomposition());
+ }
+ }
+
+ public void testCollator_GetInstance() {
+ Collator coll = Collator.getInstance();
+ Object obj1 = "a";
+ Object obj2 = "b";
+ assertEquals(-1, coll.compare(obj1, obj2));
+
+ Collator.getInstance();
+ assertFalse(coll.equals("A", "\uFF21"));
+ }
+
+ public void testGetAvailableLocales() {
+ assertTrue(Collator.getAvailableLocales().length > 0);
+ }
+
+ // Test CollationKey
+ public void testCollationKey() {
+ Collator coll = Collator.getInstance(Locale.US);
+ String text = "abc";
+ CollationKey key = coll.getCollationKey(text);
+ key.hashCode();
+
+ CollationKey key2 = coll.getCollationKey("abc");
+
+ assertEquals(0, key.compareTo(key2));
+ }
+
+ public void testNullPointerException() throws Exception {
+ //Regression for HARMONY-241
+ try {
+ new RuleBasedCollator(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testCompareNull() throws Exception {
+ //Regression for HARMONY-836
+ try {
+ new RuleBasedCollator("&9 < a").compare(null, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testEmptyRules() throws Exception {
+ new RuleBasedCollator("");
+ new RuleBasedCollator(" ");
+ new RuleBasedCollator("# This is a comment.");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/SimpleDateFormatTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/SimpleDateFormatTest.java
new file mode 100644
index 0000000..9a484ae
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/SimpleDateFormatTest.java
@@ -0,0 +1,835 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.DateFormatSymbols;
+import java.text.FieldPosition;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+
+
+public class SimpleDateFormatTest extends junit.framework.TestCase {
+
+ private SimpleDateFormat format;
+
+ private SimpleDateFormat pFormat;
+
+ private TimeZone previousDefaultTimeZone;
+
+ @Override public void setUp() {
+ previousDefaultTimeZone = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+ format = new SimpleDateFormat("", Locale.ENGLISH);
+ pFormat = new SimpleDateFormat("", Locale.ENGLISH);
+ }
+
+ @Override public void tearDown() {
+ TimeZone.setDefault(previousDefaultTimeZone);
+ }
+
+ public void test_Constructor() {
+ // Test for method java.text.SimpleDateFormat()
+ SimpleDateFormat f2 = new SimpleDateFormat();
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertTrue("Wrong default", f2.equals(DateFormat.getDateTimeInstance(
+ DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(new DateFormatSymbols()));
+ assertTrue("Doesn't work", f2.format(new Date()).getClass() == String.class);
+ }
+
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.text.SimpleDateFormat(java.lang.String)
+ SimpleDateFormat f2 = new SimpleDateFormat("yyyy");
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertEquals("Wrong pattern", "yyyy", f2.toPattern());
+ assertTrue("Wrong locale", f2.equals(new SimpleDateFormat("yyyy", Locale.getDefault())));
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(new DateFormatSymbols()));
+ assertTrue("Doesn't work", f2.format(new Date()).getClass() == String.class);
+
+ // Invalid constructor value.
+ try {
+ new SimpleDateFormat("this is an invalid simple date format");
+ fail("Expected test_ConstructorLjava_lang_String to throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+
+ // Null string value
+ try {
+ new SimpleDateFormat(null);
+ fail("Expected test_ConstructorLjava_lang_String to throw NPE.");
+ } catch (NullPointerException ex) {
+ // expected
+ }
+ }
+
+ public void test_ConstructorLjava_lang_StringLjava_text_DateFormatSymbols() {
+ // Test for method java.text.SimpleDateFormat(java.lang.String,
+ // java.text.DateFormatSymbols)
+ DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH);
+ symbols.setEras(new String[] { "Before", "After" });
+ SimpleDateFormat f2 = new SimpleDateFormat("y'y'yy", symbols);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertEquals("Wrong pattern", "y'y'yy", f2.toPattern());
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(symbols));
+ assertTrue("Doesn't work", f2.format(new Date()).getClass() == String.class);
+
+ try {
+ new SimpleDateFormat(null, symbols);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ new SimpleDateFormat("eee", symbols);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_ConstructorLjava_lang_StringLjava_util_Locale() {
+ // Test for method java.text.SimpleDateFormat(java.lang.String,
+ // java.util.Locale)
+ SimpleDateFormat f2 = new SimpleDateFormat("'yyyy' MM yy", Locale.GERMAN);
+ assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
+ assertEquals("Wrong pattern", "'yyyy' MM yy", f2.toPattern());
+ assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
+ new DateFormatSymbols(Locale.GERMAN)));
+ assertTrue("Doesn't work", f2.format(new Date()).getClass() == String.class);
+
+ try {
+ new SimpleDateFormat(null, Locale.GERMAN);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ new SimpleDateFormat("eee", Locale.GERMAN);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_applyLocalizedPatternLjava_lang_String() {
+ SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH"));
+ String pattern = "GyMdkHmsSEDFwWahKzZLc";
+ f2.applyLocalizedPattern(pattern);
+ assertEquals(pattern, f2.toPattern());
+ assertEquals(pattern, f2.toLocalizedPattern());
+
+ // test invalid patterns
+ try {
+ f2.applyLocalizedPattern("b");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ f2.applyLocalizedPattern("a '"); // Unterminated quote.
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ f2.applyLocalizedPattern(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_applyPatternLjava_lang_String() {
+ // Test for method void
+ // java.text.SimpleDateFormat.applyPattern(java.lang.String)
+ SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH"));
+ f2.applyPattern("GyMdkHmsSEDFwWahKz");
+ assertEquals("Wrong pattern", "GyMdkHmsSEDFwWahKz", f2.toPattern());
+
+ // test invalid patterns
+ try {
+ f2.applyPattern("b");
+ fail("Expected IllegalArgumentException for pattern with invalid patter letter: b");
+ } catch (IllegalArgumentException e) {
+ }
+
+// try {
+// f2.applyPattern("u");
+// fail("Expected IllegalArgumentException for pattern with invalid patter letter: u");
+// } catch (IllegalArgumentException e) {
+// }
+
+ try {
+ f2.applyPattern("a '");
+ fail("Expected IllegalArgumentException for pattern with unterminated quote: a '");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ f2.applyPattern(null);
+ fail("Expected NullPointerException for null pattern");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_clone() {
+ // Test for method java.lang.Object java.text.SimpleDateFormat.clone()
+ SimpleDateFormat f2 = new SimpleDateFormat();
+ SimpleDateFormat clone = (SimpleDateFormat) f2.clone();
+ assertTrue("Invalid clone", f2.equals(clone));
+ clone.applyPattern("y");
+ assertTrue("Format modified", !f2.equals(clone));
+ clone = (SimpleDateFormat) f2.clone();
+ // Date date = clone.get2DigitYearStart();
+ // date.setTime(0);
+ // assertTrue("Equal after date change: " +
+ // f2.get2DigitYearStart().getTime() + " " +
+ // clone.get2DigitYearStart().getTime(), !f2.equals(clone));
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.text.SimpleDateFormat.equals(java.lang.Object)
+ SimpleDateFormat format = (SimpleDateFormat) DateFormat.getInstance();
+ SimpleDateFormat clone = (SimpleDateFormat) format.clone();
+ assertTrue("clone not equal", format.equals(clone));
+ format.format(new Date());
+ assertTrue("not equal after format", format.equals(clone));
+ }
+
+ public void test_equals_afterFormat() {
+ // Regression test for HARMONY-209
+ SimpleDateFormat df = new SimpleDateFormat();
+ df.format(new Date());
+ assertEquals(df, new SimpleDateFormat());
+ }
+
+ public void test_hashCode() {
+ SimpleDateFormat format = (SimpleDateFormat) DateFormat.getInstance();
+ SimpleDateFormat clone = (SimpleDateFormat) format.clone();
+ assertTrue("clone has not equal hash code", clone.hashCode() == format.hashCode());
+ format.format(new Date());
+ assertTrue("clone has not equal hash code after format",
+ clone.hashCode() == format.hashCode());
+ DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH);
+ symbols.setEras(new String[] { "Before", "After" });
+ SimpleDateFormat format2 = new SimpleDateFormat("y'y'yy", symbols);
+ assertFalse("objects has equal hash code", format2.hashCode() == format.hashCode());
+ }
+
+ public void test_formatToCharacterIteratorLjava_lang_Object() {
+ try {
+ // Regression for HARMONY-466
+ new SimpleDateFormat().formatToCharacterIterator(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // Test for method formatToCharacterIterator(java.lang.Object)
+ new Support_SimpleDateFormat(
+ "test_formatToCharacterIteratorLjava_lang_Object")
+ .t_formatToCharacterIterator();
+ }
+
+ public void test_formatLjava_util_DateLjava_lang_StringBufferLjava_text_FieldPosition() {
+ // Test for method java.lang.StringBuffer
+ // java.text.SimpleDateFormat.format(java.util.Date,
+ // java.lang.StringBuffer, java.text.FieldPosition)
+
+ new Support_SimpleDateFormat(
+ "test_formatLjava_util_DateLjava_lang_StringBufferLjava_text_FieldPosition")
+ .t_format_with_FieldPosition();
+
+ Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
+ assertFormat(" G", cal, " AD", DateFormat.ERA_FIELD);
+ assertFormat(" GG", cal, " AD", DateFormat.ERA_FIELD);
+ assertFormat(" GGG", cal, " AD", DateFormat.ERA_FIELD);
+ assertFormat(" G", new GregorianCalendar(-1999, Calendar.JUNE, 2), " BC",
+ DateFormat.ERA_FIELD);
+
+ // This assumes Unicode behavior where 'y' and 'yyy' don't truncate,
+ // which means that it will fail on the RI.
+ assertFormat(" y", cal, " 1999", DateFormat.YEAR_FIELD);
+ assertFormat(" yy", cal, " 99", DateFormat.YEAR_FIELD);
+ assertFormat(" yy", new GregorianCalendar(2001, Calendar.JUNE, 2), " 01",
+ DateFormat.YEAR_FIELD);
+ assertFormat(" yy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 00",
+ DateFormat.YEAR_FIELD);
+ assertFormat(" yyy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 2000",
+ DateFormat.YEAR_FIELD);
+ assertFormat(" yyy", cal, " 1999", DateFormat.YEAR_FIELD);
+ assertFormat(" yyyy", cal, " 1999", DateFormat.YEAR_FIELD);
+ assertFormat(" yyyyy", cal, " 01999", DateFormat.YEAR_FIELD);
+
+ assertFormat(" M", cal, " 6", DateFormat.MONTH_FIELD);
+ assertFormat(" M", new GregorianCalendar(1999, Calendar.NOVEMBER, 2), " 11",
+ DateFormat.MONTH_FIELD);
+ assertFormat(" MM", cal, " 06", DateFormat.MONTH_FIELD);
+ assertFormat(" MMM", cal, " Jun", DateFormat.MONTH_FIELD);
+ assertFormat(" MMMM", cal, " June", DateFormat.MONTH_FIELD);
+ assertFormat(" MMMMM", cal, " J", DateFormat.MONTH_FIELD);
+
+ assertFormat(" d", cal, " 2", DateFormat.DATE_FIELD);
+ assertFormat(" d", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), " 12",
+ DateFormat.DATE_FIELD);
+ assertFormat(" dd", cal, " 02", DateFormat.DATE_FIELD);
+ assertFormat(" dddd", cal, " 0002", DateFormat.DATE_FIELD);
+
+ assertFormat(" h", cal, " 3", DateFormat.HOUR1_FIELD);
+ assertFormat(" h", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), " 12",
+ DateFormat.HOUR1_FIELD);
+ assertFormat(" hh", cal, " 03", DateFormat.HOUR1_FIELD);
+ assertFormat(" hhhh", cal, " 0003", DateFormat.HOUR1_FIELD);
+
+ assertFormat(" H", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD);
+ assertFormat(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4",
+ DateFormat.HOUR_OF_DAY0_FIELD);
+ assertFormat(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12, 0), " 12",
+ DateFormat.HOUR_OF_DAY0_FIELD);
+ assertFormat(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), " 0",
+ DateFormat.HOUR_OF_DAY0_FIELD);
+ assertFormat(" HH", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD);
+ assertFormat(" HHHH", cal, " 0015", DateFormat.HOUR_OF_DAY0_FIELD);
+
+ assertFormat(" m", cal, " 3", DateFormat.MINUTE_FIELD);
+ assertFormat(" m", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 47), " 47",
+ DateFormat.MINUTE_FIELD);
+ assertFormat(" mm", cal, " 03", DateFormat.MINUTE_FIELD);
+ assertFormat(" mmmm", cal, " 0003", DateFormat.MINUTE_FIELD);
+
+ assertFormat(" s", cal, " 6", DateFormat.SECOND_FIELD);
+ assertFormat(" s", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 47, 13), " 13",
+ DateFormat.SECOND_FIELD);
+ assertFormat(" ss", cal, " 06", DateFormat.SECOND_FIELD);
+ assertFormat(" ssss", cal, " 0006", DateFormat.SECOND_FIELD);
+
+ assertFormat(" S", cal, " 0", DateFormat.MILLISECOND_FIELD);
+ Calendar temp = new GregorianCalendar();
+ temp.set(Calendar.MILLISECOND, 961);
+
+ assertFormat(" SS", temp, " 96", DateFormat.MILLISECOND_FIELD);
+ assertFormat(" SSSS", cal, " 0000", DateFormat.MILLISECOND_FIELD);
+
+ assertFormat(" SS", cal, " 00", DateFormat.MILLISECOND_FIELD);
+
+ assertFormat(" E", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
+ assertFormat(" EE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
+ assertFormat(" EEE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
+ assertFormat(" EEEE", cal, " Wednesday", DateFormat.DAY_OF_WEEK_FIELD);
+ assertFormat(" EEEEE", cal, " W", DateFormat.DAY_OF_WEEK_FIELD);
+
+ assertFormat(" D", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD);
+ assertFormat(" DD", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD);
+ assertFormat(" DDDD", cal, " 0153", DateFormat.DAY_OF_YEAR_FIELD);
+
+ assertFormat(" F", cal, " 1", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
+ assertFormat(" F", new GregorianCalendar(1999, Calendar.NOVEMBER, 14), " 2",
+ DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
+ assertFormat(" FF", cal, " 01", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
+ assertFormat(" FFFF", cal, " 0001", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
+
+ cal.setMinimalDaysInFirstWeek(1);
+ cal.setFirstDayOfWeek(1);
+
+ assertFormat(" w", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD);
+ assertFormat(" ww", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD);
+ assertFormat(" wwww", cal, " 0023", DateFormat.WEEK_OF_YEAR_FIELD);
+
+ assertFormat(" W", cal, " 1", DateFormat.WEEK_OF_MONTH_FIELD);
+ assertFormat(" WW", cal, " 01", DateFormat.WEEK_OF_MONTH_FIELD);
+ assertFormat(" WWWW", cal, " 0001", DateFormat.WEEK_OF_MONTH_FIELD);
+
+ assertFormat(" a", cal, " PM", DateFormat.AM_PM_FIELD);
+ assertFormat(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14), " AM",
+ DateFormat.AM_PM_FIELD);
+ assertFormat(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14, 12, 0), " PM",
+ DateFormat.AM_PM_FIELD);
+ assertFormat(" aa", cal, " PM", DateFormat.AM_PM_FIELD);
+ assertFormat(" aaa", cal, " PM", DateFormat.AM_PM_FIELD);
+ assertFormat(" aaaa", cal, " PM", DateFormat.AM_PM_FIELD);
+ assertFormat(" aaaaa", cal, " PM", DateFormat.AM_PM_FIELD);
+
+ assertFormat(" k", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD);
+ assertFormat(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4",
+ DateFormat.HOUR_OF_DAY1_FIELD);
+ assertFormat(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12, 0), " 12",
+ DateFormat.HOUR_OF_DAY1_FIELD);
+ assertFormat(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), " 24",
+ DateFormat.HOUR_OF_DAY1_FIELD);
+ assertFormat(" kk", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD);
+ assertFormat(" kkkk", cal, " 0015", DateFormat.HOUR_OF_DAY1_FIELD);
+
+ assertFormat(" K", cal, " 3", DateFormat.HOUR0_FIELD);
+ assertFormat(" K", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), " 0",
+ DateFormat.HOUR0_FIELD);
+ assertFormat(" KK", cal, " 03", DateFormat.HOUR0_FIELD);
+ assertFormat(" KKKK", cal, " 0003", DateFormat.HOUR0_FIELD);
+
+ format.applyPattern("'Mkz''':.@5");
+ assertEquals("Wrong output", "Mkz':.@5", format.format(new Date()));
+
+ // Test invalid args to format.
+ SimpleDateFormat dateFormat = new SimpleDateFormat();
+ try {
+ dateFormat.format(null, new StringBuffer(), new FieldPosition(1));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ private void assertFormat(String pattern, Calendar cal, String expected, int field) {
+ StringBuffer buffer = new StringBuffer();
+ FieldPosition position = new FieldPosition(field);
+ format.applyPattern(pattern);
+ format.format(cal.getTime(), buffer, position);
+ String result = buffer.toString();
+ assertTrue("Wrong format: \"" + pattern + "\" expected: " + expected + " result: " + result,
+ result.equals(expected));
+ assertEquals("Wrong begin position: " + pattern + "\n" + "expected: " + expected + "\n" +
+ "field: " + field, 1, position.getBeginIndex());
+ assertTrue("Wrong end position: " + pattern + " expected: " + expected + " field: " + field,
+ position.getEndIndex() == result.length());
+ }
+
+ public void test_format_time_zones() throws Exception {
+ Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
+
+ format.setTimeZone(TimeZone.getTimeZone("EST"));
+ assertFormat(" z", cal, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ Calendar temp2 = new GregorianCalendar(1999, Calendar.JANUARY, 12);
+ assertFormat(" z", temp2, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zz", cal, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzz", cal, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzz", cal, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzz", temp2, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzzz", cal, " GMT-05:00", DateFormat.TIMEZONE_FIELD);
+
+ format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
+ assertFormat(" z", cal, " EDT", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" z", temp2, " EST", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zz", cal, " EDT", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzz", cal, " EDT", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzz", temp2, " Eastern Standard Time", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD);
+
+ TimeZone tz0001 = new SimpleTimeZone(60000, "ONE MINUTE");
+ TimeZone tz0130 = new SimpleTimeZone(5400000, "ONE HOUR, THIRTY");
+ TimeZone tzMinus0130 = new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY");
+
+ format.setTimeZone(tz0001);
+// test(" Z", cal, " +0001", DateFormat.TIMEZONE_FIELD);
+// test(" ZZZZ", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
+// test(" ZZZZZ", cal, " +00:01", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tz0130);
+// test(" Z", cal, " +0130", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tzMinus0130);
+// test(" Z", cal, " -0130", DateFormat.TIMEZONE_FIELD);
+
+ format.setTimeZone(tz0001);
+ assertFormat(" z", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
+ assertFormat(" zzzz", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tz0130);
+ assertFormat(" z", cal, " GMT+01:30", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tzMinus0130);
+ assertFormat(" z", cal, " GMT-01:30", DateFormat.TIMEZONE_FIELD);
+ }
+
+ public void test_timeZoneFormatting() {
+ // tests specific to formatting of timezones
+ Date summerDate = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6).getTime();
+ Date winterDate = new GregorianCalendar(1999, Calendar.JANUARY, 12).getTime();
+
+ verifyFormatTimezone(
+ "America/Los_Angeles", "PDT, Pacific Daylight Time", "-0700, GMT-07:00",
+ summerDate);
+ verifyFormatTimezone(
+ "America/Los_Angeles", "PST, Pacific Standard Time", "-0800, GMT-08:00",
+ winterDate);
+
+ verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", summerDate);
+ verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", winterDate);
+
+ verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", summerDate);
+ verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", winterDate);
+
+ // this fails on the RI!
+ verifyFormatTimezone("America/Detroit", "EDT, Eastern Daylight Time", "-0400, GMT-04:00",
+ summerDate);
+ verifyFormatTimezone("America/Detroit", "EST, Eastern Standard Time", "-0500, GMT-05:00",
+ winterDate);
+
+ // Pacific/Kiritimati is one of the timezones supported only in mJava
+ verifyFormatTimezone(
+ "Pacific/Kiritimati", "GMT+14:00, Line Islands Time", "+1400, GMT+14:00",
+ summerDate);
+ verifyFormatTimezone(
+ "Pacific/Kiritimati", "GMT+14:00, Line Islands Time", "+1400, GMT+14:00",
+ winterDate);
+
+ verifyFormatTimezone("EST", "GMT-05:00, GMT-05:00", "-0500, GMT-05:00", summerDate);
+ verifyFormatTimezone("EST", "GMT-05:00, GMT-05:00", "-0500, GMT-05:00", winterDate);
+
+ verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", summerDate);
+ verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", winterDate);
+ }
+
+ private void verifyFormatTimezone(String timeZoneId, String expected1, String expected2,
+ Date date) {
+ format.setTimeZone(SimpleTimeZone.getTimeZone(timeZoneId));
+ format.applyPattern("z, zzzz");
+ assertEquals("Test z for TimeZone : " + timeZoneId, expected1, format.format(date));
+
+ format.applyPattern("Z, ZZZZ");
+ assertEquals("Test Z for TimeZone : " + timeZoneId, expected2, format.format(date));
+ }
+
+ public void test_get2DigitYearStart() {
+ // Test for method java.util.Date
+ // java.text.SimpleDateFormat.get2DigitYearStart()
+ SimpleDateFormat f1 = new SimpleDateFormat("y");
+ Date date = f1.get2DigitYearStart();
+ Calendar cal = new GregorianCalendar();
+ int year = cal.get(Calendar.YEAR);
+ cal.setTime(date);
+ assertTrue("Wrong default year start", cal.get(Calendar.YEAR) == (year - 80));
+ }
+
+ public void test_getDateFormatSymbols() {
+ // Test for method java.text.DateFormatSymbols
+ // java.text.SimpleDateFormat.getDateFormatSymbols()
+ SimpleDateFormat df = (SimpleDateFormat) DateFormat.getInstance();
+ DateFormatSymbols dfs = df.getDateFormatSymbols();
+ assertTrue("Symbols identical", dfs != df.getDateFormatSymbols());
+ }
+
+ public void test_parseLjava_lang_StringLjava_text_ParsePosition() throws Exception {
+ // Test for method java.util.Date
+ // java.text.SimpleDateFormat.parse(java.lang.String,
+ // java.text.ParsePosition)
+ Calendar cal = new GregorianCalendar(1970, Calendar.JANUARY, 1);
+ Date time = cal.getTime();
+ assertParse("h", " 12", time, 1, 3);
+ assertParse("H", " 0", time, 1, 2);
+ assertParse("k", " 24", time, 1, 3);
+ assertParse("K", " 0", time, 1, 2);
+
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1, 1, 0);
+ time = cal.getTime();
+ assertParse("h", "1", time, 0, 1);
+ assertParse("H", "1 ", time, 0, 1);
+ assertParse("k", "1", time, 0, 1);
+ assertParse("K", "1", time, 0, 1);
+
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1, 11, 0);
+ time = cal.getTime();
+ assertParse("h", "0011 ", time, 0, 4);
+ assertParse("K", "11", time, 0, 2);
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1, 23, 0);
+ time = cal.getTime();
+ assertParse("H", "23", time, 0, 2);
+ assertParse("k", "23", time, 0, 2);
+
+ assertParse("h a", " 3 AM", new GregorianCalendar(1970,
+ Calendar.JANUARY, 1, 3, 0).getTime(), 1, 5);
+ assertParse("K a", " 3 pm ", new GregorianCalendar(1970,
+ Calendar.JANUARY, 1, 15, 0).getTime(), 1, 5);
+ assertParse("m:s", "0:59 ", new GregorianCalendar(1970,
+ Calendar.JANUARY, 1, 0, 0, 59).getTime(), 0, 4);
+ assertParse("m:s", "59:0", new GregorianCalendar(1970, Calendar.JANUARY,
+ 1, 0, 59, 0).getTime(), 0, 4);
+ assertParse("ms", "059", new GregorianCalendar(1970, Calendar.JANUARY,
+ 1, 0, 0, 59).getTime(), 0, 3);
+
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1);
+ assertParse("S", "0", cal.getTime(), 0, 1);
+ cal.setTimeZone(TimeZone.getTimeZone("HST"));
+ cal.set(Calendar.MILLISECOND, 999);
+ assertParse("S z", "999 HST", cal.getTime(), 0, 7);
+
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1);
+ cal.set(Calendar.ERA, GregorianCalendar.BC);
+ assertParse("G", "Bc ", cal.getTime(), 0, 2);
+
+ assertParse("y", "00", new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("y", "99", new GregorianCalendar(1999, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("y", "1", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 1);
+ assertParse("y", "-1", new GregorianCalendar(-1, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("y", "001", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 3);
+ assertParse("y", "2005", new GregorianCalendar(2005, Calendar.JANUARY, 1).getTime(), 0, 4);
+ assertParse("yy", "00", new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yy", "99", new GregorianCalendar(1999, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yy", "1", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 1);
+ assertParse("yy", "-1", new GregorianCalendar(-1, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yy", "001", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 3);
+ assertParse("yy", "2005", new GregorianCalendar(2005, Calendar.JANUARY, 1).getTime(), 0, 4);
+ assertParse("yyy", "99", new GregorianCalendar(99, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yyy", "1", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 1);
+ assertParse("yyy", "-1", new GregorianCalendar(-1, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yyy", "001", new GregorianCalendar(1, Calendar.JANUARY, 1).getTime(), 0, 3);
+ assertParse("yyy", "2005", new GregorianCalendar(2005, Calendar.JANUARY, 1).getTime(),
+ 0, 4);
+ assertParse("yyyy", "99", new GregorianCalendar(99, Calendar.JANUARY, 1).getTime(), 0, 2);
+ assertParse("yyyy", " 1999", new GregorianCalendar(1999, Calendar.JANUARY, 1).getTime(),
+ 2, 6);
+ assertParse("MM'M'", "4M", new GregorianCalendar(1970, Calendar.APRIL, 1).getTime(), 0, 2);
+ assertParse("MMM", "Feb", new GregorianCalendar(1970, Calendar.FEBRUARY, 1).getTime(),
+ 0, 3);
+ assertParse("MMMM d", "April 14 ",
+ new GregorianCalendar(1970, Calendar.APRIL, 14).getTime(), 0, 8);
+ assertParse("MMMMd", "April14 ", new GregorianCalendar(1970, Calendar.APRIL, 14).getTime(),
+ 0, 7);
+ assertParse("E w", "Mon 12", new GregorianCalendar(1970, Calendar.MARCH, 16).getTime(),
+ 0, 6);
+ assertParse("Ew", "Mon12", new GregorianCalendar(1970, Calendar.MARCH, 16).getTime(), 0, 5);
+ assertParse("M EE ''W", "5 Tue '2", new GregorianCalendar(1970, Calendar.MAY, 5).getTime(),
+ 0, 8);
+ assertParse("MEE''W", "5Tue'2", new GregorianCalendar(1970, Calendar.MAY, 5).getTime(),
+ 0, 6);
+ assertParse("MMM EEE F", " JUL Sunday 3",
+ new GregorianCalendar(1970, Calendar.JULY, 19).getTime(), 1, 13);
+ assertParse("MMMEEEF", " JULSunday3",
+ new GregorianCalendar(1970, Calendar.JULY, 19).getTime(), 1, 11);
+
+ cal = new GregorianCalendar(1970, Calendar.JANUARY, 1);
+ cal.setTimeZone(TimeZone.getTimeZone("GMT+0:1"));
+ cal.set(Calendar.DAY_OF_YEAR, 243);
+ assertParse("D z", "243 GMT+0:0", cal.getTime(), 0, 11);
+ cal.setTimeZone(TimeZone.getTimeZone("EST"));
+ cal.set(1970, Calendar.JANUARY, 1, 4, 30);
+ assertParse("h:m z", "4:30 GMT-5 ", cal.getTime(), 0, 10);
+ assertParse("h z", "14 GMT-24 ", new Date(51840000), 0, 9);
+ assertParse("h z", "14 GMT-23 ", new Date(133200000), 0, 9);
+ assertParse("h z", "14 GMT-0001 ", new Date(54000000), 0, 11);
+ assertParse("h z", "14 GMT+24 ", new Date(48960000), 0, 9);
+ assertParse("h z", "14 GMT+23 ", new Date(-32400000), 0, 9);
+ assertParse("h z", "14 GMT+0001 ", new Date(46800000), 0, 11);
+ assertParse("h z", "14 +0001 ", new Date(46800000), 0, 8);
+ assertParse("h z", "14 -0001 ", new Date(54000000), 0, 8);
+
+ assertParse("yyyyMMddHHmmss", "19990913171901",
+ new GregorianCalendar(1999, Calendar.SEPTEMBER, 13, 17, 19, 1).getTime(), 0, 14);
+
+ Date d = new Date(1015822800000L);
+ SimpleDateFormat df = new SimpleDateFormat("", new Locale("en", "US"));
+ df.setTimeZone(TimeZone.getTimeZone("EST"));
+
+ df.applyPattern("dd MMMM yyyy EEEE");
+ String output = df.format(d);
+ Date date = df.parse(output);
+ assertTrue("Invalid result 1: " + date, d.equals(date));
+
+ df.applyPattern("dd MMMM yyyy F");
+ output = df.format(d);
+ date = df.parse(output);
+ assertTrue("Invalid result 2: " + date, d.equals(date));
+
+ df.applyPattern("dd MMMM yyyy w");
+ output = df.format(d);
+ date = df.parse(output);
+ assertTrue("Invalid result 3: " + date, d.equals(date));
+
+ df.applyPattern("dd MMMM yyyy W");
+ output = df.format(d);
+ date = df.parse(output);
+ assertTrue("Invalid result 4: " + date, d.equals(date));
+
+ df.applyPattern("dd MMMM yyyy D");
+ date = df.parse("5 January 2002 70");
+ assertTrue("Invalid result 5: " + date, d.equals(date));
+
+ df.applyPattern("W w dd MMMM yyyy EEEE");
+ output = df.format(d);
+ date = df.parse("3 12 5 March 2002 Monday");
+ assertTrue("Invalid result 6: " + date, d.equals(date));
+
+ df.applyPattern("w W dd MMMM yyyy EEEE");
+ output = df.format(d);
+ date = df.parse("12 3 5 March 2002 Monday");
+ assertTrue("Invalid result 6a: " + date, d.equals(date));
+
+ df.applyPattern("F dd MMMM yyyy EEEE");
+ output = df.format(d);
+ date = df.parse("2 5 March 2002 Monday");
+ assertTrue("Invalid result 7: " + date, d.equals(date));
+
+ df.applyPattern("w dd MMMM yyyy EEEE");
+ output = df.format(d);
+ date = df.parse("11 5 January 2002 Monday");
+ assertTrue("Invalid result 8: " + date, d.equals(date));
+
+ df.applyPattern("w dd yyyy EEEE MMMM");
+ output = df.format(d);
+ date = df.parse("11 5 2002 Monday January");
+ assertTrue("Invalid result 9: " + date, d.equals(date));
+
+ df.applyPattern("w yyyy EEEE MMMM dd");
+ output = df.format(d);
+ date = df.parse("17 2002 Monday March 11");
+ assertTrue("Invalid result 10: " + date, d.equals(date));
+
+ df.applyPattern("dd D yyyy MMMM");
+ output = df.format(d);
+ date = df.parse("5 70 2002 January");
+ assertTrue("Invalid result 11: " + date, d.equals(date));
+
+ df.applyPattern("D dd yyyy MMMM");
+ output = df.format(d);
+ date = df.parse("240 11 2002 March");
+ assertTrue("Invalid result 12: " + date, d.equals(date));
+
+ try {
+ format.parse("240 11 2002 March", null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ format.parse(null, new ParsePosition(0));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ private void assertParse(String pattern, String input, Date expected, int start, int end) {
+ pFormat.applyPattern(pattern);
+ ParsePosition position = new ParsePosition(start);
+ Date result = pFormat.parse(input, position);
+ assertTrue("Wrong result: " + pattern + " input: " + input + " expected: " + expected +
+ " result: " + result, expected.equals(result));
+ assertTrue("Wrong end position: " + pattern + " input: " + input,
+ position.getIndex() == end);
+ }
+
+ public void test_set2DigitYearStartLjava_util_Date() {
+ // Test for method void
+ // java.text.SimpleDateFormat.set2DigitYearStart(java.util.Date)
+ SimpleDateFormat f1 = new SimpleDateFormat("yy");
+ f1.set2DigitYearStart(new GregorianCalendar(1950, Calendar.JANUARY, 1).getTime());
+ Calendar cal = new GregorianCalendar();
+ try {
+ cal.setTime(f1.parse("49"));
+ assertEquals("Incorrect year 2049", 2049, cal.get(Calendar.YEAR));
+ cal.setTime(f1.parse("50"));
+ int year = cal.get(Calendar.YEAR);
+ assertTrue("Incorrect year 1950: " + year, year == 1950);
+ f1.applyPattern("y");
+ cal.setTime(f1.parse("00"));
+ assertEquals("Incorrect year 2000", 2000, cal.get(Calendar.YEAR));
+ f1.applyPattern("yyy");
+ cal.setTime(f1.parse("50"));
+ assertEquals("Incorrect year 50", 50, cal.get(Calendar.YEAR));
+ } catch (ParseException e) {
+ fail("ParseException");
+ }
+ }
+
+ public void test_setDateFormatSymbolsLjava_text_DateFormatSymbols() {
+ // Test for method void
+ // java.text.SimpleDateFormat.setDateFormatSymbols(java.text.DateFormatSymbols)
+ SimpleDateFormat f1 = new SimpleDateFormat("a");
+ DateFormatSymbols symbols = new DateFormatSymbols();
+ symbols.setAmPmStrings(new String[] { "morning", "night" });
+ f1.setDateFormatSymbols(symbols);
+ DateFormatSymbols newSym = f1.getDateFormatSymbols();
+ assertTrue("Set incorrectly", newSym.equals(symbols));
+ assertTrue("Not a clone", f1.getDateFormatSymbols() != symbols);
+ String result = f1.format(new GregorianCalendar(1999, Calendar.JUNE, 12, 3, 0).getTime());
+ assertEquals("Incorrect symbols used", "morning", result);
+ symbols.setEras(new String[] { "before", "after" });
+ assertTrue("Identical symbols", !f1.getDateFormatSymbols().equals(symbols));
+
+ try {
+ f1.setDateFormatSymbols(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_toPattern() {
+ String pattern = "yyyy mm dd";
+ SimpleDateFormat f = new SimpleDateFormat(pattern);
+ assertEquals("Wrong pattern: " + pattern, pattern, f.toPattern());
+
+ pattern = "GyMdkHmsSEDFwWahKz";
+ f = new SimpleDateFormat("GyMdkHmsSEDFwWahKz", new Locale("de", "CH"));
+ assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern));
+
+ pattern = "G y M d Z";
+ f = new SimpleDateFormat(pattern, new Locale("de", "CH"));
+ pattern = f.toPattern();
+ assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern));
+ }
+
+ public void test_toLocalizedPattern() {
+ SimpleDateFormat f2 = new SimpleDateFormat("GyMdkHmsSEDFwWahKzZLc", new Locale("de", "CH"));
+ assertEquals(f2.toPattern(), f2.toLocalizedPattern());
+ }
+
+ public void test_parse_with_spaces() {
+ // Regression for HARMONY-502
+ SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
+ df.setLenient(false);
+
+ char allowed_chars[] = { 0x9, 0x20 };
+ String allowed_char_names[] = { "tab", "space" };
+ for (int i = 0; i < allowed_chars.length; i++) {
+ Date expected = new GregorianCalendar(1970, Calendar.JANUARY, 1, 9, 7, 6).getTime();
+ ParsePosition pp = new ParsePosition(0);
+ Date d = df.parse(allowed_chars[i] + "9:07:06", pp);
+ assertNotNull("hour may be prefixed by " + allowed_char_names[i], d);
+ assertEquals(expected, d);
+
+ pp = new ParsePosition(0);
+ d = df.parse("09:" + allowed_chars[i] + "7:06", pp);
+ assertNotNull("minute may be prefixed by " + allowed_char_names[i], d);
+ assertEquals(expected, d);
+
+ pp = new ParsePosition(0);
+ d = df.parse("09:07:" + allowed_chars[i] + "6", pp);
+ assertNotNull("second may be prefixed by " + allowed_char_names[i], d);
+ assertEquals(expected, d);
+ }
+
+ char not_allowed_chars[] = {
+ // whitespace
+ 0x1c, 0x1d, 0x1e, 0x1f, 0xa, 0xb, 0xc, 0xd, 0x2001, 0x2002,
+ 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200a, 0x200b,
+ 0x2028, 0x2029, 0x3000,
+ // non-breaking space
+ 0xA0, 0x2007, 0x202F };
+
+ for (int i = 0; i < not_allowed_chars.length; i++) {
+ ParsePosition pp = new ParsePosition(0);
+ Date d = df.parse(not_allowed_chars[i] + "9:07", pp);
+ assertNull(d);
+
+ pp = new ParsePosition(0);
+ d = df.parse("09:" + not_allowed_chars[i] + "7", pp);
+ assertNull(d);
+
+ pp = new ParsePosition(0);
+ d = df.parse("09:07:" + not_allowed_chars[i] + "6", pp);
+ assertNull(d);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/StringCharacterIteratorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/StringCharacterIteratorTest.java
new file mode 100644
index 0000000..0108089
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/StringCharacterIteratorTest.java
@@ -0,0 +1,521 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
+
+import junit.framework.TestCase;
+
+public class StringCharacterIteratorTest extends TestCase {
+
+ /**
+ * @tests java.text.StringCharacterIterator.StringCharacterIterator(String,
+ * int)
+ */
+ public void test_ConstructorI() {
+ assertNotNull(new StringCharacterIterator("value", 0));
+ assertNotNull(new StringCharacterIterator("value", "value".length()));
+ assertNotNull(new StringCharacterIterator("", 0));
+ try {
+ new StringCharacterIterator(null, 0);
+ fail("Assert 0: no null pointer");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new StringCharacterIterator("value", -1);
+ fail("Assert 1: no illegal argument");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ new StringCharacterIterator("value", "value".length() + 1);
+ fail("Assert 2: no illegal argument");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator(String, int, int, int)
+ */
+ public void test_ConstructorIII() {
+ assertNotNull(new StringCharacterIterator("value", 0, "value".length(),
+ 0));
+ assertNotNull(new StringCharacterIterator("value", 0, "value".length(),
+ 1));
+ assertNotNull(new StringCharacterIterator("", 0, 0, 0));
+
+ try {
+ new StringCharacterIterator(null, 0, 0, 0);
+ fail("no null pointer");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", -1, "value".length(), 0);
+ fail("no illegal argument: invalid begin");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", 0, "value".length() + 1, 0);
+ fail("no illegal argument: invalid end");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", 2, 1, 0);
+ fail("no illegal argument: start greater than end");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", 2, 1, 2);
+ fail("no illegal argument: start greater than end");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", 2, 4, 1);
+ fail("no illegal argument: location greater than start");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ new StringCharacterIterator("value", 0, 2, 3);
+ fail("no illegal argument: location greater than start");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ StringCharacterIterator sci0 = new StringCharacterIterator("fixture");
+ assertEquals(sci0, sci0);
+ assertFalse(sci0.equals(null));
+ assertFalse(sci0.equals("fixture"));
+
+ StringCharacterIterator sci1 = new StringCharacterIterator("fixture");
+ assertEquals(sci0, sci1);
+
+ sci1.next();
+ assertFalse(sci0.equals(sci1));
+ sci0.next();
+ assertEquals(sci0, sci1);
+
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ StringCharacterIterator it2 = new StringCharacterIterator("xxstinx", 2,
+ 6, 4);
+ assertTrue("Range is equal", !it1.equals(it2));
+ StringCharacterIterator it3 = new StringCharacterIterator("testing", 2,
+ 6, 2);
+ it3.setIndex(4);
+ assertTrue("Not equal", it1.equals(it3));
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.clone()
+ */
+ public void test_clone() {
+ StringCharacterIterator sci0 = new StringCharacterIterator("fixture");
+ assertSame(sci0, sci0);
+ StringCharacterIterator sci1 = (StringCharacterIterator) sci0.clone();
+ assertNotSame(sci0, sci1);
+ assertEquals(sci0, sci1);
+
+ StringCharacterIterator it = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ StringCharacterIterator clone = (StringCharacterIterator) it.clone();
+ assertTrue("Clone not equal", it.equals(clone));
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.current()
+ */
+ public void test_current() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals('f', fixture.current());
+ fixture.next();
+ assertEquals('i', fixture.current());
+
+ StringCharacterIterator it =
+ new StringCharacterIterator("testing", 2, 6, 4);
+ assertEquals("Wrong current char", 'i', it.current());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.first()
+ */
+ public void test_first() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals('f', fixture.first());
+ fixture.next();
+ assertEquals('f', fixture.first());
+ fixture = new StringCharacterIterator("fixture", 1);
+ assertEquals('f', fixture.first());
+ fixture = new StringCharacterIterator("fixture", 1, "fixture".length(),
+ 2);
+ assertEquals('i', fixture.first());
+
+ StringCharacterIterator it1 =
+ new StringCharacterIterator("testing", 2, 6, 4);
+ assertEquals("Wrong first char", 's', it1.first());
+ assertEquals("Wrong next char", 't', it1.next());
+ it1 = new StringCharacterIterator("testing", 2, 2, 2);
+ assertTrue("Not DONE", it1.first() == CharacterIterator.DONE);
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.getBeginIndex()
+ */
+ public void test_getBeginIndex() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals(0, fixture.getBeginIndex());
+ fixture = new StringCharacterIterator("fixture", 1);
+ assertEquals(0, fixture.getBeginIndex());
+ fixture = new StringCharacterIterator("fixture", 1, "fixture".length(),
+ 2);
+ assertEquals(1, fixture.getBeginIndex());
+
+ StringCharacterIterator it1 =
+ new StringCharacterIterator("testing", 2, 6, 4);
+ assertEquals("Wrong begin index 2", 2, it1.getBeginIndex());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.getEndIndex()
+ */
+ public void test_getEndIndex() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals("fixture".length(), fixture.getEndIndex());
+ fixture = new StringCharacterIterator("fixture", 1);
+ assertEquals("fixture".length(), fixture.getEndIndex());
+ fixture = new StringCharacterIterator("fixture", 1, "fixture".length(),
+ 2);
+ assertEquals("fixture".length(), fixture.getEndIndex());
+ fixture = new StringCharacterIterator("fixture", 1, 4, 2);
+ assertEquals(4, fixture.getEndIndex());
+
+ StringCharacterIterator it1 =
+ new StringCharacterIterator("testing", 2, 6, 4);
+ assertEquals("Wrong end index 6", 6, it1.getEndIndex());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.getIndex()
+ */
+ public void testGetIndex() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals(0, fixture.getIndex());
+ fixture = new StringCharacterIterator("fixture", 1);
+ assertEquals(1, fixture.getIndex());
+ fixture = new StringCharacterIterator("fixture", 1, "fixture".length(),
+ 2);
+ assertEquals(2, fixture.getIndex());
+ fixture = new StringCharacterIterator("fixture", 1, 4, 2);
+ assertEquals(2, fixture.getIndex());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.last()
+ */
+ public void testLast() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals('e', fixture.last());
+ fixture.next();
+ assertEquals('e', fixture.last());
+ fixture = new StringCharacterIterator("fixture", 1);
+ assertEquals('e', fixture.last());
+ fixture = new StringCharacterIterator("fixture", 1, "fixture".length(),
+ 2);
+ assertEquals('e', fixture.last());
+ fixture = new StringCharacterIterator("fixture", 1, 4, 2);
+ assertEquals('t', fixture.last());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.next()
+ */
+ public void test_next() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals(0, fixture.getIndex());
+ assertEquals('i', fixture.next());
+ assertEquals(1, fixture.getIndex());
+ assertEquals('x', fixture.next());
+ assertEquals(2, fixture.getIndex());
+ assertEquals('t', fixture.next());
+ assertEquals(3, fixture.getIndex());
+ assertEquals('u', fixture.next());
+ assertEquals(4, fixture.getIndex());
+ assertEquals('r', fixture.next());
+ assertEquals(5, fixture.getIndex());
+ assertEquals('e', fixture.next());
+ assertEquals(6, fixture.getIndex());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(7, fixture.getIndex());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(7, fixture.getIndex());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(7, fixture.getIndex());
+
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 3);
+ char result = it1.next();
+ assertEquals("Wrong next char1", 'i', result);
+ assertEquals("Wrong next char2", 'n', it1.next());
+ assertTrue("Wrong next char3", it1.next() == CharacterIterator.DONE);
+ assertTrue("Wrong next char4", it1.next() == CharacterIterator.DONE);
+ int index = it1.getIndex();
+ assertEquals("Wrong index", 6, index);
+ assertTrue("Wrong current char",
+ it1.current() == CharacterIterator.DONE);
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.previous()
+ */
+ public void test_previous() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ assertEquals(CharacterIterator.DONE, fixture.previous());
+ assertEquals('i', fixture.next());
+ assertEquals('x', fixture.next());
+ assertEquals('t', fixture.next());
+ assertEquals('u', fixture.next());
+ assertEquals('r', fixture.next());
+ assertEquals('e', fixture.next());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(CharacterIterator.DONE, fixture.next());
+ assertEquals(7, fixture.getIndex());
+ assertEquals('e', fixture.previous());
+ assertEquals(6, fixture.getIndex());
+ assertEquals('r', fixture.previous());
+ assertEquals(5, fixture.getIndex());
+ assertEquals('u', fixture.previous());
+ assertEquals(4, fixture.getIndex());
+ assertEquals('t', fixture.previous());
+ assertEquals(3, fixture.getIndex());
+ assertEquals('x', fixture.previous());
+ assertEquals(2, fixture.getIndex());
+ assertEquals('i', fixture.previous());
+ assertEquals(1, fixture.getIndex());
+ assertEquals('f', fixture.previous());
+ assertEquals(0, fixture.getIndex());
+ assertEquals(CharacterIterator.DONE, fixture.previous());
+ assertEquals(0, fixture.getIndex());
+
+ StringCharacterIterator it1 =
+ new StringCharacterIterator("testing", 2, 6, 4);
+ assertEquals("Wrong previous char1", 't', it1.previous());
+ assertEquals("Wrong previous char2", 's', it1.previous());
+ assertTrue("Wrong previous char3",
+ it1.previous() == CharacterIterator.DONE);
+ assertTrue("Wrong previous char4",
+ it1.previous() == CharacterIterator.DONE);
+ assertEquals("Wrong index", 2, it1.getIndex());
+ assertEquals("Wrong current char", 's', it1.current());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.setIndex(int)
+ */
+ public void test_setIndex() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ while (fixture.next() != CharacterIterator.DONE) {
+ // empty
+ }
+ assertEquals("fixture".length(), fixture.getIndex());
+ fixture.setIndex(0);
+ assertEquals(0, fixture.getIndex());
+ assertEquals('f', fixture.current());
+ fixture.setIndex("fixture".length() - 1);
+ assertEquals('e', fixture.current());
+ try {
+ fixture.setIndex(-1);
+ fail("no illegal argument");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ fixture.setIndex("fixture".length() + 1);
+ fail("no illegal argument");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator.setText(String)
+ */
+ public void test_setText() {
+ StringCharacterIterator fixture = new StringCharacterIterator("fixture");
+ fixture.setText("fix");
+ assertEquals('f', fixture.current());
+ assertEquals('x', fixture.last());
+
+ try {
+ fixture.setText(null);
+ fail("no null pointer");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#StringCharacterIterator(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertNotNull(new StringCharacterIterator("value"));
+ assertNotNull(new StringCharacterIterator(""));
+ try {
+ new StringCharacterIterator(null);
+ fail("Assert 0: no null pointer");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ StringCharacterIterator it = new StringCharacterIterator("testing");
+ assertEquals("Wrong begin index", 0, it.getBeginIndex());
+ assertEquals("Wrong end index", 7, it.getEndIndex());
+ assertEquals("Wrong current index", 0, it.getIndex());
+ assertEquals("Wrong current char", 't', it.current());
+ assertEquals("Wrong next char", 'e', it.next());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#StringCharacterIterator(java.lang.String,
+ * int)
+ */
+ public void test_ConstructorLjava_lang_StringI() {
+ StringCharacterIterator it = new StringCharacterIterator("testing", 3);
+ assertEquals("Wrong begin index", 0, it.getBeginIndex());
+ assertEquals("Wrong end index", 7, it.getEndIndex());
+ assertEquals("Wrong current index", 3, it.getIndex());
+ assertEquals("Wrong current char", 't', it.current());
+ assertEquals("Wrong next char", 'i', it.next());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#StringCharacterIterator(java.lang.String,
+ * int, int, int)
+ */
+ public void test_ConstructorLjava_lang_StringIII() {
+ StringCharacterIterator it = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ assertEquals("Wrong begin index", 2, it.getBeginIndex());
+ assertEquals("Wrong end index", 6, it.getEndIndex());
+ assertEquals("Wrong current index", 4, it.getIndex());
+ assertEquals("Wrong current char", 'i', it.current());
+ assertEquals("Wrong next char", 'n', it.next());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#getIndex()
+ */
+ public void test_getIndex() {
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ assertEquals("Wrong index 4", 4, it1.getIndex());
+ it1.next();
+ assertEquals("Wrong index 5", 5, it1.getIndex());
+ it1.last();
+ assertEquals("Wrong index 4/2", 5, it1.getIndex());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#hashCode()
+ */
+ public void test_hashCode() {
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ StringCharacterIterator it2 = new StringCharacterIterator("xxstinx", 2,
+ 6, 4);
+ assertTrue("Hash is equal", it1.hashCode() != it2.hashCode());
+ StringCharacterIterator it3 = new StringCharacterIterator("testing", 2,
+ 6, 2);
+ assertTrue("Hash equal1", it1.hashCode() != it3.hashCode());
+ it3 = new StringCharacterIterator("testing", 0, 6, 4);
+ assertTrue("Hash equal2", it1.hashCode() != it3.hashCode());
+ it3 = new StringCharacterIterator("testing", 2, 5, 4);
+ assertTrue("Hash equal3", it1.hashCode() != it3.hashCode());
+ it3 = new StringCharacterIterator("froging", 2, 6, 4);
+ assertTrue("Hash equal4", it1.hashCode() != it3.hashCode());
+
+ StringCharacterIterator sci0 = new StringCharacterIterator("fixture");
+ assertEquals(sci0.hashCode(), sci0.hashCode());
+
+ StringCharacterIterator sci1 = new StringCharacterIterator("fixture");
+ assertEquals(sci0.hashCode(), sci1.hashCode());
+
+ sci1.next();
+ sci0.next();
+ assertEquals(sci0.hashCode(), sci1.hashCode());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#last()
+ */
+ public void test_last() {
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 3);
+ assertEquals("Wrong last char", 'n', it1.last());
+ assertEquals("Wrong previous char", 'i', it1.previous());
+ it1 = new StringCharacterIterator("testing", 2, 2, 2);
+ assertTrue("Not DONE", it1.last() == CharacterIterator.DONE);
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#setIndex(int)
+ */
+ public void test_setIndexI() {
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ assertEquals("Wrong result1", 's', it1.setIndex(2));
+ char result = it1.next();
+ assertTrue("Wrong next char: " + result, result == 't');
+ assertTrue("Wrong result2", it1.setIndex(6) == CharacterIterator.DONE);
+ assertEquals("Wrong previous char", 'n', it1.previous());
+ }
+
+ /**
+ * @tests java.text.StringCharacterIterator#setText(java.lang.String)
+ */
+ public void test_setTextLjava_lang_String() {
+ StringCharacterIterator it1 = new StringCharacterIterator("testing", 2,
+ 6, 4);
+ it1.setText("frog");
+ assertEquals("Wrong begin index", 0, it1.getBeginIndex());
+ assertEquals("Wrong end index", 4, it1.getEndIndex());
+ assertEquals("Wrong current index", 0, it1.getIndex());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_DecimalFormat.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_DecimalFormat.java
new file mode 100644
index 0000000..0c6a824
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_DecimalFormat.java
@@ -0,0 +1,248 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Vector;
+
+public class Support_DecimalFormat extends Support_Format {
+
+ public Support_DecimalFormat(String p1) {
+ super(p1);
+ }
+
+ @Override public void runTest() {
+ t_formatToCharacterIterator();
+ t_format_with_FieldPosition();
+ }
+
+ public static void main(String[] args) {
+ new Support_DecimalFormat("").runTest();
+ }
+
+ public void t_format_with_FieldPosition() {
+ DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
+ Number number = new Double(10000000.76);
+ String text = "$10,000,000.76";
+
+ t_FormatWithField(0, format, number, text, NumberFormat.Field.CURRENCY, 0, 1);
+ t_FormatWithField(1, format, number, text, NumberFormat.Field.INTEGER, 1, 11);
+ t_FormatWithField(2, format, number, text, NumberFormat.Field.GROUPING_SEPARATOR, 3, 4);
+ t_FormatWithField(3, format, number, text, NumberFormat.Field.DECIMAL_SEPARATOR, 11, 12);
+ t_FormatWithField(4, format, number, text, NumberFormat.Field.FRACTION, 12, 14);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(5, format, number, text, NumberFormat.Field.SIGN, 0, 0);
+ t_FormatWithField(6, format, number, text, NumberFormat.Field.EXPONENT, 0, 0);
+ t_FormatWithField(7, format, number, text, NumberFormat.Field.EXPONENT_SIGN, 0, 0);
+ t_FormatWithField(8, format, number, text, NumberFormat.Field.EXPONENT_SYMBOL, 0, 0);
+ t_FormatWithField(9, format, number, text, NumberFormat.Field.PERCENT, 0, 0);
+ t_FormatWithField(10, format, number, text, NumberFormat.Field.PERMILLE, 0, 0);
+
+ // test Exponential
+ format = new DecimalFormat("000000000.0#E0");
+ text = "100000007.6E-1";
+ t_FormatWithField(11, format, number, text, NumberFormat.Field.INTEGER, 0, 9);
+ t_FormatWithField(12, format, number, text, NumberFormat.Field.DECIMAL_SEPARATOR, 9, 10);
+ t_FormatWithField(13, format, number, text, NumberFormat.Field.FRACTION, 10, 11);
+ t_FormatWithField(14, format, number, text, NumberFormat.Field.EXPONENT_SYMBOL, 11, 12);
+ t_FormatWithField(15, format, number, text, NumberFormat.Field.EXPONENT_SIGN, 12, 13);
+ t_FormatWithField(16, format, number, text, NumberFormat.Field.EXPONENT, 13, 14);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(17, format, number, text, NumberFormat.Field.GROUPING_SEPARATOR, 0, 0);
+ t_FormatWithField(18, format, number, text, NumberFormat.Field.SIGN, 0, 0);
+ t_FormatWithField(19, format, number, text, NumberFormat.Field.CURRENCY, 0, 0);
+ t_FormatWithField(20, format, number, text, NumberFormat.Field.PERCENT, 0, 0);
+ t_FormatWithField(21, format, number, text, NumberFormat.Field.PERMILLE, 0, 0);
+
+ // test currency instance with TR Locale
+ number = new Double(350.76);
+ format = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("tr", "TR"));
+ // Turkey either uses "123,45 TL" or "₺123,45"; google3 uses the former because most
+ // platforms' fonts don't include U+20BA TURKISH LIRA SIGN. http://b/16727554.
+ text = "₺350,76";
+ t_FormatWithField(23, format, number, text, NumberFormat.Field.CURRENCY, 0, 1);
+ t_FormatWithField(22, format, number, text, NumberFormat.Field.INTEGER, 1, 4);
+ t_FormatWithField(22, format, number, text, NumberFormat.Field.DECIMAL_SEPARATOR, 4, 5);
+ t_FormatWithField(22, format, number, text, NumberFormat.Field.FRACTION, 5, 7);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(25, format, number, text, NumberFormat.Field.GROUPING_SEPARATOR, 0, 0);
+ t_FormatWithField(27, format, number, text, NumberFormat.Field.SIGN, 0, 0);
+ t_FormatWithField(28, format, number, text, NumberFormat.Field.EXPONENT, 0, 0);
+ t_FormatWithField(29, format, number, text, NumberFormat.Field.EXPONENT_SIGN, 0, 0);
+ t_FormatWithField(30, format, number, text, NumberFormat.Field.EXPONENT_SYMBOL, 0, 0);
+ t_FormatWithField(31, format, number, text, NumberFormat.Field.PERCENT, 0, 0);
+ t_FormatWithField(32, format, number, text, NumberFormat.Field.PERMILLE, 0, 0);
+ }
+
+ public void t_formatToCharacterIterator() {
+ Number number = new Double(350.76);
+ Number negativeNumber = new Double(-350.76);
+
+ Locale us = Locale.US;
+ Locale tr = new Locale("tr", "TR");
+
+ // test number instance
+ t_Format(1, number, NumberFormat.getNumberInstance(us), getNumberVectorUS());
+
+ // test integer instance
+ // testFormat(2, number, NumberFormat.getIntegerInstance(us),
+ // getPercentVectorUS());
+
+ // test percent instance
+ t_Format(3, number, NumberFormat.getPercentInstance(us), getPercentVectorUS());
+
+ // test permille pattern
+ DecimalFormat format = new DecimalFormat("###0.##\u2030");
+ t_Format(4, number, format, getPermilleVector());
+
+ // test exponential pattern with positive exponent
+ format = new DecimalFormat("00.0#E0");
+ t_Format(5, number, format, getPositiveExponentVector());
+
+ // test exponential pattern with negative exponent
+ format = new DecimalFormat("0000.0#E0");
+ t_Format(6, number, format, getNegativeExponentVector());
+
+ // test currency instance with US Locale
+ t_Format(7, number, NumberFormat.getCurrencyInstance(us), getPositiveCurrencyVectorUS());
+
+ // test negative currency instance with US Locale
+ t_Format(8, negativeNumber, NumberFormat.getCurrencyInstance(us), getNegativeCurrencyVectorUS());
+
+ // test currency instance with TR Locale
+ t_Format(9, number, NumberFormat.getCurrencyInstance(tr), getPositiveCurrencyVectorTR());
+
+ // test negative currency instance with TR Locale
+ t_Format(10, negativeNumber, NumberFormat.getCurrencyInstance(tr), getNegativeCurrencyVectorTR());
+
+ // test multiple grouping separators
+ number = new Long(100300400);
+ t_Format(11, number, NumberFormat.getNumberInstance(us), getNumberVector2US());
+
+ // test 0
+ number = new Long(0);
+ t_Format(12, number, NumberFormat.getNumberInstance(us), getZeroVector());
+ }
+
+ private static Vector<FieldContainer> getNumberVectorUS() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(3, 4, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(4, 6, NumberFormat.Field.FRACTION));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getPositiveCurrencyVectorTR() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, NumberFormat.Field.CURRENCY));
+ v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(5, 7, NumberFormat.Field.FRACTION));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getNegativeCurrencyVectorTR() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN));
+ v.add(new FieldContainer(1, 2, NumberFormat.Field.CURRENCY));
+ v.add(new FieldContainer(2, 5, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(5, 6, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(6, 8, NumberFormat.Field.FRACTION));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getPositiveCurrencyVectorUS() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, NumberFormat.Field.CURRENCY));
+ v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(5, 7, NumberFormat.Field.FRACTION));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getNegativeCurrencyVectorUS() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN));
+ v.add(new FieldContainer(1, 2, NumberFormat.Field.CURRENCY));
+ v.add(new FieldContainer(2, 5, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(5, 6, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(6, 8, NumberFormat.Field.FRACTION));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getPercentVectorUS() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(2, 3, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(2, 3, NumberFormat.Field.GROUPING_SEPARATOR));
+ v.add(new FieldContainer(3, 6, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(6, 7, NumberFormat.Field.PERCENT));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getPermilleVector() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 6, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(6, 7, NumberFormat.Field.PERMILLE));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getNegativeExponentVector() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 4, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(5, 6, NumberFormat.Field.FRACTION));
+ v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SYMBOL));
+ v.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT_SIGN));
+ v.add(new FieldContainer(8, 9, NumberFormat.Field.EXPONENT));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getPositiveExponentVector() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(2, 3, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(3, 5, NumberFormat.Field.FRACTION));
+ v.add(new FieldContainer(5, 6, NumberFormat.Field.EXPONENT_SYMBOL));
+ v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getNumberVector2US() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(3, 4, NumberFormat.Field.GROUPING_SEPARATOR));
+ v.add(new FieldContainer(3, 4, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(4, 7, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(7, 8, NumberFormat.Field.GROUPING_SEPARATOR));
+ v.add(new FieldContainer(7, 8, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(8, 11, NumberFormat.Field.INTEGER));
+ return v;
+ }
+
+ private static Vector<FieldContainer> getZeroVector() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, NumberFormat.Field.INTEGER));
+ return v;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_Format.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_Format.java
new file mode 100644
index 0000000..493e27e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_Format.java
@@ -0,0 +1,139 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.text.FieldPosition;
+import java.text.Format;
+import java.text.AttributedCharacterIterator.Attribute;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Vector;
+import junit.framework.TestCase;
+
+public class Support_Format extends TestCase {
+
+ protected String text;
+
+ public Support_Format(String p1) {
+ super(p1);
+ }
+
+ protected void t_FormatWithField(int count, Format format, Object object,
+ String text, Format.Field field, int begin, int end) {
+ StringBuffer buffer = new StringBuffer();
+ FieldPosition pos = new FieldPosition(field);
+ format.format(object, buffer, pos);
+
+ // System.out.println(buffer);
+ // System.out.println(pos);
+
+ if (text == null) {
+ assertEquals("Test " + count + ": incorrect formatted text", this.text, buffer.toString());
+ } else {
+ assertEquals(text, buffer.toString());
+ }
+
+ if (begin != pos.getBeginIndex() || end != pos.getEndIndex()) {
+ assertEquals(field + " " + begin + ".." + end,
+ pos.getFieldAttribute() + " " + pos.getBeginIndex() + ".." + pos.getEndIndex());
+ }
+ }
+
+ protected void t_Format(int count, Object object, Format format, Vector<FieldContainer> expectedResults) {
+ Vector<FieldContainer> results = findFields(format.formatToCharacterIterator(object));
+ assertEquals("size mismatch\n" +
+ format.format(object) + "\n" +
+ "expectedResults=" + expectedResults + "\n" +
+ " results=" + results, expectedResults.size(), results.size());
+ for (int i = 0; i < results.size(); ++i) {
+ if (!results.contains(expectedResults.get(i))) {
+ fail("didn't find expected result " + expectedResults.get(i) + "\n" +
+ "expectedResults=" + expectedResults + "\n" +
+ " results=" + results);
+ }
+ }
+ }
+
+ /**
+ * finds attributes with regards to char index in this
+ * AttributedCharacterIterator, and puts them in a vector
+ *
+ * @param iterator
+ * @return a vector, each entry in this vector are of type FieldContainer,
+ * which stores start and end indexes and an attribute this range has
+ */
+ protected static Vector<FieldContainer> findFields(AttributedCharacterIterator iterator) {
+ Vector<FieldContainer> result = new Vector<FieldContainer>();
+ while (iterator.getIndex() != iterator.getEndIndex()) {
+ int start = iterator.getRunStart();
+ int end = iterator.getRunLimit();
+
+ Iterator<Attribute> it = iterator.getAttributes().keySet().iterator();
+ while (it.hasNext()) {
+ AttributedCharacterIterator.Attribute attribute = it.next();
+ Object value = iterator.getAttribute(attribute);
+ result.add(new FieldContainer(start, end, attribute, value));
+ // System.out.println(start + " " + end + ": " + attribute + ",
+ // " + value );
+ // System.out.println("v.add(new FieldContainer(" + start +"," +
+ // end +"," + attribute+ "," + value+ "));");
+ }
+ iterator.setIndex(end);
+ }
+ return result;
+ }
+
+ static class FieldContainer {
+ final int start;
+ final int end;
+ final Attribute attribute;
+ final Object value;
+
+ // called from Support_DecimalFormat and Support_SimpleDateFormat tests
+ public FieldContainer(int start, int end, Attribute attribute) {
+ this(start, end, attribute, attribute);
+ }
+
+ // called from Support_MessageFormat tests
+ public FieldContainer(int start, int end, Attribute attribute, int value) {
+ this(start, end, attribute, new Integer(value));
+ }
+
+ // called from Support_MessageFormat tests
+ public FieldContainer(int start, int end, Attribute attribute, Object value) {
+ this.start = start;
+ this.end = end;
+ this.attribute = attribute;
+ this.value = value;
+ }
+
+ @Override public boolean equals(Object obj) {
+ if (!(obj instanceof FieldContainer)) {
+ return false;
+ }
+
+ FieldContainer fc = (FieldContainer) obj;
+ return (start == fc.start && end == fc.end && attribute == fc.attribute && value.equals(fc.value));
+ }
+
+ @Override public String toString() {
+ return "FC[" + start + ".." + end + ",attribute=" + attribute + ",value=" + value + "]";
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_MessageFormat.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_MessageFormat.java
new file mode 100644
index 0000000..8003b88
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_MessageFormat.java
@@ -0,0 +1,118 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.text.NumberFormat;
+import java.text.MessageFormat.Field;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.Vector;
+
+
+public class Support_MessageFormat extends Support_Format {
+
+ public Support_MessageFormat(String p1) {
+ super(p1);
+ }
+
+ @Override
+ public void runTest() {
+ t_formatToCharacterIterator();
+ t_format_with_FieldPosition();
+ }
+
+ public static void main(String[] args) {
+ new Support_MessageFormat("").runTest();
+ }
+
+ public void t_format_with_FieldPosition() {
+
+ String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} hamburger{2,choice,1#|1<s} and drank {1, number} liters of coke. That was {0,choice,1#just enough|1<more than enough} food!";
+ MessageFormat format = new MessageFormat(pattern, Locale.US);
+
+ Date date = new GregorianCalendar(2005, 1, 28, 14, 20, 16).getTime();
+ Integer hamburgers = new Integer(8);
+ Object[] objects = new Object[] { hamburgers, new Double(3.5),
+ hamburgers, date, date };
+
+ super.text = "On Feb 28, 2005 at 2:20:16 PM, he ate 8 hamburgers and drank 3.5 liters of coke. That was more than enough food!";
+
+ // test with MessageFormat.Field.ARGUMENT
+ t_FormatWithField(1, format, objects, null, Field.ARGUMENT, 3, 15);
+
+ // test other format fields that are included in the formatted text
+ t_FormatWithField(2, format, objects, null, DateFormat.Field.AM_PM, 0,
+ 0);
+ t_FormatWithField(3, format, objects, null,
+ NumberFormat.Field.FRACTION, 0, 0);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(4, format, objects, null, DateFormat.Field.ERA, 0, 0);
+ t_FormatWithField(5, format, objects, null,
+ NumberFormat.Field.EXPONENT_SIGN, 0, 0);
+ }
+
+ public void t_formatToCharacterIterator() {
+ String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} hamburger{2,choice,1#|1<s} and drank {1, number} liters of coke. That was {0,choice,1#just enough|1<more than enough} food!";
+ MessageFormat format = new MessageFormat(pattern, Locale.US);
+
+ Date date = new GregorianCalendar(2005, 1, 28, 14, 20, 16).getTime();
+ Integer hamburgers = new Integer(8);
+ Object[] objects = new Object[] { hamburgers, new Double(3.5), hamburgers, date, date };
+
+ t_Format(1, objects, format, getMessageVector1());
+ }
+
+ private Vector<FieldContainer> getMessageVector1() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(3, 6, DateFormat.Field.MONTH));
+ v.add(new FieldContainer(3, 6, Field.ARGUMENT, 4));
+ v.add(new FieldContainer(6, 7, Field.ARGUMENT, 4));
+ v.add(new FieldContainer(7, 9, DateFormat.Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(7, 9, Field.ARGUMENT, 4));
+ v.add(new FieldContainer(9, 11, Field.ARGUMENT, 4));
+ v.add(new FieldContainer(11, 15, DateFormat.Field.YEAR));
+ v.add(new FieldContainer(11, 15, Field.ARGUMENT, 4));
+ v.add(new FieldContainer(19, 20, DateFormat.Field.HOUR1));
+ v.add(new FieldContainer(19, 20, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(20, 21, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(21, 23, DateFormat.Field.MINUTE));
+ v.add(new FieldContainer(21, 23, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(23, 24, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(24, 26, DateFormat.Field.SECOND));
+ v.add(new FieldContainer(24, 26, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(26, 27, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(27, 29, DateFormat.Field.AM_PM));
+ v.add(new FieldContainer(27, 29, Field.ARGUMENT, 3));
+ v.add(new FieldContainer(38, 39, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(38, 39, Field.ARGUMENT, 2));
+ v.add(new FieldContainer(49, 50, Field.ARGUMENT, 2));
+ v.add(new FieldContainer(61, 62, NumberFormat.Field.INTEGER));
+ v.add(new FieldContainer(61, 62, Field.ARGUMENT, 1));
+ v.add(new FieldContainer(62, 63, NumberFormat.Field.DECIMAL_SEPARATOR));
+ v.add(new FieldContainer(62, 63, Field.ARGUMENT, 1));
+ v.add(new FieldContainer(63, 64, NumberFormat.Field.FRACTION));
+ v.add(new FieldContainer(63, 64, Field.ARGUMENT, 1));
+ v.add(new FieldContainer(90, 106, Field.ARGUMENT, 0));
+ return v;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_SimpleDateFormat.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_SimpleDateFormat.java
new file mode 100644
index 0000000..d050e83
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/text/Support_SimpleDateFormat.java
@@ -0,0 +1,258 @@
+/*
+ * 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.tests.java.text;
+
+import java.text.DateFormat;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import java.text.DateFormat.Field;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+import java.util.Vector;
+
+import org.apache.harmony.tests.java.text.Support_Format.FieldContainer;
+
+public class Support_SimpleDateFormat extends Support_Format {
+
+ public Support_SimpleDateFormat(String p1) {
+ super(p1);
+ }
+
+ @Override public void runTest() {
+ t_formatToCharacterIterator();
+ t_format_with_FieldPosition();
+ }
+
+ public static void main(String[] args) {
+ new Support_SimpleDateFormat("").runTest();
+ }
+
+ public void t_format_with_FieldPosition() {
+ TimeZone tz = TimeZone.getTimeZone("EST");
+ Calendar cal = new GregorianCalendar(tz);
+ cal.set(1999, Calendar.SEPTEMBER, 13, 17, 19, 01);
+ cal.set(Calendar.MILLISECOND, 0);
+ Date date = cal.getTime();
+ SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
+ format.setTimeZone(tz);
+
+ // test with all pattern chars, and multiple occurences
+ format.applyPattern("G GGGG y yy yyyy M MM MMM MMMM d dd ddd " +
+ "k kk kkk H HH HHH h hh hhh m mmm s ss sss S SS SSS EE EEEE " +
+ "D DD DDD F FF w www W WWW " +
+ "a aaa K KKK z zzzz Z ZZZZ");
+
+ StringBuffer textBuffer = new StringBuffer();
+ // Really, GGGG should be "Anno Domini", but the RI doesn't support that and no one cares.
+ textBuffer.append("AD AD 1999 99 1999 9 09 Sep September 13 13 013 ");
+ textBuffer.append("17 17 017 17 17 017 5 05 005 19 019 1 01 001 0 00 000 Mon Monday ");
+ textBuffer.append("256 256 256 2 02 38 038 3 003 ");
+ textBuffer.append("PM PM 5 005 GMT-05:00 GMT-05:00 -0500 GMT-05:00");
+
+ // to avoid passing the huge StringBuffer each time.
+ super.text = textBuffer.toString();
+
+ // test if field positions are set correctly for these fields occurring
+ // multiple times.
+ t_FormatWithField(0, format, date, null, Field.ERA, 0, 2);
+ t_FormatWithField(1, format, date, null, Field.YEAR, 6, 10);
+ t_FormatWithField(2, format, date, null, Field.MONTH, 19, 20);
+ t_FormatWithField(3, format, date, null, Field.DAY_OF_MONTH, 38, 40);
+ t_FormatWithField(4, format, date, null, Field.HOUR_OF_DAY1, 48, 50);
+ t_FormatWithField(5, format, date, null, Field.HOUR_OF_DAY0, 58, 60);
+ t_FormatWithField(6, format, date, null, Field.HOUR1, 68, 69);
+ t_FormatWithField(7, format, date, null, Field.MINUTE, 77, 79);
+ t_FormatWithField(8, format, date, null, Field.SECOND, 84, 85);
+ t_FormatWithField(9, format, date, null, Field.MILLISECOND, 93, 94);
+ t_FormatWithField(10, format, date, null, Field.DAY_OF_WEEK, 102, 105);
+ t_FormatWithField(11, format, date, null, Field.DAY_OF_YEAR, 113, 116);
+ t_FormatWithField(12, format, date, null, Field.DAY_OF_WEEK_IN_MONTH, 125, 126);
+ t_FormatWithField(13, format, date, null, Field.WEEK_OF_YEAR, 130, 132);
+ t_FormatWithField(14, format, date, null, Field.WEEK_OF_MONTH, 137, 138);
+ t_FormatWithField(15, format, date, null, Field.AM_PM, 143, 145);
+ t_FormatWithField(16, format, date, null, Field.HOUR0, 151, 152);
+ t_FormatWithField(17, format, date, null, Field.TIME_ZONE, 157, 166);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(18, format, date, null, NumberFormat.Field.EXPONENT_SIGN, 0, 0);
+
+ // test with simple example
+ format.applyPattern("h:m z");
+
+ super.text = "5:19 GMT-05:00";
+ t_FormatWithField(21, format, date, null, Field.HOUR1, 0, 1);
+ t_FormatWithField(22, format, date, null, Field.MINUTE, 2, 4);
+ t_FormatWithField(23, format, date, null, Field.TIME_ZONE, 5, 14);
+
+ // test fields that are not included in the formatted text
+ t_FormatWithField(24, format, date, null, Field.ERA, 0, 0);
+ t_FormatWithField(25, format, date, null, Field.YEAR, 0, 0);
+ t_FormatWithField(26, format, date, null, Field.MONTH, 0, 0);
+ t_FormatWithField(27, format, date, null, Field.DAY_OF_MONTH, 0, 0);
+ t_FormatWithField(28, format, date, null, Field.HOUR_OF_DAY1, 0, 0);
+ t_FormatWithField(29, format, date, null, Field.HOUR_OF_DAY0, 0, 0);
+ t_FormatWithField(30, format, date, null, Field.SECOND, 0, 0);
+ t_FormatWithField(31, format, date, null, Field.MILLISECOND, 0, 0);
+ t_FormatWithField(32, format, date, null, Field.DAY_OF_WEEK, 0, 0);
+ t_FormatWithField(33, format, date, null, Field.DAY_OF_YEAR, 0, 0);
+ t_FormatWithField(34, format, date, null, Field.DAY_OF_WEEK_IN_MONTH, 0, 0);
+ t_FormatWithField(35, format, date, null, Field.WEEK_OF_YEAR, 0, 0);
+ t_FormatWithField(36, format, date, null, Field.WEEK_OF_MONTH, 0, 0);
+ t_FormatWithField(37, format, date, null, Field.AM_PM, 0, 0);
+ t_FormatWithField(38, format, date, null, Field.HOUR0, 0, 0);
+
+ t_FormatWithField(39, format, date, null, NumberFormat.Field.EXPONENT, 0, 0);
+
+ // test with simple example with pattern char Z
+ format.applyPattern("h:m Z z");
+ super.text = "5:19 -0500 GMT-05:00";
+ t_FormatWithField(40, format, date, null, Field.HOUR1, 0, 1);
+ t_FormatWithField(41, format, date, null, Field.MINUTE, 2, 4);
+ t_FormatWithField(42, format, date, null, Field.TIME_ZONE, 5, 10);
+ }
+
+ public void t_formatToCharacterIterator() {
+ TimeZone tz = TimeZone.getTimeZone("EST");
+ Calendar cal = new GregorianCalendar(tz);
+ cal.set(1999, Calendar.SEPTEMBER, 13, 17, 19, 01);
+ cal.set(Calendar.MILLISECOND, 0);
+ Date date = cal.getTime();
+ SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
+ format.setTimeZone(tz);
+
+ format.applyPattern("yyyyMMddHHmmss");
+ t_Format(1, date, format, getDateVector1());
+
+ format.applyPattern("w W dd MMMM yyyy EEEE");
+ t_Format(2, date, format, getDateVector2());
+
+ format.applyPattern("h:m z");
+ t_Format(3, date, format, getDateVector3());
+
+ format.applyPattern("h:m Z");
+ t_Format(5, date, format, getDateVector5());
+
+ // with all pattern chars, and multiple occurences
+ format.applyPattern("G GGGG y yy yyyy M MM MMM MMMM d dd ddd k kk kkk H HH HHH h hh hhh m mmm s ss sss S SS SSS EE EEEE D DD DDD F FF w www W WWW a aaa K KKK z zzzz Z ZZZZ");
+ t_Format(4, date, format, getDateVector4());
+ }
+
+ private Vector<FieldContainer> getDateVector1() {
+ // "19990913171901"
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 4, Field.YEAR));
+ v.add(new FieldContainer(4, 6, Field.MONTH));
+ v.add(new FieldContainer(6, 8, Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(8, 10, Field.HOUR_OF_DAY0));
+ v.add(new FieldContainer(10, 12, Field.MINUTE));
+ v.add(new FieldContainer(12, 14, Field.SECOND));
+ return v;
+ }
+
+ private Vector<FieldContainer> getDateVector2() {
+ // "12 3 5 March 2002 Monday"
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 2, Field.WEEK_OF_YEAR));
+ v.add(new FieldContainer(3, 4, Field.WEEK_OF_MONTH));
+ v.add(new FieldContainer(5, 7, Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(8, 17, Field.MONTH));
+ v.add(new FieldContainer(18, 22, Field.YEAR));
+ v.add(new FieldContainer(23, 29, Field.DAY_OF_WEEK));
+ return v;
+ }
+
+ private Vector<FieldContainer> getDateVector3() {
+ // "5:19 EDT"
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, Field.HOUR1));
+ v.add(new FieldContainer(2, 4, Field.MINUTE));
+ v.add(new FieldContainer(5, 14, Field.TIME_ZONE));
+ return v;
+ }
+
+ private Vector<FieldContainer> getDateVector5() {
+ // "5:19 -0400"
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+ v.add(new FieldContainer(0, 1, Field.HOUR1));
+ v.add(new FieldContainer(2, 4, Field.MINUTE));
+ v.add(new FieldContainer(5, 10, Field.TIME_ZONE));
+ return v;
+ }
+
+ private Vector<FieldContainer> getDateVector4() {
+ Vector<FieldContainer> v = new Vector<FieldContainer>();
+
+ // "AD AD 1999 99 1999 9 09 Sep September 13 13 013 17 17 017 17 17 017 5
+ // 05
+ // 005 19 019 1 01 001 0 00 000 Mon Monday 256 256 256 2 02 38 038 3 003
+ // PM
+ // PM 5 005 EDT Eastern Daylight Time -0400 -0400"
+ v.add(new FieldContainer(0, 2, Field.ERA));
+ v.add(new FieldContainer(3, 5, Field.ERA));
+ v.add(new FieldContainer(6, 10, Field.YEAR));
+ v.add(new FieldContainer(11, 13, Field.YEAR));
+ v.add(new FieldContainer(14, 18, Field.YEAR));
+ v.add(new FieldContainer(19, 20, Field.MONTH));
+ v.add(new FieldContainer(21, 23, Field.MONTH));
+ v.add(new FieldContainer(24, 27, Field.MONTH));
+ v.add(new FieldContainer(28, 37, Field.MONTH));
+ v.add(new FieldContainer(38, 40, Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(41, 43, Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(44, 47, Field.DAY_OF_MONTH));
+ v.add(new FieldContainer(48, 50, Field.HOUR_OF_DAY1));
+ v.add(new FieldContainer(51, 53, Field.HOUR_OF_DAY1));
+ v.add(new FieldContainer(54, 57, Field.HOUR_OF_DAY1));
+ v.add(new FieldContainer(58, 60, Field.HOUR_OF_DAY0));
+ v.add(new FieldContainer(61, 63, Field.HOUR_OF_DAY0));
+ v.add(new FieldContainer(64, 67, Field.HOUR_OF_DAY0));
+ v.add(new FieldContainer(68, 69, Field.HOUR1));
+ v.add(new FieldContainer(70, 72, Field.HOUR1));
+ v.add(new FieldContainer(73, 76, Field.HOUR1));
+ v.add(new FieldContainer(77, 79, Field.MINUTE));
+ v.add(new FieldContainer(80, 83, Field.MINUTE));
+ v.add(new FieldContainer(84, 85, Field.SECOND));
+ v.add(new FieldContainer(86, 88, Field.SECOND));
+ v.add(new FieldContainer(89, 92, Field.SECOND));
+ v.add(new FieldContainer(93, 94, Field.MILLISECOND));
+ v.add(new FieldContainer(95, 97, Field.MILLISECOND));
+ v.add(new FieldContainer(98, 101, Field.MILLISECOND));
+ v.add(new FieldContainer(102, 105, Field.DAY_OF_WEEK));
+ v.add(new FieldContainer(106, 112, Field.DAY_OF_WEEK));
+ v.add(new FieldContainer(113, 116, Field.DAY_OF_YEAR));
+ v.add(new FieldContainer(117, 120, Field.DAY_OF_YEAR));
+ v.add(new FieldContainer(121, 124, Field.DAY_OF_YEAR));
+ v.add(new FieldContainer(125, 126, Field.DAY_OF_WEEK_IN_MONTH));
+ v.add(new FieldContainer(127, 129, Field.DAY_OF_WEEK_IN_MONTH));
+ v.add(new FieldContainer(130, 132, Field.WEEK_OF_YEAR));
+ v.add(new FieldContainer(133, 136, Field.WEEK_OF_YEAR));
+ v.add(new FieldContainer(137, 138, Field.WEEK_OF_MONTH));
+ v.add(new FieldContainer(139, 142, Field.WEEK_OF_MONTH));
+ v.add(new FieldContainer(143, 145, Field.AM_PM));
+ v.add(new FieldContainer(147, 149, Field.AM_PM));
+ v.add(new FieldContainer(151, 152, Field.HOUR0));
+ v.add(new FieldContainer(153, 156, Field.HOUR0));
+ v.add(new FieldContainer(157, 166, Field.TIME_ZONE));
+ v.add(new FieldContainer(167, 176, Field.TIME_ZONE));
+ v.add(new FieldContainer(177, 182, Field.TIME_ZONE));
+ v.add(new FieldContainer(183, 192, Field.TIME_ZONE));
+ return v;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractCollectionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractCollectionTest.java
new file mode 100644
index 0000000..9ea6efc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractCollectionTest.java
@@ -0,0 +1,345 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractCollection;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import junit.framework.TestCase;
+
+public class AbstractCollectionTest extends TestCase {
+
+ /**
+ * java.util.AbstractCollection#add(java.lang.Object)
+ */
+ public void test_addLjava_lang_Object() {
+ AbstractCollection<Object> ac = new AbstractCollection<Object>() {
+
+ @Override
+ public Iterator<Object> iterator() {
+ fail("iterator should not get called");
+ return null;
+ }
+
+ @Override
+ public int size() {
+ fail("size should not get called");
+ return 0;
+ }
+
+ };
+ try {
+ ac.add(null);
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ /**
+ * java.util.AbstractCollection#addAll(java.util.Collection)
+ */
+ public void test_addAllLjava_util_Collection() {
+ final Collection<String> fixtures = Arrays.asList("0", "1", "2");
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+
+ @Override
+ public boolean add(String object) {
+ assertTrue(fixtures.contains(object));
+ return true;
+ }
+
+ @Override
+ public Iterator<String> iterator() {
+ fail("iterator should not get called");
+ return null;
+ }
+
+ @Override
+ public int size() {
+ fail("size should not get called");
+ return 0;
+ }
+
+ };
+ assertTrue(ac.addAll(fixtures));
+ }
+
+ /**
+ * java.util.AbstractCollection#containsAll(java.util.Collection)
+ */
+ public void test_containsAllLjava_util_Collection() {
+ final Collection<String> fixtures = Arrays.asList("0", "1", "2");
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+
+ @Override
+ public boolean contains(Object object) {
+ assertTrue(fixtures.contains(object));
+ return true;
+ }
+
+ @Override
+ public Iterator<String> iterator() {
+ fail("iterator should not get called");
+ return null;
+ }
+
+ @Override
+ public int size() {
+ fail("size should not get called");
+ return 0;
+ }
+
+ };
+ assertTrue(ac.containsAll(fixtures));
+ }
+
+ /**
+ * java.util.AbstractCollection#isEmpty()
+ */
+ public void test_isEmpty() {
+ final boolean[] sizeCalled = new boolean[1];
+ AbstractCollection<Object> ac = new AbstractCollection<Object>() {
+ @Override
+ public Iterator<Object> iterator() {
+ fail("iterator should not get called");
+ return null;
+ }
+
+ @Override
+ public int size() {
+ sizeCalled[0] = true;
+ return 0;
+ }
+ };
+ assertTrue(ac.isEmpty());
+ assertTrue(sizeCalled[0]);
+ }
+
+ /**
+ * java.util.AbstractCollection#removeAll(java.util.Collection)
+ */
+ public void test_removeAllLjava_util_Collection() {
+ final String[] removed = new String[3];
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+
+ @Override
+ public Iterator<String> iterator() {
+ return new Iterator<String>() {
+ String[] values = new String[] { "0", "1", "2" };
+ int index;
+
+ public boolean hasNext() {
+ return index < values.length;
+ }
+
+ public String next() {
+ return values[index++];
+ }
+
+ public void remove() {
+ removed[index - 1] = values[index - 1];
+ }
+
+ };
+ }
+
+ @Override
+ public int size() {
+ fail("size should not get called");
+ return 0;
+ }
+
+ };
+ assertTrue(ac.removeAll(Arrays.asList("0", "1", "2")));
+ for (String r : removed) {
+ if (!"0".equals(r) && !"1".equals(r) && !"2".equals(r)) {
+ fail("an unexpected element was removed");
+ }
+ }
+ }
+
+ /**
+ * java.util.AbstractCollection#retainAll(java.util.Collection)
+ */
+ public void test_retainAllLjava_util_Collection() {
+ final String[] removed = new String[1];
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+
+ @Override
+ public Iterator<String> iterator() {
+ return new Iterator<String>() {
+ String[] values = new String[] { "0", "1", "2" };
+ int index;
+
+ public boolean hasNext() {
+ return index < values.length;
+ }
+
+ public String next() {
+ return values[index++];
+ }
+
+ public void remove() {
+ removed[index - 1] = values[index - 1];
+ }
+
+ };
+ }
+
+ @Override
+ public int size() {
+ fail("size should not get called");
+ return 0;
+ }
+
+ };
+ assertTrue(ac.retainAll(Arrays.asList("1", "2")));
+ assertEquals("0", removed[0]);
+ }
+
+ /**
+ * java.util.AbstractCollection#toArray()
+ */
+ public void test_toArray() {
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+ @Override
+ public Iterator<String> iterator() {
+ return new Iterator<String>() {
+ String[] values = new String[] { "0", "1", "2" };
+ int index;
+
+ public boolean hasNext() {
+ return index < values.length;
+ }
+
+ public String next() {
+ return values[index++];
+ }
+
+ public void remove() {
+ fail("remove should not get called");
+ }
+
+ };
+ }
+
+ @Override
+ public int size() {
+ return 3;
+ }
+ };
+
+ Object[] array = ac.toArray();
+ assertEquals(3, array.length);
+ for (Object o : array) {
+ if (!"0".equals(o) && !"1".equals(o) && !"2".equals(o)) {
+ fail("an unexpected element was removed");
+ }
+ }
+ }
+
+ /**
+ * java.util.AbstractCollection#toArray(java.lang.Object[])
+ */
+ public void test_toArray$Ljava_lang_Object() {
+ AbstractCollection<String> ac = new AbstractCollection<String>() {
+ @Override
+ public Iterator<String> iterator() {
+ return new Iterator<String>() {
+ String[] values = new String[] { "0", "1", "2" };
+ int index;
+
+ public boolean hasNext() {
+ return index < values.length;
+ }
+
+ public String next() {
+ return values[index++];
+ }
+
+ public void remove() {
+ fail("remove should not get called");
+ }
+
+ };
+ }
+
+ @Override
+ public int size() {
+ return 3;
+ }
+ };
+ try {
+ ac.toArray(null);
+ fail("No expected NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ ac.toArray(new StringBuffer[ac.size()]);
+ fail("No expected ArrayStoreException");
+ } catch (ArrayStoreException e) {
+ // expected
+ }
+
+ String[] a = new String[3];
+ assertSame(a, ac.toArray(a));
+
+ a = new String[0];
+ assertNotSame(a, ac.toArray(a));
+ a = ac.toArray(a);
+ assertEquals(3, a.length);
+
+ CharSequence[] csa = new CharSequence[3];
+ ac.toArray(csa);
+ assertEquals(3, csa.length);
+ assertEquals("0", csa[0]);
+ assertEquals("1", csa[1]);
+ assertEquals("2", csa[2]);
+ }
+
+ /**
+ * java.util.AbstractCollection#toString()
+ */
+ public void test_toString() {
+ // see HARMONY-1522
+ // collection that returns null iterator(this is against the spec.)
+ AbstractCollection<?> c = new AbstractCollection<Object>() {
+ @Override
+ public int size() {
+ // return non-zero value to pass 'isEmpty' check
+ return 1;
+ }
+
+ @Override
+ public Iterator<Object> iterator() {
+ // this violates the spec.
+ return null;
+ }
+ };
+
+ try {
+ // AbstractCollection.toString() doesn't verify
+ // whether iterator() returns null value or not
+ c.toString();
+ fail("No expected NullPointerException");
+ } catch (NullPointerException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractListTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractListTest.java
new file mode 100644
index 0000000..efc196f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractListTest.java
@@ -0,0 +1,576 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractList;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import java.util.RandomAccess;
+
+public class AbstractListTest extends junit.framework.TestCase {
+
+ static class SimpleList extends AbstractList {
+ ArrayList arrayList;
+
+ SimpleList() {
+ this.arrayList = new ArrayList();
+ }
+
+ public Object get(int index) {
+ return this.arrayList.get(index);
+ }
+
+ public void add(int i, Object o) {
+ this.arrayList.add(i, o);
+ }
+
+ public Object remove(int i) {
+ return this.arrayList.remove(i);
+ }
+
+ public int size() {
+ return this.arrayList.size();
+ }
+ }
+
+ /**
+ * java.util.AbstractList#hashCode()
+ */
+ public void test_hashCode() {
+ List list = new ArrayList();
+ list.add(new Integer(3));
+ list.add(new Integer(15));
+ list.add(new Integer(5));
+ list.add(new Integer(1));
+ list.add(new Integer(7));
+ int hashCode = 1;
+ Iterator i = list.iterator();
+ while (i.hasNext()) {
+ Object obj = i.next();
+ hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
+ }
+ assertTrue("Incorrect hashCode returned. Wanted: " + hashCode
+ + " got: " + list.hashCode(), hashCode == list.hashCode());
+ }
+
+ /**
+ * java.util.AbstractList#iterator()
+ */
+ public void test_iterator() {
+ SimpleList list = new SimpleList();
+ list.add(new Object());
+ list.add(new Object());
+ Iterator it = list.iterator();
+ it.next();
+ it.remove();
+ it.next();
+ }
+
+ /**
+ * java.util.AbstractList#listIterator()
+ */
+ public void test_listIterator() {
+ Integer tempValue;
+ List list = new ArrayList();
+ list.add(new Integer(3));
+ list.add(new Integer(15));
+ list.add(new Integer(5));
+ list.add(new Integer(1));
+ list.add(new Integer(7));
+ ListIterator lit = list.listIterator();
+ assertTrue("Should not have previous", !lit.hasPrevious());
+ assertTrue("Should have next", lit.hasNext());
+ tempValue = (Integer) lit.next();
+ assertTrue("next returned wrong value. Wanted 3, got: " + tempValue,
+ tempValue.intValue() == 3);
+ tempValue = (Integer) lit.previous();
+
+ SimpleList list2 = new SimpleList();
+ list2.add(new Object());
+ ListIterator lit2 = list2.listIterator();
+ lit2.add(new Object());
+ lit2.next();
+
+ //Regression test for Harmony-5808
+ list = new MockArrayList();
+ ListIterator it = list.listIterator();
+ it.add("one");
+ it.add("two");
+ assertEquals(2, list.size());
+ }
+
+ /**
+ * java.util.AbstractList#subList(int, int)
+ */
+ public void test_subListII() {
+ // Test each of the SubList operations to ensure a
+ // ConcurrentModificationException does not occur on an AbstractList
+ // which does not update modCount
+ SimpleList mList = new SimpleList();
+ mList.add(new Object());
+ mList.add(new Object());
+ List sList = mList.subList(0, 2);
+ sList.add(new Object()); // calls add(int, Object)
+ sList.get(0);
+
+ sList.add(0, new Object());
+ sList.get(0);
+
+ sList.addAll(Arrays.asList(new String[] { "1", "2" }));
+ sList.get(0);
+
+ sList.addAll(0, Arrays.asList(new String[] { "3", "4" }));
+ sList.get(0);
+
+ sList.remove(0);
+ sList.get(0);
+
+ ListIterator lit = sList.listIterator();
+ lit.add(new Object());
+ lit.next();
+ lit.remove();
+ lit.next();
+
+ sList.clear(); // calls removeRange()
+ sList.add(new Object());
+
+ // test the type of sublist that is returned
+ List al = new ArrayList();
+ for (int i = 0; i < 10; i++) {
+ al.add(new Integer(i));
+ }
+ assertTrue(
+ "Sublist returned should have implemented Random Access interface",
+ al.subList(3, 7) instanceof RandomAccess);
+
+ List ll = new LinkedList();
+ for (int i = 0; i < 10; i++) {
+ ll.add(new Integer(i));
+ }
+ assertTrue(
+ "Sublist returned should not have implemented Random Access interface",
+ !(ll.subList(3, 7) instanceof RandomAccess));
+
+ }
+
+ /**
+ * java.util.AbstractList#subList(int, int)
+ */
+ public void test_subList_empty() {
+ // Regression for HARMONY-389
+ List al = new ArrayList();
+ al.add("one");
+ List emptySubList = al.subList(0, 0);
+
+ try {
+ emptySubList.get(0);
+ fail("emptySubList.get(0) should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ emptySubList.set(0, "one");
+ fail("emptySubList.set(0,Object) should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ emptySubList.remove(0);
+ fail("emptySubList.remove(0) should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ class MockArrayList<E> extends AbstractList<E> {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ ArrayList<E> list = new ArrayList<E>();
+
+ public E remove(int idx) {
+ modCount++;
+ return list.remove(idx);
+ }
+
+ @Override
+ public E get(int index) {
+ return list.get(index);
+ }
+
+ @Override
+ public int size() {
+ return list.size();
+ }
+
+ public void add(int idx, E o) {
+ modCount += 10;
+ list.add(idx, o);
+ }
+ }
+
+ /*
+ * Regression test for HY-4398
+ */
+ public void test_iterator_next() {
+ MockArrayList<String> t = new MockArrayList<String>();
+ t.list.add("a");
+ t.list.add("b");
+
+ Iterator it = t.iterator();
+
+ while (it.hasNext()) {
+ it.next();
+ }
+ try {
+ it.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException cme) {
+ // expected
+ }
+
+ t.add("c");
+ try {
+ it.remove();
+ fail("Should throw NoSuchElementException");
+ } catch (ConcurrentModificationException cme) {
+ // expected
+ }
+
+ it = t.iterator();
+ try {
+ it.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException ise) {
+ // expected
+ }
+
+ Object value = it.next();
+ assertEquals("a", value);
+ }
+
+ /**
+ * java.util.AbstractList#subList(int, int)
+ */
+ public void test_subList_addAll() {
+ // Regression for HARMONY-390
+ List mainList = new ArrayList();
+ Object[] mainObjects = { "a", "b", "c" };
+ mainList.addAll(Arrays.asList(mainObjects));
+ List subList = mainList.subList(1, 2);
+ assertFalse("subList should not contain \"a\"", subList.contains("a"));
+ assertFalse("subList should not contain \"c\"", subList.contains("c"));
+ assertTrue("subList should contain \"b\"", subList.contains("b"));
+
+ Object[] subObjects = { "one", "two", "three" };
+ subList.addAll(Arrays.asList(subObjects));
+ assertFalse("subList should not contain \"a\"", subList.contains("a"));
+ assertFalse("subList should not contain \"c\"", subList.contains("c"));
+
+ Object[] expected = { "b", "one", "two", "three" };
+ ListIterator iter = subList.listIterator();
+ for (int i = 0; i < expected.length; i++) {
+ assertTrue("subList should contain " + expected[i], subList
+ .contains(expected[i]));
+ assertTrue("should be more elements", iter.hasNext());
+ assertEquals("element in incorrect position", expected[i], iter
+ .next());
+ }
+ }
+
+ public void test_indexOfLjava_lang_Object() {
+ AbstractList al = new ArrayList();
+ al.add(0);
+ al.add(1);
+ al.add(2);
+ al.add(3);
+ al.add(4);
+
+ assertEquals(-1, al.indexOf(5));
+ assertEquals(2, al.indexOf(2));
+ }
+
+ public void test_lastIndexOfLjava_lang_Object() {
+ AbstractList al = new ArrayList();
+ al.add(0);
+ al.add(1);
+ al.add(2);
+ al.add(2);
+ al.add(2);
+ al.add(2);
+ al.add(2);
+ al.add(3);
+ al.add(4);
+
+ assertEquals(-1, al.lastIndexOf(5));
+ assertEquals(6, al.lastIndexOf(2));
+ }
+
+ public void test_listIteratorI() {
+ AbstractList al1 = new ArrayList();
+ AbstractList al2 = new ArrayList();
+ al1.add(0);
+ al1.add(1);
+ al1.add(2);
+ al1.add(3);
+ al1.add(4);
+ al2.add(2);
+ al2.add(3);
+ al2.add(4);
+
+ Iterator li1 = al1.listIterator(2);
+ Iterator li2 = al2.listIterator();
+
+ while(li1.hasNext()&&li2.hasNext()) {
+ assertEquals(li1.next(), li2.next());
+ }
+ assertSame(li1.hasNext(),li2.hasNext());
+
+ try {
+ al1.listIterator(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ al1.listIterator(al1.size() + 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+ }
+
+ protected void doneSuite() {
+ }
+
+ class MockRemoveFailureArrayList<E> extends AbstractList<E> {
+
+ @Override
+ public E get(int location) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int size() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public E remove(int idx) {
+ modCount += 2;
+ return null;
+ }
+
+ public int getModCount() {
+ return modCount;
+ }
+ }
+
+ //test remove for failure by inconsistency of modCount and expectedModCount
+ public void test_remove() {
+ MockRemoveFailureArrayList<String> mrfal = new MockRemoveFailureArrayList<String>();
+ Iterator<String> imrfal = mrfal.iterator();
+ imrfal.next();
+ imrfal.remove();
+ try {
+ imrfal.remove();
+ } catch (ConcurrentModificationException e) {
+ fail("Excepted to catch IllegalStateException not ConcurrentModificationException");
+ } catch (IllegalStateException e) {
+ //Excepted to catch IllegalStateException here
+ }
+ }
+
+ public void test_subListII2() {
+ List<Integer> holder = new ArrayList<Integer>(16);
+ for (int i = 0; i < 10; i++) {
+ holder.add(i);
+ }
+
+ // parent change should cause sublist concurrentmodification fail
+ List<Integer> sub = holder.subList(0, holder.size());
+ holder.add(11);
+ try {
+ sub.size();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.add(12);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.add(0, 11);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.clear();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.contains(11);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.get(9);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.indexOf(10);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.isEmpty();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.iterator();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.lastIndexOf(10);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.listIterator();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.listIterator(0);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.remove(0);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.remove(9);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.set(0, 0);
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.size();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.toArray();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+ try {
+ sub.toString();
+ fail("Should throw ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ }
+
+ holder.clear();
+ }
+
+ public void test_indexOf_Ljava_lang_Object() {
+ AbstractList<Integer> list = new MockArrayList<Integer>();
+ Integer[] array = { 1, 2, 3, 4, 5 };
+ list.addAll(Arrays.asList(array));
+
+ assertEquals("find 0 in the list do not contain 0", -1, list
+ .indexOf(new Integer(0)));
+ assertEquals("did not return the right location of element 3", 2, list
+ .indexOf(new Integer(3)));
+ assertEquals("find null in the list do not contain null element", -1,
+ list.indexOf(null));
+ list.add(null);
+ assertEquals("did not return the right location of element null", 5,
+ list.indexOf(null));
+ }
+
+ public void test_lastIndexOf_Ljava_lang_Object() {
+ AbstractList<Integer> list = new MockArrayList<Integer>();
+ Integer[] array = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
+ list.addAll(Arrays.asList(array));
+
+ assertEquals("find 6 in the list do not contain 6", -1, list
+ .lastIndexOf(new Integer(6)));
+ assertEquals("did not return the right location of element 4", 6, list
+ .lastIndexOf(new Integer(4)));
+ assertEquals("find null in the list do not contain null element", -1,
+ list.lastIndexOf(null));
+ list.add(null);
+ assertEquals("did not return the right location of element null", 10,
+ list.lastIndexOf(null));
+ }
+
+ public void test_remove_I() {
+ class MockList<E> extends AbstractList<E> {
+ private ArrayList<E> list;
+
+ @Override
+ public E get(int location) {
+ return list.get(location);
+ }
+
+ @Override
+ public int size() {
+ return list.size();
+ }
+
+ }
+ AbstractList<Integer> list = new MockList<Integer>();
+ try {
+ list.remove(0);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ try {
+ list.set(0, null);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractMapTest.java
new file mode 100644
index 0000000..cd06680
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractMapTest.java
@@ -0,0 +1,415 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.Vector;
+import java.util.WeakHashMap;
+
+public class AbstractMapTest extends junit.framework.TestCase {
+
+ static final String specialKey = "specialKey".intern();
+
+ static final String specialValue = "specialValue".intern();
+
+ // The impl of MyMap is not realistic, but serves to create a type
+ // that uses the default remove behavior.
+ class MyMap extends AbstractMap {
+ final Set mySet = new HashSet(1);
+
+ MyMap() {
+ mySet.add(new Map.Entry() {
+ public Object getKey() {
+ return specialKey;
+ }
+
+ public Object getValue() {
+ return specialValue;
+ }
+
+ public Object setValue(Object object) {
+ return null;
+ }
+ });
+ }
+
+ public Object put(Object key, Object value) {
+ return null;
+ }
+
+ public Set entrySet() {
+ return mySet;
+ }
+ }
+
+ /**
+ * java.util.AbstractMap#keySet()
+ */
+ public void test_keySet() {
+ AbstractMap map1 = new HashMap(0);
+ assertSame("HashMap(0)", map1.keySet(), map1.keySet());
+
+ AbstractMap map2 = new HashMap(10);
+ assertSame("HashMap(10)", map2.keySet(), map2.keySet());
+
+ Map map3 = Collections.EMPTY_MAP;
+ assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
+
+ AbstractMap map4 = new IdentityHashMap(1);
+ assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
+
+ AbstractMap map5 = new LinkedHashMap(122);
+ assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
+
+ AbstractMap map6 = new TreeMap();
+ assertSame("TreeMap", map6.keySet(), map6.keySet());
+
+ AbstractMap map7 = new WeakHashMap();
+ assertSame("WeakHashMap", map7.keySet(), map7.keySet());
+ }
+
+ /**
+ * java.util.AbstractMap#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ Object key = new Object();
+ Object value = new Object();
+
+ AbstractMap map1 = new HashMap(0);
+ map1.put("key", value);
+ assertSame("HashMap(0)", map1.remove("key"), value);
+
+ AbstractMap map4 = new IdentityHashMap(1);
+ map4.put(key, value);
+ assertSame("IdentityHashMap", map4.remove(key), value);
+
+ AbstractMap map5 = new LinkedHashMap(122);
+ map5.put(key, value);
+ assertSame("LinkedHashMap", map5.remove(key), value);
+
+ AbstractMap map6 = new TreeMap(new Comparator() {
+ // Bogus comparator
+ public int compare(Object object1, Object object2) {
+ return 0;
+ }
+ });
+ map6.put(key, value);
+ assertSame("TreeMap", map6.remove(key), value);
+
+ AbstractMap map7 = new WeakHashMap();
+ map7.put(key, value);
+ assertSame("WeakHashMap", map7.remove(key), value);
+
+ AbstractMap aSpecialMap = new MyMap();
+ aSpecialMap.put(specialKey, specialValue);
+ Object valueOut = aSpecialMap.remove(specialKey);
+ assertSame("MyMap", valueOut, specialValue);
+ }
+
+ /**
+ * java.util.AbstractMap#clear()
+ */
+ public void test_clear() {
+ // normal clear()
+ AbstractMap map = new HashMap();
+ map.put(1, 1);
+ map.clear();
+ assertTrue(map.isEmpty());
+
+ // Special entrySet return a Set with no clear method.
+ AbstractMap myMap = new MocAbstractMap();
+ try {
+ myMap.clear();
+ fail("Should throw UnsupportedOprationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ class MocAbstractMap<K, V> extends AbstractMap {
+
+ public Set entrySet() {
+ Set set = new MySet();
+ return set;
+ }
+
+ class MySet extends HashSet {
+ public void clear() {
+ throw new UnsupportedOperationException();
+ }
+ }
+ }
+
+ /**
+ * java.util.AbstractMap#containsKey(Object)
+ */
+ public void test_containsKey() {
+ AbstractMap map = new AMT();
+
+ assertFalse(map.containsKey("k"));
+ assertFalse(map.containsKey(null));
+
+ map.put("k", "v");
+ map.put("key", null);
+ map.put(null, "value");
+ map.put(null, null);
+
+ assertTrue(map.containsKey("k"));
+ assertTrue(map.containsKey("key"));
+ assertTrue(map.containsKey(null));
+ }
+
+ /**
+ * java.util.AbstractMap#containsValue(Object)
+ */
+ public void test_containValue() {
+ AbstractMap map = new AMT();
+
+ assertFalse(map.containsValue("v"));
+ assertFalse(map.containsValue(null));
+
+ map.put("k", "v");
+ map.put("key", null);
+ map.put(null, "value");
+
+ assertTrue(map.containsValue("v"));
+ assertTrue(map.containsValue("value"));
+ assertTrue(map.containsValue(null));
+ }
+
+ /**
+ * java.util.AbstractMap#get(Object)
+ */
+ public void test_get() {
+ AbstractMap map = new AMT();
+ assertNull(map.get("key"));
+ assertNull(map.get(null));
+
+ map.put("k", "v");
+ map.put("key", null);
+ map.put(null, "value");
+
+ assertEquals("v", map.get("k"));
+ assertNull(map.get("key"));
+ assertEquals("value", map.get(null));
+ }
+
+ /**
+ * java.util.AbstractMap#values()
+ */
+ public void test_values() {
+ AbstractMap map1 = new HashMap(0);
+ assertSame("HashMap(0)", map1.values(), map1.values());
+
+ AbstractMap map2 = new HashMap(10);
+ assertSame("HashMap(10)", map2.values(), map2.values());
+
+ Map map3 = Collections.EMPTY_MAP;
+ assertSame("EMPTY_MAP", map3.values(), map3.values());
+
+ AbstractMap map4 = new IdentityHashMap(1);
+ assertSame("IdentityHashMap", map4.values(), map4.values());
+
+ AbstractMap map5 = new LinkedHashMap(122);
+ assertSame("IdentityHashMap", map5.values(), map5.values());
+
+ AbstractMap map6 = new TreeMap();
+ assertSame("TreeMap", map6.values(), map6.values());
+
+ AbstractMap map7 = new WeakHashMap();
+ assertSame("WeakHashMap", map7.values(), map7.values());
+ }
+
+ /**
+ * java.util.AbstractMap#clone()
+ */
+ public void test_clone() {
+ class MyMap extends AbstractMap implements Cloneable {
+ private Map map = new HashMap();
+
+ public Set entrySet() {
+ return map.entrySet();
+ }
+
+ public Object put(Object key, Object value) {
+ return map.put(key, value);
+ }
+
+ public Map getMap() {
+ return map;
+ }
+
+ public Object clone() {
+ try {
+ return super.clone();
+ } catch (CloneNotSupportedException e) {
+ fail("Clone must be supported");
+ return null;
+ }
+ }
+ }
+ MyMap map = new MyMap();
+ map.put("one", "1");
+ Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
+ assertTrue("entry not added", entry.getKey() == "one"
+ && entry.getValue() == "1");
+ MyMap mapClone = (MyMap) map.clone();
+ assertTrue("clone not shallow", map.getMap() == mapClone.getMap());
+ }
+
+ public class AMT extends AbstractMap {
+
+ // Very crude AbstractMap implementation
+ Vector values = new Vector();
+ Vector keys = new Vector();
+
+ public Set entrySet() {
+ return new AbstractSet() {
+ public Iterator iterator() {
+ return new Iterator() {
+ int index = 0;
+
+ public boolean hasNext() {
+ return index < values.size();
+ }
+
+ public Object next() {
+ if (index < values.size()) {
+ Map.Entry me = new Map.Entry() {
+ Object v = values.elementAt(index);
+
+ Object k = keys.elementAt(index);
+
+ public Object getKey() {
+ return k;
+ }
+
+ public Object getValue() {
+ return v;
+ }
+
+ public Object setValue(Object value) {
+ return null;
+ }
+ };
+ index++;
+ return me;
+ }
+ return null;
+ }
+
+ public void remove() {
+ }
+ };
+ }
+
+ public int size() {
+ return values.size();
+ }
+ };
+ }
+
+ public Object put(Object k, Object v) {
+ keys.add(k);
+ values.add(v);
+ return v;
+ }
+ }
+
+ /**
+ * {@link java.util.AbstractMap#putAll(Map)}
+ */
+ public void test_putAllLMap() {
+ Hashtable ht = new Hashtable();
+ AMT amt = new AMT();
+ ht.put("this", "that");
+ amt.putAll(ht);
+
+ assertEquals("Should be equal", amt, ht);
+ }
+
+ public void testEqualsWithNullValues() {
+ Map<String, String> a = new HashMap<String, String>();
+ a.put("a", null);
+ a.put("b", null);
+
+ Map<String, String> b = new HashMap<String, String>();
+ a.put("c", "cat");
+ a.put("d", "dog");
+
+ assertFalse(a.equals(b));
+ assertFalse(b.equals(a));
+ }
+
+ public void testNullsOnViews() {
+ Map<String, String> nullHostile = new Hashtable<String, String>();
+
+ nullHostile.put("a", "apple");
+ testNullsOnView(nullHostile.entrySet());
+
+ nullHostile.put("a", "apple");
+ testNullsOnView(nullHostile.keySet());
+
+ nullHostile.put("a", "apple");
+ testNullsOnView(nullHostile.values());
+ }
+
+ private void testNullsOnView(Collection<?> view) {
+ try {
+ assertFalse(view.contains(null));
+ } catch (NullPointerException optional) {
+ }
+
+ try {
+ assertFalse(view.remove(null));
+ } catch (NullPointerException optional) {
+ }
+
+ Set<Object> setOfNull = Collections.singleton(null);
+ assertFalse(view.equals(setOfNull));
+
+ try {
+ assertFalse(view.removeAll(setOfNull));
+ } catch (NullPointerException optional) {
+ }
+
+ try {
+ assertTrue(view.retainAll(setOfNull)); // destructive
+ } catch (NullPointerException optional) {
+ }
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractQueueTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractQueueTest.java
new file mode 100644
index 0000000..f123bcf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractQueueTest.java
@@ -0,0 +1,323 @@
+/* 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.tests.java.util;
+
+import java.util.AbstractQueue;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Vector;
+
+import junit.framework.TestCase;
+
+public class AbstractQueueTest extends TestCase {
+
+ private MockAbstractQueue<Object> queue;
+
+ private class MockAbstractQueue<E> extends AbstractQueue<E> {
+
+ static final int CAPACITY = 10;
+
+ private int size = 0;
+
+ private Object[] elements = new Object[CAPACITY];
+
+ public Iterator<E> iterator() {
+ return new Iterator<E>() {
+
+ private int currentIndex = -1;
+
+ public boolean hasNext() {
+ return size > 0 && currentIndex < size;
+ }
+
+ public E next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ currentIndex++;
+ return (E) elements[currentIndex];
+ }
+
+ public void remove() {
+ if (-1 == currentIndex) {
+ throw new IllegalStateException();
+ }
+ for (int i = currentIndex; i < size - 1; i++) {
+ elements[i] = elements[i + 1];
+ }
+ size--;
+ }
+ };
+ }
+
+ public int size() {
+ return size;
+ }
+
+ public boolean offer(E o) {
+ if (null == o) {
+ throw new NullPointerException();
+ }
+
+ if (size >= CAPACITY) {
+ return false;
+ }
+
+ elements[size++] = o;
+ return true;
+ }
+
+ public E poll() {
+ if (isEmpty()) {
+ return null;
+ }
+ E e = (E) elements[0];
+ for (int i = 0; i < size - 1; i++) {
+ elements[i] = elements[i + 1];
+ }
+ size--;
+ return e;
+ }
+
+ public E peek() {
+ if (isEmpty()) {
+ return null;
+ }
+ return (E) elements[0];
+ }
+
+ }
+
+ /**
+ * java.util.AbstractQueue.add(E)
+ */
+ public void test_addLE_null() {
+ try {
+ queue.add(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue.add(E)
+ */
+ public void test_addLE_Full() {
+ Object o = new Object();
+
+ for(int i = 0; i < MockAbstractQueue.CAPACITY; i++ ) {
+ queue.add(o);
+ }
+
+ try {
+ queue.add(o);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#add(E)
+ */
+ public void test_addLE() {
+ Object o = new Object();
+ final int LAST_INDEX = 4;
+ for (int i = 0; i < LAST_INDEX; i++) {
+ queue.add(o);
+ }
+ Integer I = new Integer(123456);
+ queue.add(I);
+ assertTrue(queue.contains(I));
+ Iterator iter = queue.iterator();
+ for (int i = 0; i < LAST_INDEX; i++) {
+ iter.next();
+ }
+ assertTrue(I == iter.next());
+ }
+
+ /**
+ * java.util.AbstractQueue#addAll(E)
+ */
+ public void test_addAllLE_null() {
+ try {
+ queue.addAll(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#addAll(E)
+ */
+ public void test_addAllLE_with_null() {
+ List list = Arrays.asList("MYTESTSTRING", null, new Float(123.456));
+ try {
+ queue.addAll(list);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#addAll(E)
+ */
+ public void test_addAllLE_full() {
+ List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
+ try {
+ queue.addAll(list);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#addAll(E)
+ */
+ public void test_addAllLE_empty() {
+ // Regression test for HARMONY-1178
+ List list = new ArrayList<Object>(0);
+ assertFalse("Non modification to queue should return false", queue.addAll(list));
+ }
+
+ /**
+ * java.util.AbstractQueue#addAll(E)
+ */
+ public void test_addAllLE_this() {
+ try {
+ queue.addAll(queue);
+ fail("should throw IllegalArgumentException ");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void test_addAllLjava_lang_Object() {
+ Collection c = new Vector();
+
+ c.add(0);
+ c.add(1);
+ c.add(2);
+ c.add(3);
+ c.add(4);
+ c.add(5);
+
+ assertTrue(queue.addAll(c));
+ assertEquals(6, queue.size());
+ }
+
+ /**
+ * java.util.AbstractQueue#clear()
+ */
+ public void test_clear_empty() {
+ queue.clear();
+ assertTrue(queue.isEmpty());
+ assertNull(queue.peek());
+ }
+
+ /**
+ * java.util.AbstractQueue#clear()
+ */
+ public void test_clear() {
+ List list = Arrays.asList(123.456, "MYTESTSTRING", new Object(), 'c');
+ queue.addAll(list);
+ queue.clear();
+ assertTrue(queue.isEmpty());
+ assertNull(queue.peek());
+ }
+
+ /**
+ * java.util.AbstractQueue#AbstractQueue()
+ */
+ public void test_Constructor() {
+ MockAbstractQueue queue = new MockAbstractQueue();
+ assertNotNull(queue);
+ }
+
+ /**
+ * java.util.AbstractQueue#remove()
+ */
+ public void test_remove_null() {
+ try {
+ queue.remove();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.util.AbstractQueue#remove()
+ */
+ public void test_remove() {
+ char c = 'a';
+ queue.add(c);
+ c = 'b';
+ queue.add(c);
+ assertEquals('a', queue.remove());
+ assertEquals('b', queue.remove());
+ try {
+ queue.remove();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#element()
+ */
+ public void test_element_empty() {
+ try {
+ queue.element();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.AbstractQueue#element()
+ */
+ public void test_element() {
+ String s = "MYTESTSTRING_ONE";
+ queue.add(s);
+ s = "MYTESTSTRING_TWO";
+ queue.add(s);
+ assertEquals("MYTESTSTRING_ONE", queue.element());
+ // still the first element
+ assertEquals("MYTESTSTRING_ONE", queue.element());
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ queue = new MockAbstractQueue<Object>();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ queue = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractSequentialListTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractSequentialListTest.java
new file mode 100644
index 0000000..80ca4fd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/AbstractSequentialListTest.java
@@ -0,0 +1,603 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractSequentialList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.ListIterator;
+import java.util.Vector;
+
+import junit.framework.TestCase;
+
+public class AbstractSequentialListTest extends TestCase {
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ class ASLT<E> extends AbstractSequentialList<E> {
+
+ LinkedList<E> l = new LinkedList<E>();
+
+ @Override
+ public ListIterator<E> listIterator(int index) {
+ return l.listIterator(index);
+ }
+
+ @Override
+ public int size() {
+ return l.size();
+ }
+ }
+
+ /**
+ * {@link java.util.AbstractSequentialList#addAll(int, java.util.Collection)}
+ */
+ public void test_addAll_ILCollection() {
+ AbstractSequentialList<String> al = new ASLT<String>();
+ String[] someList = { "Aardvark" ,
+ "Bear" ,
+ "Chimpanzee",
+ "Duck" };
+ Collection<String> c = Arrays.asList(someList);
+ al.addAll(c);
+ assertTrue("Should return true", al.addAll(2, c));
+ }
+
+ class Mock_unsupportedListIterator implements ListIterator {
+ public void add(Object o) {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean hasNext() {
+ return true;
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public Object next() {
+ return null;
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public Object previous() {
+ return null;
+ }
+
+ public int previousIndex() {
+ return 0;
+ }
+
+ public void remove() {
+ }
+
+ public void set(Object o) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ class Mock_ListIterator<E> implements ListIterator<E> {
+ final String wrongElement = "String";
+ public void add(E o) {
+ if (o.equals(wrongElement)) throw new IllegalArgumentException();
+ if (o == null) throw new NullPointerException();
+ }
+
+ public boolean hasNext() {
+ return false;
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public E next() {
+ return null;
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public E previous() {
+ return null;
+ }
+
+ public int previousIndex() {
+ return 0;
+ }
+
+ public void remove() {
+ }
+
+ public void set(E o) {
+ }
+ }
+
+ public void test_addAllILjava_util_Collection() {
+ AbstractSequentialList asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_unsupportedListIterator();
+ }
+ };
+ Collection strV = new Vector<String>();
+
+ strV.add("String");
+ strV.add("1");
+ strV.add("3.14");
+
+ try {
+ asl.addAll(0, strV);
+ fail("UnsupportedOperationException expected.");
+ } catch (UnsupportedOperationException ee) {
+ //expected
+ }
+ try {
+ asl.addAll(0, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ //ClassCastException can not be checked for this method.
+
+ asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_ListIterator();
+ }
+ };
+
+ try {
+ asl.addAll(0, strV);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ strV.remove("String");
+ strV.add(null);
+
+ try {
+ asl.addAll(0, strV);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ strV.remove(null);
+ asl.addAll(0, strV);
+
+ asl = new LinkedList();
+
+ try {
+ asl.addAll(-10, strV);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ asl.addAll(1, strV);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ public void test_addILjava_lang_Object() {
+ AbstractSequentialList asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_unsupportedListIterator();
+ }
+ };
+
+ try {
+ asl.add(0, 1);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+
+ asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_ListIterator();
+ }
+ };
+
+ try {
+ asl.add(0, "String");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+
+ try {
+ asl.add(0, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ //ClassCastException can not be checked for this method.
+
+ asl.add(0, 1);
+
+ asl = new LinkedList();
+
+ try {
+ asl.add(-1, 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ asl.add(0, 1);
+
+ try {
+ asl.add(2, 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+ }
+
+ public void test_getI() {
+ final String buff[] = {"0", "1", "2", "3", "4", "5"};
+ AbstractSequentialList asl = new AbstractSequentialList() {
+ int currPos = 0;
+
+ @Override
+ public int size() {
+ return buff.length;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ currPos = index;
+ return new ListIterator() {
+ public void add(Object o) {
+ }
+
+ public boolean hasNext() {
+ return true;
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public Object next() {
+ return buff[currPos];
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public Object previous() {
+ return null;
+ }
+
+ public int previousIndex() {
+ return 0;
+ }
+
+ public void remove() {
+ }
+
+ public void set(Object o) {
+ }
+ };
+ }
+ };
+
+ for (int i = 0; i < buff.length; i++) {
+ assertEquals(buff[i], asl.get(i));
+ }
+
+ try {
+ asl.get(asl.size() + 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ asl.get(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ public void test_iterrator() {
+ AbstractSequentialList asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_unsupportedListIterator();
+ }
+ };
+
+ assertTrue(asl.iterator().getClass().toString().contains("Mock_unsupportedListIterator"));
+
+ asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_ListIterator();
+ }
+ };
+
+ assertTrue(asl.iterator().getClass().toString().contains("Mock_ListIterator"));
+
+ asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return null;
+ }
+ };
+ assertNull(asl.iterator());
+ }
+
+ public void test_removeI() {
+ AbstractSequentialList asl = new AbstractSequentialList() {
+ String buff[] = {"0", "1", "2", "3", "4", "5"};
+ int currPos = 0;
+
+ @Override
+ public int size() {
+ return buff.length;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ currPos = index;
+ return new ListIterator() {
+ public void add(Object o) {
+ }
+
+ public boolean hasNext() {
+ return true;
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public Object next() {
+ return buff[currPos];
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public Object previous() {
+ return null;
+ }
+
+ public int previousIndex() {
+ return 0;
+ }
+
+ public void remove() {
+ buff[currPos] = "removed element";
+ }
+
+ public void set(Object o) {
+ }
+ };
+ }
+ };
+
+ try {
+ asl.remove(asl.size() + 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ asl.remove(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ for(int i = 0; i < asl.size(); i++) {
+ assertFalse(asl.get(i).toString().contains("removed element"));
+ asl.remove(i);
+ assertTrue(asl.get(i).toString().contains("removed element"));
+ }
+ }
+
+ public void test_setILjava_lang_Object() {
+ AbstractSequentialList asl = new AbstractSequentialList() {
+ String buff[] = {"0", "1", "2", "3", "4", "5"};
+ final String illegalStr = "Illegal element";
+ int currPos = 0;
+
+ @Override
+ public int size() {
+ return buff.length;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ currPos = index;
+ return new ListIterator() {
+ public void add(Object o) {
+ }
+
+ public boolean hasNext() {
+ return true;
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public Object next() {
+ return buff[currPos];
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public Object previous() {
+ return null;
+ }
+
+ public int previousIndex() {
+ return 0;
+ }
+
+ public void remove() {
+ buff[currPos] = "removed element";
+ }
+
+ public void set(Object o) {
+ if (o == null) throw new NullPointerException();
+ if (o.equals(illegalStr)) throw new IllegalArgumentException();
+ buff[currPos] = (String) o;
+ }
+ };
+ }
+ };
+
+ try {
+ asl.set(asl.size() + 1, "new element");
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ asl.set(-1, "new element");
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ for(int i = 0; i < asl.size(); i++) {
+ assertFalse(asl.get(i).toString().contains("new element"));
+ asl.set(i, "new element");
+ assertTrue(asl.get(i).toString().contains("new element"));
+ }
+
+ try {
+ asl.set(1, new Double(1));
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //
+ }
+
+ try {
+ asl.set(1, "Illegal element");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+
+ try {
+ asl.set(1, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ asl = new AbstractSequentialList() {
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return new Mock_unsupportedListIterator();
+ }
+ };
+
+ try {
+ asl.set(0, "New element");
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayDequeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayDequeTest.java
new file mode 100644
index 0000000..11e6cfc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayDequeTest.java
@@ -0,0 +1,932 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.Serializable;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class ArrayDequeTest extends TestCase {
+
+ private Object testObjOne;
+
+ private Object testObjTwo;
+
+ private Object testObjThree;
+
+ private Object testObjFour;
+
+ private Object testObjLast;
+
+ private ArrayDeque<Object> testQue;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ testObjOne = new Object();
+ testObjTwo = new Object();
+ testObjThree = new Object();
+ testObjFour = new Object();
+ testObjLast = new Object();
+ testQue = new ArrayDeque<Object>();
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#ArrayDeque()}
+ */
+ public void test_Constructor() throws Exception {
+ assertEquals(0, new ArrayDeque<Object>().size());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#ArrayDeque(java.util.Collection)}
+ */
+ public void test_Constructor_LCollection() throws Exception {
+ assertEquals(0, new ArrayDeque<Object>(new ArrayList<Object>()).size());
+ try {
+ new ArrayDeque<Object>(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#ArrayDeque(int)}
+ */
+ public void test_Constructor_Int() throws Exception {
+ assertEquals(0, new ArrayDeque<Object>(8).size());
+ ArrayDeque<Object> zeroCapQue = new ArrayDeque<Object>(0);
+ assertEquals(0, zeroCapQue.size());
+ zeroCapQue.add(testObjOne);
+ assertEquals(1, zeroCapQue.size());
+ assertEquals(0, new ArrayDeque<Object>(0).size());
+ ArrayDeque<Object> negCapQue = new ArrayDeque<Object>(-1);
+ assertEquals(0, negCapQue.size());
+ negCapQue.add(testObjOne);
+ assertEquals(1, negCapQue.size());
+ ArrayDeque<Object> oneCapQue = new ArrayDeque<Object>(1);
+ assertEquals(0, oneCapQue.size());
+ oneCapQue.add(testObjOne);
+ assertEquals(1, oneCapQue.size());
+ oneCapQue.add(testObjOne);
+ assertEquals(2, oneCapQue.size());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#addFirst(Object)}
+ */
+ public void test_addFirst() throws Exception {
+ testQue.addFirst(testObjOne);
+ assertEquals(1, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.addFirst(testObjOne);
+ assertEquals(2, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.addFirst(testObjTwo);
+ assertEquals(3, testQue.size());
+ assertEquals(testObjTwo, testQue.peek());
+ assertEquals(testObjOne, testQue.getLast());
+ try {
+ testQue.addFirst(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#addLast(Object)}
+ */
+ public void test_addLast() throws Exception {
+ testQue.addLast(testObjOne);
+ assertEquals(1, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.addLast(testObjOne);
+ assertEquals(2, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.addLast(testObjTwo);
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertEquals(testObjTwo, testQue.getLast());
+ try {
+ testQue.addLast(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#offerFirst(Object)}
+ */
+ public void test_offerFirst() throws Exception {
+ assertTrue(testQue.offerFirst(testObjOne));
+ assertEquals(1, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertTrue(testQue.offerFirst(testObjOne));
+ assertEquals(2, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertTrue(testQue.offerFirst(testObjTwo));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjTwo, testQue.peek());
+ assertEquals(testObjOne, testQue.getLast());
+ try {
+ testQue.offerFirst(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#offerLast(Object)}
+ */
+ public void test_offerLast() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertEquals(1, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertTrue(testQue.offerLast(testObjOne));
+ assertEquals(2, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertEquals(testObjTwo, testQue.getLast());
+ try {
+ testQue.offerLast(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#removeFirst()}
+ */
+ public void test_removeFirst() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.removeFirst());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.removeFirst());
+ assertEquals(testObjThree, testQue.removeFirst());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.removeFirst();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#removeLast()}
+ */
+ public void test_removeLast() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.removeLast());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.removeLast());
+ assertEquals(testObjOne, testQue.removeLast());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.removeLast();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#pollFirst()}
+ */
+ public void test_pollFirst() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pollFirst());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.pollFirst());
+ assertEquals(testObjThree, testQue.pollFirst());
+ assertEquals(0, testQue.size());
+ assertNull(testQue.pollFirst());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#peekLast()}
+ */
+ public void test_pollLast() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.pollLast());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.pollLast());
+ assertEquals(testObjOne, testQue.pollLast());
+ assertEquals(0, testQue.size());
+ assertNull(testQue.pollFirst());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#getFirst()}
+ */
+ public void test_getFirst() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.getFirst());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pollFirst());
+ assertEquals(testObjTwo, testQue.getFirst());
+ assertEquals(testObjTwo, testQue.pollFirst());
+ assertEquals(testObjThree, testQue.pollFirst());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.getFirst();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#getLast()}
+ */
+ public void test_getLast() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.getLast());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.pollLast());
+ assertEquals(testObjTwo, testQue.getLast());
+ assertEquals(testObjTwo, testQue.pollLast());
+ assertEquals(testObjOne, testQue.pollLast());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.getLast();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#peekFirst()}
+ */
+ public void test_peekFirst() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peekFirst());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pollFirst());
+ assertEquals(testObjTwo, testQue.peekFirst());
+ assertEquals(testObjTwo, testQue.pollFirst());
+ assertEquals(testObjThree, testQue.pollFirst());
+ assertEquals(0, testQue.size());
+ assertEquals(null, testQue.peekFirst());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#peekLast()}
+ */
+ public void test_peekLast() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjThree, testQue.pollLast());
+ assertEquals(testObjTwo, testQue.peekLast());
+ assertEquals(testObjTwo, testQue.pollLast());
+ assertEquals(testObjOne, testQue.pollLast());
+ assertEquals(0, testQue.size());
+ assertNull(testQue.peekLast());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#removeFirstOccurrence(Object)}
+ */
+ public void test_removeFirstOccurrence() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertEquals(5, testQue.size());
+ assertTrue(testQue.removeFirstOccurrence(testObjOne));
+ assertFalse(testQue.removeFirstOccurrence(testObjFour));
+ assertEquals(testObjTwo, testQue.peekFirst());
+ assertEquals(testObjOne, testQue.peekLast());
+ assertEquals(4, testQue.size());
+ assertTrue(testQue.removeFirstOccurrence(testObjOne));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peekLast());
+ assertTrue(testQue.removeFirstOccurrence(testObjOne));
+ assertEquals(2, testQue.size());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertFalse(testQue.removeFirstOccurrence(testObjOne));
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#removeLastOccurrence(Object)}
+ */
+ public void test_removeLastOccurrence() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertEquals(5, testQue.size());
+ assertTrue(testQue.removeLastOccurrence(testObjOne));
+ assertFalse(testQue.removeLastOccurrence(testObjFour));
+ assertEquals(testObjOne, testQue.peekFirst());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertEquals(4, testQue.size());
+ assertTrue(testQue.removeLastOccurrence(testObjOne));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peekFirst());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertTrue(testQue.removeLastOccurrence(testObjOne));
+ assertEquals(2, testQue.size());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertFalse(testQue.removeLastOccurrence(testObjOne));
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#add(Object)}
+ */
+ public void test_add() throws Exception {
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertEquals(testObjOne, testQue.peekFirst());
+ assertEquals(testObjThree, testQue.peekLast());
+ try {
+ testQue.add(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#offer(Object)}
+ */
+ public void test_offer() throws Exception {
+ assertTrue(testQue.offer(testObjOne));
+ assertTrue(testQue.offer(testObjTwo));
+ assertTrue(testQue.offer(testObjOne));
+ assertTrue(testQue.offer(testObjThree));
+ assertEquals(testObjOne, testQue.peekFirst());
+ assertEquals(testObjThree, testQue.peekLast());
+ try {
+ testQue.offer(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#remove()}
+ */
+ public void test_remove() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.remove());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.remove());
+ assertEquals(testObjThree, testQue.remove());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.remove();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#poll()}
+ */
+ public void test_poll() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.poll());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.poll());
+ assertEquals(testObjThree, testQue.poll());
+ assertEquals(0, testQue.size());
+ assertNull(testQue.poll());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#element()}
+ */
+ public void test_element() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.element());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pollFirst());
+ assertEquals(testObjTwo, testQue.element());
+ assertEquals(testObjTwo, testQue.pollFirst());
+ assertEquals(testObjThree, testQue.element());
+ assertEquals(testObjThree, testQue.pollFirst());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.element();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#peek()}
+ */
+ public void test_peek() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pollFirst());
+ assertEquals(testObjTwo, testQue.peek());
+ assertEquals(testObjTwo, testQue.pollFirst());
+ assertEquals(testObjThree, testQue.pollFirst());
+ assertEquals(0, testQue.size());
+ assertEquals(null, testQue.peek());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#push(Object)}
+ */
+ public void test_push() throws Exception {
+ testQue.push(testObjOne);
+ assertEquals(1, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.push(testObjOne);
+ assertEquals(2, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ testQue.push(testObjTwo);
+ assertEquals(3, testQue.size());
+ assertEquals(testObjTwo, testQue.peek());
+ assertEquals(testObjOne, testQue.getLast());
+ try {
+ testQue.push(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#pop()}
+ */
+ public void test_pop() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.pop());
+ assertEquals(2, testQue.size());
+ assertEquals(testObjTwo, testQue.pop());
+ assertEquals(testObjThree, testQue.pop());
+ assertEquals(0, testQue.size());
+ try {
+ testQue.pop();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#addFirst(Object)}
+ */
+ public void test_size() throws Exception {
+ assertEquals(0, testQue.size());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertEquals(2, testQue.size());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertEquals(4, testQue.size());
+ testQue.remove();
+ testQue.remove();
+ assertEquals(2, testQue.size());
+ testQue.clear();
+ assertEquals(0, testQue.size());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#isEmpty()}
+ */
+ public void test_isEmpty() throws Exception {
+ assertTrue(testQue.isEmpty());
+ assertTrue(testQue.add(testObjOne));
+ assertFalse(testQue.isEmpty());
+ assertTrue(testQue.add(testObjTwo));
+ assertFalse(testQue.isEmpty());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertFalse(testQue.isEmpty());
+ testQue.remove();
+ testQue.remove();
+ assertFalse(testQue.isEmpty());
+ testQue.clear();
+ assertTrue(testQue.isEmpty());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#iterator()}
+ */
+ public void test_iterator() throws Exception {
+ assertFalse(testQue.iterator().hasNext());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+ Iterator result = testQue.iterator();
+ assertEquals(5, testQue.size());
+ try {
+ result.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ assertTrue(testQue.add(testObjThree));
+ try {
+ result.next();
+ fail("should throw ConcurrentModificationException");
+ } catch (ConcurrentModificationException e) {
+ // expected
+ }
+ result = testQue.iterator();
+ assertEquals(testObjOne, result.next());
+ assertEquals(testObjTwo, result.next());
+ assertEquals(testObjOne, result.next());
+ assertEquals(testObjThree, result.next());
+ assertEquals(testObjLast, result.next());
+ assertTrue(result.hasNext());
+ result.remove();
+ assertEquals(testObjThree, result.next());
+ assertFalse(result.hasNext());
+ try {
+ result.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ // test a full array
+ ArrayDeque<Object> ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 16; ++i) {
+ ad.addLast(new Object());
+ }
+ assertTrue(ad.iterator().hasNext());
+ Iterator<Object> iter = ad.iterator();
+ for (int i = 0; i < 16; ++i) {
+ assertTrue(iter.hasNext());
+ iter.next();
+ }
+ iter.remove();
+ // test un-full array
+ ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 5; ++i) {
+ ad.addLast(new Object());
+ }
+ iter = ad.iterator();
+ for (int i = 0; i < 5; ++i) {
+ assertTrue(iter.hasNext());
+ iter.next();
+ }
+ iter.remove();
+
+ ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 16; ++i) {
+ ad.addLast(new Object());
+ }
+ iter = ad.iterator();
+ assertTrue(iter.hasNext());
+ for (int i = 0; i < ad.size(); ++i) {
+ iter.next();
+ }
+ assertFalse(iter.hasNext());
+ iter.remove();
+ ad.add(new Object());
+ assertFalse(iter.hasNext());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#descendingIterator()}
+ */
+ public void test_descendingIterator() throws Exception {
+ assertFalse(testQue.descendingIterator().hasNext());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+ Iterator result = testQue.descendingIterator();
+ assertEquals(5, testQue.size());
+ try {
+ result.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ assertTrue(testQue.add(testObjFour));
+
+ // a strange behavior here, RI's descendingIterator() and iterator() is
+ // properly different. Notice spec: "The iterators returned by this
+ // class's iterator method are fail-fast". RI shows descendingIterator()
+ // is not an iterator method.
+ assertEquals(testObjLast, result.next());
+
+ result = testQue.descendingIterator();
+ assertEquals(testObjFour, result.next());
+ assertEquals(testObjLast, result.next());
+ assertEquals(testObjThree, result.next());
+ assertEquals(testObjOne, result.next());
+ assertEquals(testObjTwo, result.next());
+ assertTrue(result.hasNext());
+ result.remove();
+ assertEquals(testObjOne, result.next());
+ assertFalse(result.hasNext());
+ try {
+ result.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ // test a full array
+ ArrayDeque<Object> ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 16; ++i) {
+ ad.addLast(new Object());
+ }
+ assertTrue(ad.descendingIterator().hasNext());
+ Iterator<Object> iter = ad.descendingIterator();
+ for (int i = 0; i < 16; ++i) {
+ assertTrue(iter.hasNext());
+ iter.next();
+ }
+ iter.remove();
+ // test un-full array
+ ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 5; ++i) {
+ ad.addLast(new Object());
+ }
+ iter = ad.descendingIterator();
+ for (int i = 0; i < 5; ++i) {
+ assertTrue(iter.hasNext());
+ iter.next();
+ }
+ iter.remove();
+
+ ad = new ArrayDeque<Object>();
+ // fill the array
+ for (int i = 0; i < 16; ++i) {
+ ad.addLast(new Object());
+ }
+ iter = ad.descendingIterator();
+ assertTrue(iter.hasNext());
+ for (int i = 0; i < ad.size(); ++i) {
+ iter.next();
+ }
+ assertFalse(iter.hasNext());
+ iter.remove();
+ ad.add(new Object());
+ assertFalse(iter.hasNext());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#contains(Object)}
+ */
+ public void test_contains() throws Exception {
+ assertFalse(testQue.contains(testObjFour));
+ assertFalse(testQue.contains(null));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+
+ assertTrue(testQue.contains(testObjOne));
+ assertTrue(testQue.contains(testObjTwo));
+ assertTrue(testQue.contains(testObjThree));
+ assertTrue(testQue.contains(testObjLast));
+ assertFalse(testQue.contains(null));
+ testQue.clear();
+ assertFalse(testQue.contains(testObjOne));
+ assertFalse(testQue.contains(testObjTwo));
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#remove(Object)}
+ */
+ public void test_remove_LObject() throws Exception {
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjTwo));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertTrue(testQue.offerLast(testObjThree));
+ assertTrue(testQue.offerLast(testObjOne));
+ assertEquals(5, testQue.size());
+ assertTrue(testQue.remove(testObjOne));
+ assertFalse(testQue.remove(testObjFour));
+ assertEquals(testObjTwo, testQue.peekFirst());
+ assertEquals(testObjOne, testQue.peekLast());
+ assertEquals(4, testQue.size());
+ assertTrue(testQue.remove(testObjOne));
+ assertEquals(3, testQue.size());
+ assertEquals(testObjOne, testQue.peekLast());
+ assertTrue(testQue.remove(testObjOne));
+ assertEquals(2, testQue.size());
+ assertEquals(testObjThree, testQue.peekLast());
+ assertFalse(testQue.remove(testObjOne));
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#clear()}
+ */
+ public void test_clear() throws Exception {
+ assertTrue(testQue.isEmpty());
+ testQue.clear();
+ assertTrue(testQue.isEmpty());
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ testQue.clear();
+ assertTrue(testQue.isEmpty());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#toArray()}
+ */
+ public void test_toArray() throws Exception {
+ assertEquals(0, testQue.toArray().length);
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+ Object[] result = testQue.toArray();
+ assertEquals(5, testQue.size());
+ assertEquals(testObjOne, result[0]);
+ assertEquals(testObjTwo, result[1]);
+ assertEquals(testObjOne, result[2]);
+ assertEquals(testObjThree, result[3]);
+ assertEquals(testObjLast, result[4]);
+ // change in array do not affect ArrayDeque
+ result[0] = null;
+ assertEquals(5, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#toArray(Object[])}
+ */
+ public void test_toArray_$LObject() throws Exception {
+ Object[] array = new Object[0];
+ Object[] result = testQue.toArray(array);
+ assertEquals(0, result.length);
+ assertEquals(array, result);
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+ result = testQue.toArray(array);
+ assertEquals(5, testQue.size());
+ assertEquals(5, result.length);
+ assertEquals(0, array.length);
+ assertFalse(array == result);
+ assertEquals(testObjOne, result[0]);
+ assertEquals(testObjTwo, result[1]);
+ assertEquals(testObjOne, result[2]);
+ assertEquals(testObjThree, result[3]);
+ assertEquals(testObjLast, result[4]);
+ // change in array do not affect ArrayDeque
+ result[0] = null;
+ assertEquals(5, testQue.size());
+ assertEquals(testObjOne, testQue.peek());
+ try {
+ testQue.toArray(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * {@link java.util.ArrayDeque#clone()}
+ */
+ public void test_clone() throws Exception {
+ ArrayDeque<Object> cloned = testQue.clone();
+ assertEquals(0, cloned.size());
+ assertFalse(cloned == testQue);
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjTwo));
+ assertTrue(testQue.add(testObjOne));
+ assertTrue(testQue.add(testObjThree));
+ assertTrue(testQue.add(testObjLast));
+ assertTrue(testQue.add(testQue));
+ cloned = testQue.clone();
+ assertEquals(6, cloned.size());
+ while (0 != testQue.size()) {
+ assertEquals(testQue.remove(), cloned.remove());
+ }
+ }
+
+ /**
+ * java.util.ArrayDeque#Serialization()
+ */
+ public void test_serialization() throws Exception {
+ assertTrue(testQue.add(new Integer(1)));
+ assertTrue(testQue.add(new Integer(2)));
+ assertTrue(testQue.add(new Integer(3)));
+ assertTrue(testQue.add(new Integer(4)));
+ assertTrue(testQue.add(new Integer(5)));
+ SerializationTest.verifySelf(testQue, new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+ ArrayDeque<Object> formerQue = (ArrayDeque) initial;
+ ArrayDeque<Object> deserializedQue = (ArrayDeque) deserialized;
+ assertEquals(formerQue.remove(), deserializedQue.remove());
+ }
+ });
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationCompatibility() throws Exception {
+ assertTrue(testQue.add(new Integer(1)));
+ assertTrue(testQue.add(new Integer(2)));
+ assertTrue(testQue.add(new Integer(3)));
+ assertTrue(testQue.add(new Integer(4)));
+ assertTrue(testQue.add(new Integer(5)));
+ SerializationTest.verifyGolden(this, testQue, new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+ ArrayDeque<Object> formerQue = (ArrayDeque) initial;
+ ArrayDeque<Object> deserializedQue = (ArrayDeque) deserialized;
+ assertEquals(formerQue.remove(), deserializedQue.remove());
+ }
+ });
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayListTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayListTest.java
new file mode 100644
index 0000000..f2546e0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArrayListTest.java
@@ -0,0 +1,1071 @@
+/*
+ * 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.tests.java.util;
+
+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;
+
+ Object[] objArray;
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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 {
+ new ArrayList(-1);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * 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]);
+ try {
+ new ArrayList(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ }
+
+ public void testConstructorWithConcurrentCollection() {
+ Collection<String> collection = shrinksOnSize("A", "B", "C", "D");
+ ArrayList<String> list = new ArrayList<String>(collection);
+ assertFalse(list.contains(null));
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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]);
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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));
+
+ // 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));
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+// BEGIN android-removed
+// The spec does not mandate that IndexOutOfBoundsException be thrown in
+// preference to NullPointerException when the caller desserves both.
+//
+// /**
+// * java.util.ArrayList#addAll(int, java.util.Collection)
+// */
+// 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) {
+// }
+// }
+// END android-removed
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ */
+
+ }
+
+ /**
+ * 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));
+
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * java.util.ArrayList#ensureCapacity(int)
+ */
+ public void test_ensureCapacityI() throws Exception {
+ // 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));
+
+ ArrayList<String> list = new ArrayList<String>(1);
+ list.add("hello");
+ list.ensureCapacity(Integer.MIN_VALUE);
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * {@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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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]);
+ }
+
+ }
+
+ /**
+ * 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]);
+ }
+
+ String[] strArray = new String[100];
+ try {
+ alist.toArray(strArray);
+ fail("ArrayStoreException expected");
+ } catch (ArrayStoreException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ al.add("b");
+ Iterator it = al.iterator();
+ al.trimToSize();
+ try {
+ it.next();
+ fail("should throw a ConcurrentModificationException");
+ } catch (ConcurrentModificationException ioobe) {
+ // expected
+ }
+ }
+
+ public void test_trimToSize_02() {
+ ArrayList list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
+ "d", "e", "f", "g" }));
+ list.remove("a");
+ list.remove("f");
+ list.trimToSize();
+ }
+
+ 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 test_removeLjava_lang_Object() {
+ List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
+ "d", "e", "f", "g" }));
+ assertTrue("Removed wrong element 1", list.remove("a"));
+ assertTrue("Removed wrong element 2", list.remove("f"));
+ String[] result = new String[5];
+ list.toArray(result);
+ assertTrue("Removed wrong element 3", Arrays.equals(result,
+ new String[] { "b", "c", "d", "e", "g" }));
+ }
+
+ 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 class MockArrayList extends ArrayList {
+ public int size() {
+ return 0;
+ }
+
+ public void removeRange(int begin, int end) {
+ super.removeRange(begin, end);
+ }
+ }
+
+ public void test_removeRangeII() {
+ MockArrayList mal = new MockArrayList();
+ mal.add("a");
+ mal.add("b");
+ mal.add("c");
+ mal.add("d");
+ mal.add("e");
+ mal.add("f");
+ mal.add("g");
+ mal.add("h");
+
+ mal.removeRange(2, 4);
+
+ String[] result = new String[6];
+ mal.toArray(result);
+ assertTrue("Removed wrong element 3", Arrays.equals(result,
+ new String[] { "a", "b", "e", "f", "g", "h"}));
+ }
+
+ 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 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();
+
+ objArray = new Object[100];
+ for (int i = 0; i < objArray.length; i++) {
+ objArray[i] = new Integer(i);
+ }
+
+ alist = new ArrayList();
+ for (int i = 0; i < objArray.length; i++) {
+ alist.add(objArray[i]);
+ }
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ objArray = null;
+ alist = null;
+
+ super.tearDown();
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java
new file mode 100644
index 0000000..d6adbb5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java
@@ -0,0 +1,472 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.RandomAccess;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class Arrays2Test extends TestCase {
+
+ /**
+ * java.util.Arrays#binarySearch(double[], double)
+ */
+ 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);
+ }
+ 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));
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(float[], float)
+ */
+ 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);
+ }
+ 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));
+ }
+
+ /**
+ * java.util.Arrays#equals(double[], double[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#equals(float[], float[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#sort(double[])
+ */
+ 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);
+ }
+ Arrays.sort(reversedArray);
+ for (int counter = 0; counter < reversedArray.length; counter++) {
+ assertTrue("Assert 0: Resulting array not sorted",
+ reversedArray[counter] == counter);
+ }
+
+ // 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]);
+ }
+ 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]);
+ }
+ assertTrue("Assert 2: specials sort incorrectly " + Arrays.asList(print2),
+ Arrays.equals(specials2, answer));
+ }
+
+ /**
+ * java.util.Arrays#sort(float[])
+ */
+ 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);
+ }
+ Arrays.sort(reversedArray);
+ for (int counter = 0; counter < reversedArray.length; counter++) {
+ assertTrue("Assert 0: Resulting array not sorted",
+ reversedArray[counter] == 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("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]);
+ }
+ assertTrue("Assert 2: specials sort incorrectly" + Arrays.asList(print2),
+ Arrays.equals(specials2, answer));
+ }
+
+ /**
+ * java.util.Arrays#toString(boolean[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(byte[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(char[])
+ */
+ 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' }));
+ }
+
+ /**
+ * java.util.Arrays#toString(double[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(float[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(int[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(long[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(short[])
+ */
+ 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 }));
+ }
+
+ /**
+ * java.util.Arrays#toString(Object[])
+ */
+ 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" }));
+ }
+
+ /**
+ * java.util.Arrays#deepToString(Object[])
+ */
+ 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;
+
+ 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));
+ }
+
+ 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));
+
+ try {
+ Arrays.asList((Object[]) null);
+ fail("No NPE");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ 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) {
+ }
+
+ }
+
+ 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) {
+ }
+ }
+
+ 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) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArraysTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArraysTest.java
new file mode 100644
index 0000000..277abce
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArraysTest.java
@@ -0,0 +1,4209 @@
+/*
+ * 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.tests.java.util;
+
+import tests.support.Support_UnmodifiableCollectionTest;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Random;
+
+public class ArraysTest extends junit.framework.TestCase {
+
+ 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;
+ }
+ }
+
+ final static int arraySize = 100;
+
+ Object[] objArray;
+
+ boolean[] booleanArray;
+
+ byte[] byteArray;
+
+ char[] charArray;
+
+ double[] doubleArray;
+
+ float[] floatArray;
+
+ int[] intArray;
+
+ long[] longArray;
+
+ Object[] objectArray;
+
+ short[] shortArray;
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ public void test_Arrays_binaraySearch_byte() {
+ assertEquals(-1, Arrays.binarySearch(new byte[] { '0' }, 0, 0,
+ (byte) '1'));
+ assertEquals(-2, Arrays.binarySearch(new byte[] { '0' }, 1, 1,
+ (byte) '1'));
+ assertEquals(-2, Arrays.binarySearch(new byte[] { '0', '1' }, 1, 1,
+ (byte) '2'));
+ assertEquals(-3, Arrays.binarySearch(new byte[] { '0', '1' }, 2, 2,
+ (byte) '2'));
+ }
+
+ public void test_Arrays_binaraySearch_char() {
+ assertEquals(-1, Arrays.binarySearch(new char[] { '0' }, 0, 0, '1'));
+ assertEquals(-2, Arrays.binarySearch(new char[] { '0' }, 1, 1, '1'));
+ assertEquals(-2, Arrays
+ .binarySearch(new char[] { '0', '1' }, 1, 1, '2'));
+ assertEquals(-3, Arrays
+ .binarySearch(new char[] { '0', '1' }, 2, 2, '2'));
+ }
+
+ public void test_Arrays_binaraySearch_float() {
+ assertEquals(-1, Arrays.binarySearch(new float[] { -1.0f }, 0, 0, 0.0f));
+ assertEquals(-2, Arrays.binarySearch(new float[] { -1.0f }, 1, 1, 0.0f));
+ assertEquals(-2, Arrays.binarySearch(new float[] { -1.0f, 0f }, 1, 1,
+ 1f));
+ assertEquals(-3, Arrays.binarySearch(new float[] { -1.0f, 0f }, 2, 2,
+ 1f));
+ }
+
+ public void test_Arrays_binaraySearch_double() {
+ assertEquals(-1, Arrays.binarySearch(new double[] { -1.0 }, 0, 0, 0.0));
+ assertEquals(-2, Arrays.binarySearch(new double[] { -1.0 }, 1, 1, 0.0));
+ assertEquals(-2, Arrays.binarySearch(new double[] { -1.0, 0 }, 1, 1, 1));
+ assertEquals(-3, Arrays.binarySearch(new double[] { -1.0, 0 }, 2, 2, 1));
+ }
+
+ public void test_Arrays_binaraySearch_int() {
+ assertEquals(-1, Arrays.binarySearch(new int[] { -1 }, 0, 0, 0));
+ assertEquals(-2, Arrays.binarySearch(new int[] { -1 }, 1, 1, 0));
+ assertEquals(-2, Arrays.binarySearch(new int[] { -1, 0 }, 1, 1, 1));
+ assertEquals(-3, Arrays.binarySearch(new int[] { -1, 0 }, 2, 2, 1));
+ }
+
+ public void test_Arrays_binaraySearch_long() {
+ assertEquals(-1, Arrays.binarySearch(new long[] { -1l }, 0, 0, 0l));
+ assertEquals(-2, Arrays.binarySearch(new long[] { -1l }, 1, 1, 0l));
+ assertEquals(-2, Arrays.binarySearch(new long[] { -1l, 0l }, 1, 1, 1l));
+ assertEquals(-3, Arrays.binarySearch(new long[] { -1l, 0l }, 2, 2, 1l));
+ }
+
+ public void test_Arrays_binaraySearch_short() {
+ assertEquals(-1, Arrays.binarySearch(new short[] { (short) -1 }, 0, 0,
+ (short) 0));
+ assertEquals(-2, Arrays.binarySearch(new short[] { (short) -1 }, 1, 1,
+ (short) 0));
+ assertEquals(-2, Arrays.binarySearch(new short[] { (short) -1,
+ (short) 0 }, 1, 1, (short) 1));
+ assertEquals(-3, Arrays.binarySearch(new short[] { (short) -1,
+ (short) 0 }, 2, 2, (short) 1));
+ }
+
+ public void test_Arrays_binaraySearch_Object() {
+ assertEquals(-1, Arrays.binarySearch(new Object[] { new Integer(-1) },
+ 0, 0, new Integer(0)));
+ assertEquals(-2, Arrays.binarySearch(new Object[] { new Integer(-1) },
+ 1, 1, new Integer(0)));
+ assertEquals(-2, Arrays.binarySearch(new Object[] { new Integer(-1),
+ new Integer(0) }, 1, 1, new Integer(1)));
+ assertEquals(-3, Arrays.binarySearch(new Object[] { new Integer(-1),
+ new Integer(0) }, 2, 2, new Integer(1)));
+ }
+
+ public void test_Arrays_binaraySearch_T() {
+ ReversedIntegerComparator reversedComparator = new ReversedIntegerComparator();
+ assertEquals(-1, Arrays.binarySearch(new Integer[] { new Integer(-1) },
+ 0, 0, new Integer(0), reversedComparator));
+ assertEquals(-2, Arrays.binarySearch(new Integer[] { new Integer(-1) },
+ 1, 1, new Integer(0), reversedComparator));
+ assertEquals(-2, Arrays.binarySearch(new Integer[] { new Integer(-1),
+ new Integer(0) }, 1, 1, new Integer(1), reversedComparator));
+ assertEquals(-3, Arrays.binarySearch(new Integer[] { new Integer(-1),
+ new Integer(0) }, 2, 2, new Integer(1), reversedComparator));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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]);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, Long.MIN_VALUE);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, Long.MAX_VALUE);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, Long.MAX_VALUE);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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]);
+ }
+
+ /**
+ * 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);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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]);
+
+ try {
+ Arrays.fill(d, 10, 0, val);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, -10, 0, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.fill(d, 10, d.length+1, val);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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]));
+ }
+
+ /**
+ * 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 }));
+
+ }
+
+ /**
+ * 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 }));
+ }
+
+ /**
+ * 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 }));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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);
+
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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);
+
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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]);
+
+ Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
+ Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
+
+ try {
+ Arrays.sort(reversedArray);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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) {
+ }
+
+ Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
+ Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
+
+ try {
+ Arrays.sort(reversedArray, reversedArray.length/4, 3*reversedArray.length/4);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+
+ Arrays.sort(reversedArray, 0, reversedArray.length/4);
+ Arrays.sort(reversedArray, 3*reversedArray.length/4, reversedArray.length);
+ }
+
+ /**
+ * 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]);
+
+ Arrays.fill(originalArray, 0, originalArray.length/2, "String");
+ Arrays.fill(originalArray, originalArray.length/2, originalArray.length, new Integer(1));
+
+ try {
+ Arrays.sort(originalArray, startIndex, endIndex, comp);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+
+ Arrays.sort(originalArray, endIndex, originalArray.length, comp);
+
+ try {
+ Arrays.sort(originalArray, endIndex, originalArray.length + 1, comp);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.sort(originalArray, -1, startIndex, comp);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ Arrays.sort(originalArray, originalArray.length, endIndex, comp);
+ fail("IllegalArgumentException expected");
+ } catch(IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+
+ Arrays.fill(objectArray, 0, objectArray.length/2, "String");
+ Arrays.fill(objectArray, objectArray.length/2, objectArray.length, new Integer(1));
+
+ try {
+ Arrays.sort(objectArray, comp);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+ }
+
+ // 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++;
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(byte[], int, int)
+ */
+ 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
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(char[], int, int)
+ */
+ 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
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(double[], int, int)
+ */
+ 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
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(float[], int, int)
+ */
+ 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
+ }
+ 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ 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
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(Object[], int, int)
+ */
+ 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
+ }
+ 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
+ }
+ 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * java.util.Arrays#sort(short[], int, int)
+ */
+ 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
+ }
+ }
+
+ // Lenghts of arrays to test in test_sort;
+ private static final int[] LENGTHS = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 100, 1000, 10000 };
+
+ /**
+ * java.util.Arrays#sort()
+ */
+ public void test_sort() {
+ for (int len : LENGTHS) {
+ PrimitiveTypeArrayBuilder.reset();
+ int[] golden = new int[len];
+ for (int m = 1; m < 2 * len; m *= 2) {
+ for (PrimitiveTypeArrayBuilder builder : PrimitiveTypeArrayBuilder.values()) {
+ builder.build(golden, m);
+ int[] test = golden.clone();
+
+ for (PrimitiveTypeConverter converter : PrimitiveTypeConverter.values()) {
+ Object convertedGolden = converter.convert(golden);
+ Object convertedTest = converter.convert(test);
+ sort(convertedTest);
+ checkSorted(convertedTest);
+ assertEquals(checkSum(convertedGolden), checkSum(convertedTest));
+ }
+ }
+ }
+ }
+ }
+
+ private void sort(Object array) {
+ if (array instanceof int[]) {
+ Arrays.sort((int[]) array);
+ }
+ else if (array instanceof long[]) {
+ Arrays.sort((long[]) array);
+ } else if (array instanceof short[]) {
+ Arrays.sort((short[]) array);
+ } else if (array instanceof byte[]) {
+ Arrays.sort((byte[]) array);
+ } else if (array instanceof char[]) {
+ Arrays.sort((char[]) array);
+ } else if (array instanceof float[]) {
+ Arrays.sort((float[]) array);
+ } else if (array instanceof double[]) {
+ Arrays.sort((double[]) array);
+ } else {
+ fail("Unknow type of array: " + array.getClass());
+ }
+ }
+
+ private void checkSorted(Object array) {
+ if (array instanceof int[]) {
+ checkSorted((int[]) array);
+ } else if (array instanceof long[]) {
+ checkSorted((long[]) array);
+ } else if (array instanceof short[]) {
+ checkSorted((short[]) array);
+ } else if (array instanceof byte[]) {
+ checkSorted((byte[]) array);
+ } else if (array instanceof char[]) {
+ checkSorted((char[]) array);
+ } else if (array instanceof float[]) {
+ checkSorted((float[]) array);
+ } else if (array instanceof double[]) {
+ checkSorted((double[]) array);
+ } else {
+ fail("Unknow type of array: " + array.getClass());
+ }
+ }
+
+ private void checkSorted(int[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(long[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(short[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(byte[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(char[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(float[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+ private void checkSorted(double[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ if (a[i] > a[i + 1]) {
+ orderFail(i, "" + a[i], "" + a[i + 1]);
+ }
+ }
+ }
+
+
+ private void orderFail(int index, String value1, String value2) {
+ fail("Array is not sorted at " + index + "-th position: " + value1 + " and " + value2);
+ }
+
+ private int checkSum(Object array) {
+ if (array instanceof int[]) {
+ return checkSum((int[]) array);
+ } else if (array instanceof long[]) {
+ return checkSum((long[]) array);
+ } else if (array instanceof short[]) {
+ return checkSum((short[]) array);
+ } else if (array instanceof byte[]) {
+ return checkSum((byte[]) array);
+ } else if (array instanceof char[]) {
+ return checkSum((char[]) array);
+ } else if (array instanceof float[]) {
+ return checkSum((float[]) array);
+ } else if (array instanceof double[]) {
+ return checkSum((double[]) array);
+ } else {
+ fail("Unknow type of array: " + array.getClass());
+ }
+ throw new AssertionError(); // Needed to shut up compiler
+ }
+
+ private int checkSum(int[] a) {
+ int checkSum = 0;
+
+ for (int e : a) {
+ checkSum ^= e; // xor
+ }
+ return checkSum;
+ }
+
+ private int checkSum(long[] a) {
+ long checkSum = 0;
+
+ for (long e : a) {
+ checkSum ^= e; // xor
+ }
+ return (int) checkSum;
+ }
+
+ private int checkSum(short[] a) {
+ short checkSum = 0;
+
+ for (short e : a) {
+ checkSum ^= e; // xor
+ }
+ return (int) checkSum;
+ }
+
+ private int checkSum(byte[] a) {
+ byte checkSum = 0;
+
+ for (byte e : a) {
+ checkSum ^= e; // xor
+ }
+ return (int) checkSum;
+ }
+
+ private int checkSum(char[] a) {
+ char checkSum = 0;
+
+ for (char e : a) {
+ checkSum ^= e; // xor
+ }
+ return (int) checkSum;
+ }
+
+ private int checkSum(float[] a) {
+ int checkSum = 0;
+
+ for (float e : a) {
+ checkSum ^= (int) e; // xor
+ }
+ return checkSum;
+ }
+
+ private int checkSum(double[] a) {
+ int checkSum = 0;
+
+ for (double e : a) {
+ checkSum ^= (int) e; // xor
+ }
+ return checkSum;
+ }
+
+ private enum PrimitiveTypeArrayBuilder {
+
+ RANDOM {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = ourRandom.nextInt();
+ }
+ }
+ },
+
+ ASCENDING {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = m + i;
+ }
+ }
+ },
+
+ DESCENDING {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = a.length - m - i;
+ }
+ }
+ },
+
+ ALL_EQUAL {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = m;
+ }
+ }
+ },
+
+ SAW {
+ void build(int[] a, int m) {
+ int incCount = 1;
+ int decCount = a.length;
+ int i = 0;
+ int period = m;
+ m--;
+
+ while (true) {
+ for (int k = 1; k <= period; k++) {
+ if (i >= a.length) {
+ return;
+ }
+ a[i++] = incCount++;
+ }
+ period += m;
+
+ for (int k = 1; k <= period; k++) {
+ if (i >= a.length) {
+ return;
+ }
+ a[i++] = decCount--;
+ }
+ period += m;
+ }
+ }
+ },
+
+ REPEATED {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = i % m;
+ }
+ }
+ },
+
+ DUPLICATED {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = ourRandom.nextInt(m);
+ }
+ }
+ },
+
+ ORGAN_PIPES {
+ void build(int[] a, int m) {
+ int middle = a.length / (m + 1);
+
+ for (int i = 0; i < middle; i++) {
+ a[i] = i;
+ }
+ for (int i = middle; i < a.length ; i++) {
+ a[i] = a.length - i - 1;
+ }
+ }
+ },
+
+ STAGGER {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = (i * m + i) % a.length;
+ }
+ }
+ },
+
+ PLATEAU {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = Math.min(i, m);
+ }
+ }
+ },
+
+ SHUFFLE {
+ void build(int[] a, int m) {
+ for (int i = 0; i < a.length; i++) {
+ a[i] = ourRandom.nextBoolean() ? (ourFirst += 2) : (ourSecond += 2);
+ }
+ }
+ };
+
+ abstract void build(int[] a, int m);
+
+ static void reset() {
+ ourRandom = new Random(666);
+ ourFirst = 0;
+ ourSecond = 0;
+ }
+
+ @Override
+ public String toString() {
+ String name = name();
+
+ for (int i = name.length(); i < 12; i++) {
+ name += " " ;
+ }
+ return name;
+ }
+
+ private static int ourFirst;
+ private static int ourSecond;
+ private static Random ourRandom = new Random(666);
+ }
+
+ private enum PrimitiveTypeConverter {
+
+ INT {
+ Object convert(int[] a) {
+ return a;
+ }
+ },
+
+ LONG {
+ Object convert(int[] a) {
+ long[] b = new long[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (int) a[i];
+ }
+ return b;
+ }
+ },
+
+ BYTE {
+ Object convert(int[] a) {
+ byte[] b = new byte[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (byte) a[i];
+ }
+ return b;
+ }
+ },
+
+ SHORT {
+ Object convert(int[] a) {
+ short[] b = new short[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (short) a[i];
+ }
+ return b;
+ }
+ },
+
+ CHAR {
+ Object convert(int[] a) {
+ char[] b = new char[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (char) a[i];
+ }
+ return b;
+ }
+ },
+
+ FLOAT {
+ Object convert(int[] a) {
+ float[] b = new float[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (float) a[i];
+ }
+ return b;
+ }
+ },
+
+ DOUBLE {
+ Object convert(int[] a) {
+ double[] b = new double[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ b[i] = (double) a[i];
+ }
+ return b;
+ }
+ };
+
+ abstract Object convert(int[] a);
+
+ public String toString() {
+ String name = name();
+
+ for (int i = name.length(); i < 9; i++) {
+ name += " " ;
+ }
+ return name;
+ }
+ }
+
+
+ /**
+ * java.util.Arrays#deepEquals(Object[], Object[])
+ */
+ 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));
+ }
+
+ /**
+ * java.util.Arrays#deepHashCode(Object[])
+ */
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(boolean[] a)
+ */
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(int[] a)
+ */
+ 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));
+ }
+
+ /**
+ * java.util.Arrays#hashCode(char[] a)
+ */
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(byte[] a)
+ */
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(long[] a)
+ */
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(float[] a)
+ */
+ 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));
+ }
+
+ /**
+ * java.util.Arrays#hashCode(double[] a)
+ */
+ public void test_hashCode$LD() {
+ int listHashCode;
+ int arrayHashCode;
+
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(short[] a)
+ */
+ public void test_hashCode$LS() {
+ int listHashCode;
+ int arrayHashCode;
+
+ 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);
+ }
+
+ /**
+ * java.util.Arrays#hashCode(Object[] a)
+ */
+ 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() {
+ objArray = new Object[arraySize];
+ for (int i = 0; i < objArray.length; i++)
+ objArray[i] = new Integer(i);
+
+ 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];
+
+ 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;
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(byte[], int, int, byte)
+ */
+ public void test_binarySearch$BIIB() {
+ for (byte counter = 0; counter < arraySize; counter++) {
+ assertTrue(
+ "Binary search on byte[] answered incorrect position",
+ Arrays.binarySearch(byteArray, counter, arraySize, counter) == counter);
+ }
+ assertEquals(
+ "Binary search succeeded for value not present in array 1", -1,
+ Arrays.binarySearch(byteArray, 0, arraySize, (byte) -1));
+ assertTrue(
+ "Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(byteArray, (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, counter, arraySize,
+ (byte) (counter - 50)) == counter);
+ }
+ try {
+ Arrays.binarySearch((byte[]) null, 2, 1, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((byte[]) null, -1, 0, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((byte[]) null, -1, -2, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(byteArray, 2, 1, (byte) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays.binarySearch(byteArray, 0, 0, (byte) arraySize));
+ try {
+ Arrays.binarySearch(byteArray, -1, -2, (byte) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(byteArray, arraySize + 2, arraySize + 1,
+ (byte) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(byteArray, -1, 0, (byte) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(byteArray, 0, arraySize + 1, (byte) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(char[], char)
+ */
+ public void test_binarySearch$CIIC() {
+ for (char counter = 0; counter < arraySize; counter++) {
+ assertTrue("Binary search on char[] answered incorrect position",
+ Arrays.binarySearch(charArray, counter, arraySize,
+ (char) (counter + 1)) == counter);
+ }
+ assertEquals(
+ "Binary search succeeded for value not present in array 1", -1,
+ Arrays.binarySearch(charArray, 0, arraySize, '\u0000'));
+ assertTrue("Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(charArray, 0, arraySize,
+ (char) (arraySize + 1)) == -(arraySize + 1));
+ try {
+ Arrays.binarySearch(charArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((char[]) null, 2, 1, (char) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((char[]) null, -1, 0, (char) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((char[]) null, -1, -2, (char) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays.binarySearch(charArray, 0, 0, (char) arraySize));
+ try {
+ Arrays.binarySearch(charArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(charArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(charArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(charArray, 0, arraySize + 1, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(double[], double)
+ */
+ public void test_binarySearch$DIID() {
+ for (int counter = 0; counter < arraySize; counter++) {
+ assertTrue("Binary search on double[] answered incorrect position",
+ Arrays.binarySearch(doubleArray, counter, arraySize,
+ (double) counter) == (double) counter);
+ }
+ assertEquals(
+ "Binary search succeeded for value not present in array 1", -1,
+ Arrays.binarySearch(doubleArray, 0, arraySize, (double) -1));
+ assertTrue("Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(doubleArray, 0, arraySize,
+ (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, counter, arraySize, (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, i, specials.length, specials[i]);
+ assertTrue(specials[i] + " invalid: " + result, result == i);
+ }
+ assertEquals("-1d", -4, Arrays.binarySearch(specials, 0, specials.length, -1d));
+ assertEquals("1d", -8, Arrays.binarySearch(specials, 0, specials.length, 1d));
+ try {
+ Arrays.binarySearch((double[]) null, 2, 1, (double) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((double[]) null, -1, 0, (double) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((double[]) null, -1, -2, (double) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(doubleArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays.binarySearch(doubleArray, 0, 0, (char) arraySize));
+ try {
+ Arrays.binarySearch(doubleArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(doubleArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(doubleArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(doubleArray, 0, arraySize + 1, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(float[], float)
+ */
+ public void test_binarySearch$FIIF() {
+ for (int counter = 0; counter < arraySize; counter++) {
+ assertTrue("Binary search on float[] answered incorrect position",
+ Arrays.binarySearch(floatArray, counter, arraySize,
+ (float) counter) == (float) counter);
+ }
+ assertEquals(
+ "Binary search succeeded for value not present in array 1", -1,
+ Arrays.binarySearch(floatArray, 0, arraySize, (float) -1));
+ assertTrue("Binary search succeeded for value not present in array 2",
+ Arrays
+ .binarySearch(floatArray, 0, arraySize,
+ (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, 0, arraySize,
+ (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, i, specials.length, specials[i]);
+ assertTrue(specials[i] + " invalid: " + result, result == i);
+ }
+ assertEquals("-1f", -4, Arrays.binarySearch(specials, 0, specials.length, -1f));
+ assertEquals("1f", -8, Arrays.binarySearch(specials, 0, specials.length, 1f));
+ try {
+ Arrays.binarySearch((float[]) null, 2, 1, (float) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((float[]) null, -1, 0, (float) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((float[]) null, -1, -2, (float) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(floatArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays.binarySearch(floatArray, 0, 0,
+ (char) arraySize));
+ try {
+ Arrays.binarySearch(floatArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(floatArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(floatArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays
+ .binarySearch(floatArray, 0, arraySize + 1,
+ (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(int[], int)
+ */
+ public void test_binarySearch$IIII() {
+ for (int counter = 0; counter < arraySize; counter++) {
+ assertTrue(
+ "Binary search on int[] answered incorrect position",
+ Arrays.binarySearch(intArray, counter, arraySize, counter) == counter);
+ }
+ assertEquals(
+ "Binary search succeeded for value not present in array 1", -1,
+ Arrays.binarySearch(intArray, 0, arraySize, -1));
+ assertTrue("Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(intArray, 0, arraySize, 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, 0, arraySize, counter - 50) == counter);
+ }
+ try {
+ Arrays.binarySearch((int[]) null, 2, 1, (int) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((int[]) null, -1, 0, (int) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((int[]) null, -1, -2, (int) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(intArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays
+ .binarySearch(intArray, 0, 0, (char) arraySize));
+ try {
+ Arrays.binarySearch(intArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(intArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(intArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(intArray, 0, arraySize + 1, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(long[], long)
+ */
+ public void test_binarySearch$JIIJ() {
+ for (long counter = 0; counter < arraySize; counter++) {
+ assertTrue("Binary search on long[] answered incorrect position",
+ Arrays.binarySearch(longArray, 0, arraySize, counter) == counter);
+ }
+ assertEquals("Binary search succeeded for value not present in array 1",
+ -1, Arrays.binarySearch(longArray, 0, arraySize, (long) -1));
+ assertTrue(
+ "Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(longArray, 0, arraySize, (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, 0, arraySize, counter - (long) 50) == counter);
+ }
+ try {
+ Arrays.binarySearch((long[]) null, 2, 1, (long) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((long[]) null, -1, 0, (long) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((long[]) null, -1, -2, (long) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(longArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays
+ .binarySearch(longArray, 0, 0, (char) arraySize));
+ try {
+ Arrays.binarySearch(longArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(longArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(longArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(longArray, 0, arraySize + 1, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(java.lang.Object[],
+ *java.lang.Object)
+ */
+ public void test_binarySearch$Ljava_lang_ObjectIILjava_lang_Object() {
+ assertEquals(
+ "Binary search succeeded for non-comparable value in empty array",
+ -1, Arrays.binarySearch(new Object[] { }, 0, 0, new Object()));
+ assertEquals(
+ "Binary search succeeded for comparable value in empty array",
+ -1, Arrays.binarySearch(new Object[] { }, 0, 0, new Integer(-1)));
+ for (int counter = 0; counter < arraySize; counter++) {
+ assertTrue(
+ "Binary search on Object[] answered incorrect position",
+ Arrays.binarySearch(objectArray, counter, arraySize, objArray[counter]) == counter);
+ }
+ assertEquals("Binary search succeeded for value not present in array 1",
+ -1, Arrays.binarySearch(objectArray, 0, arraySize, new Integer(-1)));
+ assertTrue(
+ "Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(objectArray, 0, arraySize, new Integer(arraySize)) == -(arraySize + 1));
+ try {
+ Arrays.binarySearch((Object[]) null, 2, 1, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((Object[]) null, -1, 0, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((Object[]) null, -1, -2, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, 2, 1, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays
+ .binarySearch(objectArray, 0, 0, (char) arraySize));
+ try {
+ Arrays.binarySearch(objectArray, -1, -2, (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, arraySize + 2, arraySize + 1,
+ (char) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, -1, 0, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, 0, arraySize + 1, (char) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(java.lang.Object[],
+ *java.lang.Object, java.util.Comparator)
+ */
+ public void test_binarySearch$Ljava_lang_ObjectIILjava_lang_ObjectLjava_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, 0, arraySize, new Integer(-1),
+ comp) == -(arraySize + 1));
+ assertEquals(
+ "Binary search succeeded for value not present in array 2", -1,
+ Arrays.binarySearch(objectArray, 0, arraySize, 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);
+ }
+ try {
+ Arrays.binarySearch((Object[]) null, 2, 1, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((Object[]) null, -1, 0, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((Object[]) null, -1, -2, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, 2, 1, (char) arraySize, comp);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays.binarySearch(objectArray, 0, 0,
+ (char) arraySize, comp));
+ try {
+ Arrays.binarySearch(objectArray, -1, -2, (char) arraySize, comp);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, arraySize + 2, arraySize + 1,
+ (char) arraySize, comp);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, -1, 0, (char) arraySize, comp);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, 0, arraySize + 1,
+ (char) arraySize, comp);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(objectArray, 0, arraySize,
+ new LinkedList(), comp);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Arrays#binarySearch(short[], short)
+ */
+ public void test_binarySearch$SIIS() {
+ for (short counter = 0; counter < arraySize; counter++) {
+ assertTrue("Binary search on short[] answered incorrect position",
+ Arrays.binarySearch(shortArray, counter, arraySize, counter) == counter);
+ }
+ assertEquals("Binary search succeeded for value not present in array 1",
+ -1, Arrays.binarySearch(shortArray, 0, arraySize, (short) -1));
+ assertTrue(
+ "Binary search succeeded for value not present in array 2",
+ Arrays.binarySearch(shortArray, 0, arraySize, (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, counter, arraySize, (short) (counter - 50)) == counter);
+ }
+ try {
+ Arrays.binarySearch((String[]) null, 2, 1, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((String[]) null, -1, 0, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch((String[]) null, -1, -2, (byte) arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(shortArray, 2, 1, (short) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(-1, Arrays
+ .binarySearch(shortArray, 0, 0, (short) arraySize));
+ try {
+ Arrays.binarySearch(shortArray, -1, -2, (short) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(shortArray, arraySize + 2, arraySize + 1,
+ (short) arraySize);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(shortArray, -1, 0, (short) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.binarySearch(shortArray, 0, arraySize + 1, (short) arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ String[] array = { "a", "b", "c" };
+ assertEquals(-2, Arrays.binarySearch(array, 1, 2, "a", null));
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(byte[], int)
+ */
+ public void test_copyOf_$BI() throws Exception {
+ byte[] result = Arrays.copyOf(byteArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOf(byteArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ try {
+ Arrays.copyOf((byte[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(byteArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((byte[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(short[], int)
+ */
+ public void test_copyOf_$SI() throws Exception {
+ short[] result = Arrays.copyOf(shortArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOf(shortArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ try {
+ Arrays.copyOf((short[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(shortArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((short[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(int[], int)
+ */
+ public void test_copyOf_$II() throws Exception {
+ int[] result = Arrays.copyOf(intArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOf(intArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ try {
+ Arrays.copyOf((int[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(intArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((int[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(boolean[], int)
+ */
+ public void test_copyOf_$ZI() throws Exception {
+ boolean[] result = Arrays.copyOf(booleanArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(booleanArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(false, result[i]);
+ }
+ result = Arrays.copyOf(booleanArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(booleanArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((boolean[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(booleanArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((boolean[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(char[], int)
+ */
+ public void test_copyOf_$CI() throws Exception {
+ char[] result = Arrays.copyOf(charArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i + 1, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOf(charArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i + 1, result[i]);
+ }
+ try {
+ Arrays.copyOf((char[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(charArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((char[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(float[], int)
+ */
+ public void test_copyOf_$FI() throws Exception {
+ float[] result = Arrays.copyOf(floatArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(floatArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0.0f, result[i]);
+ }
+ result = Arrays.copyOf(floatArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(floatArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((float[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(floatArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((float[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(double[], int)
+ */
+ public void test_copyOf_$DI() throws Exception {
+ double[] result = Arrays.copyOf(doubleArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(doubleArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0.0, result[i]);
+ }
+ result = Arrays.copyOf(doubleArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(doubleArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((double[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(doubleArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((double[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(long[], int)
+ */
+ public void test_copyOf_$JI() throws Exception {
+ long[] result = Arrays.copyOf(longArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(longArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOf(longArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(longArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((long[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(longArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((long[]) null, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(T[], int)
+ */
+ public void test_copyOf_$TI() throws Exception {
+ Object[] result = Arrays.copyOf(objArray, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertNull(result[i]);
+ }
+ result = Arrays.copyOf(objArray, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((String[]) null, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(objArray, -1);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((String[]) null, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Date[] component = new Date[0];
+ Object object[] = new Date[0];
+
+ object = Arrays.copyOf(component, 2);
+ assertNotNull(object);
+ component = Arrays.copyOf(component, 2);
+ assertNotNull(component);
+ assertEquals(2, component.length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOf(T[], int, Class<? extends Object[]>))
+ */
+ public void test_copyOf_$TILClass() throws Exception {
+ Object[] result = Arrays.copyOf(objArray, arraySize * 2, Object[].class);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertNull(result[i]);
+ }
+ result = Arrays.copyOf(objArray, arraySize / 2, Object[].class);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ result = Arrays.copyOf(objArray, arraySize / 2, Integer[].class);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ try {
+ Arrays.copyOf((Object[]) null, arraySize, LinkedList[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(objArray, arraySize, LinkedList[].class);
+ fail("should throw ArrayStoreException ");
+ } catch (ArrayStoreException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((Object[]) null, arraySize, Object[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf(objArray, -1, Object[].class);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((Object[]) null, -1, Object[].class);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((Object[]) null, -1, LinkedList[].class);
+ fail("should throw NegativeArraySizeException");
+ } catch (NegativeArraySizeException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOf((Object[]) null, 0, LinkedList[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertEquals(0, Arrays.copyOf(objArray, 0, LinkedList[].class).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(byte[], int, int)
+ */
+ public void test_copyOfRange_$BII() throws Exception {
+ byte[] result = Arrays.copyOfRange(byteArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOfRange(byteArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ result = Arrays.copyOfRange(byteArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((byte[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((byte[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((byte[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(byteArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(byteArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(byteArray.length + 1, Arrays.copyOfRange(byteArray, 0,
+ byteArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(short[], int, int)
+ */
+ public void test_copyOfRange_$SII() throws Exception {
+ short[] result = Arrays.copyOfRange(shortArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOfRange(shortArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ result = Arrays.copyOfRange(shortArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((short[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((short[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((short[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(shortArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(shortArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(shortArray.length + 1, Arrays.copyOfRange(shortArray, 0,
+ shortArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(int[], int, int)
+ */
+ public void test_copyOfRange_$III() throws Exception {
+ int[] result = Arrays.copyOfRange(intArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOfRange(intArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ result = Arrays.copyOfRange(intArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((int[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((int[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((int[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(intArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(intArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(intArray.length + 1, Arrays.copyOfRange(intArray, 0,
+ intArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(long[], int, int)
+ */
+ public void test_copyOfRange_$JII() throws Exception {
+ long[] result = Arrays.copyOfRange(longArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOfRange(longArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i, result[i]);
+ }
+ result = Arrays.copyOfRange(longArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((long[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((long[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((long[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(longArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(longArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(longArray.length + 1, Arrays.copyOfRange(longArray, 0,
+ longArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(char[], int, int)
+ */
+ public void test_copyOfRange_$CII() throws Exception {
+ char[] result = Arrays.copyOfRange(charArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(i + 1, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0, result[i]);
+ }
+ result = Arrays.copyOfRange(charArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(i + 1, result[i]);
+ }
+ result = Arrays.copyOfRange(charArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((char[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((char[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((char[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(charArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(charArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(charArray.length + 1, Arrays.copyOfRange(charArray, 0,
+ charArray.length + 1).length);
+ }
+
+ public void test_copyOfRange_$FII() throws Exception {
+ float[] result = Arrays.copyOfRange(floatArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals((float) i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0.0f, result[i]);
+ }
+ result = Arrays.copyOfRange(floatArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals((float) i, result[i]);
+ }
+ result = Arrays.copyOfRange(floatArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((float[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((float[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((float[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(floatArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(floatArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(floatArray.length + 1, Arrays.copyOfRange(floatArray, 0,
+ floatArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(double[], int, int)
+ */
+ public void test_copyOfRange_$DII() throws Exception {
+ double[] result = Arrays.copyOfRange(doubleArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals((double) i, result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(0.0, result[i]);
+ }
+ result = Arrays.copyOfRange(doubleArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals((double) i, result[i]);
+ }
+ result = Arrays.copyOfRange(doubleArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((double[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((double[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((double[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(doubleArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(doubleArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(doubleArray.length + 1, Arrays.copyOfRange(doubleArray, 0,
+ doubleArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(boolean[], int, int)
+ */
+ public void test_copyOfRange_$ZII() throws Exception {
+ boolean[] result = Arrays.copyOfRange(booleanArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(booleanArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(false, result[i]);
+ }
+ result = Arrays.copyOfRange(booleanArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(booleanArray[i], result[i]);
+ }
+ result = Arrays.copyOfRange(booleanArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((boolean[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((boolean[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((boolean[]) null, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(booleanArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(booleanArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(booleanArray.length + 1, Arrays.copyOfRange(booleanArray, 0,
+ booleanArray.length + 1).length);
+ }
+
+ /**
+ * {@link java.util.Arrays#copyOfRange(Object[], int, int)
+ */
+ public void test_copyOfRange_$TII() throws Exception {
+ Object[] result = Arrays.copyOfRange(objArray, 0, arraySize * 2);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(null, result[i]);
+ }
+ result = Arrays.copyOfRange(objArray, 0, arraySize / 2);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ result = Arrays.copyOfRange(objArray, 0, 0);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange((Object[]) null, 0, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((Object[]) null, -1, arraySize);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((Object[]) null, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((Object[]) objArray, -1, arraySize);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange((Object[]) objArray, 0, -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(objArray.length + 1, Arrays.copyOfRange(objArray, 0,
+ objArray.length + 1).length);
+ }
+
+ public void test_copyOfRange_$TIILClass() throws Exception {
+ Object[] result = Arrays.copyOfRange(objArray, 0, arraySize * 2, Integer[].class);
+ int i = 0;
+ for (; i < arraySize; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ for (; i < result.length; i++) {
+ assertEquals(null, result[i]);
+ }
+ result = Arrays.copyOfRange(objArray, 0, arraySize / 2, Integer[].class);
+ i = 0;
+ for (; i < result.length; i++) {
+ assertEquals(objArray[i], result[i]);
+ }
+ result = Arrays.copyOfRange(objArray, 0, 0, Integer[].class);
+ assertEquals(0, result.length);
+ try {
+ Arrays.copyOfRange(null, 0, arraySize, Integer[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(null, -1, arraySize, Integer[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(null, 0, -1, Integer[].class);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(objArray, -1, arraySize, Integer[].class);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(objArray, 0, -1, Integer[].class);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(objArray, 0, -1, LinkedList[].class);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(objArray, 0, 1, LinkedList[].class);
+ fail("should throw ArrayStoreException");
+ } catch (ArrayStoreException e) {
+ // expected
+ }
+ try {
+ Arrays.copyOfRange(null, 0, 1, LinkedList[].class);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ assertEquals(objArray.length + 1, Arrays.copyOfRange(objArray, 0,
+ objArray.length + 1, LinkedList[].class).length);
+ fail("should throw ArrayStoreException");
+ } catch (ArrayStoreException e) {
+ // expected
+ }
+ assertEquals(0,
+ Arrays.copyOfRange(objArray, 0, 0, LinkedList[].class).length);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ objArray = null;
+ booleanArray = null;
+ byteArray = null;
+ charArray = null;
+ doubleArray = null;
+ floatArray = null;
+ intArray = null;
+ longArray = null;
+ objectArray = null;
+ shortArray = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/BitSetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/BitSetTest.java
new file mode 100644
index 0000000..96ffccc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/BitSetTest.java
@@ -0,0 +1,1361 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.BitSet;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class BitSetTest extends junit.framework.TestCase {
+
+ BitSet eightbs;
+
+ public void test_Constructor() {
+ BitSet bs = new BitSet();
+ // Default size for a BitSet should be 64 elements;
+ assertEquals("Created BitSet of incorrect size", 64, bs.size());
+ assertEquals("New BitSet had invalid string representation", "{}", bs
+ .toString());
+ }
+
+ public void test_ConstructorI() {
+ BitSet bs = new BitSet(128);
+ // Default size for a BitSet should be 64 elements;
+
+ assertEquals("Created 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();
+ } catch (NegativeArraySizeException expected) {
+ }
+ }
+
+ public void test_clone() {
+ BitSet bs = (BitSet) eightbs.clone();
+ assertTrue("Clone failed to return equal BitSet", eightbs.equals(bs));
+ }
+
+ 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));
+ // Grow the BitSet
+ 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));
+ }
+
+ public void test_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());
+ }
+
+ public void test_clear() {
+ eightbs.clear();
+ for (int i = 0; i < 8; i++) {
+ assertTrue("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());
+ }
+
+ public void test_clearI() {
+ 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 expected out of bounds exception");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ 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());
+
+ bs = new BitSet();
+ try {
+ bs.clear(-1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ 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);
+
+ // pos1 and pos2 are in the same bitset element
+ BitSet bs = new BitSet(16);
+ int initialSize = bs.size();
+ assertEquals(64, initialSize);
+ 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, boundary 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bs.clear(2, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ bs.set(2, 4);
+ bs.clear(2, 2);
+ assertTrue("Bit got cleared incorrectly ", bs.get(2));
+
+ try {
+ bs.clear(4, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ 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());
+ }
+
+ public void test_getI() {
+ 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ 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());
+
+ bs = new BitSet();
+ try {
+ bs.get(Integer.MIN_VALUE);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void test_getII() {
+ BitSet bitset = new BitSet(30);
+ bitset.get(3, 3);
+
+ 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());
+
+ try {
+ bs2.get(-1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bs2.get(bs2.size()/2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bs2.get(bs2.size()/2, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_setI() {
+ BitSet bs = new BitSet();
+ bs.set(8);
+ assertTrue("Failed to set bit", bs.get(8));
+
+ try {
+ bs.set(-1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // 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());
+ }
+
+ 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));
+
+ try {
+ eightbs.set(-5, false);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ 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);
+ assertEquals("{5, 7, 8, 9, 10, 15}", bs.toString());
+ for (int i = 16; i < bs.size(); i++) {
+ assertFalse("Shouldn't have set bit " + i, bs.get(i));
+ }
+
+ // pos1 and pos2 is in the same bitset element, boundary 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));
+ }
+ assertTrue("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));
+ }
+ assertTrue("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++) {
+ assertTrue("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
+ }
+ }
+
+ 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));
+
+ try {
+ eightbs.set(-3, 6, false);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ eightbs.set(3, -6, false);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ eightbs.set(6, 3, false);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+
+ public void test_flipI() {
+ 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // 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));
+ }
+
+ public void test_flipII() {
+ BitSet bitset = new BitSet();
+ for (int i = 0; i < 20; i++) {
+ bitset.set(i);
+ }
+ bitset.flip(10, 10);
+
+ // 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bs.flip(2, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ bs.flip(4, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_111478() throws Exception {
+ // BitSet shouldn't be modified by any of the operations below,
+ // since the affected bits for these methods are defined as inclusive of
+ // pos1, exclusive of pos2.
+ eightbs.flip(0, 0);
+ assertTrue("Bit got flipped incorrectly ", eightbs.get(0));
+
+ BitSet bsnew = eightbs.get(2, 2);
+ assertEquals(0, bsnew.cardinality());
+
+ eightbs.set(10, 10);
+ assertTrue("Bit got set incorrectly ", !eightbs.get(10));
+
+ eightbs.clear(3, 3);
+ assertTrue("Bit cleared incorrectly ", eightbs.get(3));
+ }
+
+ public void test_intersectsLjava_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));
+ }
+
+ public void test_andLjava_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));
+ }
+
+ bs = new BitSet(64);
+ try {
+ bs.and(null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ 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());
+
+ bs = new BitSet(64);
+ try {
+ bs.andNot(null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // Regression test for HARMONY-4213
+ bs = new BitSet(256);
+ bs2 = new BitSet(256);
+ bs.set(97);
+ bs2.set(37);
+ bs.andNot(bs2);
+ assertTrue("Incorrect value at 97 pos", bs.get(97));
+ }
+
+ public void test_orLjava_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);
+ assertTrue("OR set a bit which should be off", !bs.get(5));
+ }
+
+ public void test_xorLjava_util_BitSet() {
+ BitSet bs = (BitSet) eightbs.clone();
+ bs.xor(eightbs);
+ for (int i = 0; i < 8; i++) {
+ assertTrue("XOR failed to clear bit " + i + bs, !bs.get(i));
+ }
+ bs.xor(eightbs);
+ for (int i = 0; i < 8; i++) {
+ assertTrue("XOR failed to set bit " + i + bs, bs.get(i));
+ }
+ bs = new BitSet(0);
+ bs.xor(eightbs);
+ for (int i = 0; i < 8; i++) {
+ assertTrue("XOR(0) failed to set bit " + i + bs, bs.get(i));
+ }
+ bs = new BitSet();
+ bs.set(63);
+ assertEquals("{63}", bs.toString());
+ }
+
+ public void test_size() {
+ assertEquals("Returned incorrect size", 64, eightbs.size());
+ eightbs.set(129);
+ assertTrue("Returned incorrect size", eightbs.size() >= 129);
+
+ }
+
+ public void test_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());
+ }
+
+ public void test_length() {
+ BitSet bs = new BitSet();
+ assertEquals(bs.toString(), 0, bs.length());
+ bs.set(5);
+ assertEquals(bs.toString(), 6, bs.length());
+ bs.set(10);
+ assertEquals(bs.toString(), 11, bs.length());
+ bs.set(432);
+ assertEquals(bs.toString(), 433, bs.length());
+ bs.set(300);
+ assertEquals(bs.toString(), 433, bs.length());
+ }
+
+ public void test_nextSetBitI() {
+ 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(5, bs.nextSetBit(0));
+ assertEquals(5, bs.nextSetBit(5));
+ assertEquals(32, bs.nextSetBit(6));
+ assertEquals(32, bs.nextSetBit(32));
+ assertEquals(63, bs.nextSetBit(33));
+
+ // boundary tests
+ assertEquals(63, bs.nextSetBit(63));
+ assertEquals(64, bs.nextSetBit(64));
+
+ // at bitset element 1
+ assertEquals(71, bs.nextSetBit(65));
+ assertEquals(71, bs.nextSetBit(71));
+ assertEquals(72, bs.nextSetBit(72));
+ assertEquals(127, bs.nextSetBit(110));
+
+ // boundary tests
+ assertEquals(127, bs.nextSetBit(127));
+ assertEquals(128, bs.nextSetBit(128));
+
+ // at bitset element 2
+ assertEquals(193, bs.nextSetBit(130));
+
+ assertEquals(193, bs.nextSetBit(191));
+ assertEquals(193, bs.nextSetBit(192));
+ assertEquals(193, bs.nextSetBit(193));
+ assertEquals(450, bs.nextSetBit(194));
+ assertEquals(450, bs.nextSetBit(255));
+ assertEquals(450, bs.nextSetBit(256));
+ assertEquals(450, bs.nextSetBit(450));
+
+ assertEquals(-1, bs.nextSetBit(451));
+ assertEquals(-1, bs.nextSetBit(511));
+ assertEquals(-1, bs.nextSetBit(512));
+ assertEquals(-1, bs.nextSetBit(800));
+ }
+
+ public void test_nextClearBitI() {
+ BitSet bs = new BitSet(500);
+ // ensure all the bits from 0 to bs.size() - 1 are set to true
+ bs.set(0, bs.size() - 1);
+ bs.set(bs.size() - 1);
+ 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();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(5, bs.nextClearBit(0));
+ assertEquals(5, bs.nextClearBit(5));
+ assertEquals(32, bs.nextClearBit(6));
+ assertEquals(32, bs.nextClearBit(32));
+ assertEquals(63, bs.nextClearBit(33));
+
+ // boundary tests
+ assertEquals(63, bs.nextClearBit(63));
+ assertEquals(64, bs.nextClearBit(64));
+
+ // at bitset element 1
+ assertEquals(71, bs.nextClearBit(65));
+ assertEquals(71, bs.nextClearBit(71));
+ assertEquals(72, bs.nextClearBit(72));
+ assertEquals(127, bs.nextClearBit(110));
+
+ // boundary tests
+ assertEquals(127, bs.nextClearBit(127));
+ assertEquals(128, bs.nextClearBit(128));
+
+ // at bitset element 2
+ assertEquals(193, bs.nextClearBit(130));
+ assertEquals(193, bs.nextClearBit(191));
+
+ assertEquals(193, bs.nextClearBit(192));
+ assertEquals(193, bs.nextClearBit(193));
+ assertEquals(450, bs.nextClearBit(194));
+ assertEquals(450, bs.nextClearBit(255));
+ assertEquals(450, bs.nextClearBit(256));
+ assertEquals(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(512, bs.nextClearBit(451));
+ assertEquals(512, bs.nextClearBit(511));
+ assertEquals(512, bs.nextClearBit(512));
+
+ // if the index is larger than bs.size(), nextClearBit should return index
+ assertEquals(513, bs.nextClearBit(513));
+ assertEquals(800, bs.nextClearBit(800));
+
+ bs.clear();
+ assertEquals(0, bs.nextClearBit(0));
+ assertEquals(3, bs.nextClearBit(3));
+ assertEquals(64, bs.nextClearBit(64));
+ assertEquals(128, bs.nextClearBit(128));
+ }
+
+ // http://code.google.com/p/android/issues/detail?id=31036
+ public void test_31036_clear() {
+ BitSet bs = new BitSet(500);
+ for (int i = 0; i < 500; ++i) {
+ int nextClear = bs.nextClearBit(0);
+ assertEquals(i, nextClear);
+ bs.set(i);
+ }
+ }
+
+ // http://code.google.com/p/android/issues/detail?id=31036
+ public void test_31036_set() {
+ BitSet bs = new BitSet(500);
+ bs.set(0, 511);
+ for (int i = 0; i < 500; ++i) {
+ int nextSet = bs.nextSetBit(0);
+ assertEquals(i, nextSet);
+ bs.clear(i);
+ }
+ }
+
+ 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());
+ }
+
+ public void test_cardinality() {
+ BitSet bs = new BitSet(500);
+ bs.set(5);
+ bs.set(32);
+ bs.set(63);
+ bs.set(64);
+ assertEquals(bs.toString(), 4, bs.cardinality());
+ bs.set(71, 110);
+ bs.set(127, 130);
+ bs.set(193);
+ bs.set(450);
+ assertEquals(bs.toString(), 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());
+
+ bs.clear();
+ bs.set(0, 64);
+ assertEquals("cardinality() returned wrong value", 64, bs.cardinality());
+ }
+
+ public void test_serialization() throws Exception {
+ 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);
+ SerializationTest.verifySelf(bs);
+ }
+
+
+ protected void setUp() {
+ eightbs = new BitSet();
+ for (int i = 0; i < 8; i++) {
+ eightbs.set(i);
+ }
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CalendarTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CalendarTest.java
new file mode 100644
index 0000000..06a37c8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CalendarTest.java
@@ -0,0 +1,1099 @@
+/*
+ * 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.tests.java.util;
+
+import java.text.DateFormatSymbols;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TimeZone;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class CalendarTest extends junit.framework.TestCase {
+
+ Locale defaultLocale;
+
+ /**
+ * java.util.Calendar#set(int, int)
+ */
+ public void test_setII() {
+ // Test for correct result defined by the last set field
+ Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ assertTrue("Incorrect result 0: " + cal.getTime().getTime(), cal
+ .getTime().getTime() == 1009861200000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ assertTrue("Incorrect result 0a: " + cal.getTime(), cal.getTime()
+ .getTime() == 1014958800000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 24);
+ assertTrue("Incorrect result 0b: " + cal.getTime(), cal.getTime()
+ .getTime() == 1011848400000L);
+
+ cal.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal.set(Calendar.DATE, 31);
+ cal.set(Calendar.MONTH, Calendar.NOVEMBER);
+ cal.set(Calendar.DATE, 26);
+ assertTrue("Incorrect month: " + cal.get(Calendar.MONTH), cal
+ .get(Calendar.MONTH) == Calendar.NOVEMBER);
+
+ int dow = cal.get(Calendar.DAY_OF_WEEK);
+ cal.set(Calendar.DATE, 27);
+ assertTrue("Incorrect DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK)
+ + " expected: " + dow, cal.get(Calendar.DAY_OF_WEEK) != dow);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 0c1: " + cal.getTime().getTime(), cal
+ .getTime().getTime() == 1010379600000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
+ assertTrue("Incorrect result 0c2: " + cal.getTime().getTime(), cal
+ .getTime().getTime() == 1009861200000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
+ assertTrue("Incorrect result 0c3: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010034000000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_MONTH, 2);
+ assertTrue("Incorrect result 0d: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010293200000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
+ assertTrue("Incorrect result 0e: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010898000000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ assertTrue("Incorrect result 0f: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015736400000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 24);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ assertTrue("Incorrect result 0g: " + cal.getTime(), cal.getTime()
+ .getTime() == 1011848400000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.get(Calendar.WEEK_OF_YEAR); // Force fields to compute
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ assertTrue("Incorrect result 0h: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015909200000L);
+
+ // WEEK_OF_YEAR has priority over MONTH/DATE
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 170);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ cal.set(Calendar.DATE, 5);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 1: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // WEEK_OF_YEAR has priority over MONTH/DATE
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ cal.set(Calendar.DATE, 5);
+ cal.set(Calendar.DAY_OF_YEAR, 170);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 1a: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DAY_OF_WEEK has no effect when other fields not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
+ assertTrue("Incorrect result 1b: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+ // Regression for HARMONY-4384
+ // Set DAY_OF_WEEK without DATE
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
+ assertEquals("Incorrect result 1b: " + cal.getTime(), 1015304400000L, cal.getTime()
+ .getTime());
+
+
+ // WEEK_OF_MONTH has priority
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
+ cal.set(Calendar.WEEK_OF_MONTH, 3);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DATE, 5);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 2: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DAY_OF_WEEK_IN_MONTH has priority over WEEK_OF_YEAR
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DATE, 5);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 3: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // WEEK_OF_MONTH has priority, MONTH not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
+ cal.set(Calendar.WEEK_OF_MONTH, 3);
+ cal.set(Calendar.DATE, 25);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertTrue("Incorrect result 4: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010984400000L);
+
+ // WEEK_OF_YEAR has priority when MONTH set last and DAY_OF_WEEK set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ cal.set(Calendar.DATE, 25);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ assertTrue("Incorrect result 5: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // Use MONTH/DATE when WEEK_OF_YEAR set but not DAY_OF_WEEK
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ assertTrue("Incorrect result 5a: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // Use MONTH/DATE when DAY_OF_WEEK is not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.WEEK_OF_MONTH, 1);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ assertTrue("Incorrect result 5b: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // WEEK_OF_MONTH has priority
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DATE, 5);
+ cal.set(Calendar.WEEK_OF_MONTH, 3);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ assertTrue("Incorrect result 5c: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DATE has priority when set last
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DATE, 11);
+ assertTrue("Incorrect result 6: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DATE has priority when set last, MONTH not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 12);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ cal.set(Calendar.DATE, 14);
+ assertTrue("Incorrect result 7: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010984400000L);
+
+ // DAY_OF_YEAR has priority when MONTH set last and DATE not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 70);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ assertTrue("Incorrect result 8: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DAY/MONTH has priority when DATE set after DAY_OF_YEAR
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 170);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ assertTrue("Incorrect result 8a: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DAY_OF_YEAR has priority when set after DATE
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 15);
+ cal.set(Calendar.DAY_OF_YEAR, 70);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ assertTrue("Incorrect result 8b: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DATE has priority when set last
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 70);
+ cal.set(Calendar.DATE, 14);
+ assertTrue("Incorrect result 9: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010984400000L);
+
+ // DATE has priority when set last
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_YEAR, 15);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
+ cal.set(Calendar.DATE, 14);
+ assertTrue("Incorrect result 9a: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010984400000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ cal.set(Calendar.DATE, 14);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ assertTrue("Incorrect result 9b: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 14);
+ cal.set(Calendar.WEEK_OF_YEAR, 11);
+ assertTrue("Incorrect result 9c: " + cal.getTime(), cal.getTime()
+ .getTime() == 1010984400000L);
+
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.WEEK_OF_MONTH, 1);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DATE, 11);
+ assertTrue("Incorrect result 9d: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // DAY_OF_YEAR has priority when DAY_OF_MONTH set last and other fields
+ // not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 70);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
+ assertTrue("Incorrect result 10: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // MONTH/DATE has priority when DAY_OF_WEEK_IN_MONTH set last but
+ // DAY_OF_WEEK not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
+ assertTrue("Incorrect result 11: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // MONTH/DATE has priority when WEEK_OF_YEAR set last but DAY_OF_WEEK
+ // not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.WEEK_OF_YEAR, 15);
+ assertTrue("Incorrect result 12: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // MONTH/DATE has priority when WEEK_OF_MONTH set last but DAY_OF_WEEK
+ // not set
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DATE, 11);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.WEEK_OF_MONTH, 1);
+ assertTrue("Incorrect result 13: " + cal.getTime(), cal.getTime()
+ .getTime() == 1015822800000L);
+
+ // Ensure last date field set is reset after computing
+ cal.clear();
+ cal.set(Calendar.YEAR, 2002);
+ cal.set(Calendar.DAY_OF_YEAR, 111);
+ cal.get(Calendar.YEAR);
+ cal.set(Calendar.MONTH, Calendar.MARCH);
+ cal.set(Calendar.AM_PM, Calendar.AM);
+ assertTrue("Incorrect result 14: " + cal.getTime(), cal.getTime()
+ .getTime() == 1016686800000L);
+
+ int hour = cal.get(Calendar.HOUR);
+ cal.set(Calendar.HOUR, hour);
+ cal.set(Calendar.AM_PM, Calendar.PM);
+ assertEquals("AM_PM not changed", Calendar.PM, cal.get(Calendar.AM_PM));
+ // setting AM_PM without HOUR should not have any affect
+ cal.set(Calendar.AM_PM, Calendar.AM);
+ assertEquals("AM_PM was changed 1",
+ Calendar.AM, cal.get(Calendar.AM_PM));
+ int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
+ hour = cal.get(Calendar.HOUR);
+ cal.set(Calendar.AM_PM, Calendar.PM);
+ assertEquals("AM_PM was changed 2",
+ Calendar.PM, cal.get(Calendar.AM_PM));
+ assertEquals(hour, cal.get(Calendar.HOUR));
+ assertEquals(hourOfDay + 12, cal.get(Calendar.HOUR_OF_DAY));
+
+ // regression test for Harmony-2122
+ cal = Calendar.getInstance();
+ int oldValue = cal.get(Calendar.AM_PM);
+ int newValue = (oldValue == Calendar.AM) ? Calendar.PM : Calendar.AM;
+ cal.set(Calendar.AM_PM, newValue);
+ newValue = cal.get(Calendar.AM_PM);
+ assertTrue(newValue != oldValue);
+ }
+
+ /**
+ * java.util.Calendar#setTime(java.util.Date)
+ */
+ public void test_setTimeLjava_util_Date() {
+ Calendar cal = Calendar.getInstance();
+ // Use millisecond time for testing in Core
+ cal.setTime(new Date(884581200000L)); // (98, Calendar.JANUARY, 12)
+ assertEquals("incorrect millis", 884581200000L, cal.getTime().getTime());
+ cal.setTimeZone(TimeZone.getTimeZone("EST"));
+ cal.setTime(new Date(943506000000L)); // (99, Calendar.NOVEMBER, 25)
+ assertTrue("incorrect fields", cal.get(Calendar.YEAR) == 1999
+ && cal.get(Calendar.MONTH) == Calendar.NOVEMBER
+ && cal.get(Calendar.DATE) == 25);
+ }
+
+ /**
+ * java.util.Calendar#compareTo(Calendar)
+ */
+ public void test_compareToLjava_util_Calendar_null() {
+ Calendar cal = Calendar.getInstance();
+ try {
+ cal.compareTo(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Calendar#compareTo(Calendar)
+ */
+ public void test_compareToLjava_util_Calendar() {
+ Calendar cal = Calendar.getInstance();
+ cal.clear();
+ cal.set(1997, 12, 13, 23, 57);
+
+ Calendar anotherCal = Calendar.getInstance();
+ anotherCal.clear();
+ anotherCal.set(1997, 12, 13, 23, 57);
+ assertEquals(0, cal.compareTo(anotherCal));
+
+ anotherCal = Calendar.getInstance();
+ anotherCal.clear();
+ anotherCal.set(1997, 11, 13, 24, 57);
+ assertEquals(1, cal.compareTo(anotherCal));
+
+ anotherCal = Calendar.getInstance();
+ anotherCal.clear();
+ anotherCal.set(1997, 12, 13, 23, 58);
+ assertEquals(-1, cal.compareTo(anotherCal));
+ }
+
+ /**
+ * java.util.Calendar#clone()
+ */
+ public void test_clone() {
+ // Regression for HARMONY-475
+ Calendar cal = Calendar.getInstance();
+ cal.set(2006, 5, 6, 11, 35);
+ Calendar anotherCal = (Calendar) cal.clone();
+ // should be deep clone
+ assertNotSame("getTimeZone", cal.getTimeZone(), anotherCal
+ .getTimeZone());
+ }
+
+ /**
+ * java.util.Calendar#getTimeInMillis()
+ */
+ public void test_getTimeInMillis() {
+ Calendar cal = Calendar.getInstance();
+
+ int year = Integer.MIN_VALUE + 71;
+ cal.setTimeZone(TimeZone.getTimeZone("GMT"));
+ cal.set(Calendar.YEAR, year + 1900);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ cal.set(Calendar.DATE, 1);
+ cal.set(Calendar.HOUR_OF_DAY, 0);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+
+ assertEquals(6017546357372606464L, cal.getTimeInMillis());
+ }
+
+ private static final Locale[] locales = new Locale[] { Locale.getDefault(),
+ Locale.US, Locale.UK, Locale.TAIWAN, Locale.PRC, Locale.KOREA,
+ Locale.JAPAN, Locale.ITALIAN, Locale.GERMAN, Locale.ENGLISH,
+ Locale.CHINA, Locale.CANADA, Locale.FRANCE };
+
+ /**
+ * java.util.Calendar#before(Object)
+ * java.util.Calendar#after(Object)
+ */
+ public void test_before_after() {
+ Calendar early = Calendar.getInstance();
+ Calendar late = Calendar.getInstance();
+ // test by second
+ early.set(2008, 3, 20, 17, 28, 12);
+ late.set(2008, 3, 20, 17, 28, 22);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+
+ // test by minute
+ early.set(2008, 3, 20, 17, 18, 12);
+ late.set(2008, 3, 20, 17, 28, 12);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+
+ // test by hour
+ early.set(2008, 3, 20, 17, 28, 12);
+ late.set(2008, 3, 20, 27, 28, 12);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+
+ // test by day
+ early.set(2008, 3, 10, 17, 28, 12);
+ late.set(2008, 3, 20, 17, 28, 12);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+
+ // test by month
+ early.set(2008, 2, 20, 17, 28, 12);
+ late.set(2008, 3, 20, 17, 28, 12);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+
+ // test by year
+ early.set(2007, 3, 20, 17, 28, 12);
+ late.set(2008, 3, 20, 17, 28, 12);
+ // test before()
+ assertTrue(early.before(late));
+ assertFalse(early.before(early));
+ assertFalse(late.before(early));
+ // test after();
+ assertTrue(late.after(early));
+ assertFalse(late.after(late));
+ assertFalse(early.after(late));
+ }
+
+ /**
+ * java.util.Calendar#clear()
+ * java.util.Calendar#clear(int)
+ */
+ public void test_clear() {
+ Calendar calendar = Calendar.getInstance();
+
+ int count = 6;
+ int[] fields = new int[count];
+ int[] defaults = new int[count];
+
+ fields[0] = Calendar.YEAR;
+ fields[1] = Calendar.MONTH;
+ fields[2] = Calendar.DATE;
+ fields[3] = Calendar.HOUR_OF_DAY;
+ fields[4] = Calendar.MINUTE;
+ fields[5] = Calendar.SECOND;
+
+ defaults[0] = 1970;
+ defaults[1] = 0;
+ defaults[2] = 1;
+ defaults[3] = 0;
+ defaults[4] = 0;
+ defaults[5] = 0;
+
+ calendar.set(2008, 3, 20, 17, 28, 12);
+
+ // test clear(int)
+ for (int i = 0; i < fields.length; i++) {
+ int index = fields[i];
+ calendar.clear(index);
+ if (5 == index) {
+ // RI also doesn't change the value of DATE
+ assertEquals("Field " + index + " Should equal to 20.", 20,
+ calendar.get(index));
+ } else if (11 == index) {
+ // RI also doesn't change the value of HOUR
+ assertEquals("Field " + index + " Should equal to 17.", 17,
+ calendar.get(index));
+ } else {
+ // Other have been set to default values
+ assertEquals("Field " + index + " Should equal to "
+ + defaults[i] + ".", defaults[i], calendar.get(index));
+ }
+ }
+
+ // test clear()
+ calendar.set(2008, 3, 20, 17, 28, 12);
+
+ calendar.clear();
+
+ for (int i = 0; i < fields.length; i++) {
+ int index = fields[i];
+ assertEquals("Field " + index + " Should equal to "
+ + defaults[i] + ".", defaults[i], calendar.get(index));
+ }
+ }
+
+ /**
+ * java.util.Calendar#isSet(int)
+ */
+ public void test_isSet() {
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ for (int i = 0; i < Calendar.FIELD_COUNT; i++) {
+ assertFalse(calendar.isSet(i));
+ }
+ }
+
+ /**
+ * java.util.Calendar#getAvailableLocales()
+ */
+ public void test_getAvailableLocales() {
+ Locale[] locales = Calendar.getAvailableLocales();
+ boolean exist = false;
+ for (int i = 0; i < locales.length; i++) {
+ Locale l = locales[i];
+ if (Locale.US.equals(l)) {
+ exist = true;
+ break;
+ }
+ }
+ assertTrue(exist);
+ }
+
+ /**
+ * java.util.Calendar#getInstance(Locale)
+ * java.util.Calendar#getInstance(TimeZone, Locale)
+ */
+ public void test_getInstance() {
+ // test getInstance(Locale)
+ Calendar us_calendar = Calendar.getInstance(Locale.US);
+ Calendar de_calendar = Calendar.getInstance(Locale.GERMAN);
+ assertEquals(Calendar.SUNDAY, us_calendar
+ .getFirstDayOfWeek());
+ assertEquals(Calendar.MONDAY, de_calendar
+ .getFirstDayOfWeek());
+
+ // test getInstance(Locale, TimeZone)
+ Calendar gmt_calendar = Calendar.getInstance(TimeZone
+ .getTimeZone("GMT"), Locale.US);
+ assertEquals(TimeZone.getTimeZone("GMT"),
+ gmt_calendar.getTimeZone());
+ Calendar est_calendar = Calendar.getInstance(TimeZone
+ .getTimeZone("EST"), Locale.US);
+ assertEquals(TimeZone.getTimeZone("EST")
+ .getID(), est_calendar.getTimeZone().getID());
+ }
+
+ /**
+ * java.util.Calendar#internalGet(int)
+ */
+ public void test_internalGet() {
+ MockGregorianCalendar c = new MockGregorianCalendar();
+ c.clear(Calendar.YEAR);
+ assertEquals(0, c.internal_get(Calendar.YEAR));
+ }
+
+ /**
+ * java.util.Calendar#hashCode()
+ */
+ public void test_hashcode() {
+ Calendar calendar = Calendar.getInstance(Locale.JAPAN);
+ assertTrue(calendar.hashCode() == calendar.hashCode());
+ }
+
+ /**
+ * java.util.Calendar#roll(int, int)
+ */
+ public void test_roll() {
+ Calendar calendar = Calendar.getInstance();
+ calendar.set(2008, 3, 20, 17, 28, 12);
+
+ // roll up
+ calendar.roll(Calendar.DATE, 5);
+ assertEquals(25, calendar.get(Calendar.DATE));
+
+ // roll down
+ calendar.roll(Calendar.DATE, -5);
+ assertEquals(20, calendar.get(Calendar.DATE));
+
+ // roll 0
+ calendar.roll(Calendar.DATE, 0);
+ assertEquals(20, calendar.get(Calendar.DATE));
+
+ // roll overweight
+ calendar.set(2008, 1, 31, 17, 28, 12);
+ calendar.roll(Calendar.MONTH, 1);
+ assertEquals(2, calendar.get(Calendar.DATE));
+
+ }
+
+ /**
+ * java.util.Calendar#toString()
+ */
+ public void test_toString() {
+ Calendar calendar = Calendar.getInstance();
+ //Should be the current time with no interrogation in the string.
+ assertTrue(calendar.toString() instanceof String);
+ assertEquals(-1, calendar.toString().indexOf("?"));
+ calendar.clear();
+ assertTrue(calendar.toString() instanceof String);
+ assertTrue(0 <= calendar.toString().indexOf("?"));
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ Calendar calendar = Calendar.getInstance();
+ calendar.set(2008, 3, 20, 17, 28, 12);
+
+ SerializationTest.verifySelf(calendar);
+ }
+
+
+ private class MockGregorianCalendar extends GregorianCalendar {
+ public int internal_get(int field) {
+ return super.internalGet(field);
+ }
+ }
+
+ private class MockCalendar extends Calendar {
+
+ public MockCalendar() {
+ super();
+ }
+
+ @Override
+ public void add(int field, int value) {
+ }
+
+ @Override
+ protected void computeFields() {
+ }
+
+ @Override
+ protected void computeTime() {
+ }
+
+ @Override
+ public int getGreatestMinimum(int field) {
+ return 0;
+ }
+
+ @Override
+ public int getLeastMaximum(int field) {
+ return 0;
+ }
+
+ @Override
+ public int getMaximum(int field) {
+ return 0;
+ }
+
+ @Override
+ public int getMinimum(int field) {
+ return 0;
+ }
+
+ @Override
+ public void roll(int field, boolean increment) {
+ }
+ }
+
+ /**
+ * {@link java.util.Calendar#getDisplayName(int, int, Locale)}
+ * @since 1.6
+ */
+ public void test_getDisplayNameIILjava_util_Locale() {
+ Calendar cal = Calendar.getInstance();
+ for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
+ for (Locale locale : locales) {
+ DateFormatSymbols symbols = new DateFormatSymbols(locale);
+ String value = null;
+ switch (field) {
+ case Calendar.AM_PM:
+ cal.set(Calendar.AM_PM, Calendar.AM);
+ value = symbols.getAmPmStrings()[0];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ cal.set(Calendar.AM_PM, Calendar.PM);
+ value = symbols.getAmPmStrings()[1];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ break;
+ case Calendar.ERA:
+ cal.set(Calendar.ERA, GregorianCalendar.BC);
+ value = symbols.getEras()[0];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ cal.set(Calendar.ERA, GregorianCalendar.AD);
+ value = symbols.getEras()[1];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ break;
+ case Calendar.MONTH:
+ cal.set(Calendar.DAY_OF_MONTH, 1);
+ for (int month = 0; month <= 11; month++) {
+ cal.set(Calendar.MONTH, month);
+ value = symbols.getShortMonths()[month];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ value = symbols.getMonths()[month];
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ }
+ break;
+ case Calendar.DAY_OF_WEEK:
+ for (int day = 1; day <= 7; day++) {
+ cal.set(Calendar.DAY_OF_WEEK, day);
+ value = symbols.getShortWeekdays()[day];
+ assertEquals(cal.getDisplayName(field, Calendar.SHORT,
+ locale), value);
+ value = symbols.getWeekdays()[day];
+ assertEquals(cal.getDisplayName(field, Calendar.LONG,
+ locale), value);
+ }
+ break;
+ default:
+ assertNull(cal
+ .getDisplayName(field, Calendar.SHORT, locale));
+ assertNull(cal.getDisplayName(field, Calendar.LONG, locale));
+ }
+ }
+ }
+
+ cal.setLenient(true);
+
+ try {
+ cal.getDisplayName(-1, Calendar.SHORT, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.MONTH, -1, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.MONTH, 3, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(-1, Calendar.SHORT, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.MONTH, -1, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ // in lenient mode, following cases pass
+ cal.set(Calendar.SECOND, 999);
+ cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
+ // test for ALL_STYLES, it is equal to use SHORT
+ for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
+ for (Locale locale : locales) {
+ String result = cal.getDisplayName(field, Calendar.ALL_STYLES,
+ locale);
+ if (field == Calendar.AM_PM || field == Calendar.ERA
+ || field == Calendar.MONTH
+ || field == Calendar.DAY_OF_WEEK) {
+ assertEquals(result, cal.getDisplayName(field,
+ Calendar.SHORT, locale));
+ } else {
+ assertNull(result);
+ }
+ }
+ }
+
+ // invalid value for an un-related field when the calendar is not
+ // lenient
+ cal.setLenient(false);
+ assertNotNull(cal.getDisplayName(Calendar.MONTH, Calendar.SHORT,
+ Locale.US));
+ cal.set(Calendar.SECOND, 999);
+ try {
+ cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayName(Calendar.MONTH, Calendar.ALL_STYLES, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Calendar#getDisplayNames(int, int, Locale)}
+ * @since 1.6
+ */
+ public void test_getDisplayNamesIILjava_util_Locale() {
+ assertEquals(0, Calendar.ALL_STYLES);
+ assertEquals(1, Calendar.SHORT);
+ assertEquals(2, Calendar.LONG);
+
+ Calendar cal = Calendar.getInstance(Locale.US);
+
+ for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
+ for (Locale locale : locales) {
+ Map<String, Integer> shortResult = cal.getDisplayNames(field,
+ Calendar.SHORT, locale);
+ Map<String, Integer> longResult = cal.getDisplayNames(field,
+ Calendar.LONG, locale);
+ Map<String, Integer> allResult = cal.getDisplayNames(field,
+ Calendar.ALL_STYLES, locale);
+ DateFormatSymbols symbols = new DateFormatSymbols(locale);
+ String[] values = null;
+ switch (field) {
+ case Calendar.AM_PM:
+ case Calendar.ERA:
+ values = (field == Calendar.AM_PM) ? symbols
+ .getAmPmStrings() : symbols.getEras();
+ assertDisplayNameMap(values, shortResult, 0);
+ assertDisplayNameMap(values, longResult, 0);
+ assertDisplayNameMap(values, allResult, 0);
+ break;
+ case Calendar.MONTH:
+ values = symbols.getShortMonths();
+ assertDisplayNameMap(values, shortResult, 0);
+ values = symbols.getMonths();
+ assertDisplayNameMap(values, longResult, 0);
+ assertTrue(allResult.size() >= shortResult.size());
+ assertTrue(allResult.size() >= longResult.size());
+ assertTrue(allResult.size() <= shortResult.size()
+ + longResult.size());
+ break;
+ case Calendar.DAY_OF_WEEK:
+ values = symbols.getShortWeekdays();
+ assertDisplayNameMap(values, shortResult, 1);
+ values = symbols.getWeekdays();
+ assertDisplayNameMap(values, longResult, 1);
+ assertTrue(allResult.size() >= shortResult.size());
+ assertTrue(allResult.size() >= longResult.size());
+ assertTrue(allResult.size() <= shortResult.size()
+ + longResult.size());
+ break;
+ default:
+ assertNull(shortResult);
+ assertNull(longResult);
+ assertNull(allResult);
+ }
+ }
+ }
+
+ cal.setLenient(true);
+
+ try {
+ cal.getDisplayNames(-1, Calendar.SHORT, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(Calendar.MONTH, -1, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(Calendar.MONTH, 3, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(-1, Calendar.SHORT, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ cal.getDisplayNames(Calendar.MONTH, -1, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ cal.set(Calendar.SECOND, 999);
+ cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
+
+ // RI fails here
+ // invalid value for an un-related field when the calendar is not
+ // lenient
+ cal.setLenient(false);
+ cal.set(Calendar.SECOND, 999);
+ try {
+ cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ private void assertDisplayNameMap(String[] values,
+ Map<String, Integer> result, int shift) {
+ List<String> trimValue = new ArrayList<String>();
+ for (String value : values) {
+ if (value.trim().length() > 0) {
+ trimValue.add(value);
+ }
+ }
+ assertEquals(trimValue.size(), result.size());
+ for (int i = 0; i < trimValue.size(); i++) {
+ assertEquals(i + shift, result.get(trimValue.get(i)).intValue());
+ }
+ }
+
+ /**
+ * {@link java.util.Calendar#getActualMaximum(int)}
+ */
+ public void test_getActualMaximum_I() {
+ Calendar c = new MockCalendar();
+ assertEquals("should be equal to 0", 0, c.getActualMaximum(0));
+ }
+
+ /**
+ * {@link java.util.Calendar#getActualMinimum(int)}
+ */
+ public void test_getActualMinimum_I() {
+ Calendar c = new MockCalendar();
+ assertEquals("should be equal to 0", 0, c.getActualMinimum(0));
+ }
+
+ protected void setUp() {
+ defaultLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ }
+
+ protected void tearDown() {
+ Locale.setDefault(defaultLocale);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Collections2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Collections2Test.java
new file mode 100644
index 0000000..899cd18
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Collections2Test.java
@@ -0,0 +1,495 @@
+/*
+ * 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.tests.java.util;
+
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+import tests.util.SerializationTester;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.RandomAccess;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.Vector;
+
+public class Collections2Test extends TestCase {
+
+ private static final SerializableAssert comparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable reference, Serializable test) {
+ assertSame(reference, test);
+ }
+ };
+
+ /**
+ * java.util.Collections#binarySearch(java.util.List,
+ *java.lang.Object, java.util.Comparator)
+ */
+ public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
+ // Regression for HARMONY-94
+ LinkedList<Integer> lst = new LinkedList<Integer>();
+ lst.add(new Integer(30));
+ Collections.sort(lst, null);
+ int index = Collections.binarySearch(lst, new Integer(2), null);
+ assertEquals(-1, index);
+ }
+
+ /**
+ * java.util.Collections#binarySearch(java.util.List,
+ *java.lang.Object)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_binarySearchLjava_util_ListLjava_lang_Object() {
+ // regression for Harmony-1367
+ List localList = new LinkedList();
+ assertEquals(-1, Collections.binarySearch(localList, new Object()));
+ localList.add(new Object());
+ try {
+ Collections.binarySearch(localList, new Integer(1));
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#rotate(java.util.List, int)
+ */
+ public void test_rotateLjava_util_ListI() {
+ // Regression for HARMONY-19 Rotate an *empty* list
+ Collections.rotate(new ArrayList<Object>(), 25);
+
+ // Regression for HARMONY-20
+ List<String> list = new ArrayList<String>();
+ list.add(0, "zero");
+ list.add(1, "one");
+ list.add(2, "two");
+ list.add(3, "three");
+ list.add(4, "four");
+
+ Collections.rotate(list, Integer.MIN_VALUE);
+ assertEquals("Rotated incorrectly at position 0, ", "three",
+ list.get(0));
+ assertEquals("Rotated incorrectly at position 1, ", "four",
+ list.get(1));
+ assertEquals("Rotated incorrectly at position 2, ", "zero",
+ list.get(2));
+ assertEquals("Rotated incorrectly at position 3, ", "one",
+ list.get(3));
+ assertEquals("Rotated incorrectly at position 4, ", "two",
+ list.get(4));
+ }
+
+ /**
+ * java.util.Collections#synchronizedCollection(java.util.Collection)
+ */
+ public void test_synchronizedCollectionLjava_util_Collection() {
+ try {
+ // Regression for HARMONY-93
+ Collections.synchronizedCollection(null);
+ fail("Assert 0: synchronizedCollection(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
+ */
+ public void test_synchronizedSortedMapLjava_util_SortedMap() {
+ try {
+ // Regression for HARMONY-93
+ Collections.synchronizedSortedMap(null);
+ fail("Assert 0: synchronizedSortedMap(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#synchronizedMap(java.util.Map)
+ */
+ public void test_synchronizedMapLjava_util_Map() {
+ try {
+ // Regression for HARMONY-93
+ Collections.synchronizedMap(null);
+ fail("Assert 0: synchronizedMap(map) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#synchronizedSet(java.util.Set)
+ */
+ public void test_synchronizedSetLjava_util_Set() {
+ try {
+ // Regression for HARMONY-93
+ Collections.synchronizedSet(null);
+ fail("Assert 0: synchronizedSet(set) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
+ */
+ public void test_synchronizedSortedSetLjava_util_SortedSet() {
+ try {
+ // Regression for HARMONY-93
+ Collections.synchronizedSortedSet(null);
+ fail("Assert 0: synchronizedSortedSet(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#unmodifiableCollection(java.util.Collection)
+ */
+ public void test_unmodifiableCollectionLjava_util_Collection() {
+ try {
+ // Regression for HARMONY-93
+ Collections.unmodifiableCollection(null);
+ fail("Assert 0: unmodifiableCollection(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#unmodifiableMap(java.util.Map)
+ */
+ public void test_unmodifiableMapLjava_util_Map() {
+ try {
+ // Regression for HARMONY-93
+ Collections.unmodifiableMap(null);
+ fail("Assert 0: unmodifiableMap(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#unmodifiableSet(java.util.Set)
+ */
+ public void test_unmodifiableSetLjava_util_Set() {
+ try {
+ // Regression for HARMONY-93
+ Collections.unmodifiableSet(null);
+ fail("Assert 0: unmodifiableSet(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
+ */
+ public void test_unmodifiableSortedMapLjava_util_SortedMap() {
+ try {
+ // Regression for HARMONY-93
+ Collections.unmodifiableSortedMap(null);
+ fail("Assert 0: unmodifiableSortedMap(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
+ */
+ public void test_unmodifiableSortedSetLjava_util_SortedSet() {
+ try {
+ // Regression for HARMONY-93
+ Collections.unmodifiableSortedSet(null);
+ fail("Assert 0: unmodifiableSortedSet(null) must throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Collections#frequency(java.util.Collection, Object)
+ */
+ public void test_frequencyLjava_util_CollectionLint() {
+ try {
+ Collections.frequency(null, null);
+ fail("Assert 0: frequency(null,<any>) must throw NPE");
+ } catch (NullPointerException e) {
+ }
+
+ List<String> strings = Arrays.asList(new String[] { "1", "2", "3", "1", "1" });
+
+ assertEquals("Assert 1: did not find three \"1\" strings", 3,
+ Collections.frequency(strings, "1"));
+
+ assertEquals("Assert 2: did not find one \"2\" strings", 1, Collections
+ .frequency(strings, "2"));
+
+ assertEquals("Assert 3: did not find three \"3\" strings", 1,
+ Collections.frequency(strings, "3"));
+
+ assertEquals("Assert 4: matched on null when there are none", 0,
+ Collections.frequency(strings, null));
+
+ List<Object> objects = Arrays.asList(new Object[] { new Integer(1), null, null,
+ new Long(1) });
+
+ assertEquals("Assert 5: did not find one Integer(1)", 1, Collections
+ .frequency(objects, new Integer(1)));
+
+ assertEquals("Assert 6: did not find one Long(1)", 1, Collections
+ .frequency(objects, new Long(1)));
+
+ assertEquals("Assert 7: did not find two null references", 2,
+ Collections.frequency(objects, null));
+ }
+
+ /**
+ * java.util.Collections#reverseOrder()
+ */
+ public void test_reverseOrder() {
+ Comparator<String> roc = Collections.reverseOrder();
+ assertNotNull("Assert 0: comparator must not be null", roc);
+
+ assertTrue("Assert 1: comparator must implement Serializable",
+ roc instanceof Serializable);
+
+ String[] fixtureDesc = new String[] { "2", "1", "0" };
+ String[] numbers = new String[] { "0", "1", "2" };
+ Arrays.sort(numbers, roc);
+ assertTrue("Assert 2: the arrays are not equal, the sort failed",
+ Arrays.equals(fixtureDesc, numbers));
+ }
+
+ /**
+ * java.util.Collections#reverseOrder(java.util.Comparator)
+ */
+ public void test_reverseOrderLjava_util_Comparator() {
+ Comparator<String> roc = Collections
+ .reverseOrder(String.CASE_INSENSITIVE_ORDER);
+ assertNotNull("Assert 0: comparator must not be null", roc);
+
+ assertTrue("Assert 1: comparator must implement Serializable",
+ roc instanceof Serializable);
+
+ String[] fixtureDesc = new String[] { "2", "1", "0" };
+ String[] numbers = new String[] { "0", "1", "2" };
+ Arrays.sort(numbers, roc);
+ assertTrue("Assert 2: the arrays are not equal, the sort failed",
+ Arrays.equals(fixtureDesc, numbers));
+
+ roc = Collections.reverseOrder(null);
+ assertNotNull("Assert 3: comparator must not be null", roc);
+
+ assertTrue("Assert 4: comparator must implement Serializable",
+ roc instanceof Serializable);
+
+ numbers = new String[] { "0", "1", "2" };
+ Arrays.sort(numbers, roc);
+ assertTrue("Assert 5: the arrays are not equal, the sort failed",
+ Arrays.equals(fixtureDesc, numbers));
+ }
+
+ public void test_AddAll() {
+ List<Object> l = new ArrayList<Object>();
+ assertFalse(Collections.addAll(l, new Object[] { }));
+ assertTrue(l.isEmpty());
+ assertTrue(Collections.addAll(l, new Object[] { new Integer(1),
+ new Integer(2), new Integer(3) }));
+ assertFalse(l.isEmpty());
+ assertTrue(l.equals(Arrays.asList(new Object[] { new Integer(1),
+ new Integer(2), new Integer(3) })));
+ }
+
+ public void test_Disjoint() {
+ Object[] arr1 = new Object[10];
+ for (int i = 0; i < arr1.length; i++) {
+ arr1[i] = new Integer(i);
+ }
+ Object[] arr2 = new Object[20];
+ for (int i = 0; i < arr2.length; i++) {
+ arr2[i] = new Integer(100 + i);
+ }
+ Collection<Object> c1 = new ArrayList<Object>();
+ Collection<Object> c2 = new ArrayList<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ c1 = new LinkedList<Object>();
+ c2 = new LinkedList<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ c1 = new TreeSet<Object>();
+ c2 = new TreeSet<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ c1 = new HashSet<Object>();
+ c2 = new HashSet<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ c1 = new LinkedList<Object>();
+ c2 = new TreeSet<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ c1 = new Vector<Object>();
+ c2 = new HashSet<Object>();
+ Collections.addAll(c1, arr1);
+ Collections.addAll(c2, arr2);
+ assertTrue(Collections.disjoint(c1, c2));
+ c1.add(arr2[10]);
+ assertFalse(Collections.disjoint(c1, c2));
+
+ }
+
+ /**
+ * java.util.Collections.EmptyList#readResolve()
+ */
+ public void test_EmptyList_readResolve() throws Exception {
+ SerializationTest.verifySelf(Collections.EMPTY_LIST, comparator);
+ }
+
+ /**
+ * java.util.Collections.EmptyMap#readResolve()
+ */
+ public void test_EmptyMap_readResolve() throws Exception {
+ SerializationTest.verifySelf(Collections.EMPTY_MAP, comparator);
+ }
+
+ /**
+ * java.util.Collections.EmptySet#readResolve()
+ */
+ public void test_EmptySet_readResolve() throws Exception {
+ SerializationTest.verifySelf(Collections.EMPTY_SET, comparator);
+ }
+
+ public void test_checkedCollectionSerializationCompatability() throws Exception {
+ Collection<String> c = Collections.emptySet();
+ c = Collections.checkedCollection(c, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedCollection.golden.ser");
+ }
+
+ public void test_checkedListRandomAccessSerializationCompatability() throws Exception {
+ List<String> c = new ArrayList<String>();
+ assertTrue(c instanceof RandomAccess);
+ c = Collections.checkedList(c, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedListRandomAccess.golden.ser");
+ }
+
+ public void test_checkedListSerializationCompatability() throws Exception {
+ List<String> c = new LinkedList<String>();
+ assertFalse(c instanceof RandomAccess);
+ c = Collections.checkedList(c, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedList.golden.ser");
+ }
+
+ public void test_checkedSetSerializationCompatability() throws Exception {
+ Set<String> c = new HashSet<String>();
+ assertFalse(c instanceof SortedSet);
+ c = Collections.checkedSet(c, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedSet.golden.ser");
+ }
+
+ public void test_checkedMapSerializationCompatability() throws Exception {
+ Map<String, String> c = new HashMap<String, String>();
+ assertFalse(c instanceof SortedMap);
+ c = Collections.checkedMap(c, String.class, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedMap.golden.ser");
+ }
+
+ public void test_checkedSortedSetSerializationCompatability() throws Exception {
+ SortedSet<String> c = new TreeSet<String>();
+ c = Collections.checkedSortedSet(c, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedSortedSet.golden.ser");
+ }
+
+ public void test_checkedSortedMapSerializationCompatability() throws Exception {
+ SortedMap<String, String> c = new TreeMap<String, String>();
+ c = Collections.checkedSortedMap(c, String.class, String.class);
+ SerializationTester.assertCompabilityEquals(c, "serialization/org/apache/harmony/tests/java/util/Collections_CheckedSortedMap.golden.ser");
+ }
+
+ public void test_emptyList() {
+ List<Object> emptyList = Collections.emptyList();
+ assertEquals(0, emptyList.size());
+ assertTrue(emptyList instanceof RandomAccess);
+ }
+
+ // Regression test for http://issues.apache.org/jira/browse/HARMONY-6122
+ public void test_Collections_swap_IndexOutOfBoundsException() {
+ try {
+ Collections.swap(new ArrayList<Object>(), -1, 3);
+ fail("IOOBE expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ List<Object> list = new ArrayList<Object>();
+ list.add("0");
+ try {
+ Collections.swap(list, 0, -1);
+ fail("IOOBE expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Collections.swap(list, 0, 3);
+ fail("IOOBE expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ Collections.swap(new ArrayList<Object>(), 3, 3);
+ fail("IOOBE expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CollectionsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CollectionsTest.java
new file mode 100644
index 0000000..a1629d2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CollectionsTest.java
@@ -0,0 +1,2385 @@
+/*
+ * 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.tests.java.util;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+import tests.support.Support_CollectionTest;
+import tests.support.Support_ListTest;
+import tests.support.Support_SetTest;
+import tests.support.Support_UnmodifiableCollectionTest;
+
+import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Queue;
+import java.util.Random;
+import java.util.RandomAccess;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+public class CollectionsTest extends junit.framework.TestCase {
+
+ private LinkedList ll;
+
+ private LinkedList myll;
+
+ private LinkedList reversedLinkedList;
+
+ private LinkedList myReversedLinkedList;
+
+ private Set s;
+
+ private Set mys;
+
+ private HashMap hm;
+
+ private Integer[] objArray;
+
+ private Object[] myobjArray;
+
+ public static class ReversedMyIntComparator implements Comparator {
+ public int compare(Object o1, Object o2) {
+ return -((MyInt) o1).compareTo((MyInt) o2);
+ }
+
+ public int equals(Object o1, Object o2) {
+ return ((MyInt) o1).compareTo((MyInt) o2);
+ }
+ }
+
+ public static class SynchCollectionChecker implements Runnable {
+ Collection col;
+
+ int colSize;
+
+ int totalToRun;
+
+ boolean offset;
+
+ volatile int numberOfChecks = 0;
+
+ boolean result = true;
+
+ ArrayList normalCountingList;
+
+ ArrayList offsetCountingList;
+
+ public void run() {
+ // ensure the list either contains the numbers from 0 to size-1 or
+ // the numbers from size to 2*size -1
+ while (numberOfChecks < totalToRun) {
+ synchronized (col) {
+ if (!(col.isEmpty() || col.containsAll(normalCountingList) || col
+ .containsAll(offsetCountingList)))
+ result = false;
+ col.clear();
+ }
+ if (offset)
+ col.addAll(offsetCountingList);
+ else
+ col.addAll(normalCountingList);
+ numberOfChecks++;
+ }
+ }
+
+ public SynchCollectionChecker(Collection c, boolean offset,
+ int totalChecks) {
+ // The collection to test, whether to offset the filler values by
+ // size or not, and the min number of iterations to run
+ totalToRun = totalChecks;
+ col = c;
+ colSize = c.size();
+ normalCountingList = new ArrayList(colSize);
+ offsetCountingList = new ArrayList(colSize);
+ for (int i = 0; i < colSize; i++)
+ normalCountingList.add(new Integer(i));
+ for (int i = 0; i < colSize; i++)
+ offsetCountingList.add(new Integer(i + colSize));
+ col.clear();
+ if (offset)
+ col.addAll(offsetCountingList);
+ else
+ col.addAll(normalCountingList);
+ }
+
+ public boolean offset() {
+ // answer true iff the list is filled with a counting sequence
+ // starting at the value size to 2*size - 1
+ // else the list with be filled starting at 0 to size - 1
+ return offset;
+ }
+
+ public boolean getResult() {
+ // answer true iff no corruption has been found in the collection
+ return result;
+ }
+
+ public int getNumberOfChecks() {
+ // answer the number of checks that have been performed on the list
+ return numberOfChecks;
+ }
+ }
+
+ public static class SynchMapChecker implements Runnable {
+ Map map;
+
+ int mapSize;
+
+ int totalToRun;
+
+ boolean offset;
+
+ volatile int numberOfChecks = 0;
+
+ boolean result = true;
+
+ Map normalCountingMap;
+
+ Map offsetCountingMap;
+
+ public void run() {
+ Object firstNormalValue = normalCountingMap.get(new Integer(0));
+ Object lastNormalValue = normalCountingMap.get(new Integer(
+ mapSize - 1));
+ Object firstOffsetValue = offsetCountingMap
+ .get(new Integer(mapSize));
+ Object lastOffsetValue = offsetCountingMap.get(new Integer(
+ 2 * mapSize - 1));
+ // ensure the list either contains the numbers from 0 to size-1 or
+ // the numbers from size to 2*size -1
+ while (numberOfChecks < totalToRun) {
+ synchronized (map) {
+ if (!(map.isEmpty()
+ || (map.containsValue(firstNormalValue) && map
+ .containsValue(lastNormalValue)) || (map
+ .containsValue(firstOffsetValue) && map
+ .containsValue(lastOffsetValue))))
+ result = false;
+ map.clear();
+ }
+ if (offset)
+ map.putAll(offsetCountingMap);
+ else
+ map.putAll(normalCountingMap);
+ numberOfChecks++;
+ }
+ }
+
+ public SynchMapChecker(Map m, boolean offset, int totalChecks) {
+ // The collection to test, whether to offset the filler values by
+ // size or not, and the min number of iterations to run
+ Integer myInt;
+ totalToRun = totalChecks;
+ map = m;
+ mapSize = m.size();
+ normalCountingMap = new HashMap(mapSize);
+ offsetCountingMap = new HashMap(mapSize);
+ for (int i = 0; i < mapSize; i++) {
+ myInt = new Integer(i);
+ normalCountingMap.put(myInt, myInt);
+ }
+ for (int i = 0; i < mapSize; i++) {
+ myInt = new Integer(i + mapSize);
+ offsetCountingMap.put(myInt, myInt);
+ }
+ map.clear();
+ if (offset)
+ map.putAll(offsetCountingMap);
+ else
+ map.putAll(normalCountingMap);
+ }
+
+ public boolean offset() {
+ // answer true iff the list is filled with a counting sequence
+ // starting at the value size to 2*size - 1
+ // else the list with be filled starting at 0 to size - 1
+ return offset;
+ }
+
+ public boolean getResult() {
+ // answer true iff no corruption has been found in the collection
+ return result;
+ }
+
+ public int getNumberOfChecks() {
+ // answer the number of checks that have been performed on the list
+ return numberOfChecks;
+ }
+ }
+
+ static class MyInt {
+ int data;
+
+ public MyInt(int value) {
+ data = value;
+ }
+
+ public int compareTo(MyInt object) {
+ return data > object.data ? 1 : (data < object.data ? -1 : 0);
+ }
+ }
+
+ public void test_binarySearchLjava_util_ListLjava_lang_Object() {
+ // Test for method int
+ // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
+ // assumes ll is sorted and has no duplicate keys
+ final int llSize = ll.size();
+ // Ensure a NPE is thrown if the list is NULL
+ try {
+ Collections.binarySearch(null, new Object());
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ for (int i = 0; i < llSize; i++) {
+ assertEquals("Returned incorrect binary search item position", ll
+ .get(i), ll.get(Collections.binarySearch(ll, ll
+ .get(i))));
+ }
+ }
+
+ public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
+ // Test for method int
+ // java.util.Collections.binarySearch(java.util.List, java.lang.Object,
+ // java.util.Comparator)
+ // assumes reversedLinkedList is sorted in reversed order and has no
+ // duplicate keys
+ final int rSize = myReversedLinkedList.size();
+ ReversedMyIntComparator comp = new ReversedMyIntComparator();
+ // Ensure a NPE is thrown if the list is NULL
+ try {
+ Collections.binarySearch(null, new Object(), comp);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ for (int i = 0; i < rSize; i++) {
+ assertEquals(
+ "Returned incorrect binary search item position using custom comparator",
+ myReversedLinkedList.get(i), myReversedLinkedList
+ .get(Collections.binarySearch(myReversedLinkedList,
+ myReversedLinkedList.get(i), comp)));
+ }
+ }
+
+ class Mock_ArrayList extends ArrayList {
+ @Override
+ public
+ Object set (int index, Object o){
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public void test_copyLjava_util_ListLjava_util_List() {
+ // Test for method void java.util.Collections.copy(java.util.List,
+ // java.util.List)
+ // Ensure a NPE is thrown if the list is NULL
+ try {
+ Collections.copy(null, ll);
+ fail("Expected NullPointerException for null list first parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ try {
+ Collections.copy(ll, null);
+ fail("Expected NullPointerException for null list second parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ final int llSize = ll.size();
+ ll.set(25, null);
+ ArrayList al = new ArrayList();
+ Integer extraElement = new Integer(1);
+ Integer extraElement2 = new Integer(2);
+ al.addAll(myReversedLinkedList);
+ al.add(extraElement);
+ al.add(extraElement2);
+ Collections.copy(al, ll);
+ for (int i = 0; i < llSize; i++) {
+ assertEquals("Elements do not match after copying collection", ll
+ .get(i), al.get(i));
+ }
+ assertTrue("Elements after copied elements affected by copy",
+ extraElement == al.get(llSize)
+ && extraElement2 == al.get(llSize + 1));
+
+ ArrayList ar1 = new ArrayList();
+ ArrayList ar2 = new ArrayList();
+
+ int i;
+
+ for(i = 0; i < 5; i ++) {
+ ar2.add(new Integer(i));
+ }
+
+ for(i = 0; i < 10; i ++) {
+ ar1.add(new Integer(i));
+ }
+
+ try {
+ Collections.copy(ar2, ar1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ Mock_ArrayList mal1 = new Mock_ArrayList();
+ Mock_ArrayList mal2 = new Mock_ArrayList();
+
+ for(i = 0; i < 10; i ++) {
+ mal1.add(new Integer(i));
+ mal2.add(new Integer(10 - i));
+ }
+
+ try {
+ Collections.copy(mal1, mal2);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_copy_check_index() {
+ ArrayList a1 = new ArrayList();
+ a1.add("one");
+ a1.add("two");
+
+ ArrayList a2 = new ArrayList();
+ a2.add("aa");
+
+ try {
+ Collections.copy(a2, a1);
+ fail("Expected IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //Expected
+ }
+
+ assertEquals("aa", a2.get(0));
+ }
+
+ public void test_enumerationLjava_util_Collection() {
+ // Test for method java.util.Enumeration
+ // java.util.Collections.enumeration(java.util.Collection)
+ TreeSet ts = new TreeSet();
+ ts.addAll(s);
+ Enumeration e = Collections.enumeration(ts);
+ int count = 0;
+ while (e.hasMoreElements()) {
+ assertEquals("Returned incorrect enumeration", e.nextElement(),
+ objArray[count++]);
+ }
+ assertEquals("Enumeration missing elements: " + count, objArray.length,
+ count);
+ }
+
+ public void test_fillLjava_util_ListLjava_lang_Object() {
+ // Test for method void java.util.Collections.fill(java.util.List,
+ // java.lang.Object)
+ try {
+ Collections.fill(null, new Object());
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ final int size = ll.size();
+ Collections.fill(ll, "k");
+ assertEquals("Fill modified list size", size, ll.size());
+ Iterator i = ll.iterator();
+ while (i.hasNext())
+ assertEquals("Failed to fill elements", "k", i.next());
+
+ Collections.fill(ll, null);
+ assertEquals("Fill with nulls modified list size", size, ll.size());
+ i = ll.iterator();
+ while (i.hasNext())
+ assertNull("Failed to fill with nulls", i.next());
+
+ Mock_ArrayList mal = new Mock_ArrayList();
+
+ mal.add("one");
+ mal.add("two");
+
+ try {
+ Collections.fill(mal, "value");
+ fail("UnsupportedOperationException ecpected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_maxLjava_util_Collection() {
+ // Test for method java.lang.Object
+ // java.util.Collections.max(java.util.Collection)
+ // assumes s, objArray are sorted
+ assertEquals("Returned incorrect max element", Collections.max(s),
+ objArray[objArray.length - 1]);
+
+ ArrayList al = new ArrayList();
+
+ try {
+ Collections.max(al);
+ fail("NoSuchElementException expected");
+ } catch (NoSuchElementException e) {
+ //expected
+ }
+
+ al.add("String");
+ al.add(new Integer(1));
+ al.add(new Double(3.14));
+
+ try {
+ Collections.max(al);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+ }
+
+ public void test_maxLjava_util_CollectionLjava_util_Comparator() {
+ // Test for method java.lang.Object
+ // java.util.Collections.max(java.util.Collection, java.util.Comparator)
+ // assumes s, objArray are sorted
+
+ // With this custom (backwards) comparator the 'max' element should be
+ // the smallest in the list
+ assertEquals("Returned incorrect max element using custom comparator",
+ Collections.max(mys, new ReversedMyIntComparator()),
+ myobjArray[0]);
+ }
+
+ public void test_minLjava_util_Collection() {
+ // Test for method java.lang.Object
+ // java.util.Collections.min(java.util.Collection)
+ // assumes s, objArray are sorted
+ assertEquals("Returned incorrect min element", Collections.min(s),
+ objArray[0]);
+ }
+
+ public void test_minLjava_util_CollectionLjava_util_Comparator() {
+ // Test for method java.lang.Object
+ // java.util.Collections.min(java.util.Collection, java.util.Comparator)
+ // assumes s, objArray are sorted
+
+ // With this custom (backwards) comparator the 'min' element should be
+ // the largest in the list
+ assertEquals("Returned incorrect min element using custom comparator",
+ Collections.min(mys, new ReversedMyIntComparator()),
+ myobjArray[objArray.length - 1]);
+ }
+
+ public void test_nCopiesILjava_lang_Object() {
+ // Test for method java.util.List java.util.Collections.nCopies(int,
+ // java.lang.Object)
+ Object o = new Object();
+ List l = Collections.nCopies(100, o);
+ Iterator iterator = l.iterator();
+ Object first = iterator.next();
+ assertEquals("Returned list consists of copies not refs", first, o);
+ assertEquals("Returned list of incorrect size", 100, l.size());
+ assertTrue("Contains", l.contains(o));
+ assertFalse("Contains null", l.contains(null));
+ assertFalse("null nCopies contains", Collections.nCopies(2, null)
+ .contains(o));
+ assertTrue("null nCopies contains null", Collections.nCopies(2, null)
+ .contains(null));
+ l = Collections.nCopies(20, null);
+ iterator = l.iterator();
+ for (int i = 0; iterator.hasNext(); i++) {
+ assertTrue("List is too large", i < 20);
+ assertNull("Element should be null: " + i, iterator.next());
+ }
+ try {
+ l.add(o);
+ fail("Returned list is not immutable");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+ try {
+ Collections.nCopies(-2, new HashSet());
+ fail("nCopies with negative arg didn't throw IAE");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_reverseLjava_util_List() {
+ // Test for method void java.util.Collections.reverse(java.util.List)
+ try {
+ Collections.reverse(null);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ Collections.reverse(ll);
+ Iterator i = ll.iterator();
+ int count = objArray.length - 1;
+ while (i.hasNext()) {
+ assertEquals("Failed to reverse collection", objArray[count], i
+ .next());
+ --count;
+ }
+ ArrayList myList = new ArrayList();
+ myList.add(null);
+ myList.add(new Integer(20));
+ Collections.reverse(myList);
+ assertEquals("Did not reverse correctly--first element is: "
+ + myList.get(0), new Integer(20), myList.get(0));
+ assertNull("Did not reverse correctly--second element is: "
+ + myList.get(1), myList.get(1));
+ }
+
+ public void test_reverseOrder() {
+ // Test for method java.util.Comparator
+ // java.util.Collections.reverseOrder()
+ // assumes no duplicates in ll
+ Comparator comp = Collections.reverseOrder();
+ LinkedList list2 = new LinkedList(ll);
+ Collections.sort(list2, comp);
+ final int llSize = ll.size();
+ for (int i = 0; i < llSize; i++)
+ assertEquals("New comparator does not reverse sorting order", list2
+ .get(llSize - i - 1), ll.get(i));
+ }
+
+ public void test_shuffleLjava_util_List() {
+ // Test for method void java.util.Collections.shuffle(java.util.List)
+ // Assumes ll is sorted and has no duplicate keys and is large ( > 20
+ // elements)
+
+ // test shuffling a Sequential Access List
+ try {
+ Collections.shuffle(null);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ ArrayList al = new ArrayList();
+ al.addAll(ll);
+ testShuffle(al, "Sequential Access", false);
+
+ // test shuffling a Random Access List
+ LinkedList ll2 = new LinkedList();
+ ll2.addAll(ll);
+ testShuffle(ll2, "Random Access", false);
+ }
+
+ public void testShuffleRandomAccessWithSeededRandom() {
+ List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
+ Collections.shuffle(list, new Random(0));
+ assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
+ }
+
+ public void testShuffleWithSeededRandom() {
+ List<String> list = new LinkedList<String>(Arrays.asList(
+ "A", "B", "C", "D", "E", "F", "G"));
+ Collections.shuffle(list, new Random(0));
+ assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
+ }
+
+ private void testShuffle(List list, String type, boolean random) {
+ boolean sorted = true;
+ boolean allMatch = true;
+ int index = 0;
+ final int size = list.size();
+
+ if (random)
+ Collections.shuffle(list);
+ else
+ Collections.shuffle(list, new Random(200));
+
+ for (int i = 0; i < size - 1; i++) {
+ if (((Integer) list.get(i)).compareTo((Integer) list.get(i + 1)) > 0) {
+ sorted = false;
+ }
+ }
+ assertFalse("Shuffling sorted " + type
+ + " list resulted in sorted list (should be unlikely)", sorted);
+ for (int i = 0; i < 20; i++) {
+ index = 30031 * i % (size + 1); // 30031 is a large prime
+ if (list.get(index) != ll.get(index))
+ allMatch = false;
+ }
+ assertFalse("Too many element positions match in shuffled " + type
+ + " list", allMatch);
+ }
+
+ public void test_shuffleLjava_util_ListLjava_util_Random() {
+ // Test for method void java.util.Collections.shuffle(java.util.List,
+ // java.util.Random)
+ // Assumes ll is sorted and has no duplicate keys and is large ( > 20
+ // elements)
+
+ // test shuffling a Sequential Access List
+ try {
+ Collections.shuffle(null, new Random(200));
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Excepted
+ }
+ ArrayList al = new ArrayList();
+ al.addAll(ll);
+ testShuffle(al, "Sequential Access", true);
+
+ // test shuffling a Random Access List
+ LinkedList ll2 = new LinkedList();
+ ll2.addAll(ll);
+ testShuffle(ll2, "Random Access", true);
+
+ List l = new ArrayList();
+ l.add('a');
+ l.add('b');
+ l.add('c');
+ Collections.shuffle(l, new Random(12345678921L));
+ assertEquals("acb", l.get(0).toString() + l.get(1) + l.get(2));
+ }
+
+ public void test_singletonLjava_lang_Object() {
+ // Test for method java.util.Set
+ // java.util.Collections.singleton(java.lang.Object)
+ Object o = new Object();
+ Set single = Collections.singleton(o);
+ assertEquals("Wrong size", 1, single.size());
+ assertTrue("Contains", single.contains(o));
+ assertFalse("Contains null", single.contains(null));
+ assertFalse("null nCopies contains", Collections.singleton(null)
+ .contains(o));
+ assertTrue("null nCopies contains null", Collections.singleton(null)
+ .contains(null));
+ try {
+ single.add("l");
+ fail("Allowed modification of singleton");
+ } catch (UnsupportedOperationException e) {
+ // Excepted
+ }
+ }
+
+ public void test_sortLjava_util_List() {
+ // Test for method void java.util.Collections.sort(java.util.List)
+ // assumes no duplicate keys in ll
+ final int llSize = ll.size();
+ final int rllSize = reversedLinkedList.size();
+ try {
+ Collections.sort((List) null);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ Collections.shuffle(ll);
+ Collections.sort(ll);
+ Collections.sort(reversedLinkedList);
+ for (int i = 0; i < llSize - 1; i++) {
+ assertTrue(
+ "Sorting shuffled list resulted in unsorted list",
+ ((Integer) ll.get(i)).compareTo((Integer) ll.get(i + 1)) < 0);
+ }
+
+ for (int i = 0; i < rllSize - 1; i++) {
+ assertTrue("Sorting reversed list resulted in unsorted list",
+ ((Integer) reversedLinkedList.get(i))
+ .compareTo((Integer) reversedLinkedList.get(i + 1)) < 0);
+ }
+ }
+
+ public void test_sortLjava_util_ListLjava_util_Comparator() {
+ // Test for method void java.util.Collections.sort(java.util.List,
+ // java.util.Comparator)
+ Comparator comp = new ReversedMyIntComparator();
+ try {
+ Collections.sort(null, comp);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ Collections.shuffle(myll);
+ Collections.sort(myll, comp);
+ final int llSize = myll.size();
+
+ for (int i = 0; i < llSize - 1; i++) {
+ assertTrue(
+ "Sorting shuffled list with custom comparator resulted in unsorted list",
+ ((MyInt) myll.get(i)).compareTo((MyInt) myll
+ .get(i + 1)) >= 0);
+ }
+
+ ArrayList al = new ArrayList();
+
+ al.add("String");
+ al.add(new Integer(1));
+ al.add(new Double(3.14));
+
+ try {
+ Collections.sort(al, comp);
+ fail("ClassCastException expected");
+ } catch (ClassCastException e) {
+ //expected
+ }
+
+ Mock_ArrayList mal = new Mock_ArrayList();
+
+ mal.add(new MyInt(1));
+ mal.add(new MyInt(2));
+
+ try {
+ Collections.sort(mal, comp);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_swapLjava_util_ListII() {
+ // Test for method swap(java.util.List, int, int)
+
+ LinkedList smallList = new LinkedList();
+ for (int i = 0; i < 10; i++) {
+ smallList.add(objArray[i]);
+ }
+
+ // test exception cases
+ try {
+ Collections.swap(smallList, -1, 6);
+ fail("Expected IndexOutOfBoundsException for -1");
+ } catch (IndexOutOfBoundsException e) {
+ //Expected
+ }
+
+ try {
+ Collections.swap(smallList, 6, -1);
+ fail("Expected IndexOutOfBoundsException for -1");
+ } catch (IndexOutOfBoundsException e) {
+ //Expected
+ }
+
+ try {
+ Collections.swap(smallList, 6, 11);
+ fail("Expected IndexOutOfBoundsException for 11");
+ } catch (IndexOutOfBoundsException e) {
+ //Expected
+ }
+
+ try {
+ Collections.swap(smallList, 11, 6);
+ fail("Expected IndexOutOfBoundsException for 11");
+ } catch (IndexOutOfBoundsException e) {
+ //Expected
+ }
+
+ // Ensure a NPE is thrown if the list is NULL
+ try {
+ Collections.swap(null, 1, 1);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ // test with valid parameters
+ Collections.swap(smallList, 4, 7);
+ assertEquals("Didn't Swap the element at position 4 ", new Integer(7),
+ smallList.get(4));
+ assertEquals("Didn't Swap the element at position 7 ", new Integer(4),
+ smallList.get(7));
+
+ // make sure other elements didn't get swapped by mistake
+ for (int i = 0; i < 10; i++) {
+ if (i != 4 && i != 7)
+ assertEquals("shouldn't have swapped the element at position "
+ + i, new Integer(i), smallList.get(i));
+ }
+ }
+
+ public void test_replaceAllLjava_util_ListLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method replaceAll(java.util.List, java.lang.Object,
+ // java.lang.Object)
+
+ String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
+ char[] chars = string1.toCharArray();
+ List list = new ArrayList();
+ for (int i = 0; i < chars.length; i++) {
+ list.add(new Character(chars[i]));
+ }
+
+ try {
+ Collections.replaceAll(null, new Object(), new Object());
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ // test replace for an element that is not in the list
+ boolean result = Collections.replaceAll(list, new Character('1'),
+ new Character('Z'));
+ assertFalse("Test1: Collections.replaceAll() returned wrong result",
+ result);
+ assertEquals("Test2 : ReplaceAll modified the list incorrectly",
+ string1, getString(list));
+
+ // test replace for an element that is in the list
+ result = Collections.replaceAll(list, new Character('S'),
+ new Character('K'));
+ assertTrue("Test3: Collections.replaceAll() returned wrong result",
+ result);
+ assertEquals("Test4: ReplaceAll modified the list incorrectly",
+ (string1 = string1.replace('S', 'K')), getString(list));
+
+ // test replace for the last element in the list
+ result = Collections.replaceAll(list, new Character('Z'),
+ new Character('N'));
+ assertTrue("Test5: Collections.replaceAll() returned wrong result",
+ result);
+ assertEquals("Test6: ReplaceAll modified the list incorrectly",
+ (string1 = string1.replace('Z', 'N')), getString(list));
+
+ // test replace for the first element in the list
+ result = Collections.replaceAll(list, new Character('A'),
+ new Character('B'));
+ assertTrue("Test7: Collections.replaceAll() returned wrong result",
+ result);
+ assertEquals("Test8: ReplaceAll modified the list incorrectly",
+ (string1 = string1.replace('A', 'B')), getString(list));
+
+ // test replacing elements with null
+ LinkedList smallList = new LinkedList();
+ for (int i = 0; i < 10; i++) {
+ smallList.add(objArray[i]);
+ }
+ smallList.set(4, new Integer(5));
+ result = Collections.replaceAll(smallList, new Integer(5), null);
+ assertTrue("Test9: Collections.replaceAll() returned wrong result",
+ result);
+ for (int i = 0; i < smallList.size(); i++) {
+ if (i == 4 || i == 5)
+ assertSame("Test9: ReplaceAll didn't replace element at " + i,
+ null, smallList.get(i));
+ else
+ assertEquals(
+ "Test9: ReplaceAll shouldn't have replaced element at "
+ + i, new Integer(i), smallList.get(i));
+ }
+
+ // test replacing null elements with another value
+ result = Collections.replaceAll(smallList, null, new Integer(99));
+ assertTrue("Test10: Collections.replaceAll() returned wrong result",
+ result);
+
+ for (int i = 0; i < smallList.size(); i++) {
+ if (i == 4 || i == 5)
+ assertEquals("Test10: ReplaceAll didn't replace element at "
+ + i, new Integer(99), smallList.get(i));
+ else
+ assertEquals(
+ "Test10: ReplaceAll shouldn't have replaced element at "
+ + i, new Integer(i), smallList.get(i));
+ }
+
+ Mock_ArrayList mal = new Mock_ArrayList();
+
+ mal.add("First");
+ mal.add("Second");
+
+ try {
+ Collections.replaceAll(mal, "Second", null);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_rotateLjava_util_ListI() {
+ // Test for method rotate(java.util.List, int)
+
+ try {
+ Collections.rotate(null, 0);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ // Test rotating a Sequential Access List
+ LinkedList list1 = new LinkedList();
+ for (int i = 0; i < 10; i++) {
+ list1.add(objArray[i]);
+ }
+ testRotate(list1, "Sequential Access");
+
+ // Test rotating a Random Access List
+ ArrayList list2 = new ArrayList();
+ for (int i = 0; i < 10; i++) {
+ list2.add(objArray[i]);
+ }
+ testRotate(list2, "Random Access");
+ }
+
+ private void testRotate(List list, String type) {
+ // rotate with positive distance
+ Collections.rotate(list, 7);
+ assertEquals("Test1: rotate modified the " + type
+ + " list incorrectly,", "3456789012", getString(list));
+
+ // rotate with negative distance
+ Collections.rotate(list, -2);
+ assertEquals("Test2: rotate modified the " + type
+ + " list incorrectly,", "5678901234", getString(list));
+
+ // rotate sublist with negative distance
+ List subList = list.subList(1, 5);
+ Collections.rotate(subList, -1);
+ assertEquals("Test3: rotate modified the " + type
+ + " list incorrectly,", "5789601234", getString(list));
+
+ // rotate sublist with positive distance
+ Collections.rotate(subList, 2);
+ assertEquals("Test4: rotate modified the " + type
+ + " list incorrectly,", "5967801234", getString(list));
+
+ // rotate with positive distance that is larger than list size
+ Collections.rotate(list, 23);
+ assertEquals("Test5: rotate modified the " + type
+ + " list incorrectly,", "2345967801", getString(list));
+
+ // rotate with negative distance that is larger than list size
+ Collections.rotate(list, -23);
+ assertEquals("Test6: rotate modified the " + type
+ + " list incorrectly,", "5967801234", getString(list));
+
+ // rotate with 0 and equivalent distances, this should make no
+ // modifications to the list
+ Collections.rotate(list, 0);
+ assertEquals("Test7: rotate modified the " + type
+ + " list incorrectly,", "5967801234", getString(list));
+
+ Collections.rotate(list, -30);
+ assertEquals("Test8: rotate modified the " + type
+ + " list incorrectly,", "5967801234", getString(list));
+
+ Collections.rotate(list, 30);
+ assertEquals("Test9: rotate modified the " + type
+ + " list incorrectly,", "5967801234", getString(list));
+ }
+
+ private String getString(List list) {
+ StringBuffer buffer = new StringBuffer();
+ for (int i = 0; i < list.size(); i++) {
+ buffer.append(list.get(i));
+ }
+ return buffer.toString();
+ }
+
+ public void test_rotate2() {
+ List list = new ArrayList();
+ try {
+ Collections.rotate(list, 5);
+ } catch (UnsupportedOperationException e) {
+ fail("Unexpected UnsupportedOperationException for empty list, "
+ + e);
+ }
+
+ list.add(0, "zero");
+ list.add(1, "one");
+ list.add(2, "two");
+ list.add(3, "three");
+ list.add(4, "four");
+
+ Collections.rotate(list, Integer.MIN_VALUE);
+ assertEquals("Rotated incorrectly at position 0, ", "three",
+ (String) list.get(0));
+ assertEquals("Rotated incorrectly at position 1, ", "four",
+ (String) list.get(1));
+ assertEquals("Rotated incorrectly at position 2, ", "zero",
+ (String) list.get(2));
+ assertEquals("Rotated incorrectly at position 3, ", "one",
+ (String) list.get(3));
+ assertEquals("Rotated incorrectly at position 4, ", "two",
+ (String) list.get(4));
+ }
+
+ public void test_indexOfSubListLjava_util_ListLjava_util_List() {
+ // Test for method int indexOfSubList(java.util.List, java.util.List)
+ List list = new ArrayList();
+ try {
+ Collections.indexOfSubList(null, list);
+ fail("Expected NullPointerException for null list first parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ try {
+ Collections.indexOfSubList(list, null);
+ fail("Expected NullPointerException for null list second parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
+
+ testwithCharList(1, string1, "B", true);
+ testwithCharList(2, string1, "LIST", true);
+ testwithCharList(3, string1, "SUBLIST", true);
+ testwithCharList(4, string1, "NONE", true);
+ testwithCharList(5, string1, "END", true);
+
+ // test boundary conditions:
+ testwithCharList(6, "", "", true);
+ testwithCharList(7, "LIST", "", true);
+ testwithCharList(8, "", "SUBLIST", true);
+ }
+
+ public void test_indexOfSubList2() {
+ ArrayList sub = new ArrayList();
+ sub.add(new Integer(1));
+ sub.add(new Integer(2));
+ sub.add(new Integer(3));
+
+ ArrayList sub2 = new ArrayList();
+ sub2.add(new Integer(7));
+ sub2.add(new Integer(8));
+
+ ArrayList src = new ArrayList();
+ src.addAll(sub);
+ src.addAll(sub);
+ src.addAll(sub);
+ src.add(new Integer(5));
+ src.add(new Integer(6));
+
+ // so src becomes a list like this:
+ // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
+
+ sub = new ArrayList(src.subList(3, 11));
+ // [1, 2, 3, 1, 2, 3, 5, 6]
+ assertEquals("TestA : Returned wrong indexOfSubList, ", 3, Collections
+ .indexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(6, 11));
+ // [1, 2, 3, 5, 6]
+ assertEquals("TestB : Returned wrong indexOfSubList, ", 6, Collections
+ .indexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 3));
+ // [1, 2, 3]
+ assertEquals("TestCC : Returned wrong indexOfSubList, ", 0, Collections
+ .indexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(9, 11));
+ // [5, 6]
+ assertEquals("TestD : Returned wrong indexOfSubList, ", 9, Collections
+ .indexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(10, 11));
+ // [6]
+ assertEquals("TestE : Returned wrong indexOfSubList, ", 10, Collections
+ .indexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 11));
+ // the whole list
+ assertEquals("TestH : Returned wrong indexIndexOfSubList, ", 0,
+ Collections.indexOfSubList(src, sub));
+
+ // a non-matching list
+ assertEquals("TestI : Returned wrong indexOfSubList, ", -1, Collections
+ .indexOfSubList(src, sub2));
+ }
+
+ private void testwithCharList(int count, String string1, String string2,
+ boolean first) {
+ char[] chars = string1.toCharArray();
+ List list = new ArrayList();
+ for (int i = 0; i < chars.length; i++) {
+ list.add(new Character(chars[i]));
+ }
+ chars = string2.toCharArray();
+ List sublist = new ArrayList();
+ for (int i = 0; i < chars.length; i++) {
+ sublist.add(new Character(chars[i]));
+ }
+
+ if (first)
+ assertEquals("Test " + count + ": Returned wrong index:", string1
+ .indexOf(string2), Collections
+ .indexOfSubList(list, sublist));
+ else
+ assertEquals("Test " + count + ": Returned wrong index:", string1
+ .lastIndexOf(string2), Collections.lastIndexOfSubList(list,
+ sublist));
+ }
+
+ public void test_lastIndexOfSubListLjava_util_ListLjava_util_List() {
+ // Test for method int lastIndexOfSubList(java.util.List,
+ // java.util.List)
+ String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z-END";
+
+ List list = new ArrayList();
+ try {
+ Collections.lastIndexOfSubList(null, list);
+ fail("Expected NullPointerException for null list first parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+ try {
+ Collections.lastIndexOfSubList(list, null);
+ fail("Expected NullPointerException for null list second parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ testwithCharList(1, string1, "B", false);
+ testwithCharList(2, string1, "LIST", false);
+ testwithCharList(3, string1, "SUBLIST", false);
+ testwithCharList(4, string1, "END", false);
+ testwithCharList(5, string1, "NONE", false);
+
+ // test boundary conditions
+ testwithCharList(6, "", "", false);
+ testwithCharList(7, "LIST", "", false);
+ testwithCharList(8, "", "SUBLIST", false);
+ }
+
+ public void test_lastIndexOfSubList2() {
+ ArrayList sub = new ArrayList();
+ sub.add(new Integer(1));
+ sub.add(new Integer(2));
+ sub.add(new Integer(3));
+
+ ArrayList sub2 = new ArrayList();
+ sub2.add(new Integer(7));
+ sub2.add(new Integer(8));
+
+ ArrayList src = new ArrayList();
+ src.addAll(sub);
+ src.addAll(sub);
+ src.addAll(sub);
+ src.add(new Integer(5));
+ src.add(new Integer(6));
+
+ // so src is a list like this:
+ // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
+
+ Collections.reverse(src);
+ // it becomes like this :
+ // [6, 5, 3, 2, 1, 3, 2, 1, 3, 2, 1]
+
+ sub = new ArrayList(src.subList(0, 8));
+ // [6, 5, 3, 2, 1, 3, 2, 1]
+ assertEquals("TestA : Returned wrong lastIndexOfSubList, ", 0,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 5));
+ // [6, 5, 3, 2, 1]
+ assertEquals("TestB : Returned wrong lastIndexOfSubList, ", 0,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(2, 5));
+ // [3, 2, 1]
+ assertEquals("TestC : Returned wrong lastIndexOfSubList, ", 8,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(9, 11));
+ // [2, 1]
+ assertEquals("TestD : Returned wrong lastIndexOfSubList, ", 9,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(10, 11));
+ // [1]
+ assertEquals("TestE : Returned wrong lastIndexOfSubList, ", 10,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 2));
+ // [6, 5]
+ assertEquals("TestF : Returned wrong lastIndexOfSubList, ", 0,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 1));
+ // [6]
+ assertEquals("TestG : Returned wrong lastIndexOfSubList, ", 0,
+ Collections.lastIndexOfSubList(src, sub));
+
+ sub = new ArrayList(src.subList(0, 11));
+ // the whole list
+ assertEquals("TestH : Returned wrong lastIndexOfSubList, ", 0,
+ Collections.lastIndexOfSubList(src, sub));
+
+ // a non-matching list
+ assertEquals("TestI : Returned wrong lastIndexOfSubList, ", -1,
+ Collections.lastIndexOfSubList(src, sub2));
+ }
+
+ public void test_listLjava_util_Enumeration() {
+ // Test for method java.util.ArrayList list(java.util.Enumeration)
+
+ Enumeration e = Collections.enumeration(ll);
+ ArrayList al = Collections.list(e);
+
+ int size = al.size();
+ assertEquals("Wrong size", ll.size(), size);
+
+ for (int i = 0; i < size; i++) {
+ assertEquals("wrong element at position " + i + ",", ll.get(i), al
+ .get(i));
+ }
+ }
+
+ public void test_synchronizedCollectionLjava_util_Collection() {
+ // Test for method java.util.Collection
+ // java.util.Collections.synchronizedCollection(java.util.Collection)
+
+ LinkedList smallList = new LinkedList();
+ for (int i = 0; i < 50; i++) {
+ smallList.add(objArray[i]);
+ }
+
+ final int numberOfLoops = 200;
+ Collection synchCol = Collections.synchronizedCollection(smallList);
+ // Replacing the previous line with the line below *should* cause the
+ // test to fail--the collecion below isn't synchronized
+ // Collection synchCol = smallList;
+
+ SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
+ synchCol, false, numberOfLoops);
+ SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
+ synchCol, true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ }
+ }
+ assertTrue("Returned collection corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail("join() interrupted");
+ }
+
+ synchCol.add(null);
+ assertTrue("Trying to use nulls in collection failed", synchCol
+ .contains(null));
+
+ smallList = new LinkedList();
+ for (int i = 0; i < 100; i++) {
+ smallList.add(objArray[i]);
+ }
+ new Support_CollectionTest("", Collections
+ .synchronizedCollection(smallList)).runTest();
+
+ //Test self reference
+ synchCol = Collections.synchronizedCollection(smallList);
+ synchCol.add(smallList);
+ assertTrue("should contain self ref", synchCol.toString().indexOf("(this") > -1);
+ }
+
+ public void test_synchronizedListLjava_util_List() {
+ try {
+ Collections.synchronizedList(null);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ //Expected
+ }
+
+ // test with a Sequential Access List
+ List smallList = new LinkedList();
+ testSynchronizedList(smallList, "Sequential Access");
+
+ smallList = new LinkedList();
+ List myList;
+ for (int i = 0; i < 100; i++) {
+ smallList.add(objArray[i]);
+ }
+ myList = Collections.synchronizedList(smallList);
+ new Support_ListTest("", myList).runTest();
+
+ // test with a Random Access List
+ smallList = new ArrayList();
+ testSynchronizedList(smallList, "Random Access");
+
+ smallList = new ArrayList();
+ for (int i = 0; i < 100; i++) {
+ smallList.add(objArray[i]);
+ }
+ myList = Collections.synchronizedList(smallList);
+ new Support_ListTest("", myList).runTest();
+
+ //Test self reference
+ myList = Collections.synchronizedList(smallList);
+ myList.add(smallList);
+ assertTrue("should contain self ref", myList.toString().indexOf("(this") > -1);
+ }
+
+ private void testSynchronizedList(List smallList, String type) {
+ for (int i = 0; i < 50; i++) {
+ smallList.add(objArray[i]);
+ }
+ final int numberOfLoops = 200;
+ List synchList = Collections.synchronizedList(smallList);
+ if (type.equals("Random Access"))
+ assertTrue(
+ "Returned synchronized list should implement the Random Access interface",
+ synchList instanceof RandomAccess);
+ else
+ assertTrue(
+ "Returned synchronized list should not implement the Random Access interface",
+ !(synchList instanceof RandomAccess));
+
+ // Replacing the previous line with the line below *should* cause the
+ // test to fail--the list below isn't synchronized
+ // List synchList = smallList;
+ SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
+ synchList, false, numberOfLoops);
+ SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
+ synchList, true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //Expected
+ }
+ }
+ assertTrue(
+ type
+ + " list tests: Returned list corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail(type + " list tests: join() interrupted");
+ }
+ synchList.set(25, null);
+ assertNull(type + " list tests: Trying to use nulls in list failed",
+ synchList.get(25));
+ }
+
+ public void test_synchronizedMapLjava_util_Map() {
+ // Test for method java.util.Map
+ // java.util.Collections.synchronizedMap(java.util.Map)
+ HashMap smallMap = new HashMap();
+ for (int i = 0; i < 50; i++) {
+ smallMap.put(objArray[i], objArray[i]);
+ }
+
+ final int numberOfLoops = 200;
+ Map synchMap = Collections.synchronizedMap(smallMap);
+ // Replacing the previous line with the line below should cause the test
+ // to fail--the list below isn't synchronized
+ // Map synchMap = smallMap;
+
+ SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
+ false, numberOfLoops);
+ SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
+ true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //Expected
+ }
+ }
+ assertTrue("Returned map corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail("join() interrupted");
+ }
+
+ // synchronized map does not have to permit null keys or values
+ synchMap.put(new Long(25), null);
+ synchMap.put(null, new Long(30));
+ assertNull("Trying to use a null value in map failed", synchMap
+ .get(new Long(25)));
+ assertTrue("Trying to use a null key in map failed", synchMap.get(null)
+ .equals(new Long(30)));
+
+ smallMap = new HashMap();
+ for (int i = 0; i < 100; i++) {
+ smallMap.put(objArray[i].toString(), objArray[i]);
+ }
+ synchMap = Collections.synchronizedMap(smallMap);
+ new MapTestSupport(synchMap).runTest();
+ synchMap.keySet().remove(objArray[50].toString());
+ assertNull(
+ "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map: ",
+ synchMap.get(objArray[50].toString()));
+ assertNull(
+ "Removing a key from the keySet of the synchronized map did not remove it from the original map",
+ smallMap.get(objArray[50].toString()));
+ }
+
+ public void test_unmodifiableMap_LinkedHashMap() {
+ // LinkedHashMap has a well defined iteration order and shows ordering issues with
+ // entrySet() / keySet() methods: iterator(), toArray(T[]) and toArray(). See bug 72073.
+ LinkedHashMap<String, Integer> smallMap = new LinkedHashMap<String, Integer>();
+ for (int i = 0; i < 100; i++) {
+ Integer object = objArray[i];
+ smallMap.put(object.toString(), object);
+ }
+ new MapTestSupport(smallMap).runTest();
+ }
+
+ public void test_synchronizedSetLjava_util_Set() {
+ // Test for method java.util.Set
+ // java.util.Collections.synchronizedSet(java.util.Set)
+ HashSet smallSet = new HashSet();
+ for (int i = 0; i < 50; i++) {
+ smallSet.add(objArray[i]);
+ }
+
+ final int numberOfLoops = 200;
+ Set synchSet = Collections.synchronizedSet(smallSet);
+ // Replacing the previous line with the line below should cause the test
+ // to fail--the set below isn't synchronized
+ // Set synchSet = smallSet;
+
+ SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
+ synchSet, false, numberOfLoops);
+ SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
+ synchSet, true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //Expected
+ }
+ }
+ assertTrue("Returned set corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail("join() interrupted");
+ }
+
+ Set mySet = Collections.synchronizedSet(smallSet);
+ mySet.add(null);
+ assertTrue("Trying to use nulls in list failed", mySet.contains(null));
+
+ smallSet = new HashSet();
+ for (int i = 0; i < 100; i++) {
+ smallSet.add(objArray[i]);
+ }
+ new Support_SetTest("", Collections.synchronizedSet(smallSet))
+ .runTest();
+
+ //Test self reference
+ mySet = Collections.synchronizedSet(smallSet);
+ mySet.add(smallSet);
+ assertTrue("should contain self ref", mySet.toString().indexOf("(this") > -1);
+ }
+
+ public void test_synchronizedSortedMapLjava_util_SortedMap() {
+ // Test for method java.util.SortedMap
+ // java.util.Collections.synchronizedSortedMap(java.util.SortedMap)
+ TreeMap smallMap = new TreeMap();
+ for (int i = 0; i < 50; i++) {
+ smallMap.put(objArray[i], objArray[i]);
+ }
+
+ final int numberOfLoops = 200;
+ Map synchMap = Collections.synchronizedMap(smallMap);
+ // Replacing the previous line with the line below should cause the test
+ // to fail--the list below isn't synchronized
+ // Map synchMap = smallMap;
+
+ SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
+ false, numberOfLoops);
+ SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
+ true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //Expected
+ }
+ }
+ assertTrue("Returned map corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail("join() interrupted");
+ }
+
+ smallMap = new TreeMap();
+ for (int i = 0; i < 100; i++) {
+ smallMap.put(objArray[i].toString(), objArray[i]);
+ }
+ synchMap = Collections.synchronizedSortedMap(smallMap);
+ new MapTestSupport(synchMap).runTest();
+ synchMap.keySet().remove(objArray[50].toString());
+ assertNull(
+ "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map",
+ synchMap.get(objArray[50].toString()));
+ assertNull(
+ "Removing a key from the keySet of the synchronized map did not remove it from the original map",
+ smallMap.get(objArray[50].toString()));
+ }
+
+ public void test_synchronizedSortedSetLjava_util_SortedSet() {
+ // Test for method java.util.SortedSet
+ // java.util.Collections.synchronizedSortedSet(java.util.SortedSet)
+ TreeSet smallSet = new TreeSet();
+ for (int i = 0; i < 50; i++) {
+ smallSet.add(objArray[i]);
+ }
+
+ final int numberOfLoops = 200;
+ Set synchSet = Collections.synchronizedSet(smallSet);
+ // Replacing the previous line with the line below should cause the test
+ // to fail--the list below isn't synchronized
+ // Set synchSet = smallSet;
+
+ SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
+ synchSet, false, numberOfLoops);
+ SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
+ synchSet, true, numberOfLoops);
+ Thread normalThread = new Thread(normalSynchChecker);
+ Thread offsetThread = new Thread(offsetSynchChecker);
+ normalThread.start();
+ offsetThread.start();
+ while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
+ || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //Expected
+ }
+ }
+ assertTrue("Returned set corrupted by multiple thread access",
+ normalSynchChecker.getResult()
+ && offsetSynchChecker.getResult());
+ try {
+ normalThread.join(5000);
+ offsetThread.join(5000);
+ } catch (InterruptedException e) {
+ fail("join() interrupted");
+ }
+ }
+
+ public void test_unmodifiableCollectionLjava_util_Collection() {
+ // Test for method java.util.Collection
+ // java.util.Collections.unmodifiableCollection(java.util.Collection)
+ boolean exception = false;
+ Collection c = Collections.unmodifiableCollection(ll);
+ assertTrue("Returned collection is of incorrect size", c.size() == ll
+ .size());
+ Iterator iterator = ll.iterator();
+ while (iterator.hasNext())
+ assertTrue("Returned list missing elements", c.contains(iterator.next()));
+ try {
+ c.add(new Object());
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+ if (!exception) {
+ fail("Allowed modification of collection");
+ }
+
+ try {
+ c.remove(new Object());
+ fail("Allowed modification of collection");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ }
+
+ Collection myCollection = new ArrayList();
+ myCollection.add(new Integer(20));
+ myCollection.add(null);
+ c = Collections.unmodifiableCollection(myCollection);
+ assertTrue("Collection should contain null", c.contains(null));
+ assertTrue("Collection should contain Integer(20)", c
+ .contains(new Integer(20)));
+
+ myCollection = new ArrayList();
+ for (int i = 0; i < 100; i++) {
+ myCollection.add(objArray[i]);
+ }
+ new Support_UnmodifiableCollectionTest("", Collections
+ .unmodifiableCollection(myCollection)).runTest();
+ }
+
+ public void test_unmodifiableListLjava_util_List() {
+ // Test for method java.util.List
+ // java.util.Collections.unmodifiableList(java.util.List)
+
+ // test with a Sequential Access List
+ boolean exception = false;
+ List c = Collections.unmodifiableList(ll);
+ // Ensure a NPE is thrown if the list is NULL
+ try {
+ Collections.unmodifiableList(null);
+ fail("Expected NullPointerException for null list parameter");
+ } catch (NullPointerException e) {
+ }
+
+ assertTrue("Returned list is of incorrect size", c.size() == ll.size());
+ assertTrue(
+ "Returned List should not implement Random Access interface",
+ !(c instanceof RandomAccess));
+
+ Iterator iterator = ll.iterator();
+ while (iterator.hasNext())
+ assertTrue("Returned list missing elements", c.contains(iterator.next()));
+ try {
+ c.add(new Object());
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+ if (!exception) {
+ fail("Allowed modification of list");
+ }
+
+ try {
+ c.remove(new Object());
+ fail("Allowed modification of list");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ }
+
+ // test with a Random Access List
+ List smallList = new ArrayList();
+ smallList.add(null);
+ smallList.add("yoink");
+ c = Collections.unmodifiableList(smallList);
+ assertNull("First element should be null", c.get(0));
+ assertTrue("List should contain null", c.contains(null));
+ assertTrue(
+ "T1. Returned List should implement Random Access interface",
+ c instanceof RandomAccess);
+
+ smallList = new ArrayList();
+ for (int i = 0; i < 100; i++) {
+ smallList.add(objArray[i]);
+ }
+ List myList = Collections.unmodifiableList(smallList);
+ assertTrue("List should not contain null", !myList.contains(null));
+ assertTrue(
+ "T2. Returned List should implement Random Access interface",
+ myList instanceof RandomAccess);
+
+ assertTrue("get failed on unmodifiable list", myList.get(50).equals(
+ new Integer(50)));
+ ListIterator listIterator = myList.listIterator();
+ for (int i = 0; listIterator.hasNext(); i++) {
+ assertTrue("List has wrong elements", ((Integer) listIterator
+ .next()).intValue() == i);
+ }
+ new Support_UnmodifiableCollectionTest("", smallList).runTest();
+ }
+
+ public void test_unmodifiableMapLjava_util_Map() {
+ // Test for method java.util.Map
+ // java.util.Collections.unmodifiableMap(java.util.Map)
+ boolean exception = false;
+ Map c = Collections.unmodifiableMap(hm);
+ assertTrue("Returned map is of incorrect size", c.size() == hm.size());
+ Iterator iterator = hm.keySet().iterator();
+ while (iterator.hasNext()) {
+ Object x = iterator.next();
+ assertTrue("Returned map missing elements", c.get(x).equals(
+ hm.get(x)));
+ }
+ try {
+ c.put(new Object(), "");
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+ assertTrue("Allowed modification of map", exception);
+
+ exception = false;
+ try {
+ c.remove(new Object());
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Allowed modification of map", exception);
+
+ exception = false;
+ Iterator entrySetIterator = c.entrySet().iterator();
+ Map.Entry entry = (Map.Entry) entrySetIterator.next();
+ try {
+ entry.setValue("modified");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Allowed modification of entry", exception);
+
+ exception = false;
+ Object[] array = c.entrySet().toArray();
+ try {
+ ((Map.Entry) array[0]).setValue("modified");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Allowed modification of array entry", exception);
+
+ exception = false;
+ Map.Entry[] array2 = (Map.Entry[]) c.entrySet().toArray(
+ new Map.Entry[0]);
+ try {
+ array2[0].setValue("modified");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ exception = true;
+ }
+ assertTrue("Allowed modification of array entry2", exception);
+
+ HashMap smallMap = new HashMap();
+ smallMap.put(null, new Long(30));
+ smallMap.put(new Long(25), null);
+ Map unmodMap = Collections.unmodifiableMap(smallMap);
+
+ assertNull("Trying to use a null value in map failed", unmodMap
+ .get(new Long(25)));
+ assertTrue("Trying to use a null key in map failed", unmodMap.get(null)
+ .equals(new Long(30)));
+
+ smallMap = new HashMap();
+ for (int i = 0; i < 100; i++) {
+ smallMap.put(objArray[i].toString(), objArray[i]);
+ }
+ new MapTestSupport(smallMap).runTest();
+ }
+
+ public void test_unmodifiableSetLjava_util_Set() {
+ // Test for method java.util.Set
+ // java.util.Collections.unmodifiableSet(java.util.Set)
+ boolean exception = false;
+ Set c = Collections.unmodifiableSet(s);
+ assertTrue("Returned set is of incorrect size", c.size() == s.size());
+ Iterator iterator = ll.iterator();
+ while (iterator.hasNext())
+ assertTrue("Returned set missing elements", c.contains(iterator.next()));
+ try {
+ c.add(new Object());
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+ if (!exception) {
+ fail("Allowed modification of set");
+ }
+ try {
+ c.remove(new Object());
+ fail("Allowed modification of set");
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ }
+
+ Set mySet = Collections.unmodifiableSet(new HashSet());
+ assertTrue("Should not contain null", !mySet.contains(null));
+ mySet = Collections.unmodifiableSet(Collections.singleton(null));
+ assertTrue("Should contain null", mySet.contains(null));
+
+ mySet = new TreeSet();
+ for (int i = 0; i < 100; i++) {
+ mySet.add(objArray[i]);
+ }
+ new Support_UnmodifiableCollectionTest("", Collections
+ .unmodifiableSet(mySet)).runTest();
+ }
+
+ public void test_unmodifiableSortedMapLjava_util_SortedMap() {
+ // Test for method java.util.SortedMap
+ // java.util.Collections.unmodifiableSortedMap(java.util.SortedMap)
+ boolean exception = false;
+ TreeMap tm = new TreeMap();
+ tm.putAll(hm);
+ Map c = Collections.unmodifiableSortedMap(tm);
+ assertTrue("Returned map is of incorrect size", c.size() == tm.size());
+ Iterator i = hm.keySet().iterator();
+ while (i.hasNext()) {
+ Object x = i.next();
+ assertTrue("Returned map missing elements", c.get(x).equals(
+ tm.get(x)));
+ }
+ try {
+ c.put(new Object(), "");
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+
+ if (!exception) {
+ fail("Allowed modification of map");
+ }
+ try {
+ c.remove(new Object());
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ return;
+ }
+ fail("Allowed modification of map");
+ }
+
+ public void test_unmodifiableSortedSetLjava_util_SortedSet() {
+ // Test for method java.util.SortedSet
+ // java.util.Collections.unmodifiableSortedSet(java.util.SortedSet)
+ boolean exception = false;
+ SortedSet ss = new TreeSet();
+ ss.addAll(s);
+ SortedSet c = Collections.unmodifiableSortedSet(ss);
+ assertTrue("Returned set is of incorrect size", c.size() == ss.size());
+ Iterator i = ll.iterator();
+ while (i.hasNext())
+ assertTrue("Returned set missing elements", c.contains(i.next()));
+ try {
+ c.add(new Object());
+ } catch (UnsupportedOperationException e) {
+ exception = true;
+ // Correct
+ }
+ if (!exception) {
+ fail("Allowed modification of set");
+ }
+ try {
+ c.remove(new Object());
+ } catch (UnsupportedOperationException e) {
+ // Correct
+ return;
+ }
+ fail("Allowed modification of set");
+ }
+
+ /**
+ * Test unmodifiable objects toString methods
+ */
+ public void test_unmodifiable_toString_methods() {
+ // Regression for HARMONY-552
+ ArrayList al = new ArrayList();
+ al.add("a");
+ al.add("b");
+ Collection uc = Collections.unmodifiableCollection(al);
+ assertEquals("[a, b]", uc.toString());
+ HashMap m = new HashMap();
+ m.put("one", "1");
+ m.put("two", "2");
+ Map um = Collections.unmodifiableMap(m);
+ assertTrue("{one=1, two=2}".equals(um.toString()) ||
+ "{two=2, one=1}".equals(um.toString()));
+ }
+
+
+ public void test_singletonListLjava_lang_Object() {
+ // Test for method java.util.Set
+ // java.util.Collections.singleton(java.lang.Object)
+ String str = "Singleton";
+
+ List single = Collections.singletonList(str);
+ assertEquals(1, single.size());
+ assertTrue(single.contains(str));
+ assertFalse(single.contains(null));
+ assertFalse(Collections.singletonList(null).contains(str));
+ assertTrue(Collections.singletonList(null).contains(null));
+
+ try {
+ single.add("New element");
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_singletonMapLjava_lang_Object() {
+ // Test for method java.util.Set
+ // java.util.Collections.singleton(java.lang.Object)
+ Double key = new Double (3.14);
+ String value = "Fundamental constant";
+
+ Map single = Collections.singletonMap(key, value);
+ assertEquals(1, single.size());
+ assertTrue(single.containsKey(key));
+ assertTrue(single.containsValue(value));
+ assertFalse(single.containsKey(null));
+ assertFalse(single.containsValue(null));
+ assertFalse(Collections.singletonMap(null, null).containsKey(key));
+ assertFalse(Collections.singletonMap(null, null).containsValue(value));
+ assertTrue(Collections.singletonMap(null, null).containsKey(null));
+ assertTrue(Collections.singletonMap(null, null).containsValue(null));
+
+ try {
+ single.clear();
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+
+ try {
+ single.put(new Double(1), "one wrong value");
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_checkType_Ljava_lang_Object_Ljava_lang_Class() throws Exception {
+ Method m = Collections.class.getDeclaredMethod("checkType", Object.class, Class.class);
+ m.setAccessible(true);
+ m.invoke(null, new Object(), Object.class);
+
+ try {
+ m.invoke(null, new Object(), int.class);
+ fail();
+ } catch (InvocationTargetException expected) {
+ }
+ }
+
+ public void test_binarySearch_asymmetry_with_comparator() throws Exception {
+ List list = new ArrayList();
+ String s1 = new String("a");
+ String s2 = new String("aa");
+ String s3 = new String("aaa");
+ list.add(s1);
+ list.add(s2);
+ list.add(s3);
+ Collections.sort(list);
+ Object o = Collections.binarySearch(list, 1, new StringComparator());
+ assertSame(0, o);
+ }
+
+ public void test_binarySearch_asymmetry() throws Exception {
+ List list = new LinkedList();
+ String s1 = new String("a");
+ String s2 = new String("aa");
+ String s3 = new String("aaa");
+ list.add(new MyComparable(s1));
+ list.add(new MyComparable(s2));
+ list.add(new MyComparable(s3));
+ Collections.sort(list);
+ Object o = Collections.binarySearch(list, 1);
+ assertSame(0, o);
+ }
+
+
+ private class MyComparable implements Comparable {
+
+ public String s;
+
+ public MyComparable(String s) {
+ this.s = s;
+
+ }
+
+ public int compareTo(Object another) {
+ int length = 0;
+ if (another instanceof MyComparable) {
+ length = (((MyComparable) another).s).length();
+ } else {
+ length = (Integer) another;
+ }
+ return s.length() - length;
+ }
+
+ }
+
+ private class StringComparator implements Comparator {
+
+ public int compare(Object object1, Object object2) {
+ String s = (String) object1;
+ int length;
+ if (object2 instanceof String) {
+ length = ((String) object2).length();
+ } else {
+ length = (Integer) object2;
+ }
+ return s.length() - length;
+ }
+ }
+
+
+ public void test_newSetFromMap_LMap() throws Exception {
+ Integer testInt[] = new Integer[100];
+ for (int i = 0; i < testInt.length; i++) {
+ testInt[i] = new Integer(i);
+ }
+ Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
+ Set<Integer> set = Collections.newSetFromMap(map);
+ for (int i = 0; i < testInt.length; i++) {
+ map.put(testInt[i], true);
+ }
+ // operater on map successed
+ map.put(testInt[1], false);
+ assertTrue(map.containsKey(testInt[1]));
+ assertEquals(100, map.size());
+ assertFalse(map.get(testInt[1]));
+ assertEquals(100, set.size());
+ assertTrue(set.contains(testInt[16]));
+ Iterator setIter = set.iterator();
+ Iterator mapIter = map.keySet().iterator();
+ int i = 0;
+ // in the same order
+ while (setIter.hasNext()) {
+ assertEquals(mapIter.next(), setIter.next());
+ }
+
+ // operator on set successed
+ Integer testInt101 = new Integer(101);
+ Integer testInt102 = new Integer(102);
+ set.add(testInt101);
+ assertTrue(set.contains(testInt101));
+ assertTrue(map.get(testInt101));
+
+ // operator on map still passes
+ map.put(testInt102, false);
+ assertTrue(set.contains(testInt102));
+ assertFalse(map.get(testInt102));
+
+ // exception thrown
+ try {
+ Collections.newSetFromMap(map);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationSelf_newSetFromMap() throws Exception {
+ Integer testInt[] = new Integer[100];
+ for (int i = 0; i < testInt.length; i++) {
+ testInt[i] = new Integer(i);
+ }
+ Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
+ Set<Integer> set = Collections.newSetFromMap(map);
+ for (int i = 0; i < testInt.length; i++) {
+ map.put(testInt[i], true);
+ }
+ SerializationTest.verifySelf(set);
+ }
+
+ public void test_asLifoQueue() throws Exception {
+ Integer testInt[] = new Integer[100];
+ Integer test101 = new Integer(101);
+ for (int i = 0; i < testInt.length; i++) {
+ testInt[i] = new Integer(i);
+ }
+ Deque deque = new ArrayDeque<Integer>();
+ Queue<Integer> que = Collections.asLifoQueue(deque);
+ for (int i = 0; i < testInt.length; i++) {
+ que.add(testInt[i]);
+ }
+ assertEquals(100, deque.size());
+ assertEquals(100, que.size());
+ for (int i = testInt.length - 1; i >= 0; i--) {
+ assertEquals(testInt[i], deque.pop());
+ }
+ assertEquals(0, deque.size());
+ assertEquals(0, que.size());
+ for (int i = 0; i < testInt.length; i++) {
+ deque.push(testInt[i]);
+ }
+ assertEquals(100, deque.size());
+ assertEquals(100, que.size());
+ Collection col = new LinkedList<Integer>();
+ col.add(test101);
+ que.addAll(col);
+ assertEquals(test101, que.remove());
+ for (int i = testInt.length - 1; i >= 0; i--) {
+ assertEquals(testInt[i], que.remove());
+ }
+ assertEquals(0, deque.size());
+ assertEquals(0, que.size());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationSelf_asLifoQueue() throws Exception {
+ Integer testInt[] = new Integer[100];
+ for (int i = 0; i < testInt.length; i++) {
+ testInt[i] = new Integer(i);
+ }
+ Deque deque = new ArrayDeque<Integer>();
+ Queue<Integer> que = Collections.asLifoQueue(deque);
+ for (int i = 0; i < testInt.length; i++) {
+ que.add(testInt[i]);
+ }
+ SerializationTest.verifySelf(que, new SerializableAssert() {
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ Queue<Integer> initque = (Queue) initial;
+ Queue<Integer> deserque = (Queue) deserialized;
+ while (!initque.isEmpty()) {
+ assertEquals(initque.remove(), deserque.remove());
+ }
+ }
+ });
+ }
+
+ public void test_emptyList() {
+ List<String> list = Collections.emptyList();
+ assertTrue("should be true", list.isEmpty());
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ objArray = new Integer[1000];
+ myobjArray = new Object[1000];
+ for (int i = 0; i < objArray.length; i++) {
+ objArray[i] = i;
+ myobjArray[i] = new MyInt(i);
+ }
+
+ ll = new LinkedList();
+ myll = new LinkedList();
+ s = new HashSet();
+ mys = new HashSet();
+ reversedLinkedList = new LinkedList(); // to be sorted in reverse order
+ myReversedLinkedList = new LinkedList(); // to be sorted in reverse
+ // order
+ hm = new HashMap();
+ for (int i = 0; i < objArray.length; i++) {
+ ll.add(objArray[i]);
+ myll.add(myobjArray[i]);
+ s.add(objArray[i]);
+ mys.add(myobjArray[i]);
+ reversedLinkedList.add(objArray[objArray.length - i - 1]);
+ myReversedLinkedList.add(myobjArray[myobjArray.length - i - 1]);
+ hm.put(objArray[i].toString(), objArray[i]);
+ }
+ }
+
+ /**
+ * A class shared by various Map-related tests that checks the properties and contents of a
+ * supplied Map and compares the some methods to the same map when wrapped with
+ * {@link Collections#unmodifiableMap(java.util.Map)}.
+ */
+ static class MapTestSupport {
+
+ // must be a map containing the string keys "0"-"99" paired with the Integer
+ // values Integer(0) to Integer(99)
+ private final Map<String, Integer> modifiableMap;
+ private final Map<String, Integer> unmodifiableMap;
+
+ public MapTestSupport(Map<String, Integer> modifiableMap) {
+ this.modifiableMap = modifiableMap;
+ unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
+ }
+
+ public void runTest() {
+ testContents(modifiableMap);
+ testContents(unmodifiableMap);
+
+ // values()
+ new Support_UnmodifiableCollectionTest("values() from map test", modifiableMap.values())
+ .runTest();
+ new Support_UnmodifiableCollectionTest("values() from unmodifiable map test",
+ unmodifiableMap.values()).runTest();
+
+ // entrySet()
+ testEntrySet(modifiableMap.entrySet(), unmodifiableMap.entrySet());
+
+ // keySet()
+ testKeySet(modifiableMap.keySet(), unmodifiableMap.keySet());
+ }
+
+ private static void testContents(Map<String, Integer> map) {
+ // size
+ assertTrue("Size should return 100, returned: " + map.size(), map.size() == 100);
+
+ // containsKey
+ assertTrue("Should contain the key \"0\"", map.containsKey("0"));
+ assertTrue("Should contain the key \"50\"", map.containsKey("50"));
+ assertTrue("Should not contain the key \"100\"", !map.containsKey("100"));
+
+ // containsValue
+ assertTrue("Should contain the value 0", map.containsValue(0));
+ assertTrue("Should contain the value 50", map.containsValue(50));
+ assertTrue("Should not contain value 100", !map.containsValue(100));
+
+ // get
+ assertTrue("getting \"0\" didn't return 0", map.get("0") == 0);
+ assertTrue("getting \"50\" didn't return 50", map.get("50") == 50);
+ assertNull("getting \"100\" didn't return null", map.get("100"));
+
+ // isEmpty
+ assertTrue("should have returned false to isEmpty", !map.isEmpty());
+ }
+
+ private static void testEntrySet(
+ Set<Map.Entry<String, Integer>> referenceEntrySet,
+ Set<Map.Entry<String, Integer>> entrySet) {
+ // entrySet should be a set of mappings {"0", 0}, {"1",1}... {"99", 99}
+ assertEquals(100, referenceEntrySet.size());
+ assertEquals(100, entrySet.size());
+
+ // The ordering may be undefined for a map implementation but the ordering must be the
+ // same across iterator(), toArray() and toArray(T[]) for a given map *and* the same for the
+ // modifiable and unmodifiable map.
+ crossCheckOrdering(referenceEntrySet, entrySet, Map.Entry.class);
+ }
+
+ private static void testKeySet(Set<String> referenceKeySet, Set<String> keySet) {
+ // keySet should be a set of the strings "0" to "99"
+ testKeySetContents(referenceKeySet);
+ testKeySetContents(keySet);
+
+ // The ordering may be undefined for a map implementation but the ordering must be the
+ // same across iterator(), toArray() and toArray(T[]) for a given map *and* the same for the
+ // modifiable and unmodifiable map.
+ crossCheckOrdering(referenceKeySet, keySet, String.class);
+ }
+
+ private static void testKeySetContents(Set<String> keySet) {
+ // contains
+ assertTrue("should contain \"0\"", keySet.contains("0"));
+ assertTrue("should contain \"50\"", keySet.contains("50"));
+ assertTrue("should not contain \"100\"", !keySet.contains("100"));
+
+ // containsAll
+ HashSet<String> hs = new HashSet<String>();
+ hs.add("0");
+ hs.add("25");
+ hs.add("99");
+ assertTrue("Should contain set of \"0\", \"25\", and \"99\"", keySet.containsAll(hs));
+ hs.add("100");
+ assertTrue("Should not contain set of \"0\", \"25\", \"99\" and \"100\"",
+ !keySet.containsAll(hs));
+
+ // isEmpty
+ assertTrue("Should not be empty", !keySet.isEmpty());
+
+ // size
+ assertEquals("Returned wrong size.", 100, keySet.size());
+ }
+
+ private static <T> void crossCheckOrdering(Set<T> set1, Set<T> set2, Class<?> elementType) {
+ Iterator<T> set1Iterator = set1.iterator();
+ Iterator<T> set2Iterator = set2.iterator();
+
+ T[] zeroLengthArray = createArray(elementType, 0);
+ T[] set1TypedArray1 = set1.toArray(zeroLengthArray);
+ assertEquals(set1.size(), set1TypedArray1.length);
+
+ // Compare set1.iterator(), set2.iterator() and set1.toArray(new T[0])
+ int entryCount = 0;
+ while (set1Iterator.hasNext()) {
+ T set1Entry = set1Iterator.next();
+ T set2Entry = set2Iterator.next();
+
+ // Compare set1 with set2
+ assertEquals(set1Entry, set2Entry);
+
+ // Compare the iterator with the array. The arrays will be checked against each other.
+ assertEquals(set1Entry, set1TypedArray1[entryCount]);
+
+ entryCount++;
+ }
+ assertFalse(set2Iterator.hasNext());
+ assertEquals(set1.size(), entryCount);
+
+ // Compare the various arrays with each other.
+
+ // set1.toArray(new T[size])
+ T[] parameterArray1 = createArray(elementType, set1.size());
+ T[] set1TypedArray2 = set1.toArray(parameterArray1);
+ assertSame(set1TypedArray2, parameterArray1);
+ assertArrayEquals(set1TypedArray1, set1TypedArray2);
+
+ // set1.toArray()
+ Object[] set1UntypedArray = set1.toArray();
+ assertEquals(set1.size(), set1UntypedArray.length);
+ assertArrayEquals(set1TypedArray1, set1UntypedArray);
+
+ // set2.toArray(new T[0])
+ T[] set2TypedArray1 = set2.toArray(zeroLengthArray);
+ assertEquals(set1.size(), set2TypedArray1.length);
+ assertArrayEquals(set1TypedArray1, set2TypedArray1);
+
+ // set2.toArray(new T[size])
+ T[] parameterArray2 = createArray(elementType, set2.size());
+ T[] set2TypedArray2 = set1.toArray(parameterArray2);
+ assertSame(set2TypedArray2, parameterArray2);
+ assertArrayEquals(set1TypedArray1, set1TypedArray2);
+
+ // set2.toArray()
+ Object[] set2UntypedArray = set2.toArray();
+ assertArrayEquals(set1TypedArray1, set2UntypedArray);
+ }
+
+ private static <T> void assertArrayEquals(T[] array1, T[] array2) {
+ assertTrue(Arrays.equals(array1, array2));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T[] createArray(Class<?> elementType, int size) {
+ return (T[]) Array.newInstance(elementType, size);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModTest.java
new file mode 100644
index 0000000..2e2553d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModTest.java
@@ -0,0 +1,667 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractList;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.List;
+import java.util.Vector;
+
+import junit.framework.TestCase;
+
+public class ConcurrentModTest extends TestCase {
+
+ /*
+ * Test method for 'java.util.AbstractList.subList(int, int)'
+ */
+ public void testGet() {
+ AbstractList al = new ArrayList();
+ Double one = new Double(1.0);
+ Double two = new Double(2.0);
+ Double three = new Double(3.0);
+ Double four = new Double(4.0);
+ al.add(one);
+ al.add(two);
+ al.add(three);
+ al.add(four);
+ List sub = al.subList(1, 3);
+ assertEquals(2, sub.size());
+ // the sub.get(1) is 3.0
+ assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
+ assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
+
+ al.remove(1); // remove the 2.0
+
+ try {
+ // illegal call the subList's method get(int).
+ sub.get(1);
+ fail("It should throws ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ return;
+ }
+
+ try {
+ al.get(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ al.get(al.size()+1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+ }
+
+ /*
+ * Test method for 'java.util.AbstractList.subList(int, int)'
+ */
+ public void testSet() {
+ AbstractList al = new ArrayList();
+ Double one = new Double(1.0);
+ Double two = new Double(2.0);
+ Double three = new Double(3.0);
+ Double four = new Double(4.0);
+ al.add(one);
+ al.add(two);
+ al.add(three);
+ al.add(four);
+ List sub = al.subList(1, 3);
+ assertEquals(2, sub.size());
+ // the sub.get(1) is 3.0
+ assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
+ assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
+
+ al.remove(1); // remove the 2.0
+
+ try {
+ // illegal call the subList's method set(int,Object).
+ sub.set(1, two);
+ fail("It should throws ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ return;
+ }
+ }
+
+ /*
+ * Test method for 'java.util.AbstractList.subList(int, int)'
+ */
+ public void testAdd() {
+ AbstractList al = new ArrayList();
+ Double one = new Double(1.0);
+ Double two = new Double(2.0);
+ Double three = new Double(3.0);
+ Double four = new Double(4.0);
+ al.add(one);
+ al.add(two);
+ al.add(three);
+ al.add(four);
+ List sub = al.subList(1, 3);
+ assertEquals(2, sub.size());
+ // the sub.get(1) is 3.0
+ assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
+ assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
+
+ al.remove(1); // remove the 2.0
+
+ try {
+ // illegal call the subList's method Add(int,Object).
+ sub.add(1, two);
+ fail("It should throws ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ return;
+ }
+ }
+
+ /*
+ * Test method for 'java.util.AbstractList.subList(int, int)'
+ */
+ public void testRemove() {
+ AbstractList al = new ArrayList();
+ Double one = new Double(1.0);
+ Double two = new Double(2.0);
+ Double three = new Double(3.0);
+ Double four = new Double(4.0);
+ al.add(one);
+ al.add(two);
+ al.add(three);
+ al.add(four);
+ List sub = al.subList(1, 3);
+ assertEquals(2, sub.size());
+ // the sub.get(1) is 3.0
+ assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
+ assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
+
+ al.remove(1); // remove the 2.0
+
+ try {
+ // illegal call the subList's method remove(int).
+ sub.remove(1);
+ fail("It should throws ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ return;
+ }
+
+ try {
+ sub.remove(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ sub.remove(sub.size() + 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ al = new AbstractList() {
+
+ @Override
+ public Object get(int index) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int size() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+ };
+
+ try {
+ al.remove(1);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException ee) {
+ //expected
+ }
+ }
+
+ /*
+ * Test method for 'java.util.AbstractList.subList(int, int)'
+ */
+ public void testAddAll() {
+ AbstractList al = new ArrayList();
+ Double one = new Double(1.0);
+ Double two = new Double(2.0);
+ Double three = new Double(3.0);
+ Double four = new Double(4.0);
+ al.add(one);
+ al.add(two);
+ al.add(three);
+ al.add(four);
+ List sub = al.subList(1, 3);
+ assertEquals(2, sub.size());
+ // the sub.get(1) is 3.0
+ assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
+ assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
+
+ al.remove(1); // remove the 2.0
+
+ try {
+ // illegal call the subList's method addAll(int,Collection).
+ Collection c = new Vector();
+ Double five = new Double(5.0);
+ c.add(five);
+ sub.addAll(1, c);
+ fail("It should throws ConcurrentModificationException.");
+ } catch (ConcurrentModificationException e) {
+ return;
+ }
+ }
+
+ public void test_addLjava_lang_Object() {
+ AbstractList abstr = new AbstractList() {
+
+ @Override
+ public Object get(int arg0) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ };
+
+ try {
+ abstr.add(null);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //ecpected
+ }
+ abstr = new AbstractList<Double>() {
+ @Override
+ public boolean add(Double value) {
+ return true;
+ }
+
+ @Override
+ public Double get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.add(1);
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expected
+ }
+
+ abstr = new AbstractList<Integer>() {
+ final int forbiddenValue = 33;
+ @Override
+ public boolean add(Integer value) {
+ if (value == forbiddenValue) {
+ throw new IllegalArgumentException();
+ }
+ return true;
+ }
+
+ @Override
+ public Integer get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ abstr.add(1);
+ try {
+ abstr.add(33);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+ }
+
+ public void test_addILjava_lang_Object() {
+ AbstractList abstr = new AbstractList() {
+
+ @Override
+ public Object get(int arg0) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ };
+
+ try {
+ abstr.add(1, null);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //ecpected
+ }
+ abstr = new AbstractList<Double>() {
+ @Override
+ public void add(int index, Double value) {
+ }
+
+ @Override
+ public Double get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.add(1, 1);
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expected
+ }
+
+ abstr = new AbstractList<Integer>() {
+ final int forbiddenValue = 33;
+ @Override
+ public void add(int index, Integer value) {
+ if (value == forbiddenValue) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ @Override
+ public Integer get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ abstr.add(1, 1);
+ try {
+ abstr.add(1, 33);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+
+ abstr = new ArrayList();
+
+ abstr.add(0, "element");
+ abstr.add(1, null);
+ abstr.add(2, 1);
+ abstr.add(3, new Double(33));
+
+ try {
+ abstr.add(-3, new Double(33));
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ abstr.add(abstr.size() + 1, new Double(33));
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+ }
+
+ public void test_addAllILjava_util_Collection() {
+ Collection c = new Vector();
+ c.add(new Double(33));
+ c.add(10);
+ c.add("String");
+
+ AbstractList abstr = new AbstractList() {
+ @Override
+ public Object get(int arg0) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.addAll(0, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ abstr.addAll(0, c);
+ fail("UnsuportedOperationException expected");
+ } catch (UnsupportedOperationException ee) {
+ //expected
+ }
+
+ abstr = new AbstractList<Double>() {
+ @Override
+ public void add(int index, Double value) {
+ }
+
+ @Override
+ public Double get(int arg0) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.addAll(0, c);
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expectd
+ }
+
+ abstr = new AbstractList<Integer>() {
+ final int forbiddenValue = 33;
+ @Override
+ public void add(int index, Integer value) {
+ if (value == forbiddenValue) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ @Override
+ public Integer get(int arg0) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+ c.clear();
+ c.add(new Integer(1));
+ c.add(new Integer(2));
+ c.add(new Integer(3));
+ c.add(new Integer(4));
+ c.add(new Integer(5));
+
+ abstr.addAll(0, c);
+
+ c.add(new Integer(33));
+
+ try {
+ abstr.addAll(0, c);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+ abstr = new ArrayList();
+ abstr.addAll(0, c);
+
+ try {
+ abstr.addAll(-1, c);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ abstr.addAll(abstr.size() + 1, c);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+ }
+
+ public void test_clear() {
+ AbstractList abstr = new ArrayList();
+
+ assertEquals(0, abstr.size());
+ abstr.add("String");
+ abstr.add("1");
+ abstr.add(2);
+ abstr.add(new Double(3));
+ assertEquals(4, abstr.size());
+ abstr.clear();
+ assertEquals(0, abstr.size());
+ }
+
+ public void test_equalsLjava_lang_Object() {
+ Collection c = new Vector();
+ c.add(new Double(33));
+ c.add(10);
+ c.add("String");
+
+ AbstractList abstr = new ArrayList();
+ AbstractList abstr1 = new ArrayList();
+
+ assertFalse(abstr.equals(this));
+ abstr.add(new Double(33));
+ abstr.add(10);
+ abstr.add("String");
+ assertTrue(abstr.equals(c));
+ abstr1.addAll(c);
+ assertTrue(abstr.equals(abstr1));
+ }
+
+ public void test_setILjava_lang_Object() {
+ Collection c = new Vector();
+ c.add(new Double(33));
+ c.add(10);
+ c.add("String");
+
+ AbstractList abstr1 = new ArrayList();
+ AbstractList abstr2 = new ArrayList();
+
+ abstr1.addAll(c);
+ abstr2.addAll(c);
+ assertTrue(abstr1.equals(abstr2));
+ abstr1.set(1, 1);
+ assertFalse(abstr1.equals(abstr2));
+
+ try {
+ abstr1.set(abstr1.size() + 1, 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ try {
+ abstr1.set(-1, 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException ee) {
+ //expected
+ }
+
+ AbstractList abstr = new AbstractList() {
+
+ @Override
+ public Object get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ };
+
+ try {
+ abstr.set(0, null);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException ee) {
+ //expected
+ }
+
+ abstr = new AbstractList<Double>() {
+ @Override
+ public Double set(int index, Double value) {
+ return value;
+ }
+
+ @Override
+ public Double get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.set(0, 1);
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expected
+ }
+
+ abstr = new AbstractList<Integer>() {
+ final int forbiddenValue = 33;
+ @Override
+ public Integer set(int index, Integer value) {
+ if (value == forbiddenValue) {
+ throw new IllegalArgumentException();
+ }
+ return value;
+ }
+
+ @Override
+ public Integer get(int index) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+ };
+
+ try {
+ abstr.set(0, 33);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ //expected
+ }
+ }
+ class Mock_ArrayList extends ArrayList {
+ @Override
+ public void removeRange(int fromIndex, int toIndex) {
+ super.removeRange(fromIndex, toIndex);
+ }
+ }
+
+ public void test_removeRangeII() {
+ Mock_ArrayList al1 = new Mock_ArrayList();
+ al1.add(1);
+ al1.add(2);
+ al1.add(3);
+ al1.add(4);
+ al1.add(5);
+ Mock_ArrayList al2 = new Mock_ArrayList();
+
+ al2.add(1);
+ al2.add(5);
+ assertNotSame(al1,al2);
+ al1.removeRange(1, 4);
+ assertEquals(al1,al2);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModificationExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModificationExceptionTest.java
new file mode 100644
index 0000000..2bbcd1e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ConcurrentModificationExceptionTest.java
@@ -0,0 +1,107 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.LinkedList;
+
+public class ConcurrentModificationExceptionTest extends
+ junit.framework.TestCase {
+
+ static public class CollectionModifier implements Runnable {
+ Collection col;
+
+ boolean keepGoing = true;
+
+ public CollectionModifier(Collection c) {
+ col = c;
+ }
+
+ public void stopNow() {
+ keepGoing = false;
+ }
+
+ public void run() {
+ Object someItem = new Integer(-1);
+ while (keepGoing) {
+ col.add(someItem);
+ col.remove(someItem);
+ }
+ }
+ }
+
+ /**
+ * java.util.ConcurrentModificationException#ConcurrentModificationException()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.ConcurrentModificationException()
+ Collection myCollection = new LinkedList();
+ Iterator myIterator = myCollection.iterator();
+ for (int counter = 0; counter < 50; counter++)
+ myCollection.add(new Integer(counter));
+ CollectionModifier cm = new CollectionModifier(myCollection);
+ Thread collectionSlapper = new Thread(cm);
+ try {
+ collectionSlapper.start();
+ while (myIterator.hasNext())
+ myIterator.next();
+ } catch (ConcurrentModificationException e) {
+ cm.stopNow();
+ return;
+ }
+ cm.stopNow();
+ // The exception should have been thrown--if the code flow makes it here
+ // the test has failed
+ fail("Failed to throw expected ConcurrentModificationException");
+ }
+
+ /**
+ * java.util.ConcurrentModificationException#ConcurrentModificationException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method
+ // java.util.ConcurrentModificationException(java.lang.String)
+ String errorMessage = "This is an error message";
+ try {
+ // This is here to stop "unreachable code" unresolved problem
+ if (true)
+ throw new ConcurrentModificationException(errorMessage);
+ } catch (ConcurrentModificationException e) {
+ assertTrue("Exception thrown without error message", e.getMessage()
+ .equals(errorMessage));
+ return;
+ }
+ fail("Failed to throw expected ConcurrentModificationException");
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ControlTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ControlTest.java
new file mode 100644
index 0000000..d0b236d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ControlTest.java
@@ -0,0 +1,682 @@
+/*
+ * 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.tests.java.util;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.ListResourceBundle;
+import java.util.Locale;
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+import java.util.ResourceBundle.Control;
+import java.util.Scanner;
+import static java.util.ResourceBundle.Control.*;
+
+/**
+ * Test cases for java.util.ResourceBundle.Control
+ *
+ * @since 1.6
+ */
+public class ControlTest extends TestCase {
+
+ /**
+ * Control with format:FORMAT_PROPERTIES
+ */
+ private Control controlP;
+
+ /**
+ * Control with format:FORMAT_CLASS
+ */
+ private Control controlC;
+
+ /**
+ * Control with format:FORMAT_DEFAULT
+ */
+ private Control control;
+
+ /**
+ * {@link java.util.ResourceBundle.Control#Control()}.
+ */
+ @SuppressWarnings("nls")
+ public void test_Constructor() {
+
+ class SubControl extends Control {
+ SubControl() {
+ super();
+ }
+ }
+ Control subControl = new SubControl();
+ assertEquals(FORMAT_DEFAULT, subControl.getFormats(""));
+ assertFalse(control.equals(subControl));
+ }
+
+ /**
+ * Test for all the public constants.
+ *
+ * {@link java.util.ResourceBundle.Control#FORMAT_CLASS}
+ * {@link java.util.ResourceBundle.Control#FORMAT_DEFAULT}
+ * {@link java.util.ResourceBundle.Control#FORMAT_PROPERTIES}
+ * {@link java.util.ResourceBundle.Control#TTL_DONT_CACHE}
+ * {@link java.util.ResourceBundle.Control#TTL_NO_EXPIRATION_CONTROL}
+ */
+ @SuppressWarnings("nls")
+ public void test_Constants() {
+ List<String> list = FORMAT_CLASS;
+ assertEquals(1, list.size());
+ assertEquals("java.class", list.get(0));
+ list = FORMAT_PROPERTIES;
+ assertEquals(1, list.size());
+ assertEquals("java.properties", list.get(0));
+ list = FORMAT_DEFAULT;
+ assertEquals(2, list.size());
+ assertEquals("java.class", list.get(0));
+ assertEquals("java.properties", list.get(1));
+ try {
+ FORMAT_CLASS.add("");
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ FORMAT_DEFAULT.add("");
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ FORMAT_PROPERTIES.add("");
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ Class<?> unmodifiableListClass = Collections.unmodifiableList(
+ new ArrayList<String>()).getClass();
+ assertEquals(FORMAT_CLASS.getClass(), unmodifiableListClass);
+ assertEquals(FORMAT_DEFAULT.getClass(), unmodifiableListClass);
+ assertEquals(FORMAT_PROPERTIES.getClass(), unmodifiableListClass);
+ assertEquals(-1L, TTL_DONT_CACHE);
+ assertEquals(-2L, TTL_NO_EXPIRATION_CONTROL);
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getControl(java.util.List)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getControl_LList() {
+ // singleton
+ assertSame(control, Control.getControl(FORMAT_DEFAULT));
+ assertSame(controlC, Control.getControl(FORMAT_CLASS));
+ assertSame(controlP, Control.getControl(FORMAT_PROPERTIES));
+
+ // class
+ assertTrue(control.getClass() == Control.class);
+ assertTrue(controlC.getClass() != Control.class);
+ assertTrue(controlP.getClass() != Control.class);
+
+ // formats: need not same, just need equal
+ List<String> list = new ArrayList<String>(FORMAT_CLASS);
+ assertSame(controlC, Control.getControl(list));
+ // can add
+ list.add(FORMAT_PROPERTIES.get(0));
+ assertSame(control, Control.getControl(list));
+
+ // exceptions
+ try {
+ Control.getControl(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ list = new ArrayList<String>();
+ try {
+ Control.getControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ list = new ArrayList<String>(FORMAT_CLASS);
+ // java.class -> JAVA.CLASS
+ list.set(0, list.get(0).toUpperCase());
+ try {
+ Control.getControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ list = new ArrayList<String>(FORMAT_CLASS);
+ list.add("");
+ try {
+ Control.getControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getNoFallbackControl(java.util.List)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getNoFallbackControl_LList() {
+ assertNotSame(control, Control.getNoFallbackControl(FORMAT_DEFAULT));
+ assertNotSame(controlC, Control.getNoFallbackControl(FORMAT_CLASS));
+ assertNotSame(controlP, Control.getNoFallbackControl(FORMAT_PROPERTIES));
+ controlP = Control.getNoFallbackControl(FORMAT_PROPERTIES);
+ controlC = Control.getNoFallbackControl(FORMAT_CLASS);
+ control = Control.getNoFallbackControl(FORMAT_DEFAULT);
+ // singleton
+ assertSame(control, Control.getNoFallbackControl(FORMAT_DEFAULT));
+ assertSame(controlC, Control.getNoFallbackControl(FORMAT_CLASS));
+ assertSame(controlP, Control.getNoFallbackControl(FORMAT_PROPERTIES));
+
+ // class
+ assertTrue(control.getClass() != Control.class);
+ assertTrue(controlC.getClass() != Control.class);
+ assertTrue(controlP.getClass() != Control.class);
+
+ // format
+ assertEquals(FORMAT_CLASS, controlC.getFormats(""));
+ assertEquals(FORMAT_DEFAULT, control.getFormats(""));
+ assertEquals(FORMAT_PROPERTIES, controlP.getFormats(""));
+
+ // no fall back locale
+ Locale defaultLocale = Locale.getDefault();
+ Locale.setDefault(new Locale("TestLanguage", "TestCountry", "Var"));
+ assertNull(control.getFallbackLocale("message", Locale.US));
+ try {
+ control.getFallbackLocale("message", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.getFallbackLocale(null, Locale.US);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ Locale.setDefault(defaultLocale);
+
+ // formats: need not same, just need equal
+ List<String> list = new ArrayList<String>(FORMAT_CLASS);
+ assertSame(controlC, Control.getNoFallbackControl(list));
+ // can add
+ list.add(FORMAT_PROPERTIES.get(0));
+ assertSame(control, Control.getNoFallbackControl(list));
+
+ // exceptions
+ try {
+ Control.getNoFallbackControl(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ list = new ArrayList<String>();
+ try {
+ Control.getNoFallbackControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ list = new ArrayList<String>(FORMAT_CLASS);
+ // java.class -> JAVA.CLASS
+ list.set(0, list.get(0).toUpperCase());
+ try {
+ Control.getNoFallbackControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ list = new ArrayList<String>(FORMAT_CLASS);
+ list.add("");
+ try {
+ Control.getNoFallbackControl(list);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getFormats(java.lang.String)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getFormats_LString() {
+ assertEquals(FORMAT_DEFAULT, control.getFormats(""));
+ assertEquals(FORMAT_PROPERTIES, controlP.getFormats(""));
+ assertEquals(FORMAT_CLASS, controlC.getFormats(""));
+ try {
+ controlC.getFormats(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getCandidateLocales(java.lang.String, java.util.Locale)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getCandidateLocales_LStringLLocale() {
+ // the ResourceBundle for this baseName and Locale does not exists
+ List<Locale> result = control.getCandidateLocales("baseName",
+ new Locale("one", "two", "three"));
+ assertEquals(4, result.size());
+ Locale locale = result.get(0);
+ assertEquals("one", locale.getLanguage());
+ assertEquals("TWO", locale.getCountry());
+ assertEquals("three", locale.getVariant());
+ assertEquals(new Locale("one", "TWO"), result.get(1));
+ assertEquals(new Locale("one"), result.get(2));
+ assertSame(Locale.ROOT, result.get(3));
+ // ArrayList is not immutable
+ assertTrue(ArrayList.class == result.getClass());
+
+ result = control.getCandidateLocales("baseName", new Locale("one",
+ "two", ""));
+ assertEquals(new Locale("one", "TWO"), result.get(0));
+ assertEquals(new Locale("one"), result.get(1));
+ assertSame(Locale.ROOT, result.get(2));
+
+ result = control.getCandidateLocales("baseName", new Locale("one", "",
+ "three"));
+ assertEquals(new Locale("one", "", "three"), result.get(0));
+ assertEquals(new Locale("one"), result.get(1));
+ assertSame(Locale.ROOT, result.get(2));
+
+ result = control.getCandidateLocales("baseName", new Locale("", "two",
+ "three"));
+ assertEquals(new Locale("", "TWO", "three"), result.get(0));
+ assertEquals(new Locale("", "TWO"), result.get(1));
+ assertSame(Locale.ROOT, result.get(2));
+
+ result = control.getCandidateLocales("baseName", new Locale("", "",
+ "three"));
+ assertEquals(new Locale("", "", "three"), result.get(0));
+ assertSame(Locale.ROOT, result.get(1));
+
+ result = control.getCandidateLocales("baseName", new Locale("", "two",
+ ""));
+ assertEquals(new Locale("", "TWO"), result.get(0));
+ assertSame(Locale.ROOT, result.get(1));
+
+ result = control.getCandidateLocales("baseName", Locale.ROOT);
+ assertSame(Locale.ROOT, result.get(0));
+
+ try {
+ control.getCandidateLocales(null, Locale.US);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ control.getCandidateLocales("baseName", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getFallbackLocale(java.lang.String, java.util.Locale)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getFallbackLocale_LStringLLocale() {
+ Locale defaultLocale = Locale.getDefault();
+ Locale testLocale = new Locale("TestLanguage", "TestCountry", "Var");
+ Locale.setDefault(testLocale);
+ assertSame(testLocale, control.getFallbackLocale("baseName",
+ Locale.ROOT));
+ assertSame(testLocale, control.getFallbackLocale("baseName", Locale.US));
+ assertSame(null, control.getFallbackLocale("baseName", testLocale));
+ try {
+ control.getFallbackLocale(null, Locale.US);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ control.getFallbackLocale("baseName", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ // restore
+ Locale.setDefault(defaultLocale);
+ }
+
+ @SuppressWarnings("nls")
+ static File copyFile(final URL src) throws IOException {
+ String tail = src.getFile().split("hyts_resource")[1];
+ String tmpdir = System.getProperty("java.io.tmpdir");
+ if (null == tmpdir) {
+ return null;
+ }
+ String copyName = tmpdir + File.separator + "hyts_resource_copy" + tail;
+ File copy = new File(copyName);
+ if (copy.exists()) {
+ copy.delete();
+ }
+ copy.createNewFile();
+ copy.deleteOnExit();
+
+ Reader in = new InputStreamReader(src.openStream());
+ Writer out = new FileWriter(copy);
+ int c;
+ while ((c = in.read()) != -1) {
+ out.write(c);
+ }
+ in.close();
+ out.close();
+ return copy;
+ }
+
+ static class SubRBStaticPrivate extends ListResourceBundle {
+ private SubRBStaticPrivate() {
+ super();
+ }
+
+ @Override
+ protected Object[][] getContents() {
+ return null;
+ }
+ }
+
+ /*
+ * change the value in the .properties file
+ */
+ @SuppressWarnings("nls")
+ static void changeProperties(File file) throws FileNotFoundException {
+ String newValue = "property=changedValue";
+ PrintWriter writer = new PrintWriter(file);
+ writer.write(newValue);
+ writer.flush();
+ writer.close();
+ Scanner scanner = new Scanner(file);
+ assertEquals(newValue, scanner.nextLine());
+ scanner.close();
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#getTimeToLive(java.lang.String, java.util.Locale)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_getTimeToLive_LStringLLocale() {
+ assertEquals(TTL_NO_EXPIRATION_CONTROL, control.getTimeToLive(
+ "baseName", Locale.US));
+ try {
+ control.getTimeToLive(null, Locale.US);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.getTimeToLive("baseName", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @throws Exception
+ * {@link java.util.ResourceBundle.Control#needsReload(java.lang.String, java.util.Locale, java.lang.String, java.lang.ClassLoader, java.util.ResourceBundle, long)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_needsReload_LStringLLocaleLStringLClassLoaderResourceBundleJ()
+ throws Exception {
+ String className = "tests.support.Support_TestResource";
+ String propertiesName = Support_Resources.RESOURCE_PACKAGE_NAME
+ + ".hyts_resource";
+ String propertiesNameCopy = "hyts_resource_copy";
+ String CLASS = "java.class";
+ String PROPERTIES = "java.properties";
+ Locale frFR = new Locale("fr", "FR");
+ ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
+ ClassLoader URLLoader = systemLoader;
+ ResourceBundle bundle = null;
+ long time = 0L;
+ final URL srcFile = URLLoader.getResource(control.toResourceName(
+ control.toBundleName(propertiesName, frFR), "properties"));
+ assertNotNull(srcFile);
+ final File copyFile = copyFile(srcFile);
+
+ // 1. format = "java.properties"
+ if (null != URLLoader.getResourceAsStream(copyFile.toURL().toString())) {
+ Thread.sleep(1000);
+ bundle = control.newBundle(propertiesNameCopy, frFR, PROPERTIES,
+ URLLoader, false);
+ time = System.currentTimeMillis();
+ assertTrue(bundle.getClass() == PropertyResourceBundle.class);
+ assertEquals("fr_FR_resource", bundle.getString("property"));
+ assertFalse(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, bundle, time));
+ // change the file
+ Thread.sleep(2000);
+ changeProperties(copyFile);
+ assertTrue(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, bundle, time));
+ // detect again
+ assertTrue(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, bundle, time));
+ // long long ago
+ assertTrue(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, bundle, 2006L));
+ // other loader
+ assertFalse(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, systemLoader, bundle, time));
+ // other bundle
+ ResourceBundle otherBundle = control.newBundle(propertiesName,
+ Locale.ROOT, PROPERTIES, systemLoader, false);
+ assertEquals("parent", otherBundle.getString("property"));
+ assertTrue(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, otherBundle, time));
+ otherBundle = control.newBundle(propertiesName, Locale.ROOT,
+ PROPERTIES, URLLoader, false);
+ assertEquals("resource", otherBundle.getString("property"));
+ assertTrue(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, otherBundle, time));
+ // other time
+ assertFalse(control.needsReload(propertiesNameCopy, frFR,
+ PROPERTIES, URLLoader, bundle, System.currentTimeMillis()));
+ } else {
+ System.err
+ .println("Can not find the test file, some code of this test 'test_needsReload_LStringLLocaleLStringLClassLoaderResourceBundleJ' did not run.");
+
+ }
+
+ // 2. format = "java.class"
+ bundle = control.newBundle(className, frFR, CLASS, systemLoader, false);
+ time = System.currentTimeMillis();
+ assertEquals("frFRValue3", bundle.getString("parent3"));
+ assertFalse(control.needsReload(className, frFR, CLASS, systemLoader,
+ bundle, time));
+ // exceptions
+ control.needsReload(propertiesName, frFR, PROPERTIES, URLLoader,
+ bundle, time);
+ try {
+ control
+ .needsReload(null, frFR, PROPERTIES, URLLoader, bundle,
+ time);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.needsReload(propertiesName, null, PROPERTIES, URLLoader,
+ bundle, time);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.needsReload(propertiesName, frFR, null, URLLoader, bundle,
+ time);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.needsReload(propertiesName, frFR, PROPERTIES, null, bundle,
+ time);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ control.needsReload(propertiesName, frFR, PROPERTIES, URLLoader,
+ null, time);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#toBundleName(java.lang.String, java.util.Locale)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_toBundleName_LStringLLocale() {
+ assertEquals("baseName_one_TWO_three", control.toBundleName("baseName",
+ new Locale("one", "two", "three")));
+ assertEquals("baseName_one_TWO", control.toBundleName("baseName",
+ new Locale("one", "two")));
+ assertEquals("baseName_one__three", control.toBundleName("baseName",
+ new Locale("one", "", "three")));
+ assertEquals("baseName__TWO_three", control.toBundleName("baseName",
+ new Locale("", "two", "three")));
+ assertEquals("baseName_one", control.toBundleName("baseName",
+ new Locale("one", "", "")));
+ assertEquals("baseName___three", control.toBundleName("baseName",
+ new Locale("", "", "three")));
+ assertEquals("baseName__TWO", control.toBundleName("baseName",
+ new Locale("", "two", "")));
+ assertEquals("baseName", control.toBundleName("baseName", new Locale(
+ "", "", "")));
+ assertEquals("baseName", control.toBundleName("baseName", Locale.ROOT));
+ assertEquals("_one_TWO_three", control.toBundleName("", new Locale(
+ "one", "two", "three")));
+ assertEquals("", control.toBundleName("", Locale.ROOT));
+
+ assertEquals("does.not.exists_one_TWO_three", control.toBundleName(
+ "does.not.exists", new Locale("one", "two", "three")));
+ assertEquals("does/not/exists_one_TWO_three", control.toBundleName(
+ "does/not/exists", new Locale("one", "two", "three")));
+ assertEquals("does_not_exists__one_TWO_three", control.toBundleName(
+ "does_not_exists_", new Locale("one", "two", "three")));
+
+ assertEquals("...", control.toBundleName("...", Locale.ROOT));
+ assertEquals("s/./\\//g", control
+ .toBundleName("s/./\\//g", Locale.ROOT));
+ assertEquals("123_one", control.toBundleName("123", new Locale("one")));
+
+ try {
+ control.toBundleName(null, Locale.US);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ control.toBundleName("baseName", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.ResourceBundle.Control#toResourceName(java.lang.String, java.lang.String)}.
+ */
+ @SuppressWarnings("nls")
+ public void test_toResourceNameLStringLString() {
+ assertEquals("does/not/exists_language_country.someSuffix", control
+ .toResourceName("does.not.exists_language_country",
+ "someSuffix"));
+ assertEquals("does/not/exists_language_country.someSuffix", control
+ .toResourceName("does/not/exists_language_country",
+ "someSuffix"));
+ assertEquals("does///not//exists_language/country.someSuffix", control
+ .toResourceName("does...not..exists_language.country",
+ "someSuffix"));
+ assertEquals("does\\not\\exists_language_country.someSuffix", control
+ .toResourceName("does\\not\\exists_language_country",
+ "someSuffix"));
+ assertEquals("does/not/exists_language_country/.someSuffix", control
+ .toResourceName("does.not.exists_language_country.",
+ "someSuffix"));
+ assertEquals("does/not/exists_language_country../someSuffix", control
+ .toResourceName("does.not.exists_language_country",
+ "./someSuffix"));
+
+ assertEquals("///.//", control.toResourceName("...", "//"));
+ assertEquals("///...", control.toResourceName("///", ".."));
+ assertEquals("123...", control.toResourceName("123", ".."));
+ assertEquals("base.", control.toResourceName("base", ""));
+ assertEquals(".suffix", control.toResourceName("", "suffix"));
+ assertEquals(".", control.toResourceName("", ""));
+
+ try {
+ control.toResourceName(null, "suffix");
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ control.toResourceName("bundleName", null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ controlP = Control.getControl(FORMAT_PROPERTIES);
+ controlC = Control.getControl(FORMAT_CLASS);
+ control = Control.getControl(FORMAT_DEFAULT);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CurrencyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CurrencyTest.java
new file mode 100644
index 0000000..07256e4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CurrencyTest.java
@@ -0,0 +1,405 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Currency;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+public class CurrencyTest extends junit.framework.TestCase {
+
+ private Locale originalLocale;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ originalLocale = Locale.getDefault();
+ }
+
+ @Override
+ protected void tearDown() {
+ Locale.setDefault(originalLocale);
+ }
+
+ /**
+ * java.util.Currency#getInstance(java.lang.String)
+ */
+ public void test_getInstanceLjava_lang_String() {
+ // see test_getInstanceLjava_util_Locale() tests
+ }
+
+ /**
+ * java.util.Currency#getInstance(java.util.Locale)
+ */
+ public void test_getInstanceLjava_util_Locale() {
+ /*
+ * the behaviour in all these three cases should be the same since this
+ * method ignores language and variant component of the locale.
+ */
+ Currency c0 = Currency.getInstance("CAD");
+ Currency c1 = Currency.getInstance(new Locale("en", "CA"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
+ c1 == c0);
+ Currency c2 = Currency.getInstance(new Locale("fr", "CA"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
+ c2 == c0);
+ Currency c3 = Currency.getInstance(new Locale("", "CA"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
+ c3 == c0);
+
+ c0 = Currency.getInstance("JPY");
+ c1 = Currency.getInstance(new Locale("ja", "JP"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
+ c1 == c0);
+ c2 = Currency.getInstance(new Locale("", "JP"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
+ c2 == c0);
+ c3 = Currency.getInstance(new Locale("bogus", "JP"));
+ assertTrue(
+ "Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
+ c3 == c0);
+
+ Locale localeGu = new Locale("gu", "IN");
+ Currency cGu = Currency.getInstance(localeGu);
+ Locale localeKn = new Locale("kn", "IN");
+ Currency cKn = Currency.getInstance(localeKn);
+ assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))"
+ + "isn't equal to " + "Currency.getInstance(Locale_"
+ + localeKn.toString() + "))", cGu == cKn);
+
+ // some teritories do not have currencies, like Antarctica
+ Locale loc = new Locale("", "AQ");
+ try {
+ Currency curr = Currency.getInstance(loc);
+ assertNull(
+ "Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null",
+ curr);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException " + e);
+ }
+
+ // unsupported/legacy iso3 countries
+ loc = new Locale("", "ZR");
+ try {
+ Currency curr = Currency.getInstance(loc);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+
+ loc = new Locale("", "ZAR");
+ try {
+ Currency curr = Currency.getInstance(loc);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+
+ loc = new Locale("", "FX");
+ try {
+ Currency curr = Currency.getInstance(loc);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+
+ loc = new Locale("", "FXX");
+ try {
+ Currency curr = Currency.getInstance(loc);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.Currency#getSymbol()
+ */
+ public void test_getSymbol() {
+ Currency currK = Currency.getInstance("KRW");
+ Currency currI = Currency.getInstance("IEP");
+ Currency currUS = Currency.getInstance("USD");
+
+ Locale.setDefault(Locale.US);
+ // BEGIN android-changed
+ // KRW currency symbol is \u20a9 since CLDR1.7 release.
+ assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
+ // IEP currency symbol is IEP since CLDR2.0 release.
+ assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
+ // END android-changed
+ assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
+
+ Locale.setDefault(new Locale("en", "IE"));
+ // BEGIN android-changed
+ assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
+ assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
+ assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
+ // END android-changed
+
+ // Test what happens if the default is an invalid locale, one with the country Korea (KR)
+ // but a currently unsupported language. "kr" == Kanuri (Korean is actually "ko").
+ // All these values are those defined in the "root" locale or the currency code if one isn't
+ // defined.
+ Locale.setDefault(new Locale("kr", "KR"));
+ // BEGIN android-changed
+ assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
+ assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
+ assertEquals("currUS.getSymbol()", "US$", currUS.getSymbol());
+ // END android-changed
+ }
+
+ /**
+ * java.util.Currency#getSymbol(java.util.Locale)
+ */
+ public void test_getSymbolLjava_util_Locale() {
+ //Tests was simplified because java specification not
+ // includes strong requirements for returning symbol.
+ // on android platform used wrong character for yen
+ // sign: \u00a5 instead of \uffe5
+ Locale[] desiredLocales = new Locale[]{
+ Locale.JAPAN, Locale.JAPANESE,
+ Locale.FRANCE, Locale.FRENCH,
+ Locale.US, Locale.UK,
+ Locale.CANADA, Locale.CANADA_FRENCH,
+ Locale.ENGLISH,
+ new Locale("ja", "JP"), new Locale("", "JP"),
+
+ new Locale("fr", "FR"), new Locale("", "FR"),
+
+ new Locale("en", "US"), new Locale("", "US"),
+ new Locale("es", "US"), new Locale("ar", "US"),
+ new Locale("ja", "US"),
+
+ new Locale("en", "CA"), new Locale("fr", "CA"),
+ new Locale("", "CA"), new Locale("ar", "CA"),
+
+ new Locale("ja", "JP"), new Locale("", "JP"),
+ new Locale("ar", "JP"),
+
+ new Locale("ja", "AE"), new Locale("en", "AE"),
+ new Locale("ar", "AE"),
+
+ new Locale("da", "DK"), new Locale("", "DK"),
+
+ new Locale("da", ""), new Locale("ja", ""),
+ new Locale("en", "")};
+
+ Set<Locale> availableLocales = new HashSet<Locale>(Arrays.asList(Locale.getAvailableLocales()));
+
+ ArrayList<Locale> locales = new ArrayList<Locale>();
+ for (Locale desiredLocale : desiredLocales) {
+ if (availableLocales.contains(desiredLocale)) {
+ locales.add(desiredLocale);
+ }
+ }
+
+ Locale[] loc1 = locales.toArray(new Locale[locales.size()]);
+
+ String[] euro = new String[] {"EUR", "\u20ac"};
+ // \u00a5 and \uffe5 are actually the same symbol, just different code points.
+ // But the RI returns the \uffe5 and Android returns those with \u00a5
+ String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
+ String[] dollar = new String[] {"USD", "$", "US$", "$US"};
+ // BEGIN android-changed
+ // Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
+ String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
+ // END android-changed
+
+ Currency currE = Currency.getInstance("EUR");
+ Currency currJ = Currency.getInstance("JPY");
+ Currency currUS = Currency.getInstance("USD");
+ Currency currCA = Currency.getInstance("CAD");
+
+ int i, j, k;
+ boolean flag;
+
+ for(k = 0; k < loc1.length; k++) {
+ Locale.setDefault(loc1[k]);
+
+ for (i = 0; i < loc1.length; i++) {
+ flag = false;
+ for (j = 0; j < euro.length; j++) {
+ if (currE.getSymbol(loc1[i]).equals(euro[j])) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("Default Locale is: " + Locale.getDefault()
+ + ". For locale " + loc1[i]
+ + " the Euro currency returned "
+ + currE.getSymbol(loc1[i])
+ + ". Expected was one of these: "
+ + Arrays.toString(euro), flag);
+ }
+
+ for (i = 0; i < loc1.length; i++) {
+ flag = false;
+ for (j = 0; j < yen.length; j++) {
+ if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("Default Locale is: " + Locale.getDefault()
+ + ". For locale " + loc1[i]
+ + " the Yen currency returned "
+ + currJ.getSymbol(loc1[i])
+ + ". Expected was one of these: "
+ + Arrays.toString(yen), flag);
+ }
+
+ for (i = 0; i < loc1.length; i++) {
+ flag = false;
+ for (j = 0; j < dollar.length; j++) {
+ if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("Default Locale is: " + Locale.getDefault()
+ + ". For locale " + loc1[i]
+ + " the Dollar currency returned "
+ + currUS.getSymbol(loc1[i])
+ + ". Expected was one of these: "
+ + Arrays.toString(dollar), flag);
+ }
+
+ for (i = 0; i < loc1.length; i++) {
+ flag = false;
+ for (j = 0; j < cDollar.length; j++) {
+ if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("Default Locale is: " + Locale.getDefault()
+ + ". For locale " + loc1[i]
+ + " the Canadian Dollar currency returned "
+ + currCA.getSymbol(loc1[i])
+ + ". Expected was one of these: "
+ + Arrays.toString(cDollar), flag);
+ }
+ }
+ }
+
+ /**
+ * java.util.Currency#getDefaultFractionDigits()
+ */
+ public void test_getDefaultFractionDigits() {
+
+ Currency c1 = Currency.getInstance("TND");
+ c1.getDefaultFractionDigits();
+ assertEquals(" Currency.getInstance(\"" + c1
+ + "\") returned incorrect number of digits. ", 3, c1
+ .getDefaultFractionDigits());
+
+ Currency c2 = Currency.getInstance("EUR");
+ c2.getDefaultFractionDigits();
+ assertEquals(" Currency.getInstance(\"" + c2
+ + "\") returned incorrect number of digits. ", 2, c2
+ .getDefaultFractionDigits());
+
+ Currency c3 = Currency.getInstance("JPY");
+ c3.getDefaultFractionDigits();
+ assertEquals(" Currency.getInstance(\"" + c3
+ + "\") returned incorrect number of digits. ", 0, c3
+ .getDefaultFractionDigits());
+
+ Currency c4 = Currency.getInstance("XXX");
+ c4.getDefaultFractionDigits();
+ assertEquals(" Currency.getInstance(\"" + c4
+ + "\") returned incorrect number of digits. ", -1, c4
+ .getDefaultFractionDigits());
+ }
+
+ /**
+ * java.util.Currency#getCurrencyCode() Note: lines under remarks
+ * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
+ * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
+ * on SUN VM
+ */
+ public void test_getCurrencyCode() {
+ final Collection<Locale> locVal = Arrays.asList(
+ Locale.CANADA,
+ Locale.CANADA_FRENCH,
+ Locale.CHINA,
+ // Locale.CHINESE,
+ // Locale.ENGLISH,
+ Locale.FRANCE,
+ // Locale.FRENCH,
+ // Locale.GERMAN,
+ Locale.GERMANY,
+ // Locale.ITALIAN,
+ Locale.ITALY, Locale.JAPAN,
+ // Locale.JAPANESE,
+ Locale.KOREA,
+ // Locale.KOREAN,
+ Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
+ Locale.UK, Locale.US);
+ final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
+ "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
+
+ Iterator<String> dat = locDat.iterator();
+ for (Locale l : locVal) {
+ String d = dat.next().trim();
+ assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l)
+ .getCurrencyCode(), d);
+ }
+ }
+
+ /**
+ * java.util.Currency#toString() Note: lines under remarks
+ * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
+ * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
+ * on SUN VM
+ */
+ public void test_toString() {
+ final Collection<Locale> locVal = Arrays.asList(
+ Locale.CANADA,
+ Locale.CANADA_FRENCH,
+ Locale.CHINA,
+ // Locale.CHINESE,
+ // Locale.ENGLISH,
+ Locale.FRANCE,
+ // Locale.FRENCH,
+ // Locale.GERMAN,
+ Locale.GERMANY,
+ // Locale.ITALIAN,
+ Locale.ITALY, Locale.JAPAN,
+ // Locale.JAPANESE,
+ Locale.KOREA,
+ // Locale.KOREAN,
+ Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
+ Locale.UK, Locale.US);
+ final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
+ "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
+
+ Iterator<String> dat = locDat.iterator();
+ for (Locale l : locVal) {
+ String d = dat.next().trim();
+ assertEquals("For locale " + l + " Currency.toString method returns wrong value",
+ Currency.getInstance(l).toString(), d);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DateTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DateTest.java
new file mode 100644
index 0000000..0ce971d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DateTest.java
@@ -0,0 +1,520 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+public class DateTest extends junit.framework.TestCase {
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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()));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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));
+
+ try {
+ d1.after(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+
+ try {
+ d1.before(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+
+ try {
+ d1.compareTo(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.Date#getTimezoneOffset()
+ */
+ public void test_getTimezoneOffset() {
+ // Test for method int java.util.Date.getTimezoneOffset()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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()
+ );
+ }
+
+ /**
+ * 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("GMT-5"));
+ try {
+ Date d1 = new Date(0);
+ assertTrue("Returned incorrect string: " + d1, d1.toString()
+ .equals("Wed Dec 31 19:00:00 GMT-05:00 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")
+ && d2.toString().endsWith("2008"));
+ }
+
+ /**
+ * 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);
+ }
+ /**
+ * java.util.Date#toLocaleString() Test for method java.lang.String
+ * java.util.Date.toGMTString()
+ */
+ public void test_toLocaleString() {
+ Locale loc = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ TimeZone tz = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ try {
+ assertEquals("Did not convert epoch to GMT string correctly", "Jan 1, 1970 12:00:00 AM",
+ new Date(0).toLocaleString());
+ assertEquals("Did not convert epoch + 1yr to GMT string correctly",
+ "Jan 1, 1971 12:00:00 AM", new Date((long)365 * 24 * 60 * 60 * 1000)
+ .toLocaleString());
+ } finally {
+ Locale.setDefault(loc);
+ TimeZone.setDefault(tz);
+ }
+ }
+
+ 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DuplicateFormatFlagsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DuplicateFormatFlagsExceptionTest.java
new file mode 100644
index 0000000..d59decb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/DuplicateFormatFlagsExceptionTest.java
@@ -0,0 +1,94 @@
+/* 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.tests.java.util;
+
+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;
+
+public class DuplicateFormatFlagsExceptionTest extends TestCase {
+
+ /**
+ * java.util.DuplicateFormatFlagsException#DuplicateFormatFlagsException(String)
+ */
+ public void test_duplicateFormatFlagsException() {
+ try {
+ new DuplicateFormatFlagsException(null);
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // desired
+ }
+ }
+
+ /**
+ * java.util.DuplicateFormatFlagsException#getFlags()
+ */
+ public void test_getFlags() {
+ String strFlags = "MYTESTFLAGS";
+ DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException(
+ strFlags);
+ assertEquals(strFlags, duplicateFormatException.getFlags());
+ }
+
+ /**
+ * java.util.DuplicateFormatFlagsException#getMessage()
+ */
+ public void test_getMessage() {
+ String strFlags = "MYTESTFLAGS";
+ DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException(
+ strFlags);
+ assertTrue(null != duplicateFormatException.getFlags());
+
+ }
+
+ // comparator for DuplicateFormatFlagsException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ DuplicateFormatFlagsException initEx = (DuplicateFormatFlagsException) initial;
+ DuplicateFormatFlagsException desrEx = (DuplicateFormatFlagsException) deserialized;
+
+ assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new DuplicateFormatFlagsException(
+ "TESTDESC"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new DuplicateFormatFlagsException(
+ "TESTDESC"), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EmptyStackExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EmptyStackExceptionTest.java
new file mode 100644
index 0000000..fdba5bf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EmptyStackExceptionTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.EmptyStackException;
+import java.util.Stack;
+
+public class EmptyStackExceptionTest extends junit.framework.TestCase {
+
+ Object[] objArray = new Object[10];
+ Stack s;
+
+ /**
+ * java.util.EmptyStackException#EmptyStackException()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.EmptyStackException()
+ try {
+ for (int counter = 0; counter < objArray.length + 1; counter++)
+ s.pop();
+ } catch (EmptyStackException e) {
+ return;
+ }
+ fail("Expected EmptyStackException not thrown");
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ for (int counter = 0; counter < objArray.length; counter++) {
+ objArray[counter] = new Integer(counter);
+ }
+
+ s = new Stack();
+ for (int counter = 0; counter < objArray.length; counter++) {
+ s.push(objArray[counter]);
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ objArray = null;
+ s = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumMapTest.java
new file mode 100644
index 0000000..2a37a18
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumMapTest.java
@@ -0,0 +1,1175 @@
+/* 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.tests.java.util;
+
+import dalvik.annotation.AndroidOnly;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+import junit.framework.TestCase;
+
+public class EnumMapTest extends TestCase {
+ enum Size {
+ Small, Middle, Big {};
+ }
+
+ enum Color {
+ Red, Green, Blue {};
+ }
+
+ enum Empty {
+ //Empty
+ }
+
+ private static class MockEntry<K, V> implements Map.Entry<K, V> {
+ private K key;
+
+ private V value;
+
+ public MockEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ @Override
+ public int hashCode() {
+ return (key == null ? 0 : key.hashCode())
+ ^ (value == null ? 0 : value.hashCode());
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public V setValue(V object) {
+ V oldValue = value;
+ value = object;
+ return oldValue;
+ }
+ }
+
+ /**
+ * java.util.EnumMap#EnumMap(Class)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_ConstructorLjava_lang_Class() {
+ try {
+ new EnumMap((Class) null);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+
+ try {
+ new EnumMap(Size.Big.getClass());
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ new EnumMap(Integer.class);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ assertNull("Return non-null for non mapped key", enumColorMap.put(
+ Color.Green, 2));
+ assertEquals("Get returned incorrect value for given key", 2,
+ enumColorMap.get(Color.Green));
+
+ EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
+ try {
+ enumEmptyMap.put(Color.Red, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertNull("Return non-null for non mapped key", enumSizeMap.put(
+ Size.Big, 2));
+ assertEquals("Get returned incorrect value for given key", 2,
+ enumSizeMap.get(Size.Big));
+ try {
+ enumSizeMap.put(Color.Red, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ enumSizeMap = new EnumMap(Size.Middle.getClass());
+ assertNull("Return non-null for non mapped key", enumSizeMap.put(
+ Size.Small, 1));
+ assertEquals("Get returned incorrect value for given key", 1,
+ enumSizeMap.get(Size.Small));
+ try {
+ enumSizeMap.put(Color.Red, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#EnumMap(EnumMap)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_ConstructorLjava_util_EnumMap() {
+ EnumMap enumMap;
+ EnumMap enumColorMap = null;
+ try {
+ enumMap = new EnumMap(enumColorMap);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+ Double double1 = new Double(1);
+ enumColorMap.put(Color.Green, 2);
+ enumColorMap.put(Color.Blue, double1);
+
+ enumMap = new EnumMap(enumColorMap);
+ assertEquals("Constructor fails", 2, enumMap.get(Color.Green));
+ assertSame("Constructor fails", double1, enumMap.get(Color.Blue));
+ assertNull("Constructor fails", enumMap.get(Color.Red));
+ enumMap.put(Color.Red, 1);
+ assertEquals("Wrong value", 1, enumMap.get(Color.Red));
+
+ try {
+ enumMap.put(Size.Middle, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#EnumMap(Map)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_ConstructorLjava_util_Map() {
+ EnumMap enumMap;
+ Map enumColorMap = null;
+ try {
+ enumMap = new EnumMap(enumColorMap);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumMap = new EnumMap(enumColorMap);
+ enumColorMap.put(Color.Blue, 3);
+ enumMap = new EnumMap(enumColorMap);
+
+ HashMap hashColorMap = null;
+ try {
+ enumMap = new EnumMap(hashColorMap);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ hashColorMap = new HashMap();
+ try {
+ enumMap = new EnumMap(hashColorMap);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ hashColorMap.put(Color.Green, 2);
+ enumMap = new EnumMap(hashColorMap);
+ assertEquals("Constructor fails", 2, enumMap.get(Color.Green));
+ assertNull("Constructor fails", enumMap.get(Color.Red));
+ enumMap.put(Color.Red, 1);
+ assertEquals("Wrong value", 1, enumMap.get(Color.Red));
+ hashColorMap.put(Size.Big, 3);
+ try {
+ enumMap = new EnumMap(hashColorMap);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ hashColorMap = new HashMap();
+ hashColorMap.put(new Integer(1), 1);
+ try {
+ enumMap = new EnumMap(hashColorMap);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#clear()
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_clear() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Small, 1);
+ enumSizeMap.clear();
+ assertNull("Failed to clear all elements", enumSizeMap.get(Size.Small));
+ }
+
+ /**
+ * java.util.EnumMap#containsKey(Object)
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_containsKeyLjava_lang_Object() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertFalse("Returned true for uncontained key", enumSizeMap
+ .containsKey(Size.Small));
+ enumSizeMap.put(Size.Small, 1);
+ assertTrue("Returned false for contained key", enumSizeMap
+ .containsKey(Size.Small));
+
+ enumSizeMap.put(Size.Big, null);
+ assertTrue("Returned false for contained key", enumSizeMap
+ .containsKey(Size.Big));
+
+ assertFalse("Returned true for uncontained key", enumSizeMap
+ .containsKey(Color.Red));
+ assertFalse("Returned true for uncontained key", enumSizeMap
+ .containsKey(new Integer("3")));
+ assertFalse("Returned true for uncontained key", enumSizeMap
+ .containsKey(null));
+ }
+
+ /**
+ * java.util.EnumMap#clone()
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_clone() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ Integer integer = new Integer("3");
+ enumSizeMap.put(Size.Small, integer);
+ EnumMap enumSizeMapClone = enumSizeMap.clone();
+ assertNotSame("Should not be same", enumSizeMap, enumSizeMapClone);
+ assertEquals("Clone answered unequal EnumMap", enumSizeMap,
+ enumSizeMapClone);
+
+ assertSame("Should be same", enumSizeMap.get(Size.Small),
+ enumSizeMapClone.get(Size.Small));
+ assertSame("Clone is not shallow clone", integer, enumSizeMapClone
+ .get(Size.Small));
+ enumSizeMap.remove(Size.Small);
+ assertSame("Clone is not shallow clone", integer, enumSizeMapClone
+ .get(Size.Small));
+ }
+
+ /**
+ * java.util.EnumMap#containsValue(Object)
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_containsValueLjava_lang_Object() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ Double double1 = new Double(3);
+ Double double2 = new Double(3);
+
+ assertFalse("Returned true for uncontained value", enumSizeMap
+ .containsValue(double1));
+ enumSizeMap.put(Size.Middle, 2);
+ enumSizeMap.put(Size.Small, double1);
+ assertTrue("Returned false for contained value", enumSizeMap
+ .containsValue(double1));
+ assertTrue("Returned false for contained value", enumSizeMap
+ .containsValue(double2));
+ assertTrue("Returned false for contained value", enumSizeMap
+ .containsValue(2));
+ assertFalse("Returned true for uncontained value", enumSizeMap
+ .containsValue(1));
+
+ assertFalse("Returned true for uncontained value", enumSizeMap
+ .containsValue(null));
+ enumSizeMap.put(Size.Big, null);
+ assertTrue("Returned false for contained value", enumSizeMap
+ .containsValue(null));
+ }
+
+ /**
+ * java.util.EnumMap#entrySet()
+ */
+ @AndroidOnly("Map.Entry is indirectly modified on RI when Iterator.next() is invoked")
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_entrySet() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ MockEntry mockEntry = new MockEntry(Size.Middle, 1);
+ Set set = enumSizeMap.entrySet();
+
+ Set set1 = enumSizeMap.entrySet();
+ assertSame("Should be same", set1, set);
+ try {
+ set.add(mockEntry);
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+
+ assertTrue("Returned false for contained object", set
+ .contains(mockEntry));
+ mockEntry = new MockEntry(Size.Middle, null);
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+ assertFalse("Returned true for uncontained object", set
+ .contains(Size.Small));
+ mockEntry = new MockEntry(new Integer(1), 1);
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+ assertFalse("Returned true for uncontained object", set
+ .contains(new Integer(1)));
+
+ mockEntry = new MockEntry(Size.Big, null);
+ assertTrue("Returned false for contained object", set
+ .contains(mockEntry));
+ assertTrue("Returned false when the object can be removed", set
+ .remove(mockEntry));
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(mockEntry));
+ mockEntry = new MockEntry(new Integer(1), 1);
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(mockEntry));
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(new Integer(1)));
+
+ // The set is backed by the map so changes to one are reflected by the
+ // other.
+ enumSizeMap.put(Size.Big, 3);
+ mockEntry = new MockEntry(Size.Big, 3);
+ assertTrue("Returned false for contained object", set
+ .contains(mockEntry));
+ enumSizeMap.remove(Size.Big);
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+
+ assertEquals("Wrong size", 1, set.size());
+ set.clear();
+ assertEquals("Wrong size", 0, set.size());
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.entrySet();
+ Collection c = new ArrayList();
+ c.add(new MockEntry(Size.Middle, 1));
+ assertTrue("Return wrong value", set.containsAll(c));
+ assertTrue("Remove does not success", set.removeAll(c));
+
+ enumSizeMap.put(Size.Middle, 1);
+ c.add(new MockEntry(Size.Big, 3));
+ assertTrue("Remove does not success", set.removeAll(c));
+ assertFalse("Should return false", set.removeAll(c));
+ assertEquals("Wrong size", 1, set.size());
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.entrySet();
+ c = new ArrayList();
+ c.add(new MockEntry(Size.Middle, 1));
+ c.add(new MockEntry(Size.Big, 3));
+
+ assertTrue("Retain does not success", set.retainAll(c));
+ assertEquals("Wrong size", 1, set.size());
+ assertFalse("Should return false", set.retainAll(c));
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+
+ set = enumSizeMap.entrySet();
+ Object[] array = set.toArray();
+ assertEquals("Wrong length", 2, array.length);
+ Map.Entry entry = (Map.Entry) array[0];
+ assertEquals("Wrong key", Size.Middle, entry.getKey());
+ assertEquals("Wrong value", 1, entry.getValue());
+
+ Object[] array1 = new Object[10];
+ array1 = set.toArray();
+ assertEquals("Wrong length", 2, array1.length);
+ entry = (Map.Entry) array[0];
+ assertEquals("Wrong key", Size.Middle, entry.getKey());
+ assertEquals("Wrong value", 1, entry.getValue());
+
+ array1 = new Object[10];
+ array1 = set.toArray(array1);
+ assertEquals("Wrong length", 10, array1.length);
+ entry = (Map.Entry) array[1];
+ assertEquals("Wrong key", Size.Big, entry.getKey());
+ assertNull("Should be null", array1[2]);
+
+ set = enumSizeMap.entrySet();
+ Integer integer = new Integer("1");
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(integer));
+ assertTrue("Returned false when the object can be removed", set
+ .remove(entry));
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.entrySet();
+ Iterator iter = set.iterator();
+ entry = (Map.Entry) iter.next();
+ assertTrue("Returned false for contained object", set.contains(entry));
+ mockEntry = new MockEntry(Size.Middle, 2);
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+ mockEntry = new MockEntry(new Integer(2), 2);
+ assertFalse("Returned true for uncontained object", set
+ .contains(mockEntry));
+ entry = (Map.Entry) iter.next();
+ assertTrue("Returned false for contained object", set.contains(entry));
+
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.remove(Size.Big);
+ mockEntry = new MockEntry(Size.Big, null);
+ assertEquals("Wrong size", 1, set.size());
+ assertFalse("Returned true for uncontained object", set.contains(mockEntry));
+ enumSizeMap.put(Size.Big, 2);
+ mockEntry = new MockEntry(Size.Big, 2);
+ assertTrue("Returned false for contained object", set
+ .contains(mockEntry));
+
+ iter.remove();
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ try {
+ entry.setValue(2);
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ try {
+ set.contains(entry);
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.entrySet();
+ iter = set.iterator();
+ entry = (Map.Entry) iter.next();
+ assertEquals("Wrong key", Size.Middle, entry.getKey());
+
+ assertTrue("Returned false for contained object", set.contains(entry));
+ enumSizeMap.put(Size.Middle, 3);
+ assertTrue("Returned false for contained object", set.contains(entry));
+ entry.setValue(2);
+ assertTrue("Returned false for contained object", set.contains(entry));
+ assertFalse("Returned true for uncontained object", set
+ .remove(new Integer(1)));
+
+ iter.next();
+ assertEquals("Wrong key", Size.Middle, entry.getKey());
+ set.clear();
+ assertEquals("Wrong size", 0, set.size());
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.entrySet();
+ iter = set.iterator();
+ mockEntry = new MockEntry(Size.Middle, 1);
+
+ assertFalse("Wrong result", entry.equals(mockEntry));
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ entry = (Map.Entry) iter.next();
+ assertEquals("Wrong key", Size.Middle, entry.getKey());
+ assertTrue("Should return true", entry.equals(mockEntry));
+ assertEquals("Should be equal", mockEntry.hashCode(), entry.hashCode());
+ mockEntry = new MockEntry(Size.Big, 1);
+ assertFalse("Wrong result", entry.equals(mockEntry));
+
+ entry = (Map.Entry) iter.next();
+ assertFalse("Wrong result", entry.equals(mockEntry));
+ assertEquals("Wrong key", Size.Big, entry.getKey());
+ iter.remove();
+ assertFalse("Wrong result", entry.equals(mockEntry));
+ assertEquals("Wrong size", 1, set.size());
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ try {
+ iter.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#equals(Object)
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_equalsLjava_lang_Object() {
+ EnumMap enumMap = new EnumMap(Size.class);
+ enumMap.put(Size.Small, 1);
+
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertFalse("Returned true for unequal EnumMap", enumSizeMap
+ .equals(enumMap));
+ enumSizeMap.put(Size.Small, 1);
+ assertTrue("Returned false for equal EnumMap", enumSizeMap
+ .equals(enumMap));
+ enumSizeMap.put(Size.Big, null);
+ assertFalse("Returned true for unequal EnumMap", enumSizeMap
+ .equals(enumMap));
+
+ enumMap.put(Size.Middle, null);
+ assertFalse("Returned true for unequal EnumMap", enumSizeMap
+ .equals(enumMap));
+ enumMap.remove(Size.Middle);
+ enumMap.put(Size.Big, 3);
+ assertFalse("Returned true for unequal EnumMap", enumSizeMap
+ .equals(enumMap));
+ enumMap.put(Size.Big, null);
+ assertTrue("Returned false for equal EnumMap", enumSizeMap
+ .equals(enumMap));
+
+ HashMap hashMap = new HashMap();
+ hashMap.put(Size.Small, 1);
+ assertFalse("Returned true for unequal EnumMap", hashMap
+ .equals(enumMap));
+ hashMap.put(Size.Big, null);
+ assertTrue("Returned false for equal EnumMap", enumMap.equals(hashMap));
+
+ assertFalse("Should return false", enumSizeMap
+ .equals(new Integer(1)));
+ }
+
+ /**
+ * java.util.EnumMap#keySet()
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_keySet() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 2);
+ enumSizeMap.put(Size.Big, null);
+ Set set = enumSizeMap.keySet();
+
+ Set set1 = enumSizeMap.keySet();
+ assertSame("Should be same", set1, set);
+ try {
+ set.add(Size.Big);
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+
+ assertTrue("Returned false for contained object", set
+ .contains(Size.Middle));
+ assertTrue("Returned false for contained object", set
+ .contains(Size.Big));
+ assertFalse("Returned true for uncontained object", set
+ .contains(Size.Small));
+ assertFalse("Returned true for uncontained object", set
+ .contains(new Integer(1)));
+ assertTrue("Returned false when the object can be removed", set
+ .remove(Size.Big));
+ assertFalse("Returned true for uncontained object", set
+ .contains(Size.Big));
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(Size.Big));
+ assertFalse("Returned true when the object can not be removed", set
+ .remove(new Integer(1)));
+
+ // The set is backed by the map so changes to one are reflected by the
+ // other.
+ enumSizeMap.put(Size.Big, 3);
+ assertTrue("Returned false for contained object", set
+ .contains(Size.Big));
+ enumSizeMap.remove(Size.Big);
+ assertFalse("Returned true for uncontained object", set
+ .contains(Size.Big));
+
+ assertEquals("Wrong size", 1, set.size());
+ set.clear();
+ assertEquals("Wrong size", 0, set.size());
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.keySet();
+ Collection c = new ArrayList();
+ c.add(Size.Big);
+ assertTrue("Should return true", set.containsAll(c));
+ c.add(Size.Small);
+ assertFalse("Should return false", set.containsAll(c));
+ assertTrue("Should return true", set.removeAll(c));
+ assertEquals("Wrong size", 1, set.size());
+ assertFalse("Should return false", set.removeAll(c));
+ assertEquals("Wrong size", 1, set.size());
+ try {
+ set.addAll(c);
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+
+ enumSizeMap.put(Size.Big, null);
+ assertEquals("Wrong size", 2, set.size());
+ assertTrue("Should return true", set.retainAll(c));
+ assertEquals("Wrong size", 1, set.size());
+ assertFalse("Should return false", set.retainAll(c));
+ assertEquals(1, set.size());
+ Object[] array = set.toArray();
+ assertEquals("Wrong length", 1, array.length);
+ assertEquals("Wrong key", Size.Big, array[0]);
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.keySet();
+ c = new ArrayList();
+ c.add(Color.Blue);
+ assertFalse("Should return false", set.remove(c));
+ assertEquals("Wrong size", 2, set.size());
+ assertTrue("Should return true", set.retainAll(c));
+ assertEquals("Wrong size", 0, set.size());
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.keySet();
+
+ Iterator iter = set.iterator();
+ Enum enumKey = (Enum) iter.next();
+ assertTrue("Returned false for contained object", set.contains(enumKey));
+ enumKey = (Enum) iter.next();
+ assertTrue("Returned false for contained object", set.contains(enumKey));
+
+ enumSizeMap.remove(Size.Big);
+ assertFalse("Returned true for uncontained object", set
+ .contains(enumKey));
+ iter.remove();
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ assertFalse("Returned true for uncontained object", set
+ .contains(enumKey));
+
+ iter = set.iterator();
+ enumKey = (Enum) iter.next();
+ assertTrue("Returned false for contained object", set.contains(enumKey));
+ enumSizeMap.put(Size.Middle, 3);
+ assertTrue("Returned false for contained object", set.contains(enumKey));
+
+ enumSizeMap = new EnumMap(Size.class);
+ enumSizeMap.put(Size.Middle, 1);
+ enumSizeMap.put(Size.Big, null);
+ set = enumSizeMap.keySet();
+ iter = set.iterator();
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ enumKey = (Enum) iter.next();
+ assertEquals("Wrong key", Size.Middle, enumKey);
+ assertSame("Wrong key", Size.Middle, enumKey);
+ assertFalse("Returned true for unequal object", iter.equals(enumKey));
+ iter.remove();
+ assertFalse("Returned true for uncontained object", set
+ .contains(enumKey));
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+
+ assertEquals("Wrong size", 1, set.size());
+ enumKey = (Enum) iter.next();
+ assertEquals("Wrong key", Size.Big, enumKey);
+ iter.remove();
+ try {
+ iter.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#get(Object)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_getLjava_lang_Object() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertNull("Get returned non-null for non mapped key", enumSizeMap
+ .get(Size.Big));
+ enumSizeMap.put(Size.Big, 1);
+ assertEquals("Get returned incorrect value for given key", 1,
+ enumSizeMap.get(Size.Big));
+
+ assertNull("Get returned non-null for non mapped key", enumSizeMap
+ .get(Size.Small));
+ assertNull("Get returned non-null for non existent key", enumSizeMap
+ .get(Color.Red));
+ assertNull("Get returned non-null for non existent key", enumSizeMap
+ .get(new Integer(1)));
+ assertNull("Get returned non-null for non existent key", enumSizeMap
+ .get(null));
+
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Green));
+ enumColorMap.put(Color.Green, 2);
+ assertEquals("Get returned incorrect value for given key", 2,
+ enumColorMap.get(Color.Green));
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Blue));
+
+ enumColorMap.put(Color.Green, new Double(4));
+ assertEquals("Get returned incorrect value for given key",
+ new Double(4), enumColorMap.get(Color.Green));
+ enumColorMap.put(Color.Green, new Integer("3"));
+ assertEquals("Get returned incorrect value for given key", new Integer(
+ "3"), enumColorMap.get(Color.Green));
+ enumColorMap.put(Color.Green, null);
+ assertNull("Can not handle null value", enumColorMap.get(Color.Green));
+ Float f = new Float("3.4");
+ enumColorMap.put(Color.Green, f);
+ assertSame("Get returned incorrect value for given key", f,
+ enumColorMap.get(Color.Green));
+ }
+
+ /**
+ * java.util.EnumMap#put(Object,Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ try {
+ enumSizeMap.put(Color.Red, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ assertNull("Return non-null for non mapped key", enumSizeMap.put(
+ Size.Small, 1));
+
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ try {
+ enumColorMap.put(Size.Big, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ try {
+ enumColorMap.put(null, 2);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ assertNull("Return non-null for non mapped key", enumColorMap.put(
+ Color.Green, 2));
+ assertEquals("Return wrong value", 2, enumColorMap.put(Color.Green,
+ new Double(4)));
+ assertEquals("Return wrong value", new Double(4), enumColorMap.put(
+ Color.Green, new Integer("3")));
+ assertEquals("Return wrong value", new Integer("3"), enumColorMap.put(
+ Color.Green, null));
+ Float f = new Float("3.4");
+ assertNull("Return non-null for non mapped key", enumColorMap.put(
+ Color.Green, f));
+ assertNull("Return non-null for non mapped key", enumColorMap.put(
+ Color.Blue, 2));
+ assertEquals("Return wrong value", 2, enumColorMap.put(Color.Blue,
+ new Double(4)));
+ }
+
+ /**
+ * java.util.EnumMap#putAll(Map)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_putAllLjava_util_Map() {
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Green, 2);
+
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ enumColorMap.putAll(enumSizeMap);
+
+ enumSizeMap.put(Size.Big, 1);
+ try {
+ enumColorMap.putAll(enumSizeMap);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ EnumMap enumColorMap1 = new EnumMap<Color, Double>(Color.class);
+ enumColorMap1.put(Color.Blue, 3);
+ enumColorMap.putAll(enumColorMap1);
+ assertEquals("Get returned incorrect value for given key", 3,
+ enumColorMap.get(Color.Blue));
+ assertEquals("Wrong Size", 2, enumColorMap.size());
+
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+
+ HashMap hashColorMap = null;
+ try {
+ enumColorMap.putAll(hashColorMap);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ hashColorMap = new HashMap();
+ enumColorMap.putAll(hashColorMap);
+
+ hashColorMap.put(Color.Green, 2);
+ enumColorMap.putAll(hashColorMap);
+ assertEquals("Get returned incorrect value for given key", 2,
+ enumColorMap.get(Color.Green));
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Red));
+ hashColorMap.put(Color.Red, new Integer(1));
+ enumColorMap.putAll(hashColorMap);
+ assertEquals("Get returned incorrect value for given key", new Integer(
+ 2), enumColorMap.get(Color.Green));
+ hashColorMap.put(Size.Big, 3);
+ try {
+ enumColorMap.putAll(hashColorMap);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ hashColorMap = new HashMap();
+ hashColorMap.put(new Integer(1), 1);
+ try {
+ enumColorMap.putAll(hashColorMap);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.EnumMap#remove(Object)
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_removeLjava_lang_Object() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertNull("Remove of non-mapped key returned non-null", enumSizeMap
+ .remove(Size.Big));
+ enumSizeMap.put(Size.Big, 3);
+ enumSizeMap.put(Size.Middle, 2);
+
+ assertNull("Get returned non-null for non mapped key", enumSizeMap
+ .get(Size.Small));
+ assertEquals("Remove returned incorrect value", 3, enumSizeMap
+ .remove(Size.Big));
+ assertNull("Get returned non-null for non mapped key", enumSizeMap
+ .get(Size.Big));
+ assertNull("Remove of non-mapped key returned non-null", enumSizeMap
+ .remove(Size.Big));
+ assertNull("Remove of non-existent key returned non-null", enumSizeMap
+ .remove(Color.Red));
+ assertNull("Remove of non-existent key returned non-null", enumSizeMap
+ .remove(new Double(4)));
+ assertNull("Remove of non-existent key returned non-null", enumSizeMap
+ .remove(null));
+
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Green));
+ enumColorMap.put(Color.Green, new Double(4));
+ assertEquals("Remove returned incorrect value", new Double(4),
+ enumColorMap.remove(Color.Green));
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Green));
+ enumColorMap.put(Color.Green, null);
+ assertNull("Can not handle null value", enumColorMap
+ .remove(Color.Green));
+ assertNull("Get returned non-null for non mapped key", enumColorMap
+ .get(Color.Green));
+ }
+
+ /**
+ * java.util.EnumMap#size()
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void test_size() {
+ EnumMap enumSizeMap = new EnumMap(Size.class);
+ assertEquals("Wrong size", 0, enumSizeMap.size());
+ enumSizeMap.put(Size.Small, 1);
+ assertEquals("Wrong size", 1, enumSizeMap.size());
+ enumSizeMap.put(Size.Small, 0);
+ assertEquals("Wrong size", 1, enumSizeMap.size());
+ try {
+ enumSizeMap.put(Color.Red, 2);
+ fail("Expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ assertEquals("Wrong size", 1, enumSizeMap.size());
+
+ enumSizeMap.put(Size.Middle, null);
+ assertEquals("Wrong size", 2, enumSizeMap.size());
+ enumSizeMap.remove(Size.Big);
+ assertEquals("Wrong size", 2, enumSizeMap.size());
+ enumSizeMap.remove(Size.Middle);
+ assertEquals("Wrong size", 1, enumSizeMap.size());
+ enumSizeMap.remove(Color.Green);
+ assertEquals("Wrong size", 1, enumSizeMap.size());
+
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Green, 2);
+ assertEquals("Wrong size", 1, enumColorMap.size());
+ enumColorMap.remove(Color.Green);
+ assertEquals("Wrong size", 0, enumColorMap.size());
+
+ EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
+ assertEquals("Wrong size", 0, enumEmptyMap.size());
+ }
+
+ /**
+ * java.util.EnumMap#values()
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_values() {
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, null);
+ Collection collection = enumColorMap.values();
+
+ Collection collection1 = enumColorMap.values();
+ assertSame("Should be same", collection1, collection);
+ try {
+ collection.add(new Integer(1));
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+
+ assertTrue("Returned false for contained object", collection
+ .contains(1));
+ assertTrue("Returned false for contained object", collection
+ .contains(null));
+ assertFalse("Returned true for uncontained object", collection
+ .contains(2));
+
+ assertTrue("Returned false when the object can be removed", collection
+ .remove(null));
+ assertFalse("Returned true for uncontained object", collection
+ .contains(null));
+ assertFalse("Returned true when the object can not be removed",
+ collection.remove(null));
+
+ // The set is backed by the map so changes to one are reflected by the
+ // other.
+ enumColorMap.put(Color.Blue, 3);
+ assertTrue("Returned false for contained object", collection
+ .contains(3));
+ enumColorMap.remove(Color.Blue);
+ assertFalse("Returned true for uncontained object", collection
+ .contains(3));
+
+ assertEquals("Wrong size", 1, collection.size());
+ collection.clear();
+ assertEquals("Wrong size", 0, collection.size());
+
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, null);
+ collection = enumColorMap.values();
+ Collection c = new ArrayList();
+ c.add(new Integer(1));
+ assertTrue("Should return true", collection.containsAll(c));
+ c.add(new Double(3.4));
+ assertFalse("Should return false", collection.containsAll(c));
+ assertTrue("Should return true", collection.removeAll(c));
+ assertEquals("Wrong size", 1, collection.size());
+ assertFalse("Should return false", collection.removeAll(c));
+ assertEquals("Wrong size", 1, collection.size());
+ try {
+ collection.addAll(c);
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // Expected
+ }
+
+ enumColorMap.put(Color.Red, 1);
+ assertEquals("Wrong size", 2, collection.size());
+ assertTrue("Should return true", collection.retainAll(c));
+ assertEquals("Wrong size", 1, collection.size());
+ assertFalse("Should return false", collection.retainAll(c));
+ assertEquals(1, collection.size());
+ Object[] array = collection.toArray();
+ assertEquals("Wrong length", 1, array.length);
+ assertEquals("Wrong key", 1, array[0]);
+
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, null);
+ collection = enumColorMap.values();
+
+ assertEquals("Wrong size", 2, collection.size());
+ assertFalse("Returned true when the object can not be removed",
+ collection.remove(new Integer("10")));
+
+ Iterator iter = enumColorMap.values().iterator();
+ Object value = iter.next();
+ assertTrue("Returned false for contained object", collection
+ .contains(value));
+ value = iter.next();
+ assertTrue("Returned false for contained object", collection
+ .contains(value));
+
+ enumColorMap.put(Color.Green, 1);
+ enumColorMap.remove(Color.Blue);
+ assertFalse("Returned true for uncontained object", collection
+ .contains(value));
+ iter.remove();
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ assertFalse("Returned true for uncontained object", collection
+ .contains(value));
+
+ iter = enumColorMap.values().iterator();
+ value = iter.next();
+ assertTrue("Returned false for contained object", collection
+ .contains(value));
+ enumColorMap.put(Color.Green, 3);
+ assertTrue("Returned false for contained object", collection
+ .contains(value));
+ assertTrue("Returned false for contained object", collection
+ .remove(new Integer("1")));
+ assertEquals("Wrong size", 1, collection.size());
+ collection.clear();
+ assertEquals("Wrong size", 0, collection.size());
+
+ enumColorMap = new EnumMap<Color, Double>(Color.class);
+ Integer integer1 = new Integer(1);
+ enumColorMap.put(Color.Green, integer1);
+ enumColorMap.put(Color.Blue, null);
+ collection = enumColorMap.values();
+ iter = enumColorMap.values().iterator();
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ value = iter.next();
+ assertEquals("Wrong value", integer1, value);
+ assertSame("Wrong value", integer1, value);
+ assertFalse("Returned true for unequal object", iter.equals(value));
+ iter.remove();
+ assertFalse("Returned true for unequal object", iter.equals(value));
+ try {
+ iter.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ assertEquals("Wrong size", 1, collection.size());
+ value = iter.next();
+ assertFalse("Returned true for unequal object", iter.equals(value));
+ iter.remove();
+ try {
+ iter.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationSelf() throws Exception {
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Blue, 3);
+ SerializationTest.verifySelf(enumColorMap);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationCompatibility() throws Exception {
+ EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
+ enumColorMap.put(Color.Red, 1);
+ enumColorMap.put(Color.Blue, 3);
+ SerializationTest.verifyGolden(this, enumColorMap);
+ }
+
+ /**
+ * Sets up the fixture.
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ /**
+ * Tears down the fixture.
+ */
+ @Override
+ protected void tearDown() throws Exception{
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumSetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumSetTest.java
new file mode 100644
index 0000000..612c9f1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EnumSetTest.java
@@ -0,0 +1,2003 @@
+/* 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.tests.java.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class EnumSetTest extends TestCase {
+ static final boolean disableRIBugs = true;
+
+ static enum EnumWithInnerClass {
+ a, b, c, d, e, f {
+ },
+ }
+
+ enum EnumWithAllInnerClass {
+ a {},
+ b {},
+ }
+
+ static enum EnumFoo {
+ a, b,c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll,
+ }
+
+ static enum EmptyEnum {
+ // expected
+ }
+
+ static enum HugeEnumWithInnerClass {
+ a{}, b{}, c{}, d{}, e{}, f{}, g{}, h{}, i{}, j{}, k{}, l{}, m{}, n{}, o{}, p{}, q{}, r{}, s{}, t{}, u{}, v{}, w{}, x{}, y{}, z{}, A{}, B{}, C{}, D{}, E{}, F{}, G{}, H{}, I{}, J{}, K{}, L{}, M{}, N{}, O{}, P{}, Q{}, R{}, S{}, T{}, U{}, V{}, W{}, X{}, Y{}, Z{}, aa{}, bb{}, cc{}, dd{}, ee{}, ff{}, gg{}, hh{}, ii{}, jj{}, kk{}, ll{}, mm{},
+ }
+
+ static enum HugeEnum {
+ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm,
+ }
+
+ static enum HugeEnumCount {
+ NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, NO13, NO14, NO15, NO16, NO17, NO18, NO19, NO20,
+ NO21, NO22, NO23, NO24, NO25, NO26, NO27, NO28, NO29, NO30, NO31, NO32, NO33, NO34, NO35, NO36, NO37, NO38, NO39, NO40,
+ NO41, NO42, NO43, NO44, NO45, NO46, NO47, NO48, NO49, NO50, NO51, NO52, NO53, NO54, NO55, NO56, NO57, NO58, NO59, NO60,
+ NO61, NO62, NO63, NO64, NO65, NO66, NO67, NO68, NO69, NO70, NO71, NO72, NO73, NO74, NO75, NO76, NO77, NO78, NO79, NO80,
+ NO81, NO82, NO83, NO84, NO85, NO86, NO87, NO88, NO89, NO90, NO91, NO92, NO93, NO94, NO95, NO96, NO97, NO98, NO99, NO100,
+ NO101, NO102, NO103, NO104, NO105, NO106, NO107, NO108, NO109, NO110, NO111, NO112, NO113, NO114, NO115, NO116, NO117, NO118, NO119, NO120,
+ NO121, NO122, NO123, NO124, NO125, NO126, NO127, NO128, NO129, NO130,
+ }
+
+ /**
+ * java.util.EnumSet#noneOf(java.lang.Class)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_NoneOf_LClass() {
+ try {
+ EnumSet.noneOf((Class) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.noneOf(Enum.class);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException cce) {
+ // expected
+ }
+
+ Class<EnumWithAllInnerClass> c = (Class<EnumWithAllInnerClass>) EnumWithAllInnerClass.a
+ .getClass();
+ try {
+ EnumSet.noneOf(c);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ EnumSet<EnumWithAllInnerClass> setWithInnerClass = EnumSet
+ .noneOf(EnumWithAllInnerClass.class);
+ assertNotNull(setWithInnerClass);
+
+ // test enum type with more than 64 elements
+ Class<HugeEnumWithInnerClass> hc = (Class<HugeEnumWithInnerClass>) HugeEnumWithInnerClass.a
+ .getClass();
+ try {
+ EnumSet.noneOf(hc);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ EnumSet<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ assertNotNull(hugeSetWithInnerClass);
+ }
+
+ /**
+ * java.util.HugeEnumSet#iterator()
+ */
+ public void test_iterator_HugeEnumSet() {
+ EnumSet<HugeEnumCount> set;
+ Object[] array;
+
+ // Test HugeEnumSet with 65 elements
+ // which is more than the bits of Long
+ set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO65);
+ array = set.toArray();
+ for (HugeEnumCount count : set) {
+ assertEquals(count, (HugeEnumCount) array[count.ordinal()]);
+ }
+
+ // Test HugeEnumSet with 130 elements
+ // which is more than twice of the bits of Long
+ set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO130);
+ array = set.toArray();
+ for (HugeEnumCount count : set) {
+ assertEquals(count, (HugeEnumCount) array[count.ordinal()]);
+ }
+ }
+
+ public void testRemoveIteratorRemoveFromHugeEnumSet() {
+ EnumSet<HugeEnumCount> set = EnumSet.noneOf(HugeEnumCount.class);
+ set.add(HugeEnumCount.NO64);
+ set.add(HugeEnumCount.NO65);
+ set.add(HugeEnumCount.NO128);
+ Iterator<HugeEnumCount> iterator = set.iterator();
+ assertTrue(iterator.hasNext());
+ assertEquals(HugeEnumCount.NO64, iterator.next());
+ assertTrue(iterator.hasNext());
+ iterator.remove();
+ assertEquals(HugeEnumCount.NO65, iterator.next());
+ assertTrue(iterator.hasNext());
+ assertEquals(HugeEnumCount.NO128, iterator.next());
+ assertFalse(iterator.hasNext());
+ assertEquals(EnumSet.of(HugeEnumCount.NO65, HugeEnumCount.NO128), set);
+ iterator.remove();
+ assertEquals(EnumSet.of(HugeEnumCount.NO65), set);
+ }
+
+ /**
+ * java.util.EnumSet#allOf(java.lang.Class)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_AllOf_LClass() {
+ try {
+ EnumSet.allOf((Class) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.allOf(Enum.class);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException cce) {
+ // expected
+ }
+
+ EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
+ assertEquals("Size of enumSet should be 64", 64, enumSet.size());
+
+ assertFalse(
+ "enumSet should not contain null value", enumSet.contains(null));
+ assertTrue(
+ "enumSet should contain EnumFoo.a", enumSet.contains(EnumFoo.a));
+ assertTrue(
+ "enumSet should contain EnumFoo.b", enumSet.contains(EnumFoo.b));
+
+ enumSet.add(EnumFoo.a);
+ assertEquals("Should be equal", 64, enumSet.size());
+
+ EnumSet<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
+ assertEquals("Should be equal", enumSet, anotherSet);
+ assertNotSame("Should not be identical", enumSet, anotherSet);
+
+ // test enum with more than 64 elements
+ EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
+ assertEquals(65, hugeEnumSet.size());
+
+ assertFalse(hugeEnumSet.contains(null));
+ assertTrue(hugeEnumSet.contains(HugeEnum.a));
+ assertTrue(hugeEnumSet.contains(HugeEnum.b));
+
+ hugeEnumSet.add(HugeEnum.a);
+ assertEquals(65, hugeEnumSet.size());
+
+ EnumSet<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
+ assertEquals(hugeEnumSet, anotherHugeSet);
+ assertNotSame(hugeEnumSet, anotherHugeSet);
+
+ }
+
+ /**
+ * java.util.EnumSet#add(E)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_add_E() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.a);
+ set.add(EnumFoo.b);
+
+ try {
+ set.add(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ Set rawSet = set;
+ try {
+ rawSet.add(HugeEnumWithInnerClass.b);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ set.clear();
+ try {
+ set.add(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ boolean result = set.add(EnumFoo.a);
+ assertEquals("Size should be 1:", 1, set.size());
+ assertTrue("Return value should be true", result);
+
+ result = set.add(EnumFoo.a);
+ assertEquals("Size should be 1:", 1, set.size());
+ assertFalse("Return value should be false", result);
+
+ set.add(EnumFoo.b);
+ assertEquals("Size should be 2:", 2, set.size());
+
+ rawSet = set;
+ try {
+ rawSet.add(EnumWithAllInnerClass.a);
+ fail("Should throw ClassCastException");
+ } catch(ClassCastException e) {
+ // expected
+ }
+
+ try {
+ rawSet.add(EnumWithInnerClass.a);
+ fail("Should throw ClassCastException");
+ } catch(ClassCastException e) {
+ // expected
+ }
+
+ try {
+ rawSet.add(new Object());
+ fail("Should throw ClassCastException");
+ } catch(ClassCastException e) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ result = hugeSet.add(HugeEnum.a);
+ assertTrue(result);
+
+ result = hugeSet.add(HugeEnum.a);
+ assertFalse(result);
+
+ try {
+ hugeSet.add(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ rawSet = hugeSet;
+ try {
+ rawSet.add(HugeEnumWithInnerClass.b);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ try {
+ rawSet.add(new Object());
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ result = hugeSet.add(HugeEnum.mm);
+ assertTrue(result);
+ result = hugeSet.add(HugeEnum.mm);
+ assertFalse(result);
+ assertEquals(2, hugeSet.size());
+
+ }
+
+ /**
+ * java.util.EnumSet#addAll(Collection)
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_addAll_LCollection() {
+
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ assertEquals("Size should be 0:", 0, set.size());
+
+ try {
+ set.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Set emptySet = EnumSet.noneOf(EmptyEnum.class);
+ Enum[] elements = EmptyEnum.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ emptySet.add(elements[i]);
+ }
+ boolean result = set.addAll(emptySet);
+ assertFalse(result);
+
+ Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
+ collection.add(EnumFoo.a);
+ collection.add(EnumFoo.b);
+ result = set.addAll(collection);
+ assertTrue("addAll should be successful", result);
+ assertEquals("Size should be 2:", 2, set.size());
+
+ set = EnumSet.noneOf(EnumFoo.class);
+
+ Collection rawCollection = new ArrayList<Integer>();
+ result = set.addAll(rawCollection);
+ assertFalse(result);
+ rawCollection.add(1);
+ try {
+ set.addAll(rawCollection);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ Set<EnumFoo> fullSet = EnumSet.noneOf(EnumFoo.class);
+ fullSet.add(EnumFoo.a);
+ fullSet.add(EnumFoo.b);
+ result = set.addAll(fullSet);
+ assertTrue("addAll should be successful", result);
+ assertEquals("Size of set should be 2", 2, set.size());
+
+ try {
+ fullSet.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Set fullSetWithSubclass = EnumSet.noneOf(EnumWithInnerClass.class);
+ elements = EnumWithInnerClass.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ fullSetWithSubclass.add(elements[i]);
+ }
+ try {
+ set.addAll(fullSetWithSubclass);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ Set<EnumWithInnerClass> setWithSubclass = fullSetWithSubclass;
+ result = setWithSubclass.addAll(setWithSubclass);
+ assertFalse("Should return false", result);
+
+ Set<EnumWithInnerClass> anotherSetWithSubclass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ elements = EnumWithInnerClass.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ anotherSetWithSubclass.add((EnumWithInnerClass) elements[i]);
+ }
+ result = setWithSubclass.addAll(anotherSetWithSubclass);
+ assertFalse("Should return false", result);
+
+ anotherSetWithSubclass.remove(EnumWithInnerClass.a);
+ result = setWithSubclass.addAll(anotherSetWithSubclass);
+ assertFalse("Should return false", result);
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ assertEquals(0, hugeSet.size());
+
+ try {
+ hugeSet.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ hugeSet = EnumSet.allOf(HugeEnum.class);
+ result = hugeSet.addAll(hugeSet);
+ assertFalse(result);
+
+ hugeSet = EnumSet.noneOf(HugeEnum.class);
+ Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
+ hugeCollection.add(HugeEnum.a);
+ hugeCollection.add(HugeEnum.b);
+ result = hugeSet.addAll(hugeCollection);
+ assertTrue(result);
+ assertEquals(2, set.size());
+
+ hugeSet = EnumSet.noneOf(HugeEnum.class);
+
+ rawCollection = new ArrayList<Integer>();
+ result = hugeSet.addAll(rawCollection);
+ assertFalse(result);
+ rawCollection.add(1);
+ try {
+ hugeSet.addAll(rawCollection);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ EnumSet<HugeEnum> aHugeSet = EnumSet.noneOf(HugeEnum.class);
+ aHugeSet.add(HugeEnum.a);
+ aHugeSet.add(HugeEnum.b);
+ result = hugeSet.addAll(aHugeSet);
+ assertTrue(result);
+ assertEquals(2, hugeSet.size());
+
+ try {
+ aHugeSet.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Set hugeSetWithSubclass = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ try {
+ hugeSet.addAll(hugeSetWithSubclass);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ Set<HugeEnumWithInnerClass> hugeSetWithInnerSubclass = hugeSetWithSubclass;
+ result = hugeSetWithInnerSubclass.addAll(hugeSetWithInnerSubclass);
+ assertFalse(result);
+
+ Set<HugeEnumWithInnerClass> anotherHugeSetWithSubclass = EnumSet
+ .allOf(HugeEnumWithInnerClass.class);
+ result = hugeSetWithSubclass.addAll(anotherHugeSetWithSubclass);
+ assertFalse(result);
+
+ anotherHugeSetWithSubclass.remove(HugeEnumWithInnerClass.a);
+ result = setWithSubclass.addAll(anotherSetWithSubclass);
+ assertFalse(result);
+
+ }
+
+ /**
+ * java.util.EnumSet#remove(Object)
+ */
+ public void test_remove_LOject() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ Enum[] elements = EnumFoo.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ set.add((EnumFoo) elements[i]);
+ }
+
+ boolean result = set.remove(null);
+ assertFalse("'set' does not contain null", result);
+
+ result = set.remove(EnumFoo.a);
+ assertTrue("Should return true", result);
+ result = set.remove(EnumFoo.a);
+ assertFalse("Should return false", result);
+
+ assertEquals("Size of set should be 63:", 63, set.size());
+
+ result = set.remove(EnumWithInnerClass.a);
+ assertFalse("Should return false", result);
+ result = set.remove(EnumWithInnerClass.f);
+ assertFalse("Should return false", result);
+
+ // test enum with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
+
+ result = hugeSet.remove(null);
+ assertFalse("'set' does not contain null", result);
+
+ result = hugeSet.remove(HugeEnum.a);
+ assertTrue("Should return true", result);
+ result = hugeSet.remove(HugeEnum.a);
+ assertFalse("Should return false", result);
+
+ assertEquals("Size of set should be 64:", 64, hugeSet.size());
+
+ result = hugeSet.remove(HugeEnumWithInnerClass.a);
+ assertFalse("Should return false", result);
+ result = hugeSet.remove(HugeEnumWithInnerClass.f);
+ assertFalse("Should return false", result);
+ }
+
+ /**
+ * java.util.EnumSet#equals(Object)
+ */
+ public void test_equals_LObject() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ Enum[] elements = EnumFoo.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ set.add((EnumFoo) elements[i]);
+ }
+
+ assertFalse("Should return false", set.equals(null));
+ assertFalse(
+ "Should return false", set.equals(new Object()));
+
+ Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
+ elements = EnumFoo.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ anotherSet.add((EnumFoo) elements[i]);
+ }
+ assertTrue("Should return true", set.equals(anotherSet));
+
+ anotherSet.remove(EnumFoo.a);
+ assertFalse(
+ "Should return false", set.equals(anotherSet));
+
+ Set<EnumWithInnerClass> setWithInnerClass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ elements = EnumWithInnerClass.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ setWithInnerClass.add((EnumWithInnerClass) elements[i]);
+ }
+
+ assertFalse(
+ "Should return false", set.equals(setWithInnerClass));
+
+ setWithInnerClass.clear();
+ set.clear();
+ assertTrue("Should be equal", set.equals(setWithInnerClass));
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ assertTrue(hugeSet.equals(set));
+
+ hugeSet = EnumSet.allOf(HugeEnum.class);
+ assertFalse(hugeSet.equals(null));
+ assertFalse(hugeSet.equals(new Object()));
+
+ Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
+ anotherHugeSet.remove(HugeEnum.a);
+ assertFalse(hugeSet.equals(anotherHugeSet));
+
+ Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
+ .allOf(HugeEnumWithInnerClass.class);
+ assertFalse(hugeSet.equals(hugeSetWithInnerClass));
+ hugeSetWithInnerClass.clear();
+ hugeSet.clear();
+ assertTrue(hugeSet.equals(hugeSetWithInnerClass));
+ }
+
+ /**
+ * java.util.EnumSet#clear()
+ */
+ public void test_clear() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.a);
+ set.add(EnumFoo.b);
+ assertEquals("Size should be 2", 2, set.size());
+
+ set.clear();
+
+ assertEquals("Size should be 0", 0, set.size());
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
+ assertEquals(65, hugeSet.size());
+
+ boolean result = hugeSet.contains(HugeEnum.aa);
+ assertTrue(result);
+
+ hugeSet.clear();
+ assertEquals(0, hugeSet.size());
+ result = hugeSet.contains(HugeEnum.aa);
+ assertFalse(result);
+ }
+
+ /**
+ * java.util.EnumSet#size()
+ */
+ public void test_size() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.a);
+ set.add(EnumFoo.b);
+ assertEquals("Size should be 2", 2, set.size());
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ hugeSet.add(HugeEnum.a);
+ hugeSet.add(HugeEnum.bb);
+ assertEquals("Size should be 2", 2, hugeSet.size());
+ }
+
+ /**
+ * java.util.EnumSet#complementOf(java.util.EnumSet)
+ */
+ public void test_ComplementOf_LEnumSet() {
+
+ try {
+ EnumSet.complementOf((EnumSet<EnumFoo>) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ EnumSet<EnumWithInnerClass> set = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ set.add(EnumWithInnerClass.d);
+ set.add(EnumWithInnerClass.e);
+ set.add(EnumWithInnerClass.f);
+
+ assertEquals("Size should be 3:", 3, set.size());
+
+ EnumSet<EnumWithInnerClass> complementOfE = EnumSet.complementOf(set);
+ assertTrue(set.contains(EnumWithInnerClass.d));
+ assertEquals(
+ "complementOfE should have size 3", 3, complementOfE.size());
+ assertTrue("complementOfE should contain EnumWithSubclass.a:",
+ complementOfE.contains(EnumWithInnerClass.a));
+ assertTrue("complementOfE should contain EnumWithSubclass.b:",
+ complementOfE.contains(EnumWithInnerClass.b));
+ assertTrue("complementOfE should contain EnumWithSubclass.c:",
+ complementOfE.contains(EnumWithInnerClass.c));
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ assertEquals(0, hugeSet.size());
+ Set<HugeEnum> complementHugeSet = EnumSet.complementOf(hugeSet);
+ assertEquals(65, complementHugeSet.size());
+
+ hugeSet.add(HugeEnum.A);
+ hugeSet.add(HugeEnum.mm);
+ complementHugeSet = EnumSet.complementOf(hugeSet);
+ assertEquals(63, complementHugeSet.size());
+
+ try {
+ EnumSet.complementOf((EnumSet<HugeEnum>) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.EnumSet#contains(Object)
+ */
+ public void test_contains_LObject() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ Enum[] elements = EnumFoo.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ set.add((EnumFoo)elements[i]);
+ }
+ boolean result = set.contains(null);
+ assertFalse("Should not contain null:", result);
+
+ result = set.contains(EnumFoo.a);
+ assertTrue("Should contain EnumFoo.a", result);
+ result = set.contains(EnumFoo.ll);
+ assertTrue("Should contain EnumFoo.ll", result);
+
+ result = set.contains(EnumFoo.b);
+ assertTrue("Should contain EnumFoo.b", result);
+
+ result = set.contains(new Object());
+ assertFalse("Should not contain Object instance", result);
+
+ result = set.contains(EnumWithInnerClass.a);
+ assertFalse("Should not contain EnumWithSubclass.a", result);
+
+ set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.aa);
+ set.add(EnumFoo.bb);
+ set.add(EnumFoo.cc);
+
+ assertEquals("Size of set should be 3", 3, set.size());
+ assertTrue("set should contain EnumFoo.aa", set.contains(EnumFoo.aa));
+
+ Set<EnumWithInnerClass> setWithSubclass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ setWithSubclass.add(EnumWithInnerClass.a);
+ setWithSubclass.add(EnumWithInnerClass.b);
+ setWithSubclass.add(EnumWithInnerClass.c);
+ setWithSubclass.add(EnumWithInnerClass.d);
+ setWithSubclass.add(EnumWithInnerClass.e);
+ setWithSubclass.add(EnumWithInnerClass.f);
+ result = setWithSubclass.contains(EnumWithInnerClass.f);
+ assertTrue("Should contain EnumWithSubclass.f", result);
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
+ hugeSet.add(HugeEnum.a);
+ result = hugeSet.contains(HugeEnum.a);
+ assertTrue(result);
+
+ result = hugeSet.contains(HugeEnum.b);
+ assertTrue(result);
+
+ result = hugeSet.contains(null);
+ assertFalse(result);
+
+ result = hugeSet.contains(HugeEnum.a);
+ assertTrue(result);
+
+ result = hugeSet.contains(HugeEnum.ll);
+ assertTrue(result);
+
+ result = hugeSet.contains(new Object());
+ assertFalse(result);
+
+ result = hugeSet.contains(Enum.class);
+ assertFalse(result);
+
+ }
+
+ /**
+ * java.util.EnumSet#containsAll(Collection)
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void test_containsAll_LCollection() {
+ EnumSet<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ Enum[] elements = EnumFoo.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ set.add((EnumFoo)elements[i]);
+ }
+ try {
+ set.containsAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ EnumSet<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
+ elements = EmptyEnum.class.getEnumConstants();
+ for(int i = 0; i < elements.length; i++) {
+ emptySet.add((EmptyEnum)elements[i]);
+ }
+ boolean result = set.containsAll(emptySet);
+ assertTrue("Should return true", result);
+
+ Collection rawCollection = new ArrayList();
+ result = set.containsAll(rawCollection);
+ assertTrue("Should contain empty collection:", result);
+
+ rawCollection.add(1);
+ result = set.containsAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ rawCollection.add(EnumWithInnerClass.a);
+ result = set.containsAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ EnumSet rawSet = EnumSet.noneOf(EnumFoo.class);
+ result = set.containsAll(rawSet);
+ assertTrue("Should contain empty set", result);
+
+ emptySet = EnumSet.noneOf(EmptyEnum.class);
+ result = set.containsAll(emptySet);
+ assertTrue("No class cast should be performed on empty set", result);
+
+ Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
+ collection.add(EnumFoo.a);
+ result = set.containsAll(collection);
+ assertTrue("Should contain all elements in collection", result);
+
+ EnumSet<EnumFoo> fooSet = EnumSet.noneOf(EnumFoo.class);
+ fooSet.add(EnumFoo.a);
+ result = set.containsAll(fooSet);
+ assertTrue("Should return true", result);
+
+ set.clear();
+ try {
+ set.containsAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Collection<EnumWithInnerClass> collectionWithSubclass = new ArrayList<EnumWithInnerClass>();
+ collectionWithSubclass.add(EnumWithInnerClass.a);
+ result = set.containsAll(collectionWithSubclass);
+ assertFalse("Should return false", result);
+
+ EnumSet<EnumWithInnerClass> setWithSubclass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ setWithSubclass.add(EnumWithInnerClass.a);
+ result = set.containsAll(setWithSubclass);
+ assertFalse("Should return false", result);
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ hugeSet.add(HugeEnum.a);
+ hugeSet.add(HugeEnum.b);
+ hugeSet.add(HugeEnum.aa);
+ hugeSet.add(HugeEnum.bb);
+ hugeSet.add(HugeEnum.cc);
+ hugeSet.add(HugeEnum.dd);
+
+ Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
+ hugeSet.add(HugeEnum.b);
+ hugeSet.add(HugeEnum.cc);
+ result = hugeSet.containsAll(anotherHugeSet);
+ assertTrue(result);
+
+ try {
+ hugeSet.containsAll(null);
+ fail("Should throw NullPointerException");
+ } catch(NullPointerException e) {
+ // expected
+ }
+
+ Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
+ hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
+ result = hugeSetWithInnerClass.containsAll(hugeSetWithInnerClass);
+ assertTrue(result);
+ result = hugeSet.containsAll(hugeSetWithInnerClass);
+ assertFalse(result);
+
+ rawCollection = new ArrayList();
+ result = hugeSet.containsAll(rawCollection);
+ assertTrue("Should contain empty collection:", result);
+
+ rawCollection.add(1);
+ result = hugeSet.containsAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ rawCollection.add(EnumWithInnerClass.a);
+ result = set.containsAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ rawSet = EnumSet.noneOf(HugeEnum.class);
+ result = hugeSet.containsAll(rawSet);
+ assertTrue("Should contain empty set", result);
+
+ EnumSet<HugeEnumWithInnerClass> emptyHugeSet
+ = EnumSet.noneOf(HugeEnumWithInnerClass.class);
+ result = hugeSet.containsAll(emptyHugeSet);
+ assertTrue("No class cast should be performed on empty set", result);
+
+ Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
+ hugeCollection.add(HugeEnum.a);
+ result = hugeSet.containsAll(hugeCollection);
+ assertTrue("Should contain all elements in collection", result);
+
+ hugeSet.clear();
+ try {
+ hugeSet.containsAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Collection<HugeEnumWithInnerClass> hugeCollectionWithSubclass = new ArrayList<HugeEnumWithInnerClass>();
+ hugeCollectionWithSubclass.add(HugeEnumWithInnerClass.a);
+ result = hugeSet.containsAll(hugeCollectionWithSubclass);
+ assertFalse("Should return false", result);
+
+ EnumSet<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
+ result = hugeSet.containsAll(hugeSetWithSubclass);
+ assertFalse("Should return false", result);
+ }
+
+ /**
+ * java.util.EnumSet#copyOf(java.util.Collection)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_CopyOf_LCollection() {
+ try {
+ EnumSet.copyOf((Collection) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ Collection collection = new ArrayList();
+ try {
+ EnumSet.copyOf(collection);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ collection.add(new Object());
+ try {
+ EnumSet.copyOf(collection);
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ Collection<EnumFoo> enumCollection = new ArrayList<EnumFoo>();
+ enumCollection.add(EnumFoo.b);
+
+ EnumSet<EnumFoo> copyOfEnumCollection = EnumSet.copyOf(enumCollection);
+ assertEquals("Size of copyOfEnumCollection should be 1:",
+ 1, copyOfEnumCollection.size());
+ assertTrue("copyOfEnumCollection should contain EnumFoo.b:",
+ copyOfEnumCollection.contains(EnumFoo.b));
+
+ enumCollection.add(null);
+ assertEquals("Size of enumCollection should be 2:",
+ 2, enumCollection.size());
+
+ try {
+ copyOfEnumCollection = EnumSet.copyOf(enumCollection);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ Collection rawEnumCollection = new ArrayList();
+ rawEnumCollection.add(EnumFoo.a);
+ rawEnumCollection.add(EnumWithInnerClass.a);
+ try {
+ EnumSet.copyOf(rawEnumCollection);
+ fail("Should throw ClassCastException");
+ } catch(ClassCastException e) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ Collection<HugeEnum> hugeEnumCollection = new ArrayList<HugeEnum>();
+ hugeEnumCollection.add(HugeEnum.b);
+
+ EnumSet<HugeEnum> copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
+ assertEquals(1, copyOfHugeEnumCollection.size());
+ assertTrue(copyOfHugeEnumCollection.contains(HugeEnum.b));
+
+ hugeEnumCollection.add(null);
+ assertEquals(2, hugeEnumCollection.size());
+
+ try {
+ copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ rawEnumCollection = new ArrayList();
+ rawEnumCollection.add(HugeEnum.a);
+ rawEnumCollection.add(HugeEnumWithInnerClass.a);
+ try {
+ EnumSet.copyOf(rawEnumCollection);
+ fail("Should throw ClassCastException");
+ } catch(ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.EnumSet#copyOf(java.util.EnumSet)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_CopyOf_LEnumSet() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ enumSet.add(EnumWithInnerClass.a);
+ enumSet.add(EnumWithInnerClass.f);
+ EnumSet<EnumWithInnerClass> copyOfE = EnumSet.copyOf(enumSet);
+ assertEquals("Size of enumSet and copyOfE should be equal",
+ enumSet.size(), copyOfE.size());
+
+ assertTrue("EnumWithSubclass.a should be contained in copyOfE",
+ copyOfE.contains(EnumWithInnerClass.a));
+ assertTrue("EnumWithSubclass.f should be contained in copyOfE",
+ copyOfE.contains(EnumWithInnerClass.f));
+
+ Object[] enumValue = copyOfE.toArray();
+ assertSame("enumValue[0] should be identical with EnumWithSubclass.a",
+ enumValue[0], EnumWithInnerClass.a);
+ assertSame("enumValue[1] should be identical with EnumWithSubclass.f",
+ enumValue[1], EnumWithInnerClass.f);
+
+ try {
+ EnumSet.copyOf((EnumSet) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ hugeEnumSet.add(HugeEnumWithInnerClass.a);
+ hugeEnumSet.add(HugeEnumWithInnerClass.f);
+ EnumSet<HugeEnumWithInnerClass> copyOfHugeEnum = EnumSet.copyOf(hugeEnumSet);
+ assertEquals(enumSet.size(), copyOfE.size());
+
+ assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.a));
+ assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.f));
+
+ Object[] hugeEnumValue = copyOfHugeEnum.toArray();
+ assertSame(hugeEnumValue[0], HugeEnumWithInnerClass.a);
+ assertSame(hugeEnumValue[1], HugeEnumWithInnerClass.f);
+ }
+
+ /**
+ * java.util.EnumSet#removeAll(Collection)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_removeAll_LCollection() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ try {
+ set.removeAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ set = EnumSet.allOf(EnumFoo.class);
+ assertEquals("Size of set should be 64:", 64, set.size());
+
+ try {
+ set.removeAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
+ collection.add(EnumFoo.a);
+
+ boolean result = set.removeAll(collection);
+ assertTrue("Should return true", result);
+ assertEquals("Size of set should be 63", 63, set.size());
+
+ collection = new ArrayList();
+ result = set.removeAll(collection);
+ assertFalse("Should return false", result);
+
+ Set<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
+ result = set.removeAll(emptySet);
+ assertFalse("Should return false", result);
+
+ EnumSet<EnumFoo> emptyFooSet = EnumSet.noneOf(EnumFoo.class);
+ result = set.removeAll(emptyFooSet);
+ assertFalse("Should return false", result);
+
+ emptyFooSet.add(EnumFoo.a);
+ result = set.removeAll(emptyFooSet);
+ assertFalse("Should return false", result);
+
+ Set<EnumWithInnerClass> setWithSubclass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ result = set.removeAll(setWithSubclass);
+ assertFalse("Should return false", result);
+
+ setWithSubclass.add(EnumWithInnerClass.a);
+ result = set.removeAll(setWithSubclass);
+ assertFalse("Should return false", result);
+
+ Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
+ anotherSet.add(EnumFoo.a);
+
+ set = EnumSet.allOf(EnumFoo.class);
+ result = set.removeAll(anotherSet);
+ assertTrue("Should return true", result);
+ assertEquals("Size of set should be 63:", 63, set.size());
+
+ Set<EnumWithInnerClass> setWithInnerClass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ setWithInnerClass.add(EnumWithInnerClass.a);
+ setWithInnerClass.add(EnumWithInnerClass.b);
+
+ Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ anotherSetWithInnerClass.add(EnumWithInnerClass.c);
+ anotherSetWithInnerClass.add(EnumWithInnerClass.d);
+ result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
+ assertFalse("Should return false", result);
+
+ anotherSetWithInnerClass.add(EnumWithInnerClass.a);
+ result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
+ assertTrue("Should return true", result);
+ assertEquals("Size of anotherSetWithInnerClass should remain 2",
+ 2, anotherSetWithInnerClass.size());
+
+ anotherSetWithInnerClass.remove(EnumWithInnerClass.c);
+ anotherSetWithInnerClass.remove(EnumWithInnerClass.d);
+ result = anotherSetWithInnerClass.remove(setWithInnerClass);
+ assertFalse("Should return false", result);
+
+ Set rawSet = EnumSet.allOf(EnumWithAllInnerClass.class);
+ result = rawSet.removeAll(EnumSet.allOf(EnumFoo.class));
+ assertFalse("Should return false", result);
+
+ setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
+ anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
+ setWithInnerClass.remove(EnumWithInnerClass.a);
+ anotherSetWithInnerClass.remove(EnumWithInnerClass.f);
+ result = setWithInnerClass.removeAll(anotherSetWithInnerClass);
+ assertTrue("Should return true", result);
+ assertEquals("Size of setWithInnerClass should be 1", 1, setWithInnerClass.size());
+
+ result = setWithInnerClass.contains(EnumWithInnerClass.f);
+ assertTrue("Should return true", result);
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
+
+ Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
+ hugeCollection.add(HugeEnum.a);
+
+ result = hugeSet.removeAll(hugeCollection);
+ assertTrue(result);
+ assertEquals(64, hugeSet.size());
+
+ collection = new ArrayList();
+ result = hugeSet.removeAll(collection);
+ assertFalse(result);
+
+ Set<HugeEnum> emptyHugeSet = EnumSet.noneOf(HugeEnum.class);
+ result = hugeSet.removeAll(emptyHugeSet);
+ assertFalse(result);
+
+ Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ result = hugeSet.removeAll(hugeSetWithSubclass);
+ assertFalse(result);
+
+ hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
+ result = hugeSet.removeAll(hugeSetWithSubclass);
+ assertFalse(result);
+
+ Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
+ anotherHugeSet.add(HugeEnum.a);
+
+ hugeSet = EnumSet.allOf(HugeEnum.class);
+ result = hugeSet.removeAll(anotherHugeSet);
+ assertTrue(result);
+ assertEquals(63, set.size());
+
+ Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
+ hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
+
+ Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.c);
+ anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.d);
+ result = anotherHugeSetWithInnerClass.removeAll(setWithInnerClass);
+ assertFalse("Should return false", result);
+
+ anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
+ result = anotherHugeSetWithInnerClass.removeAll(hugeSetWithInnerClass);
+ assertTrue(result);
+ assertEquals(2, anotherHugeSetWithInnerClass.size());
+
+ anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.c);
+ anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.d);
+ result = anotherHugeSetWithInnerClass.remove(hugeSetWithInnerClass);
+ assertFalse(result);
+
+ rawSet = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ result = rawSet.removeAll(EnumSet.allOf(HugeEnum.class));
+ assertFalse(result);
+
+ hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.a);
+ anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
+ result = hugeSetWithInnerClass.removeAll(anotherHugeSetWithInnerClass);
+ assertTrue(result);
+ assertEquals(1, hugeSetWithInnerClass.size());
+
+ result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.f);
+ assertTrue(result);
+ }
+
+ /**
+ * java.util.EnumSet#retainAll(Collection)
+ */
+ @SuppressWarnings("unchecked")
+ public void test_retainAll_LCollection() {
+ Set<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
+
+ try {
+ set.retainAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ set.clear();
+ boolean result = set.retainAll(null);
+ assertFalse("Should return false", result);
+
+ Collection rawCollection = new ArrayList();
+ result = set.retainAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ rawCollection.add(EnumFoo.a);
+ result = set.retainAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ rawCollection.add(EnumWithInnerClass.a);
+ result = set.retainAll(rawCollection);
+ assertFalse("Should return false", result);
+ assertEquals("Size of set should be 0:", 0, set.size());
+
+ rawCollection.remove(EnumFoo.a);
+ result = set.retainAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ Set<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
+ result = set.retainAll(anotherSet);
+ assertFalse("Should return false", result);
+ assertEquals("Size of set should be 0", 0, set.size());
+
+ Set<EnumWithInnerClass> setWithInnerClass = EnumSet
+ .allOf(EnumWithInnerClass.class);
+ result = set.retainAll(setWithInnerClass);
+ assertFalse("Should return false", result);
+ assertEquals("Size of set should be 0", 0, set.size());
+
+ setWithInnerClass = EnumSet.noneOf(EnumWithInnerClass.class);
+ result = set.retainAll(setWithInnerClass);
+ assertFalse("Should return false", result);
+
+ Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
+ result = set.retainAll(emptySet);
+ assertFalse("Should return false", result);
+
+ Set<EnumWithAllInnerClass> setWithAllInnerClass = EnumSet
+ .allOf(EnumWithAllInnerClass.class);
+ result = set.retainAll(setWithAllInnerClass);
+ assertFalse("Should return false", result);
+
+ set.add(EnumFoo.a);
+ result = set.retainAll(setWithInnerClass);
+ assertTrue("Should return true", result);
+ assertEquals("Size of set should be 0", 0, set.size());
+
+ setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
+ setWithInnerClass.remove(EnumWithInnerClass.f);
+ Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
+ .noneOf(EnumWithInnerClass.class);
+ anotherSetWithInnerClass.add(EnumWithInnerClass.e);
+ anotherSetWithInnerClass.add(EnumWithInnerClass.f);
+
+ result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
+ assertTrue("Should return true", result);
+ result = setWithInnerClass.contains(EnumWithInnerClass.e);
+ assertTrue("Should contain EnumWithInnerClass.e", result);
+ result = setWithInnerClass.contains(EnumWithInnerClass.b);
+ assertFalse("Should not contain EnumWithInnerClass.b", result);
+ assertEquals("Size of set should be 1:", 1, setWithInnerClass.size());
+
+ anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
+ result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
+
+ assertFalse("Return value should be false", result);
+
+ rawCollection = new ArrayList();
+ rawCollection.add(EnumWithInnerClass.e);
+ rawCollection.add(EnumWithInnerClass.f);
+ result = setWithInnerClass.retainAll(rawCollection);
+ assertFalse("Should return false", result);
+
+ set = EnumSet.allOf(EnumFoo.class);
+ set.remove(EnumFoo.a);
+ anotherSet = EnumSet.noneOf(EnumFoo.class);
+ anotherSet.add(EnumFoo.a);
+ result = set.retainAll(anotherSet);
+ assertTrue("Should return true", result);
+ assertEquals("size should be 0", 0, set.size());
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
+
+ try {
+ hugeSet.retainAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ hugeSet.clear();
+ result = hugeSet.retainAll(null);
+ assertFalse(result);
+
+ rawCollection = new ArrayList();
+ result = hugeSet.retainAll(rawCollection);
+ assertFalse(result);
+
+ rawCollection.add(HugeEnum.a);
+ result = hugeSet.retainAll(rawCollection);
+ assertFalse(result);
+
+ rawCollection.add(HugeEnumWithInnerClass.a);
+ result = hugeSet.retainAll(rawCollection);
+ assertFalse(result);
+ assertEquals(0, set.size());
+
+ rawCollection.remove(HugeEnum.a);
+ result = set.retainAll(rawCollection);
+ assertFalse(result);
+
+ Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
+ result = hugeSet.retainAll(anotherHugeSet);
+ assertFalse(result);
+ assertEquals(0, hugeSet.size());
+
+ Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
+ .allOf(HugeEnumWithInnerClass.class);
+ result = hugeSet.retainAll(hugeSetWithInnerClass);
+ assertFalse(result);
+ assertEquals(0, hugeSet.size());
+
+ hugeSetWithInnerClass = EnumSet.noneOf(HugeEnumWithInnerClass.class);
+ result = hugeSet.retainAll(hugeSetWithInnerClass);
+ assertFalse(result);
+
+ Set<HugeEnumWithInnerClass> hugeSetWithAllInnerClass = EnumSet
+ .allOf(HugeEnumWithInnerClass.class);
+ result = hugeSet.retainAll(hugeSetWithAllInnerClass);
+ assertFalse(result);
+
+ hugeSet.add(HugeEnum.a);
+ result = hugeSet.retainAll(hugeSetWithInnerClass);
+ assertTrue(result);
+ assertEquals(0, hugeSet.size());
+
+ hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
+ Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
+ .noneOf(HugeEnumWithInnerClass.class);
+ anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.e);
+ anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.f);
+
+ result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
+ assertTrue(result);
+ result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.e);
+ assertTrue("Should contain HugeEnumWithInnerClass.e", result);
+ result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.b);
+ assertFalse("Should not contain HugeEnumWithInnerClass.b", result);
+ assertEquals("Size of hugeSet should be 1:", 1, hugeSetWithInnerClass.size());
+
+ anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
+ result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
+
+ assertFalse("Return value should be false", result);
+
+ rawCollection = new ArrayList();
+ rawCollection.add(HugeEnumWithInnerClass.e);
+ rawCollection.add(HugeEnumWithInnerClass.f);
+ result = hugeSetWithInnerClass.retainAll(rawCollection);
+ assertFalse(result);
+
+ hugeSet = EnumSet.allOf(HugeEnum.class);
+ hugeSet.remove(HugeEnum.a);
+ anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
+ anotherHugeSet.add(HugeEnum.a);
+ result = hugeSet.retainAll(anotherHugeSet);
+ assertTrue(result);
+ assertEquals(0, hugeSet.size());
+ }
+
+ /**
+ * java.util.EnumSet#iterator()
+ */
+ public void test_iterator() {
+ Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.a);
+ set.add(EnumFoo.b);
+
+ Iterator<EnumFoo> iterator = set.iterator();
+ Iterator<EnumFoo> anotherIterator = set.iterator();
+ assertNotSame("Should not be same", iterator, anotherIterator);
+ try {
+ iterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expectedd
+ }
+
+ assertTrue("Should has next element:", iterator.hasNext());
+ assertSame("Should be identical", EnumFoo.a, iterator.next());
+ iterator.remove();
+ assertTrue("Should has next element:", iterator.hasNext());
+ assertSame("Should be identical", EnumFoo.b, iterator.next());
+ assertFalse("Should not has next element:", iterator.hasNext());
+ assertFalse("Should not has next element:", iterator.hasNext());
+
+ assertEquals("Size should be 1:", 1, set.size());
+
+ try {
+ iterator.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ set = EnumSet.noneOf(EnumFoo.class);
+ set.add(EnumFoo.a);
+ iterator = set.iterator();
+ assertEquals("Should be equal", EnumFoo.a, iterator.next());
+ iterator.remove();
+ try {
+ iterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch(IllegalStateException e) {
+ // expected
+ }
+
+ Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
+ Iterator<EmptyEnum> emptyIterator = emptySet.iterator();
+ try {
+ emptyIterator.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ Set<EnumWithInnerClass> setWithSubclass = EnumSet
+ .allOf(EnumWithInnerClass.class);
+ setWithSubclass.remove(EnumWithInnerClass.e);
+ Iterator<EnumWithInnerClass> iteratorWithSubclass = setWithSubclass
+ .iterator();
+ assertSame("Should be same", EnumWithInnerClass.a, iteratorWithSubclass.next());
+
+ assertTrue("Should return true", iteratorWithSubclass.hasNext());
+ assertSame("Should be same", EnumWithInnerClass.b, iteratorWithSubclass.next());
+
+ setWithSubclass.remove(EnumWithInnerClass.c);
+ assertTrue("Should return true", iteratorWithSubclass.hasNext());
+ assertSame("Should be same", EnumWithInnerClass.c, iteratorWithSubclass.next());
+
+ assertTrue("Should return true", iteratorWithSubclass.hasNext());
+ assertSame("Should be same", EnumWithInnerClass.d, iteratorWithSubclass.next());
+
+ setWithSubclass.add(EnumWithInnerClass.e);
+ assertTrue("Should return true", iteratorWithSubclass.hasNext());
+ assertSame("Should be same", EnumWithInnerClass.f, iteratorWithSubclass.next());
+
+ set = EnumSet.noneOf(EnumFoo.class);
+ iterator = set.iterator();
+ try {
+ iterator.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ set.add(EnumFoo.a);
+ iterator = set.iterator();
+ assertEquals("Should return EnumFoo.a", EnumFoo.a, iterator.next());
+ assertEquals("Size of set should be 1", 1, set.size());
+ iterator.remove();
+ assertEquals("Size of set should be 0", 0, set.size());
+ assertFalse("Should return false", set.contains(EnumFoo.a));
+
+ set.add(EnumFoo.a);
+ set.add(EnumFoo.b);
+ iterator = set.iterator();
+ assertEquals("Should be equals", EnumFoo.a, iterator.next());
+ iterator.remove();
+ try {
+ iterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch(IllegalStateException e) {
+ // expected
+ }
+
+ assertTrue("Should have next element", iterator.hasNext());
+ try {
+ iterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ assertEquals("Size of set should be 1", 1, set.size());
+ assertTrue("Should have next element", iterator.hasNext());
+ assertEquals("Should return EnumFoo.b", EnumFoo.b, iterator.next());
+ set.remove(EnumFoo.b);
+ assertEquals("Size of set should be 0", 0, set.size());
+ iterator.remove();
+ assertFalse("Should return false", set.contains(EnumFoo.a));
+
+ // RI's bug, EnumFoo.b should not exist at the moment.
+ if (!disableRIBugs) {
+ assertFalse("Should return false", set.contains(EnumFoo.b));
+ }
+
+ // test enum type with more than 64 elements
+ Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
+ hugeSet.add(HugeEnum.a);
+ hugeSet.add(HugeEnum.b);
+
+ Iterator<HugeEnum> hIterator = hugeSet.iterator();
+ Iterator<HugeEnum> anotherHugeIterator = hugeSet.iterator();
+ assertNotSame(hIterator, anotherHugeIterator);
+ try {
+ hIterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expectedd
+ }
+
+ assertTrue(hIterator.hasNext());
+ assertSame(HugeEnum.a, hIterator.next());
+ hIterator.remove();
+ assertTrue(hIterator.hasNext());
+ assertSame(HugeEnum.b, hIterator.next());
+ assertFalse(hIterator.hasNext());
+ assertFalse(hIterator.hasNext());
+
+ assertEquals(1, hugeSet.size());
+
+ try {
+ hIterator.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
+ .allOf(HugeEnumWithInnerClass.class);
+ hugeSetWithSubclass.remove(HugeEnumWithInnerClass.e);
+ Iterator<HugeEnumWithInnerClass> hugeIteratorWithSubclass = hugeSetWithSubclass
+ .iterator();
+ assertSame(HugeEnumWithInnerClass.a, hugeIteratorWithSubclass.next());
+
+ assertTrue(hugeIteratorWithSubclass.hasNext());
+ assertSame(HugeEnumWithInnerClass.b, hugeIteratorWithSubclass.next());
+
+ setWithSubclass.remove(HugeEnumWithInnerClass.c);
+ assertTrue(hugeIteratorWithSubclass.hasNext());
+ assertSame(HugeEnumWithInnerClass.c, hugeIteratorWithSubclass.next());
+
+ assertTrue(hugeIteratorWithSubclass.hasNext());
+ assertSame(HugeEnumWithInnerClass.d, hugeIteratorWithSubclass.next());
+
+ hugeSetWithSubclass.add(HugeEnumWithInnerClass.e);
+ assertTrue(hugeIteratorWithSubclass.hasNext());
+ assertSame(HugeEnumWithInnerClass.f, hugeIteratorWithSubclass.next());
+
+ hugeSet = EnumSet.noneOf(HugeEnum.class);
+ hIterator = hugeSet.iterator();
+ try {
+ hIterator.next();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ hugeSet.add(HugeEnum.a);
+ hIterator = hugeSet.iterator();
+ assertEquals(HugeEnum.a, hIterator.next());
+ assertEquals(1, hugeSet.size());
+ hIterator.remove();
+ assertEquals(0, hugeSet.size());
+ assertFalse(hugeSet.contains(HugeEnum.a));
+
+ hugeSet.add(HugeEnum.a);
+ hugeSet.add(HugeEnum.b);
+ hIterator = hugeSet.iterator();
+ hIterator.next();
+ hIterator.remove();
+
+ assertTrue(hIterator.hasNext());
+ try {
+ hIterator.remove();
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ assertEquals(1, hugeSet.size());
+ assertTrue(hIterator.hasNext());
+ assertEquals(HugeEnum.b, hIterator.next());
+ hugeSet.remove(HugeEnum.b);
+ assertEquals(0, hugeSet.size());
+ hIterator.remove();
+ assertFalse(hugeSet.contains(HugeEnum.a));
+ // RI's bug, EnumFoo.b should not exist at the moment.
+ if(!disableRIBugs) {
+ assertFalse("Should return false", set.contains(EnumFoo.b));
+ }
+ }
+
+ /**
+ * java.util.EnumSet#of(E)
+ */
+ public void test_Of_E() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a);
+ assertEquals("enumSet should have length 1:", 1, enumSet.size());
+
+ assertTrue("enumSet should contain EnumWithSubclass.a:",
+ enumSet.contains(EnumWithInnerClass.a));
+
+ try {
+ EnumSet.of((EnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a);
+ assertEquals(1, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ }
+
+ /**
+ * java.util.EnumSet#of(E, E)
+ */
+ public void test_Of_EE() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
+ EnumWithInnerClass.b);
+ assertEquals("enumSet should have length 2:", 2, enumSet.size());
+
+ assertTrue("enumSet should contain EnumWithSubclass.a:",
+ enumSet.contains(EnumWithInnerClass.a));
+ assertTrue("enumSet should contain EnumWithSubclass.b:",
+ enumSet.contains(EnumWithInnerClass.b));
+
+ try {
+ EnumSet.of((EnumWithInnerClass) null, EnumWithInnerClass.a);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ EnumSet.of( EnumWithInnerClass.a, (EnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ EnumSet.of( (EnumWithInnerClass) null, (EnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.a);
+ assertEquals("Size of enumSet should be 1",
+ 1, enumSet.size());
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
+ HugeEnumWithInnerClass.b);
+ assertEquals(2, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.b));
+
+ try {
+ EnumSet.of((HugeEnumWithInnerClass) null, HugeEnumWithInnerClass.a);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ EnumSet.of( HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ EnumSet.of( (HugeEnumWithInnerClass) null, (HugeEnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
+ assertEquals(1, hugeEnumSet.size());
+ }
+
+ /**
+ * java.util.EnumSet#of(E, E, E)
+ */
+ public void test_Of_EEE() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
+ EnumWithInnerClass.b, EnumWithInnerClass.c);
+ assertEquals("Size of enumSet should be 3:", 3, enumSet.size());
+
+ assertTrue(
+ "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a));
+ assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c));
+
+ try {
+ EnumSet.of((EnumWithInnerClass) null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.b,
+ EnumWithInnerClass.b);
+ assertEquals("enumSet should contain 2 elements:", 2, enumSet.size());
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
+ HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c);
+ assertEquals(3, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
+
+ try {
+ EnumSet.of((HugeEnumWithInnerClass) null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.b,
+ HugeEnumWithInnerClass.b);
+ assertEquals(2, hugeEnumSet.size());
+ }
+
+ /**
+ * java.util.EnumSet#of(E, E, E, E)
+ */
+ public void test_Of_EEEE() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
+ EnumWithInnerClass.b, EnumWithInnerClass.c,
+ EnumWithInnerClass.d);
+ assertEquals("Size of enumSet should be 4", 4, enumSet.size());
+
+ assertTrue(
+ "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a));
+ assertTrue("enumSet should contain EnumWithSubclass.d:", enumSet
+ .contains(EnumWithInnerClass.d));
+
+ try {
+ EnumSet.of((EnumWithInnerClass) null, null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
+ HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
+ HugeEnumWithInnerClass.d);
+ assertEquals(4, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.d));
+
+ try {
+ EnumSet.of((HugeEnumWithInnerClass) null, null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.EnumSet#of(E, E, E, E, E)
+ */
+ public void test_Of_EEEEE() {
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
+ EnumWithInnerClass.b, EnumWithInnerClass.c,
+ EnumWithInnerClass.d, EnumWithInnerClass.e);
+ assertEquals("Size of enumSet should be 5:", 5, enumSet.size());
+
+ assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a));
+ assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.e));
+
+ try {
+ EnumSet.of((EnumWithInnerClass) null, null, null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // test enum with more than 64 elements
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
+ HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
+ HugeEnumWithInnerClass.d, HugeEnumWithInnerClass.e);
+ assertEquals(5, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.e));
+
+ try {
+ EnumSet.of((HugeEnumWithInnerClass) null, null, null, null, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.EnumSet#of(E, E...)
+ */
+ public void test_Of_EEArray() {
+ EnumWithInnerClass[] enumArray = new EnumWithInnerClass[] {
+ EnumWithInnerClass.b, EnumWithInnerClass.c };
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
+ enumArray);
+ assertEquals("Should be equal", 3, enumSet.size());
+
+ assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a));
+ assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c));
+
+ try {
+ EnumSet.of(EnumWithInnerClass.a, (EnumWithInnerClass[])null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ EnumFoo[] foos = {EnumFoo.a, EnumFoo.c, EnumFoo.d};
+ EnumSet<EnumFoo> set = EnumSet.of(EnumFoo.c, foos);
+ assertEquals("size of set should be 1", 3, set.size());
+ assertTrue("Should contain EnumFoo.a", set.contains(EnumFoo.a));
+ assertTrue("Should contain EnumFoo.c", set.contains(EnumFoo.c));
+ assertTrue("Should contain EnumFoo.d", set.contains(EnumFoo.d));
+
+ // test enum type with more than 64 elements
+ HugeEnumWithInnerClass[] hugeEnumArray = new HugeEnumWithInnerClass[] {
+ HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c };
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
+ hugeEnumArray);
+ assertEquals(3, hugeEnumSet.size());
+
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
+
+ try {
+ EnumSet.of(HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass[])null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ HugeEnumWithInnerClass[] huges = {HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.d};
+ EnumSet<HugeEnumWithInnerClass> hugeSet = EnumSet.of(HugeEnumWithInnerClass.c, huges);
+ assertEquals(3, hugeSet.size());
+ assertTrue(hugeSet.contains(HugeEnumWithInnerClass.a));
+ assertTrue(hugeSet.contains(HugeEnumWithInnerClass.c));
+ assertTrue(hugeSet.contains(HugeEnumWithInnerClass.d));
+ }
+
+ /**
+ * java.util.EnumSet#range(E, E)
+ */
+ public void test_Range_EE() {
+ try {
+ EnumSet.range(EnumWithInnerClass.c, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(null, EnumWithInnerClass.c);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(null, (EnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(EnumWithInnerClass.b, EnumWithInnerClass.a);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ EnumSet<EnumWithInnerClass> enumSet = EnumSet.range(
+ EnumWithInnerClass.a, EnumWithInnerClass.a);
+ assertEquals("Size of enumSet should be 1", 1, enumSet.size());
+
+ enumSet = EnumSet.range(
+ EnumWithInnerClass.a, EnumWithInnerClass.c);
+ assertEquals("Size of enumSet should be 3", 3, enumSet.size());
+
+ // test enum with more than 64 elements
+ try {
+ EnumSet.range(HugeEnumWithInnerClass.c, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(null, HugeEnumWithInnerClass.c);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(null, (HugeEnumWithInnerClass) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ EnumSet.range(HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.a);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.range(
+ HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
+ assertEquals(1, hugeEnumSet.size());
+
+ hugeEnumSet = EnumSet.range(
+ HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.aa);
+ assertEquals(51, hugeEnumSet.size());
+
+ hugeEnumSet = EnumSet.range(
+ HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.mm);
+ assertEquals(65, hugeEnumSet.size());
+
+ hugeEnumSet = EnumSet.range(
+ HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.mm);
+ assertEquals(64, hugeEnumSet.size());
+ }
+
+ /**
+ * java.util.EnumSet#clone()
+ */
+ public void test_Clone() {
+ EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
+ EnumSet<EnumFoo> clonedEnumSet = enumSet.clone();
+ assertEquals(enumSet, clonedEnumSet);
+ assertNotSame(enumSet, clonedEnumSet);
+ assertTrue(clonedEnumSet.contains(EnumFoo.a));
+ assertTrue(clonedEnumSet.contains(EnumFoo.b));
+ assertEquals(64, clonedEnumSet.size());
+
+ // test enum type with more than 64 elements
+ EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
+ EnumSet<HugeEnum> hugeClonedEnumSet = hugeEnumSet.clone();
+ assertEquals(hugeEnumSet, hugeClonedEnumSet);
+ assertNotSame(hugeEnumSet, hugeClonedEnumSet);
+ assertTrue(hugeClonedEnumSet.contains(HugeEnum.a));
+ assertTrue(hugeClonedEnumSet.contains(HugeEnum.b));
+ assertEquals(65, hugeClonedEnumSet.size());
+
+ hugeClonedEnumSet.remove(HugeEnum.a);
+ assertEquals(64, hugeClonedEnumSet.size());
+ assertFalse(hugeClonedEnumSet.contains(HugeEnum.a));
+ assertEquals(65, hugeEnumSet.size());
+ assertTrue(hugeEnumSet.contains(HugeEnum.a));
+ }
+
+ /**
+ * java.util.EnumSet#Serialization()
+ */
+ public void test_serialization() throws Exception {
+ EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
+ SerializationTest.verifySelf(set);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings( { "unchecked", "boxing" })
+ public void testSerializationCompatibility() throws Exception {
+ EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
+ SerializationTest.verifyGolden(this, set);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EventObjectTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EventObjectTest.java
new file mode 100644
index 0000000..bea2a44
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/EventObjectTest.java
@@ -0,0 +1,70 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.EventObject;
+
+public class EventObjectTest extends junit.framework.TestCase {
+
+ Object myObject;
+
+ EventObject myEventObject;
+
+ /**
+ * java.util.EventObject#EventObject(java.lang.Object)
+ */
+ public void test_ConstructorLjava_lang_Object() {
+ // Test for method java.util.EventObject(java.lang.Object)
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.util.EventObject#getSource()
+ */
+ public void test_getSource() {
+ // Test for method java.lang.Object java.util.EventObject.getSource()
+ assertTrue("Wrong source returned",
+ myEventObject.getSource() == myObject);
+ }
+
+ /**
+ * java.util.EventObject#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.util.EventObject.toString()
+ assertTrue("Incorrect toString returned: " + myEventObject.toString(),
+ myEventObject.toString().indexOf(
+ "java.util.EventObject[source=java.lang.Object@") == 0);
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ myObject = new Object();
+ myEventObject = new EventObject(myObject);
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java
new file mode 100644
index 0000000..bc9c480
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java
@@ -0,0 +1,115 @@
+/* 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.tests.java.util;
+
+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;
+
+public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
+
+ /**
+ * java.util.FormatFlagsConversionMismatchException#FormatFlagsConversionMismatchException(String,
+ *char)
+ */
+ public void test_formatFlagsConversionMismatchException() {
+ try {
+ new FormatFlagsConversionMismatchException(null, ' ');
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.util.FormatFlagsConversionMismatchException#getFlags()
+ */
+ public void test_getFlags() {
+ String flags = "MYTESTFLAGS";
+ char conversion = 'T';
+ FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
+ flags, conversion);
+ assertEquals(flags, formatFlagsConversionMismatchException.getFlags());
+ }
+
+ /**
+ * java.util.FormatFlagsConversionMismatchException#getConversion()
+ */
+ public void test_getConversion() {
+ String flags = "MYTESTFLAGS";
+ char conversion = 'T';
+ FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
+ flags, conversion);
+ assertEquals(conversion, formatFlagsConversionMismatchException
+ .getConversion());
+
+ }
+
+ /**
+ * java.util.FormatFlagsConversionMismatchException#getMessage()
+ */
+ public void test_getMessage() {
+ String flags = "MYTESTFLAGS";
+ char conversion = 'T';
+ FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
+ flags, conversion);
+ assertTrue(null != formatFlagsConversionMismatchException.getMessage());
+
+ }
+
+ // comparator for FormatFlagsConversionMismatchException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ FormatFlagsConversionMismatchException initEx = (FormatFlagsConversionMismatchException) initial;
+ FormatFlagsConversionMismatchException desrEx = (FormatFlagsConversionMismatchException) deserialized;
+
+ assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
+ assertEquals("Conversion", initEx.getConversion(), desrEx
+ .getConversion());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(
+ new FormatFlagsConversionMismatchException("MYTESTFLAGS", 'T'),
+ exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new FormatFlagsConversionMismatchException("MYTESTFLAGS", 'T'),
+ exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormattableFlagsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormattableFlagsTest.java
new file mode 100644
index 0000000..dc51e86
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormattableFlagsTest.java
@@ -0,0 +1,27 @@
+/* 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.tests.java.util;
+
+import java.util.FormattableFlags;
+import junit.framework.TestCase;
+
+public class FormattableFlagsTest extends TestCase {
+ public void test_ConstantFieldValues() {
+ assertEquals(1, FormattableFlags.LEFT_JUSTIFY);
+ assertEquals(2, FormattableFlags.UPPERCASE);
+ assertEquals(4, FormattableFlags.ALTERNATE);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterClosedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterClosedExceptionTest.java
new file mode 100644
index 0000000..e89576a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterClosedExceptionTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.util;
+
+import java.util.FormatterClosedException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class FormatterClosedExceptionTest extends TestCase {
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new FormatterClosedException());
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new FormatterClosedException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterTest.java
new file mode 100644
index 0000000..c0e814e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/FormatterTest.java
@@ -0,0 +1,4244 @@
+/* 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.tests.java.util;
+
+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;
+
+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 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;
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ 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());
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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");
+ try {
+ 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());
+ } finally {
+ 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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$
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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 {
+ f.format("%(o", false);
+ fail();
+ } catch (FormatFlagsConversionMismatchException expected) {
+ } catch (IllegalFormatConversionException expected) {
+ }
+
+ try {
+ f.format("%.4o", false);
+ fail();
+ } catch (IllegalFormatPrecisionException expected) {
+ } catch (IllegalFormatConversionException expected) {
+ }
+
+ try {
+ f.format("%+ .4o", big);
+ fail();
+ } catch (IllegalFormatPrecisionException expected) {
+ } catch (IllegalFormatFlagsException expected) {
+ }
+
+ try {
+ f.format("%+ -o", big);
+ fail();
+ } catch (MissingFormatWidthException expected) {
+ } catch (IllegalFormatFlagsException expected) {
+ }
+
+ try {
+ f.format("%-O", big);
+ fail();
+ } catch (MissingFormatWidthException expected) {
+ } catch (UnknownFormatConversionException expected) {
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.Formatter.BigDecimalLayoutForm#values()
+ */
+ 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]);
+ }
+
+ /**
+ * java.util.Formatter.BigDecimalLayoutForm#valueOf(String)
+ */
+ 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);
+
+ 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/GregorianCalendarTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/GregorianCalendarTest.java
new file mode 100644
index 0000000..f35be4b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/GregorianCalendarTest.java
@@ -0,0 +1,753 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.BitSet;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+import java.util.Vector;
+
+public class GregorianCalendarTest extends junit.framework.TestCase {
+
+ private static final TimeZone AMERICA_CHICAGO = TimeZone.getTimeZone("America/Chicago");
+ private static final TimeZone AMERICA_NEW_YORK = TimeZone.getTimeZone("America/New_York");
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.GregorianCalendar()
+ assertTrue("Constructed incorrect calendar", (new GregorianCalendar()
+ .isLenient()));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(int, int, int)
+ */
+ public void test_ConstructorIII() {
+ // Test for method java.util.GregorianCalendar(int, int, int)
+ GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER, 13);
+ assertEquals("Incorrect calendar constructed 1",
+ 1972, gc.get(Calendar.YEAR));
+ assertTrue("Incorrect calendar constructed 2",
+ gc.get(Calendar.MONTH) == Calendar.OCTOBER);
+ assertEquals("Incorrect calendar constructed 3", 13, gc
+ .get(Calendar.DAY_OF_MONTH));
+ assertTrue("Incorrect calendar constructed 4", gc.getTimeZone().equals(
+ TimeZone.getDefault()));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(int, int, int, int,
+ *int)
+ */
+ public void test_ConstructorIIIII() {
+ // Test for method java.util.GregorianCalendar(int, int, int, int, int)
+ GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
+ 13, 19, 9);
+ assertEquals("Incorrect calendar constructed",
+ 1972, gc.get(Calendar.YEAR));
+ assertTrue("Incorrect calendar constructed",
+ gc.get(Calendar.MONTH) == Calendar.OCTOBER);
+ assertEquals("Incorrect calendar constructed", 13, gc
+ .get(Calendar.DAY_OF_MONTH));
+ assertEquals("Incorrect calendar constructed", 7, gc.get(Calendar.HOUR));
+ assertEquals("Incorrect calendar constructed",
+ 1, gc.get(Calendar.AM_PM));
+ assertEquals("Incorrect calendar constructed",
+ 9, gc.get(Calendar.MINUTE));
+ assertTrue("Incorrect calendar constructed", gc.getTimeZone().equals(
+ TimeZone.getDefault()));
+
+ //Regression for HARMONY-998
+ gc = new GregorianCalendar(1900, 0, 0, 0, Integer.MAX_VALUE);
+ assertEquals("Incorrect calendar constructed",
+ 5983, gc.get(Calendar.YEAR));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(int, int, int, int,
+ *int, int)
+ */
+ public void test_ConstructorIIIIII() {
+ // Test for method java.util.GregorianCalendar(int, int, int, int, int,
+ // int)
+ GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
+ 13, 19, 9, 59);
+ assertEquals("Incorrect calendar constructed",
+ 1972, gc.get(Calendar.YEAR));
+ assertTrue("Incorrect calendar constructed",
+ gc.get(Calendar.MONTH) == Calendar.OCTOBER);
+ assertEquals("Incorrect calendar constructed", 13, gc
+ .get(Calendar.DAY_OF_MONTH));
+ assertEquals("Incorrect calendar constructed", 7, gc.get(Calendar.HOUR));
+ assertEquals("Incorrect calendar constructed",
+ 1, gc.get(Calendar.AM_PM));
+ assertEquals("Incorrect calendar constructed",
+ 9, gc.get(Calendar.MINUTE));
+ assertEquals("Incorrect calendar constructed",
+ 59, gc.get(Calendar.SECOND));
+ assertTrue("Incorrect calendar constructed", gc.getTimeZone().equals(
+ TimeZone.getDefault()));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(java.util.Locale)
+ */
+ public void test_ConstructorLjava_util_Locale() {
+ // Test for method java.util.GregorianCalendar(java.util.Locale)
+ Date date = new Date();
+ GregorianCalendar gcJapan = new GregorianCalendar(Locale.JAPAN);
+ gcJapan.setTime(date);
+ GregorianCalendar gcJapan2 = new GregorianCalendar(Locale.JAPAN);
+ gcJapan2.setTime(date);
+ GregorianCalendar gcItaly = new GregorianCalendar(Locale.ITALY);
+ gcItaly.setTime(date);
+ assertTrue("Locales not created correctly", gcJapan.equals(gcJapan2)
+ && !gcJapan.equals(gcItaly));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(java.util.TimeZone)
+ */
+ public void test_ConstructorLjava_util_TimeZone() {
+ // Test for method java.util.GregorianCalendar(java.util.TimeZone)
+ Date date = new Date(2008, 1, 1);
+ TimeZone.getDefault();
+ GregorianCalendar gc1 = new GregorianCalendar(AMERICA_NEW_YORK);
+ gc1.setTime(date);
+ GregorianCalendar gc2 = new GregorianCalendar(AMERICA_CHICAGO);
+ gc2.setTime(date);
+ // Chicago is 1 hour before New York, add 1 to the Chicago time and convert to 0-12 value
+ assertEquals("Incorrect calendar returned",
+ gc1.get(Calendar.HOUR), ((gc2.get(Calendar.HOUR) + 1) % 12));
+
+ // Regression test for HARMONY-2961
+ SimpleTimeZone timezone = new SimpleTimeZone(-3600 * 24 * 1000 * 2,
+ "GMT");
+ GregorianCalendar gc = new GregorianCalendar(timezone);
+
+ // Regression test for HARMONY-5195
+ Calendar c1 = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+ c1.set(Calendar.YEAR, 1999);
+ c1.set(Calendar.MONTH, Calendar.JUNE);
+ c1.set(Calendar.DAY_OF_MONTH, 2);
+ c1.set(Calendar.HOUR, 15);
+ c1.set(Calendar.MINUTE, 34);
+ c1.set(Calendar.SECOND, 16);
+ assertEquals(34, c1.get(Calendar.MINUTE));
+ c1.setTimeZone(new SimpleTimeZone(60000, "ONE MINUTE"));
+ assertEquals(35, c1.get(Calendar.MINUTE));
+ }
+
+ /**
+ * java.util.GregorianCalendar#GregorianCalendar(java.util.TimeZone,
+ *java.util.Locale)
+ */
+ public void test_ConstructorLjava_util_TimeZoneLjava_util_Locale() {
+ // Test for method java.util.GregorianCalendar(java.util.TimeZone,
+ // java.util.Locale)
+ Date date = new Date(2008, 1, 1);
+ TimeZone.getDefault();
+ GregorianCalendar gc1 = new GregorianCalendar(AMERICA_NEW_YORK, Locale.JAPAN);
+ gc1.setTime(date);
+ GregorianCalendar gc2 = new GregorianCalendar(AMERICA_NEW_YORK, Locale.JAPAN);
+ gc2.setTime(date);
+ GregorianCalendar gc3 = new GregorianCalendar(AMERICA_CHICAGO, Locale.ITALY);
+ gc3.setTime(date);
+ // Chicago is 1 hour before New York, add 1 to the Chicago time and convert to 0-12 value
+ assertEquals("Incorrect calendar returned",
+ gc1.get(Calendar.HOUR), ((gc3.get(Calendar.HOUR) + 1) % 12));
+ assertTrue("Locales not created correctly", gc1.equals(gc2)
+ && !gc1.equals(gc3));
+ }
+
+ /**
+ * java.util.GregorianCalendar#add(int, int)
+ */
+ public void test_addII() {
+ // Test for method void java.util.GregorianCalendar.add(int, int)
+ GregorianCalendar gc1 = new GregorianCalendar(1998, 11, 6);
+ gc1.add(GregorianCalendar.YEAR, 1);
+ assertEquals("Add failed to Increment",
+ 1999, gc1.get(GregorianCalendar.YEAR));
+
+ gc1 = new GregorianCalendar(1999, Calendar.JULY, 31);
+ gc1.add(Calendar.MONTH, 7);
+ assertEquals("Wrong result year 1", 2000, gc1.get(Calendar.YEAR));
+ assertTrue("Wrong result month 1",
+ gc1.get(Calendar.MONTH) == Calendar.FEBRUARY);
+ assertEquals("Wrong result date 1", 29, gc1.get(Calendar.DATE));
+
+ gc1.add(Calendar.YEAR, -1);
+ assertEquals("Wrong result year 2", 1999, gc1.get(Calendar.YEAR));
+ assertTrue("Wrong result month 2",
+ gc1.get(Calendar.MONTH) == Calendar.FEBRUARY);
+ assertEquals("Wrong result date 2", 28, gc1.get(Calendar.DATE));
+
+ gc1 = new GregorianCalendar(AMERICA_NEW_YORK);
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.MILLISECOND, 24 * 60 * 60 * 1000);
+ assertEquals("Wrong time after MILLISECOND change", 17, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.SECOND, 24 * 60 * 60);
+ assertEquals("Wrong time after SECOND change", 17, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.MINUTE, 24 * 60);
+ assertEquals("Wrong time after MINUTE change", 17, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.HOUR, 24);
+ assertEquals("Wrong time after HOUR change", 17, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.HOUR_OF_DAY, 24);
+ assertEquals("Wrong time after HOUR_OF_DAY change", 17, gc1
+ .get(Calendar.HOUR_OF_DAY));
+
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.AM_PM, 2);
+ assertEquals("Wrong time after AM_PM change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.DATE, 1);
+ assertEquals("Wrong time after DATE change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.DAY_OF_YEAR, 1);
+ assertEquals("Wrong time after DAY_OF_YEAR change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.DAY_OF_WEEK, 1);
+ assertEquals("Wrong time after DAY_OF_WEEK change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.WEEK_OF_YEAR, 1);
+ assertEquals("Wrong time after WEEK_OF_YEAR change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.WEEK_OF_MONTH, 1);
+ assertEquals("Wrong time after WEEK_OF_MONTH change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+ gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
+ gc1.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
+ assertEquals("Wrong time after DAY_OF_WEEK_IN_MONTH change", 16, gc1
+ .get(Calendar.HOUR_OF_DAY));
+
+ gc1.clear();
+ gc1.set(2000, Calendar.APRIL, 1, 23, 0);
+ gc1.add(Calendar.DATE, 1);
+ assertTrue("Wrong time after DATE change near DST boundary", gc1
+ .get(Calendar.MONTH) == Calendar.APRIL
+ && gc1.get(Calendar.DATE) == 2
+ && gc1.get(Calendar.HOUR_OF_DAY) == 23);
+ }
+
+ /**
+ * java.util.GregorianCalendar#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.GregorianCalendar.equals(java.lang.Object)
+ GregorianCalendar gc1 = new GregorianCalendar(1998, 11, 6);
+ GregorianCalendar gc2 = new GregorianCalendar(2000, 11, 6);
+ GregorianCalendar gc3 = new GregorianCalendar(1998, 11, 6);
+ assertTrue("Equality check failed", gc1.equals(gc3));
+ assertTrue("Equality check failed", !gc1.equals(gc2));
+ gc3.setGregorianChange(new Date());
+ assertTrue("Different gregorian change", !gc1.equals(gc3));
+ }
+
+ /**
+ * java.util.GregorianCalendar#getActualMaximum(int)
+ */
+ public void test_getActualMaximumI() {
+ // Test for method int java.util.GregorianCalendar.getActualMaximum(int)
+ GregorianCalendar gc1 = new GregorianCalendar(1900, 1, 1);
+ GregorianCalendar gc2 = new GregorianCalendar(1996, 1, 1);
+ GregorianCalendar gc3 = new GregorianCalendar(1997, 1, 1);
+ GregorianCalendar gc4 = new GregorianCalendar(2000, 1, 1);
+ GregorianCalendar gc5 = new GregorianCalendar(2000, 9, 9);
+ GregorianCalendar gc6 = new GregorianCalendar(2000, 3, 3);
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1900",
+ 28, gc1.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1996",
+ 29, gc2.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1998",
+ 28, gc3.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 2000",
+ 29, gc4.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Oct 2000",
+ 31, gc5.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Apr 2000",
+ 30, gc6.getActualMaximum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong actual maximum value for MONTH", gc1
+ .getActualMaximum(Calendar.MONTH) == Calendar.DECEMBER);
+ assertEquals("Wrong actual maximum value for HOUR_OF_DAY", 23, gc1
+ .getActualMaximum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong actual maximum value for HOUR", 11, gc1
+ .getActualMaximum(Calendar.HOUR));
+ assertEquals("Wrong actual maximum value for DAY_OF_WEEK_IN_MONTH", 4, gc6
+ .getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH));
+
+
+ // Regression test for harmony 2954
+ Date date = new Date(Date.parse("Jan 15 00:00:01 GMT 2000"));
+ GregorianCalendar gc = new GregorianCalendar();
+ gc.setTimeInMillis(Date.parse("Dec 15 00:00:01 GMT 1582"));
+ assertEquals(355, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
+ gc.setGregorianChange(date);
+ gc.setTimeInMillis(Date.parse("Jan 16 00:00:01 GMT 2000"));
+ assertEquals(353, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
+
+ //Regression test for HARMONY-3004
+ gc = new GregorianCalendar(1900, 7, 1);
+ String[] ids = TimeZone.getAvailableIDs();
+ for (int i = 0; i < ids.length; i++) {
+ TimeZone tz = TimeZone.getTimeZone(ids[i]);
+ gc.setTimeZone(tz);
+ for (int j = 1900; j < 2000; j++) {
+ gc.set(Calendar.YEAR, j);
+ assertEquals(7200000, gc.getActualMaximum(Calendar.DST_OFFSET));
+ }
+ }
+ }
+
+ /**
+ * java.util.GregorianCalendar#getActualMinimum(int)
+ */
+ public void test_getActualMinimumI() {
+ // Test for method int java.util.GregorianCalendar.getActualMinimum(int)
+ GregorianCalendar gc1 = new GregorianCalendar(1900, 1, 1);
+ new GregorianCalendar(1996, 1, 1);
+ new GregorianCalendar(1997, 1, 1);
+ new GregorianCalendar(2000, 1, 1);
+ new GregorianCalendar(2000, 9, 9);
+ GregorianCalendar gc6 = new GregorianCalendar(2000, 3, 3);
+ assertEquals("Wrong actual minimum value for DAY_OF_MONTH for Feb 1900",
+ 1, gc1.getActualMinimum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong actual minimum value for MONTH", gc1
+ .getActualMinimum(Calendar.MONTH) == Calendar.JANUARY);
+ assertEquals("Wrong actual minimum value for HOUR_OF_DAY", 0, gc1
+ .getActualMinimum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong actual minimum value for HOUR", 0, gc1
+ .getActualMinimum(Calendar.HOUR));
+ assertEquals("Wrong actual minimum value for DAY_OF_WEEK_IN_MONTH", 1, gc6
+ .getActualMinimum(Calendar.DAY_OF_WEEK_IN_MONTH));
+ }
+
+ /**
+ * java.util.GregorianCalendar#getGreatestMinimum(int)
+ */
+ public void test_getGreatestMinimumI() {
+ // Test for method int
+ // java.util.GregorianCalendar.getGreatestMinimum(int)
+ GregorianCalendar gc = new GregorianCalendar();
+ assertEquals("Wrong greatest minimum value for DAY_OF_MONTH", 1, gc
+ .getGreatestMinimum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong greatest minimum value for MONTH", gc
+ .getGreatestMinimum(Calendar.MONTH) == Calendar.JANUARY);
+ assertEquals("Wrong greatest minimum value for HOUR_OF_DAY", 0, gc
+ .getGreatestMinimum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong greatest minimum value for HOUR", 0, gc
+ .getGreatestMinimum(Calendar.HOUR));
+
+ BitSet result = new BitSet();
+ int[] min = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, -46800000,
+ 0 };
+ for (int i = 0; i < min.length; i++) {
+ if (gc.getGreatestMinimum(i) != min[i])
+ result.set(i);
+ }
+ assertTrue("Wrong greatest min for " + result, result.length() == 0);
+ }
+
+ /**
+ * java.util.GregorianCalendar#getGregorianChange()
+ */
+ public void test_getGregorianChange() {
+ // Test for method java.util.Date
+ // java.util.GregorianCalendar.getGregorianChange()
+ GregorianCalendar gc = new GregorianCalendar();
+ GregorianCalendar returnedChange = new GregorianCalendar(AMERICA_NEW_YORK);
+ returnedChange.setTime(gc.getGregorianChange());
+ assertEquals("Returned incorrect year",
+ 1582, returnedChange.get(Calendar.YEAR));
+ assertTrue("Returned incorrect month", returnedChange
+ .get(Calendar.MONTH) == Calendar.OCTOBER);
+ assertEquals("Returned incorrect day of month", 4, returnedChange
+ .get(Calendar.DAY_OF_MONTH));
+ }
+
+ /**
+ * java.util.GregorianCalendar#getLeastMaximum(int)
+ */
+ public void test_getLeastMaximumI() {
+ // Test for method int java.util.GregorianCalendar.getLeastMaximum(int)
+ GregorianCalendar gc = new GregorianCalendar();
+ assertEquals("Wrong least maximum value for DAY_OF_MONTH", 28, gc
+ .getLeastMaximum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong least maximum value for MONTH", gc
+ .getLeastMaximum(Calendar.MONTH) == Calendar.DECEMBER);
+ assertEquals("Wrong least maximum value for HOUR_OF_DAY", 23, gc
+ .getLeastMaximum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong least maximum value for HOUR", 11, gc
+ .getLeastMaximum(Calendar.HOUR));
+
+ BitSet result = new BitSet();
+ Vector values = new Vector();
+ int[] max = { 1, 292269054, 11, 50, 3, 28, 355, 7, 3, 1, 11, 23, 59,
+ 59, 999, 50400000, 1200000 };
+ for (int i = 0; i < max.length; i++) {
+ if (gc.getLeastMaximum(i) != max[i]) {
+ result.set(i);
+ values.add(new Integer(gc.getLeastMaximum(i)));
+ }
+ }
+ assertTrue("Wrong least max for " + result + " = " + values, result
+ .length() == 0);
+
+ // Regression test for harmony-2947
+ Date date = new Date(Date.parse("Jan 1 00:00:01 GMT 2000"));
+ gc = new GregorianCalendar();
+ gc.setGregorianChange(date);
+ gc.setTime(date);
+ assertEquals(gc.getActualMaximum(Calendar.WEEK_OF_YEAR), gc
+ .getLeastMaximum(Calendar.WEEK_OF_YEAR));
+ }
+
+ /**
+ * java.util.GregorianCalendar#getMaximum(int)
+ */
+ public void test_getMaximumI() {
+ // Test for method int java.util.GregorianCalendar.getMaximum(int)
+ GregorianCalendar gc = new GregorianCalendar();
+ assertEquals("Wrong maximum value for DAY_OF_MONTH", 31, gc
+ .getMaximum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong maximum value for MONTH", gc
+ .getMaximum(Calendar.MONTH) == Calendar.DECEMBER);
+ assertEquals("Wrong maximum value for HOUR_OF_DAY", 23, gc
+ .getMaximum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong maximum value for HOUR",
+ 11, gc.getMaximum(Calendar.HOUR));
+
+ BitSet result = new BitSet();
+ Vector values = new Vector();
+ int[] max = { 1, 292278994, 11, 53, 6, 31, 366, 7, 6, 1, 11, 23, 59,
+ 59, 999, 50400000, 7200000 };
+ for (int i = 0; i < max.length; i++) {
+ if (gc.getMaximum(i) != max[i]) {
+ result.set(i);
+ values.add(new Integer(gc.getMaximum(i)));
+ }
+ }
+ assertTrue("Wrong max for " + result + " = " + values,
+ result.length() == 0);
+ }
+
+ /**
+ * java.util.GregorianCalendar#getMinimum(int)
+ */
+ public void test_getMinimumI() {
+ // Test for method int java.util.GregorianCalendar.getMinimum(int)
+ GregorianCalendar gc = new GregorianCalendar();
+ assertEquals("Wrong minimum value for DAY_OF_MONTH", 1, gc
+ .getMinimum(Calendar.DAY_OF_MONTH));
+ assertTrue("Wrong minimum value for MONTH", gc
+ .getMinimum(Calendar.MONTH) == Calendar.JANUARY);
+ assertEquals("Wrong minimum value for HOUR_OF_DAY", 0, gc
+ .getMinimum(Calendar.HOUR_OF_DAY));
+ assertEquals("Wrong minimum value for HOUR",
+ 0, gc.getMinimum(Calendar.HOUR));
+
+ BitSet result = new BitSet();
+ int[] min = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, -46800000,
+ 0 };
+ for (int i = 0; i < min.length; i++) {
+ if (gc.getMinimum(i) != min[i])
+ result.set(i);
+ }
+ assertTrue("Wrong min for " + result, result.length() == 0);
+ }
+
+ /**
+ * java.util.GregorianCalendar#isLeapYear(int)
+ */
+ public void test_isLeapYearI() {
+ // Test for method boolean java.util.GregorianCalendar.isLeapYear(int)
+ GregorianCalendar gc = new GregorianCalendar(1998, 11, 6);
+ assertTrue("Returned incorrect value for leap year", !gc
+ .isLeapYear(1998));
+ assertTrue("Returned incorrect value for leap year", gc
+ .isLeapYear(2000));
+
+ }
+
+ /**
+ * java.util.GregorianCalendar#roll(int, int)
+ */
+ public void test_rollII() {
+ // Test for method void java.util.GregorianCalendar.roll(int, int)
+ GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8,
+ 2, 5, 0);
+ gc.roll(Calendar.DAY_OF_MONTH, -1);
+ assertTrue("Failed to roll DAY_OF_MONTH down by 1", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 7, 2, 5,
+ 0)));
+ gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8, 2, 5, 0);
+ gc.roll(Calendar.DAY_OF_MONTH, 25);
+ assertTrue("Failed to roll DAY_OF_MONTH up by 25", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 2, 2, 5,
+ 0)));
+ gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8, 2, 5, 0);
+ gc.roll(Calendar.DAY_OF_MONTH, -10);
+ assertTrue("Failed to roll DAY_OF_MONTH down by 10", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 29, 2, 5,
+ 0)));
+ }
+
+ /**
+ * java.util.GregorianCalendar#roll(int, boolean)
+ */
+ public void test_rollIZ() {
+ // Test for method void java.util.GregorianCalendar.roll(int, boolean)
+ GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
+ 13, 19, 9, 59);
+ gc.roll(Calendar.DAY_OF_MONTH, false);
+ assertTrue("Failed to roll day_of_month down", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 12, 19,
+ 9, 59)));
+ gc = new GregorianCalendar(1972, Calendar.OCTOBER, 13, 19, 9, 59);
+ gc.roll(Calendar.DAY_OF_MONTH, true);
+ assertTrue("Failed to roll day_of_month up", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 14, 19,
+ 9, 59)));
+ gc = new GregorianCalendar(1972, Calendar.OCTOBER, 31, 19, 9, 59);
+ gc.roll(Calendar.DAY_OF_MONTH, true);
+ assertTrue("Failed to roll day_of_month up", gc
+ .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 1, 19, 9,
+ 59)));
+
+ GregorianCalendar cal = new GregorianCalendar();
+ int result;
+ try {
+ cal.roll(Calendar.ZONE_OFFSET, true);
+ result = 0;
+ } catch (IllegalArgumentException e) {
+ result = 1;
+ }
+ assertEquals("ZONE_OFFSET roll", 1, result);
+ try {
+ cal.roll(Calendar.DST_OFFSET, true);
+ result = 0;
+ } catch (IllegalArgumentException e) {
+ result = 1;
+ }
+ assertEquals("ZONE_OFFSET roll", 1, result);
+
+ cal.set(2004, Calendar.DECEMBER, 31, 5, 0, 0);
+ cal.roll(Calendar.WEEK_OF_YEAR, true);
+ assertEquals("Wrong year: " + cal.getTime(), 2004, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.JANUARY, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 9, cal.get(Calendar.DATE));
+
+ // Regression for HARMONY-4372
+ cal.set(1994, 11, 30, 5, 0, 0);
+ cal.setMinimalDaysInFirstWeek(4);
+ cal.roll(Calendar.WEEK_OF_YEAR, true);
+ assertEquals("Wrong year: " + cal.getTime(), 1994, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.JANUARY, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 7, cal.get(Calendar.DATE));
+
+ cal.roll(Calendar.WEEK_OF_YEAR, true);
+ assertEquals("Wrong year: " + cal.getTime(), 1994, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.JANUARY, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 14, cal.get(Calendar.DATE));
+
+ cal.roll(Calendar.WEEK_OF_YEAR, false);
+ assertEquals("Wrong year: " + cal.getTime(), 1994, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.JANUARY, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 7, cal.get(Calendar.DATE));
+
+ cal.roll(Calendar.WEEK_OF_YEAR, false);
+ assertEquals("Wrong year: " + cal.getTime(), 1994, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.DECEMBER, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 30, cal.get(Calendar.DATE));
+
+ cal.roll(Calendar.WEEK_OF_YEAR, false);
+ assertEquals("Wrong year: " + cal.getTime(), 1994, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.DECEMBER, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 23, cal.get(Calendar.DATE));
+
+ // Regression for HARMONY-4510
+ cal.set(1999, Calendar.DECEMBER, 31, 23, 59, 59);
+ cal.roll(GregorianCalendar.WEEK_OF_YEAR, true);
+ assertEquals("Wrong year: " + cal.getTime(), 1999, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.JANUARY, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 8, cal.get(Calendar.DATE));
+ cal.roll(GregorianCalendar.WEEK_OF_YEAR, false);
+ assertEquals("Wrong year: " + cal.getTime(), 1999, cal
+ .get(Calendar.YEAR));
+ assertEquals("Wrong month: " + cal.getTime(), Calendar.DECEMBER, cal
+ .get(Calendar.MONTH));
+ assertEquals("Wrong date: " + cal.getTime(), 31, cal.get(Calendar.DATE));
+ }
+
+ /**
+ * java.util.GregorianCalendar#setGregorianChange(java.util.Date)
+ */
+ public void test_setGregorianChangeLjava_util_Date() {
+ // Test for method void
+ // java.util.GregorianCalendar.setGregorianChange(java.util.Date)
+ GregorianCalendar gc1 = new GregorianCalendar(1582, Calendar.OCTOBER,
+ 4, 0, 0);
+ GregorianCalendar gc2 = new GregorianCalendar(1972, Calendar.OCTOBER,
+ 13, 0, 0);
+ gc1.setGregorianChange(gc2.getTime());
+ assertTrue("Returned incorrect value", gc2.getTime().equals(
+ gc1.getGregorianChange()));
+ }
+
+ /**
+ * java.util.GregorianCalendar#clone()
+ */
+ public void test_clone() {
+
+ // Regression for HARMONY-498
+ GregorianCalendar gCalend = new GregorianCalendar();
+
+ gCalend.set(Calendar.MILLISECOND, 0);
+ int dayOfMonth = gCalend.get(Calendar.DAY_OF_MONTH);
+
+ // create clone object and change date
+ GregorianCalendar gCalendClone = (GregorianCalendar) gCalend.clone();
+ gCalendClone.add(Calendar.DATE, 1);
+
+ assertEquals("Before", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
+ gCalend.set(Calendar.MILLISECOND, 0);//changes nothing
+ assertEquals("After", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
+ }
+
+ /**
+ * java.util.GregorianCalendar#getMinimalDaysInFirstWeek()
+ */
+ public void test_getMinimalDaysInFirstWeek() {
+ // Regression for Harmony-1037
+ // Some non-bug differences below because of different CLDR data of Harmony
+ GregorianCalendar g = new GregorianCalendar(TimeZone
+ .getTimeZone("Europe/London"), new Locale("en", "GB"));
+ int minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
+ assertEquals(4, minimalDaysInFirstWeek);
+
+ g = new GregorianCalendar(TimeZone.getTimeZone("Europe/London"),
+ new Locale("fr"));
+ minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
+ assertEquals(4, minimalDaysInFirstWeek);
+
+ g = new GregorianCalendar(TimeZone.getTimeZone("Europe/London"),
+ new Locale("fr", "CA"));
+ minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
+ assertEquals(1, minimalDaysInFirstWeek);
+
+ }
+
+ /**
+ * java.util.GregorianCalendar#computeTime()
+ */
+ public void test_computeTime() {
+ // Regression for Harmony-493
+ GregorianCalendar g = new GregorianCalendar(
+ TimeZone.getTimeZone("Europe/London"),
+ new Locale("en", "GB")
+ );
+ g.clear();
+ g.set(2006, Calendar.MARCH, 26, 01, 50, 00);
+ assertEquals(1143337800000L, g.getTimeInMillis());
+
+ GregorianCalendar g1 = new GregorianCalendar(
+ TimeZone.getTimeZone("Europe/Moscow"));
+ g1.clear();
+ g1.set(2006, Calendar.MARCH, 26, 02, 20, 00);
+ assertEquals(1143328800000L, g1.getTimeInMillis());
+ assertEquals(3, g1.get(Calendar.HOUR_OF_DAY));
+ assertEquals(20, g1.get(Calendar.MINUTE));
+
+ g1.clear();
+ g1.set(2006, Calendar.OCTOBER, 29, 02, 50, 00);
+ assertEquals(1162079400000L, g1.getTimeInMillis());
+ assertEquals(2, g1.get(Calendar.HOUR_OF_DAY));
+ assertEquals(50, g1.get(Calendar.MINUTE));
+ // End of regression test
+ }
+
+ /**
+ * java.util.GregorianCalendar#get(int)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_getI() {
+ // Regression test for HARMONY-2959
+ Date date = new Date(Date.parse("Jan 15 00:00:01 GMT 2000"));
+ GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+ gc.setGregorianChange(date);
+ gc.setTimeInMillis(Date.parse("Dec 24 00:00:01 GMT 2000"));
+ assertEquals(346, gc.get(Calendar.DAY_OF_YEAR));
+
+ // Regression test for HARMONY-3003
+ date = new Date(Date.parse("Feb 28 00:00:01 GMT 2000"));
+ gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+ gc.setGregorianChange(date);
+ gc.setTimeInMillis(Date.parse("Dec 1 00:00:01 GMT 2000"));
+ assertEquals(1, gc.get(Calendar.DAY_OF_MONTH));
+ assertEquals(11, gc.get(Calendar.MONTH));
+
+ // Regression test for HARMONY-4513
+ gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+ gc.set(1582, Calendar.OCTOBER, 15, 0, 0, 0);
+ // reset millisecond to zero in order to be the same time as cutover
+ gc.set(Calendar.MILLISECOND, 0);
+ assertEquals(0, gc.get(Calendar.MILLISECOND));
+ assertEquals(1582, gc.get(Calendar.YEAR));
+ assertEquals(Calendar.OCTOBER, gc.get(Calendar.MONTH));
+ assertEquals(15, gc.get(Calendar.DAY_OF_MONTH));
+ assertEquals(0, gc.get(Calendar.HOUR_OF_DAY));
+ assertEquals(0, gc.get(Calendar.MINUTE));
+ assertEquals(0, gc.get(Calendar.SECOND));
+ gc.set(1582, Calendar.OCTOBER, 14, 0, 0, 0);
+ assertEquals(24, gc.get(Calendar.DAY_OF_MONTH));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashMapTest.java
new file mode 100644
index 0000000..26d0a8e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashMapTest.java
@@ -0,0 +1,755 @@
+/*
+ * 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.tests.java.util;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.support.Support_MapTest2;
+import tests.support.Support_UnmodifiableCollectionTest;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+import java.util.TreeMap;
+
+public class HashMapTest extends junit.framework.TestCase {
+ class MockMap extends AbstractMap {
+ public Set entrySet() {
+ return Collections.EMPTY_SET;
+ }
+
+ public int size() {
+ return 0;
+ }
+ }
+
+ private static class MockMapNull extends AbstractMap {
+ public Set entrySet() {
+ return null;
+ }
+
+ public int size() {
+ return 10;
+ }
+ }
+
+ interface MockInterface {
+ public String mockMethod();
+ }
+
+ 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();
+ }
+ return result;
+ }
+ }
+
+
+ HashMap hm;
+
+ final static int hmSize = 1000;
+
+ Object[] objArray;
+
+ Object[] objArray2;
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ HashMap empty = new HashMap(0);
+ assertNull("Empty hashmap access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * 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);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ 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");
+ }
+
+ /**
+ * 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]));
+
+ Map mockMap = new MockMap();
+ hm = new HashMap(mockMap);
+ assertEquals(hm, mockMap);
+ }
+
+ /**
+ * 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));
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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)));
+ }
+
+ /**
+ * 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)));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.HashMap#entrySet()
+ */
+ public void test_entrySetEquals() {
+ Set s1 = hm.entrySet();
+ Set s2 = new HashMap(hm).entrySet();
+ assertEquals(s1, s2);
+ }
+
+ /**
+ * java.util.HashMap#entrySet()
+ */
+ public void test_removeFromViews() {
+ hm.put("A", null);
+ hm.put("B", null);
+ assertTrue(hm.keySet().remove("A"));
+
+ Map<String, String> m2 = new HashMap<String, String>();
+ m2.put("B", null);
+ assertTrue(hm.entrySet().remove(m2.entrySet().iterator().next()));
+ }
+
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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;
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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.
+ }
+ }
+
+ public void test_putAllLjava_util_Map_Resize() {
+ Random rnd = new Random(666);
+
+ Map<Integer,Integer> m1 = new HashMap<Integer, Integer>();
+ int MID = 10000;
+ for (int i = 0; i < MID; i++) {
+ Integer j = rnd.nextInt();
+ m1.put(j, j);
+ }
+
+ Map<Integer,Integer> m2 = new HashMap<Integer, Integer>();
+ int HI = 30000;
+ for (int i = MID; i < HI; i++) {
+ Integer j = rnd.nextInt();
+ m2.put(j, j);
+ }
+
+ m1.putAll(m2);
+
+ rnd = new Random(666);
+ for (int i = 0; i < HI; i++) {
+ Integer j = rnd.nextInt();
+ assertEquals(j, m1.get(j));
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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)));
+
+ }
+
+ /**
+ * 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() {
+ 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();
+ }
+
+ 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");
+ }
+
+ protected void tearDown() {
+ hm = null;
+ objArray = null;
+ objArray2 = null;
+ }
+
+ 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();
+ }
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ HashMap<String, String> hm = new HashMap<String, String>();
+ hm.put("key", "value");
+
+ SerializationTest.verifySelf(hm);
+
+ // regression for HARMONY-1583
+ hm.put(null, "null");
+ SerializationTest.verifySelf(hm);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashSetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashSetTest.java
new file mode 100644
index 0000000..ed9c596
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashSetTest.java
@@ -0,0 +1,253 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.io.ObjectOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class HashSetTest extends junit.framework.TestCase {
+
+ HashSet hs;
+
+ Object[] objArray;
+
+ /**
+ * java.util.HashSet#HashSet()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.HashSet()
+ HashSet hs2 = new HashSet();
+ assertEquals("Created incorrect HashSet", 0, hs2.size());
+ }
+
+ /**
+ * java.util.HashSet#HashSet(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.HashSet(int)
+ HashSet hs2 = new HashSet(5);
+ assertEquals("Created incorrect HashSet", 0, hs2.size());
+ try {
+ new HashSet(-1);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ fail(
+ "Failed to throw IllegalArgumentException for capacity < 0");
+ }
+
+ /**
+ * java.util.HashSet#HashSet(int, float)
+ */
+ public void test_ConstructorIF() {
+ // Test for method java.util.HashSet(int, float)
+ HashSet hs2 = new HashSet(5, (float) 0.5);
+ assertEquals("Created incorrect HashSet", 0, hs2.size());
+ try {
+ new HashSet(0, 0);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ fail(
+ "Failed to throw IllegalArgumentException for initial load factor <= 0");
+ }
+
+ /**
+ * java.util.HashSet#HashSet(java.util.Collection)
+ */
+ public void test_ConstructorLjava_util_Collection() {
+ // Test for method java.util.HashSet(java.util.Collection)
+ HashSet hs2 = new HashSet(Arrays.asList(objArray));
+ for (int counter = 0; counter < objArray.length; counter++)
+ assertTrue("HashSet does not contain correct elements", hs
+ .contains(objArray[counter]));
+ assertTrue("HashSet created from collection incorrect size",
+ hs2.size() == objArray.length);
+
+ try {
+ new HashSet(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.HashSet#add(java.lang.Object)
+ */
+ public void test_addLjava_lang_Object() {
+ // Test for method boolean java.util.HashSet.add(java.lang.Object)
+ int size = hs.size();
+ hs.add(new Integer(8));
+ assertTrue("Added element already contained by set", hs.size() == size);
+ hs.add(new Integer(-9));
+ assertTrue("Failed to increment set size after add",
+ hs.size() == size + 1);
+ assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
+ }
+
+ /**
+ * java.util.HashSet#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.HashSet.clear()
+ Set orgSet = (Set) hs.clone();
+ hs.clear();
+ Iterator i = orgSet.iterator();
+ assertEquals("Returned non-zero size after clear", 0, hs.size());
+ while (i.hasNext())
+ assertTrue("Failed to clear set", !hs.contains(i.next()));
+ }
+
+ /**
+ * java.util.HashSet#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.HashSet.clone()
+ HashSet hs2 = (HashSet) hs.clone();
+ assertTrue("clone returned an equivalent HashSet", hs != hs2);
+ assertTrue("clone did not return an equal HashSet", hs.equals(hs2));
+ }
+
+ /**
+ * java.util.HashSet#contains(java.lang.Object)
+ */
+ public void test_containsLjava_lang_Object() {
+ // Test for method boolean java.util.HashSet.contains(java.lang.Object)
+ assertTrue("Returned false for valid object", hs.contains(objArray[90]));
+ assertTrue("Returned true for invalid Object", !hs
+ .contains(new Object()));
+
+ HashSet s = new HashSet();
+ s.add(null);
+ assertTrue("Cannot handle null", s.contains(null));
+ }
+
+ /**
+ * java.util.HashSet#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.HashSet.isEmpty()
+ assertTrue("Empty set returned false", new HashSet().isEmpty());
+ assertTrue("Non-empty set returned true", !hs.isEmpty());
+ }
+
+ /**
+ * java.util.HashSet#iterator()
+ */
+ public void test_iterator() {
+ // Test for method java.util.Iterator java.util.HashSet.iterator()
+ Iterator i = hs.iterator();
+ int x = 0;
+ while (i.hasNext()) {
+ assertTrue("Failed to iterate over all elements", hs.contains(i
+ .next()));
+ ++x;
+ }
+ assertTrue("Returned iteration of incorrect size", hs.size() == x);
+
+ HashSet s = new HashSet();
+ s.add(null);
+ assertNull("Cannot handle null", s.iterator().next());
+ }
+
+ /**
+ * java.util.HashSet#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method boolean java.util.HashSet.remove(java.lang.Object)
+ int size = hs.size();
+ hs.remove(new Integer(98));
+ assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
+ assertTrue("Failed to decrement set size", hs.size() == size - 1);
+
+ HashSet s = new HashSet();
+ s.add(null);
+ assertTrue("Cannot handle null", s.remove(null));
+ assertFalse(hs.remove(new Integer(-98)));
+ }
+
+ /**
+ * java.util.HashSet#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.HashSet.size()
+ assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
+ hs.clear();
+ assertEquals("Cleared set returned non-zero size", 0, hs.size());
+ }
+
+ /**
+ * java.util.HashSet#SerializationTest
+ */
+ public void test_Serialization() throws Exception{
+ HashSet<String> hs = new HashSet<String>();
+ hs.add("hello");
+ hs.add("world");
+ SerializationTest.verifySelf(hs, comparator);
+ SerializationTest.verifyGolden(this, hs, comparator);
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ objArray = new Object[1000];
+ for (int i = 0; i < objArray.length; i++) {
+ objArray[i] = new Integer(i);
+ }
+
+ hs = new HashSet();
+ for (int i = 0; i < objArray.length; i++) {
+ hs.add(objArray[i]);
+ }
+
+ hs.add(null);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ hs = null;
+ objArray = null;
+ }
+
+ private static final SerializationTest.SerializableAssert comparator = new
+ SerializationTest.SerializableAssert() {
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ HashSet<String> initialHs = (HashSet<String>) initial;
+ HashSet<String> deseriaHs = (HashSet<String>) deserialized;
+ assertEquals("should be equal", initialHs.size(), deseriaHs.size());
+ assertEquals("should be equal", initialHs, deseriaHs);
+ }
+
+ };
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashtableTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashtableTest.java
new file mode 100644
index 0000000..2c81f65
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/HashtableTest.java
@@ -0,0 +1,935 @@
+/*
+ * 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.tests.java.util;
+
+import tests.support.Support_MapTest2;
+import tests.support.Support_UnmodifiableCollectionTest;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.Vector;
+
+public class HashtableTest extends junit.framework.TestCase {
+
+ private Hashtable ht10;
+
+ private Hashtable ht100;
+
+ private Hashtable htfull;
+
+ private Vector keyVector;
+
+ private Vector elmVector;
+
+ private String h10sVal;
+
+ /**
+ * java.util.Hashtable#Hashtable()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.Hashtable()
+ new Support_MapTest2(new Hashtable()).runTest();
+
+ Hashtable h = new Hashtable();
+
+ assertEquals("Created incorrect hashtable", 0, h.size());
+ }
+
+ /**
+ * java.util.Hashtable#Hashtable(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.Hashtable(int)
+ Hashtable h = new Hashtable(9);
+
+ assertEquals("Created incorrect hashtable", 0, h.size());
+
+ Hashtable empty = new Hashtable(0);
+ assertNull("Empty hashtable access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * java.util.Hashtable#Hashtable(int, float)
+ */
+ public void test_ConstructorIF() {
+ // Test for method java.util.Hashtable(int, float)
+ Hashtable h = new java.util.Hashtable(10, 0.5f);
+ assertEquals("Created incorrect hashtable", 0, h.size());
+
+ Hashtable empty = new Hashtable(0, 0.75f);
+ assertNull("Empty hashtable access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+
+ try {
+ new Hashtable(-1, 0.75f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new Hashtable(0, -0.75f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#Hashtable(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ // Test for method java.util.Hashtable(java.util.Map)
+ Map map = new TreeMap();
+ Object firstVal = "Gabba";
+ Object secondVal = new Integer(5);
+ map.put("Gah", firstVal);
+ map.put("Ooga", secondVal);
+ Hashtable ht = new Hashtable(map);
+ assertTrue("a) Incorrect Hashtable constructed",
+ ht.get("Gah") == firstVal);
+ assertTrue("b) Incorrect Hashtable constructed",
+ ht.get("Ooga") == secondVal);
+
+ try {
+ new Hashtable(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ public void test_HashTable_Constructor() {
+ Hashtable hashTable = new Hashtable();
+ hashTable.put(hashTable, hashTable.keySet());
+ new Hashtable(hashTable);
+ }
+
+ /**
+ * java.util.Hashtable#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.Hashtable.clear()
+ Hashtable h = hashtableClone(htfull);
+ h.clear();
+ assertEquals("Hashtable was not cleared", 0, h.size());
+ Enumeration el = h.elements();
+ Enumeration keys = h.keys();
+ assertTrue("Hashtable improperly cleared", !el.hasMoreElements()
+ && !(keys.hasMoreElements()));
+ }
+
+ /**
+ * java.util.Hashtable#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.Hashtable.clone()
+
+ Hashtable h = (Hashtable) htfull.clone();
+ assertTrue("Clone different size than original", h.size() == htfull
+ .size());
+
+ Enumeration org = htfull.keys();
+ Enumeration cpy = h.keys();
+
+ String okey, ckey;
+ while (org.hasMoreElements()) {
+ assertTrue("Key comparison failed", (okey = (String) org
+ .nextElement()).equals(ckey = (String) cpy.nextElement()));
+ assertTrue("Value comparison failed", ((String) htfull.get(okey))
+ .equals((String) h.get(ckey)));
+ }
+ assertTrue("Copy has more keys than original", !cpy.hasMoreElements());
+ }
+
+ /**
+ * java.util.Hashtable#contains(java.lang.Object)
+ */
+ public void test_containsLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.Hashtable.contains(java.lang.Object)
+ assertTrue("Element not found", ht10.contains("Val 7"));
+ assertTrue("Invalid element found", !ht10.contains("ZZZZZZZZZZZZZZZZ"));
+
+ try {
+ ht10.contains(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.Hashtable.containsKey(java.lang.Object)
+
+ assertTrue("Failed to find key", htfull.containsKey("FKey 4"));
+ assertTrue("Failed to find key", !htfull.containsKey("FKey 99"));
+
+ try {
+ htfull.containsKey(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.Hashtable.containsValue(java.lang.Object)
+ Enumeration e = elmVector.elements();
+ while (e.hasMoreElements())
+ assertTrue("Returned false for valid value", ht10.containsValue(e
+ .nextElement()));
+ assertTrue("Returned true for invalid value", !ht10
+ .containsValue(new Object()));
+
+ try {
+ ht10.containsValue(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#elements()
+ */
+ public void test_elements() {
+ // Test for method java.util.Enumeration java.util.Hashtable.elements()
+ Enumeration elms = ht10.elements();
+ int i = 0;
+ while (elms.hasMoreElements()) {
+ String s = (String) elms.nextElement();
+ assertTrue("Missing key from enumeration", elmVector.contains(s));
+ ++i;
+ }
+
+ assertEquals("All keys not retrieved", 10, ht10.size());
+
+ assertFalse(elms.hasMoreElements());
+ try {
+ elms.nextElement();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+// BEGIN android-removed
+// implementation dependent
+// /**
+// * java.util.Hashtable#elements()
+// */
+// public void test_elements_subtest0() {
+// // this is the reference implementation behavior
+// final Hashtable ht = new Hashtable(7);
+// ht.put("1", "a");
+// // these three elements hash to the same bucket in a 7 element Hashtable
+// ht.put("2", "b");
+// ht.put("9", "c");
+// ht.put("12", "d");
+// // Hashtable looks like:
+// // 0: "1"
+// // 1: "12" -> "9" -> "2"
+// Enumeration en = ht.elements();
+// // cache the first entry
+// en.hasMoreElements();
+// ht.remove("12");
+// ht.remove("9");
+// boolean exception = false;
+// try {
+// // cached "12"
+// Object result = en.nextElement();
+// assertNull("unexpected: " + result, result);
+// // next is removed "9"
+// result = en.nextElement();
+// assertNull("unexpected: " + result, result);
+// result = en.nextElement();
+// assertTrue("unexpected: " + result, "b".equals(result));
+// } catch (NoSuchElementException e) {
+// exception = true;
+// }
+// assertTrue("unexpected NoSuchElementException", !exception);
+// }
+// END android-removed
+
+ /**
+ * java.util.Hashtable#entrySet()
+ */
+ public void test_entrySet() {
+ // Test for method java.util.Set java.util.Hashtable.entrySet()
+ Set s = ht10.entrySet();
+ Set s2 = new HashSet();
+ Iterator i = s.iterator();
+ while (i.hasNext())
+ s2.add(((Map.Entry) i.next()).getValue());
+ Enumeration e = elmVector.elements();
+ while (e.hasMoreElements())
+ assertTrue("Returned incorrect entry set", s2.contains(e
+ .nextElement()));
+// BEGIN android-removed
+// implementation dependent
+// assertEquals("Not synchronized",
+// "java.util.Collections$SynchronizedSet", s.getClass().getName());
+// END android-removed
+
+ boolean exception = false;
+ try {
+ ((Map.Entry) ht10.entrySet().iterator().next()).setValue(null);
+ } catch (NullPointerException e1) {
+ exception = true;
+ }
+ assertTrue(
+ "Should not be able to assign null to a Hashtable entrySet() Map.Entry",
+ exception);
+ }
+
+ /**
+ * java.util.Hashtable#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean java.util.Hashtable.equals(java.lang.Object)
+ Hashtable h = hashtableClone(ht10);
+ assertTrue("Returned false for equal tables", ht10.equals(h));
+ assertTrue("Returned true for unequal tables", !ht10.equals(htfull));
+ }
+
+ /**
+ * java.util.Hashtable#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.Hashtable.get(java.lang.Object)
+ Hashtable h = hashtableClone(htfull);
+ assertEquals("Could not retrieve element", "FVal 2", ((String) h.get("FKey 2"))
+ );
+
+// BEGIN android-removed
+// implementation dependent
+// // Regression for HARMONY-262
+// ReusableKey k = new ReusableKey();
+// Hashtable h2 = new Hashtable();
+// k.setKey(1);
+// h2.put(k, "value1");
+//
+// k.setKey(13);
+// assertNull(h2.get(k));
+//
+// k.setKey(12);
+// assertNull(h2.get(k));
+//
+// try {
+// h2.get(null);
+// fail("NullPointerException expected");
+// } catch (NullPointerException e) {
+// //expected
+// }
+// END android-removed
+ }
+
+ /**
+ * java.util.Hashtable#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.util.Hashtable.hashCode()
+ Set entrySet = ht10.entrySet();
+ Iterator iterator = entrySet.iterator();
+ int expectedHash;
+ for (expectedHash = 0; iterator.hasNext(); expectedHash += iterator
+ .next().hashCode())
+ ;
+ assertTrue("Incorrect hashCode returned. Wanted: " + expectedHash
+ + " got: " + ht10.hashCode(), expectedHash == ht10.hashCode());
+ }
+
+ /**
+ * java.util.Hashtable#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.Hashtable.isEmpty()
+
+ assertTrue("isEmpty returned incorrect value", !ht10.isEmpty());
+ assertTrue("isEmpty returned incorrect value",
+ new java.util.Hashtable().isEmpty());
+
+ final Hashtable ht = new Hashtable();
+ ht.put("0", "");
+ Thread t1 = new Thread() {
+ public void run() {
+ while (!ht.isEmpty())
+ ;
+ ht.put("final", "");
+ }
+ };
+ t1.start();
+ for (int i = 1; i < 10000; i++) {
+ synchronized (ht) {
+ ht.remove(String.valueOf(i - 1));
+ ht.put(String.valueOf(i), "");
+ }
+ int size;
+ if ((size = ht.size()) != 1) {
+ String result = "Size is not 1: " + size + " " + ht;
+ // terminate the thread
+ ht.clear();
+ fail(result);
+ }
+ }
+ // terminate the thread
+ ht.clear();
+ }
+
+ /**
+ * java.util.Hashtable#keys()
+ */
+ public void test_keys() {
+ // Test for method java.util.Enumeration java.util.Hashtable.keys()
+
+ Enumeration keys = ht10.keys();
+ int i = 0;
+ while (keys.hasMoreElements()) {
+ String s = (String) keys.nextElement();
+ assertTrue("Missing key from enumeration", keyVector.contains(s));
+ ++i;
+ }
+
+ assertEquals("All keys not retrieved", 10, ht10.size());
+
+ assertFalse(keys.hasMoreElements());
+ try {
+ keys.nextElement();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#keys()
+ */
+ public void test_keys_subtest0() {
+ // this is the reference implementation behavior
+ final Hashtable ht = new Hashtable(3);
+ ht.put("initial", "");
+ Enumeration en = ht.keys();
+ en.hasMoreElements();
+ ht.remove("initial");
+ boolean exception = false;
+ try {
+ Object result = en.nextElement();
+ assertTrue("unexpected: " + result, "initial".equals(result));
+ } catch (NoSuchElementException e) {
+ exception = true;
+ }
+ assertTrue("unexpected NoSuchElementException", !exception);
+ }
+
+ /**
+ * java.util.Hashtable#keySet()
+ */
+ public void test_keySet() {
+ // Test for method java.util.Set java.util.Hashtable.keySet()
+ Set s = ht10.keySet();
+ Enumeration e = keyVector.elements();
+ while (e.hasMoreElements())
+ assertTrue("Returned incorrect key set", s
+ .contains(e.nextElement()));
+
+// BEGIN android-removed
+// implementation dependent
+// assertEquals("Not synchronized",
+// "java.util.Collections$SynchronizedSet", s.getClass().getName());
+// END android-removed
+
+ Map map = new Hashtable(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.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 Hashtable(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));
+ }
+
+ /**
+ * java.util.Hashtable#keySet()
+ */
+ public void test_keySet_subtest0() {
+ Set s1 = ht10.keySet();
+ assertTrue("should contain key", s1.remove("Key 0"));
+ assertTrue("should not contain key", !s1.remove("Key 0"));
+
+ final int iterations = 10000;
+ final Hashtable ht = new Hashtable();
+ Thread t1 = new Thread() {
+ public void run() {
+ for (int i = 0; i < iterations; i++) {
+ ht.put(String.valueOf(i), "");
+ ht.remove(String.valueOf(i));
+ }
+ }
+ };
+ t1.start();
+ Set set = ht.keySet();
+ for (int i = 0; i < iterations; i++) {
+ Iterator it = set.iterator();
+ try {
+ it.next();
+ it.remove();
+ int size;
+ // ensure removing with the iterator doesn't corrupt the
+ // Hashtable
+ if ((size = ht.size()) < 0) {
+ fail("invalid size: " + size);
+ }
+ } catch (NoSuchElementException e) {
+ } catch (ConcurrentModificationException e) {
+ }
+ }
+ }
+
+// BEGIN android-removed
+// implementation dependent
+// /**
+// * java.util.Hashtable#keySet()
+// */
+// public void test_keySet_subtest1() {
+// // this is the reference implementation behavior
+// final Hashtable ht = new Hashtable(7);
+// ht.put("1", "a");
+// // these three elements hash to the same bucket in a 7 element Hashtable
+// ht.put("2", "b");
+// ht.put("9", "c");
+// ht.put("12", "d");
+// // Hashtable looks like:
+// // 0: "1"
+// // 1: "12" -> "9" -> "2"
+// Enumeration en = ht.elements();
+// // cache the first entry
+// en.hasMoreElements();
+// Iterator it = ht.keySet().iterator();
+// // this is mostly a copy of the test in test_elements_subtest0()
+// // test removing with the iterator does not null the values
+// while (it.hasNext()) {
+// String key = (String) it.next();
+// if ("12".equals(key) || "9".equals(key)) {
+// it.remove();
+// }
+// }
+// it.remove();
+// boolean exception = false;
+// try {
+// // cached "12"
+// Object result = en.nextElement();
+// assertTrue("unexpected: " + result, "d".equals(result));
+// // next is removed "9"
+// result = en.nextElement();
+// assertTrue("unexpected: " + result, "c".equals(result));
+// result = en.nextElement();
+// assertTrue("unexpected: " + result, "b".equals(result));
+// } catch (NoSuchElementException e) {
+// exception = true;
+// }
+// assertTrue("unexpected NoSuchElementException", !exception);
+// }
+// END android-removed
+
+ /**
+ * java.util.Hashtable#put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.Hashtable.put(java.lang.Object, java.lang.Object)
+ Hashtable h = hashtableClone(ht100);
+ Integer key = new Integer(100);
+ h.put("Value 100", key);
+ assertTrue("Key/Value not inserted", h.size() == 1 && (h.contains(key)));
+
+ // Put into "full" table
+ h = hashtableClone(htfull);
+ h.put("Value 100", key);
+ assertTrue("Key/Value not inserted into full table", h.size() == 8
+ && (h.contains(key)));
+
+ try {
+ h.put(null, key);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ try {
+ h.put("Value 100", null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ // Test for method void java.util.Hashtable.putAll(java.util.Map)
+ Hashtable h = new Hashtable();
+ h.putAll(ht10);
+ Enumeration e = keyVector.elements();
+ while (e.hasMoreElements()) {
+ Object x = e.nextElement();
+ assertTrue("Failed to put all elements", h.get(x).equals(
+ ht10.get(x)));
+ }
+
+ try {
+ h.putAll(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Hashtable#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.Hashtable.remove(java.lang.Object)
+ Hashtable h = hashtableClone(htfull);
+ Object k = h.remove("FKey 0");
+ assertTrue("Remove failed", !h.containsKey("FKey 0") || k == null);
+ assertNull(h.remove("FKey 0"));
+
+ try {
+ h.remove(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ public void test_HashTable_remove_scenario1() {
+ Hashtable hashTable = new Hashtable();
+ Set keySet = hashTable.keySet();
+ hashTable.put(hashTable, keySet);
+ hashTable.remove(hashTable);
+ }
+
+ public void test_HashTable_remove_scenario2() {
+ Hashtable hashTable = new Hashtable();
+ Set keySet = hashTable.keySet();
+ hashTable.put(hashTable, hashTable);
+ hashTable.remove(hashTable);
+ }
+
+ public void test_HashTable_remove_scenario3() {
+ Hashtable hashTable = new Hashtable();
+ Hashtable keyHashTable = new Hashtable();
+ keyHashTable.put(hashTable, keyHashTable);
+ hashTable.put(keyHashTable, hashTable);
+ hashTable.remove(keyHashTable);
+ }
+
+ /**
+ * java.util.Hashtable#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.Hashtable.size()
+ assertTrue("Returned invalid size", ht10.size() == 10
+ && (ht100.size() == 0));
+
+ final Hashtable ht = new Hashtable();
+ ht.put("0", "");
+ Thread t1 = new Thread() {
+ public void run() {
+ while (ht.size() > 0)
+ ;
+ ht.put("final", "");
+ }
+ };
+ t1.start();
+ for (int i = 1; i < 10000; i++) {
+ synchronized (ht) {
+ ht.remove(String.valueOf(i - 1));
+ ht.put(String.valueOf(i), "");
+ }
+ int size;
+ if ((size = ht.size()) != 1) {
+ String result = "Size is not 1: " + size + " " + ht;
+ // terminate the thread
+ ht.clear();
+ fail(result);
+ }
+ }
+ // terminate the thread
+ ht.clear();
+ }
+
+ /**
+ * java.util.Hashtable#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.util.Hashtable.toString()
+ Hashtable h = new Hashtable();
+ assertEquals("Incorrect toString for Empty table",
+ "{}", h.toString());
+
+ h.put("one", "1");
+ h.put("two", h);
+ h.put(h, "3");
+ h.put(h, h);
+ String result = h.toString();
+ assertTrue("should contain self ref", result.indexOf("(this") > -1);
+ }
+
+ /**
+ * java.util.Hashtable#values()
+ */
+ public void test_values() {
+ // Test for method java.util.Collection java.util.Hashtable.values()
+ Collection c = ht10.values();
+ Enumeration e = elmVector.elements();
+ while (e.hasMoreElements())
+ assertTrue("Returned incorrect values", c.contains(e.nextElement()));
+
+// BEGIN android-removed
+// implementation dependent
+// assertEquals("Not synchronized",
+// "java.util.Collections$SynchronizedCollection", c.getClass().getName());
+// END android-removed
+
+ Hashtable myHashtable = new Hashtable();
+ for (int i = 0; i < 100; i++)
+ myHashtable.put(new Integer(i), new Integer(i));
+ Collection values = myHashtable.values();
+ new Support_UnmodifiableCollectionTest(
+ "Test Returned Collection From Hashtable.values()", values)
+ .runTest();
+ values.remove(new Integer(0));
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myHashtable.containsValue(new Integer(0)));
+ }
+
+ /**
+ * Regression Test for JIRA 2181
+ */
+ public void test_entrySet_remove() {
+ Hashtable<String, String> hashtable = new Hashtable<String, String>();
+ hashtable.put("my.nonexistent.prop", "AAA");
+ hashtable.put("parse.error", "BBB");
+ Iterator<Map.Entry<String, String>> iterator =
+ hashtable.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry entry = iterator.next();
+ final Object value = entry.getValue();
+ if (value.equals("AAA")) {
+ iterator.remove();
+ }
+ }
+ assertFalse(hashtable.containsKey("my.nonexistent.prop"));
+ }
+
+ class Mock_Hashtable extends Hashtable {
+ boolean flag = false;
+
+ public Mock_Hashtable(int i) {
+ super(i);
+ }
+
+ @Override
+ protected void rehash() {
+ flag = true;
+ super.rehash();
+ }
+
+ public boolean isRehashed() {
+ return flag;
+ }
+ }
+
+ public void test_rehash() {
+ Mock_Hashtable mht = new Mock_Hashtable(5);
+
+ assertFalse(mht.isRehashed());
+ for(int i = 0; i < 10; i++) {
+ mht.put(i, "New value");
+ }
+ assertTrue(mht.isRehashed());
+ }
+
+ /**
+ * java.util.Hashtable#elements()
+ * java.util.Hashtable#keys()
+ * java.util.Hashtable#keySet()
+ */
+ public void test_keys_elements_keySet_Exceptions() {
+ Hashtable hashTable = new Hashtable();
+ String key = "key";
+ String value = "value";
+ hashTable.put(key, value);
+
+ Enumeration enumeration = hashTable.keys();
+ assertTrue(enumeration.hasMoreElements());
+ enumeration.nextElement();
+ assertFalse(enumeration.hasMoreElements());
+
+ enumeration = hashTable.elements();
+ assertTrue(enumeration.hasMoreElements());
+ enumeration.nextElement();
+ assertFalse(enumeration.hasMoreElements());
+
+ Iterator iterator = hashTable.keySet().iterator();
+ assertTrue(iterator.hasNext());
+ try {
+ iterator.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // Expected
+ }
+ iterator.next();
+ iterator.remove();
+ assertFalse(iterator.hasNext());
+
+ hashTable.clear();
+ for (int i = 0; i < 10; i++) {
+ hashTable.put(key + i, value + i);
+ }
+
+ enumeration = hashTable.keys();
+ assertTrue(enumeration.hasMoreElements());
+ for (int i = 0; i < 10; i++) {
+ enumeration.nextElement();
+ }
+ assertFalse(enumeration.hasMoreElements());
+ try {
+ enumeration.nextElement();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ enumeration = hashTable.elements();
+ assertTrue(enumeration.hasMoreElements());
+ for (int i = 0; i < 10; i++) {
+ enumeration.nextElement();
+ }
+ assertFalse(enumeration.hasMoreElements());
+ try {
+ enumeration.nextElement();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ iterator = hashTable.keySet().iterator();
+ assertTrue(iterator.hasNext());
+ for (int i = 0; i < 10; i++) {
+ iterator.next();
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ protected Hashtable hashtableClone(Hashtable s) {
+ return (Hashtable) s.clone();
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+
+ ht10 = new Hashtable(10);
+ ht100 = new Hashtable(100);
+ htfull = new Hashtable(10);
+ keyVector = new Vector(10);
+ elmVector = new Vector(10);
+
+ for (int i = 0; i < 10; i++) {
+ ht10.put("Key " + i, "Val " + i);
+ keyVector.addElement("Key " + i);
+ elmVector.addElement("Val " + i);
+ }
+
+ for (int i = 0; i < 7; i++)
+ htfull.put("FKey " + i, "FVal " + i);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ ht10 = null;
+ ht100 = null;
+ htfull = null;
+ keyVector = null;
+ elmVector = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMap2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMap2Test.java
new file mode 100644
index 0000000..7882077
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMap2Test.java
@@ -0,0 +1,467 @@
+/*
+ * 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.tests.java.util;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.support.Support_MapTest2;
+import java.io.Serializable;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+public class IdentityHashMap2Test extends junit.framework.TestCase {
+ private static final String ID = "hello";
+
+ class MockMap extends AbstractMap {
+ public Set entrySet() {
+ return null;
+ }
+
+ public int size() {
+ return 0;
+ }
+ }
+ private IdentityHashMap hm;
+
+ private final static int hmSize = 20;
+
+ private Object[] objArray;
+
+ private Object[] objArray2;
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.IdentityHashMap()
+ new Support_MapTest2(new IdentityHashMap()).runTest();
+
+ IdentityHashMap hm2 = new IdentityHashMap();
+ assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.IdentityHashMap(int)
+ IdentityHashMap hm2 = new IdentityHashMap(5);
+ assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
+ try {
+ new IdentityHashMap(-1);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ fail(
+ "Failed to throw IllegalArgumentException for initial capacity < 0");
+
+ IdentityHashMap empty = new IdentityHashMap(0);
+ assertNull("Empty IdentityHashMap access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ // Test for method java.util.IdentityHashMap(java.util.Map)
+ Map myMap = new TreeMap();
+ for (int counter = 0; counter < hmSize; counter++)
+ myMap.put(objArray2[counter], objArray[counter]);
+ IdentityHashMap hm2 = new IdentityHashMap(myMap);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Failed to construct correct IdentityHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+
+ Map mockMap = new MockMap();
+ hm2 = new IdentityHashMap(mockMap);
+ assertEquals("Size should be 0", 0, hm2.size());
+ }
+
+ public void test_IdentityHashMap_Constructor_BigSize() {
+ try {
+ new IdentityHashMap(Integer.MAX_VALUE);
+ fail("should throw OutOfMemoryError");
+ } catch (OutOfMemoryError e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.IdentityHashMap.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]));
+
+ }
+
+ /**
+ * java.util.IdentityHashMap#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.IdentityHashMap.clone()
+ IdentityHashMap hm2 = (IdentityHashMap) hm.clone();
+ assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Clone answered unequal IdentityHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+
+ IdentityHashMap map = new IdentityHashMap();
+ map.put("key", "value");
+ // get the keySet() and values() on the original Map
+ Set keys = map.keySet();
+ Collection values = map.values();
+ assertSame("values() does not work",
+ "value", values.iterator().next());
+ assertSame("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);
+ assertSame("keySet() was not cloned",
+ "key2", key2.iterator().next());
+ }
+
+ /**
+ * java.util.IdentityHashMap#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ IdentityHashMap m = new IdentityHashMap();
+ m.put(null, "test");
+ assertTrue("Failed with null key", m.containsKey(null));
+ assertFalse("Failed with missing key matching null hash", m.containsKey(new Integer(0)));
+ }
+
+ public static class TestKey implements Cloneable {
+ private final String foo;
+
+ TestKey(String foo) {
+ this.foo = foo;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof TestKey && foo.equals(((TestKey) o).foo);
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+ }
+
+ public void test_containsKey_copies() throws Exception {
+ TestKey a = new TestKey("a");
+ hm.put(a, new Object());
+ assertTrue(hm.containsKey(a));
+ assertFalse(hm.containsKey(a.clone()));
+ }
+
+ /**
+ * java.util.IdentityHashMap#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.IdentityHashMap.containsValue(java.lang.Object)
+ assertTrue("Returned false for valid value", hm
+ .containsValue(objArray[19]));
+ assertTrue("Returned true for invalid valie", !hm
+ .containsValue(new Integer(-9)));
+ }
+
+ /**
+ * java.util.IdentityHashMap#entrySet()
+ */
+ public void test_entrySet() {
+ // Test for method java.util.Set java.util.IdentityHashMap.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()));
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.get(java.lang.Object)
+ assertNull("Get returned non-null for non existent key",
+ hm.get("T"));
+ hm.put("T", "HELLO");
+ assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ 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)));
+ }
+
+ /**
+ * java.util.IdentityHashMap#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.IdentityHashMap.isEmpty()
+ assertTrue("Returned false for new map", new IdentityHashMap()
+ .isEmpty());
+ assertTrue("Returned true for non-empty", !hm.isEmpty());
+ }
+
+ /**
+ * java.util.IdentityHashMap#keySet()
+ */
+ public void test_keySet() {
+ // Test for method java.util.Set java.util.IdentityHashMap.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(objArray2[i]));
+ }
+
+ IdentityHashMap m = new IdentityHashMap();
+ 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 IdentityHashMap(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 IdentityHashMap(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));
+ }
+
+ /**
+ * java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object)
+ hm.put("KEY", "VALUE");
+ assertEquals("Failed to install key/value pair",
+ "VALUE", hm.get("KEY"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ Short s0 = new Short((short) 0);
+ m.put(s0, "short");
+ m.put(null, "test");
+ Integer i0 = new Integer(0);
+ m.put(i0, "int");
+ assertEquals("Failed adding to bucket containing null",
+ "short", m.get(s0));
+ assertEquals("Failed adding to bucket containing null2", "int", m.get(i0)
+ );
+ }
+
+ /**
+ * java.util.IdentityHashMap#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ // Test for method void java.util.IdentityHashMap.putAll(java.util.Map)
+ IdentityHashMap hm2 = new IdentityHashMap();
+ hm2.putAll(hm);
+ for (int i = 0; i < hmSize; i++) {
+ assertTrue("Failed to clear all elements", hm2.get(objArray2[i])
+ .equals((new Integer(i))));
+ }
+
+ hm2 = new IdentityHashMap();
+ Map mockMap = new MockMap();
+ hm2.putAll(mockMap);
+ assertEquals("Size should be 0", 0, hm2.size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.remove(java.lang.Object)
+ int size = hm.size();
+ Integer x = ((Integer) hm.remove(objArray2[9]));
+ assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
+ assertNull("Failed to remove given key", hm.get(objArray2[9]));
+ assertTrue("Failed to decrement size", hm.size() == (size - 1));
+ assertNull("Remove of non-existent key returned non-null", hm
+ .remove("LCLCLC"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ m.put(null, "test");
+ assertNull("Failed with same hash as null",
+ m.remove(objArray[0]));
+ assertEquals("Failed with null key", "test", m.remove(null));
+ }
+
+ /**
+ * java.util.IdentityHashMap#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.IdentityHashMap.size()
+ assertEquals("Returned incorrect size, ", (objArray.length), hm.size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ IdentityHashMap mapOne = new IdentityHashMap();
+ IdentityHashMap mapTwo = new IdentityHashMap();
+ IdentityHashMap mapThree = new IdentityHashMap();
+ IdentityHashMap mapFour = new IdentityHashMap();
+
+ String one = "one";
+ String alsoOne = new String(one); // use the new operator to ensure a
+ // new reference is constructed
+ String two = "two";
+ String alsoTwo = new String(two); // use the new operator to ensure a
+ // new reference is constructed
+
+ mapOne.put(one, two);
+ mapFour.put(one, two);
+
+ // these two are not equal to the above two
+ mapTwo.put(alsoOne, two);
+ mapThree.put(one, alsoTwo);
+
+ assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour);
+ assertTrue("failure of non-equality of IdentityHashMaps one and two",
+ !mapOne.equals(mapTwo));
+ assertTrue("failure of non-equality of IdentityHashMaps one and three",
+ !mapOne.equals(mapThree));
+ assertTrue("failure of non-equality of IdentityHashMaps two and three",
+ !mapTwo.equals(mapThree));
+
+ HashMap hashMapTwo = new HashMap();
+ HashMap hashMapThree = new HashMap();
+ hashMapTwo.put(alsoOne, two);
+ hashMapThree.put(one, alsoTwo);
+
+ assertTrue(
+ "failure of non-equality of IdentityHashMaps one and Hashmap two",
+ !mapOne.equals(hashMapTwo));
+ assertTrue(
+ "failure of non-equality of IdentityHashMaps one and Hashmap three",
+ !mapOne.equals(hashMapThree));
+ }
+
+ /**
+ * java.util.IdentityHashMap#values()
+ */
+ public void test_values() {
+ // Test for method java.util.Collection
+ // java.util.IdentityHashMap.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]));
+
+ IdentityHashMap myIdentityHashMap = new IdentityHashMap();
+ for (int i = 0; i < hmSize; i++)
+ myIdentityHashMap.put(objArray2[i], objArray[i]);
+ Collection values = myIdentityHashMap.values();
+ values.remove(objArray[0]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myIdentityHashMap.containsValue(objArray2[0]));
+
+ }
+
+ protected void setUp() {
+ 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();
+ }
+
+ hm = new IdentityHashMap();
+ for (int i = 0; i < objArray.length; i++) {
+ hm.put(objArray2[i], objArray[i]);
+ }
+ }
+
+
+ private static final SerializationTest.SerializableAssert comparator = new
+ SerializationTest.SerializableAssert() {
+
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial;
+ IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized;
+ assertEquals("should be equal", initialMap.size(), deseriaMap.size());
+ }
+
+ };
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMapTest.java
new file mode 100644
index 0000000..4ddaf65
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IdentityHashMapTest.java
@@ -0,0 +1,871 @@
+/*
+ * 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.tests.java.util;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+import tests.support.Support_MapTest2;
+import java.io.Serializable;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+public class IdentityHashMapTest extends junit.framework.TestCase {
+ private static final String ID = "hello";
+
+ class MockMap extends AbstractMap {
+ public Set entrySet() {
+ return null;
+ }
+ public int size(){
+ return 0;
+ }
+ }
+ /*
+ * TODO: change all the statements testing the keys and values with equals()
+ * method to check for reference equality instead
+ */
+
+ IdentityHashMap hm;
+
+ final static int hmSize = 1000;
+
+ Object[] objArray;
+
+ Object[] objArray2;
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.IdentityHashMap()
+ new Support_MapTest2(new IdentityHashMap()).runTest();
+
+ IdentityHashMap hm2 = new IdentityHashMap();
+ assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.IdentityHashMap(int)
+ IdentityHashMap hm2 = new IdentityHashMap(5);
+ assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
+ try {
+ new IdentityHashMap(-1);
+ fail("Failed to throw IllegalArgumentException for initial capacity < 0");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ IdentityHashMap empty = new IdentityHashMap(0);
+ assertNull("Empty IdentityHashMap access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * java.util.IdentityHashMap#IdentityHashMap(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ // Test for method java.util.IdentityHashMap(java.util.Map)
+ Map myMap = new TreeMap();
+ for (int counter = 0; counter < hmSize; counter++)
+ myMap.put(objArray2[counter], objArray[counter]);
+ IdentityHashMap hm2 = new IdentityHashMap(myMap);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Failed to construct correct IdentityHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+
+ Map mockMap = new MockMap();
+ hm2 = new IdentityHashMap(mockMap);
+ assertEquals("Size should be 0", 0, hm2.size());
+
+ try {
+ new IdentityHashMap(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.IdentityHashMap.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]));
+
+ }
+
+ /**
+ * java.util.IdentityHashMap#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.IdentityHashMap.clone()
+ IdentityHashMap hm2 = (IdentityHashMap) hm.clone();
+ assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Clone answered unequal IdentityHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+
+ IdentityHashMap map = new IdentityHashMap();
+ 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());
+ }
+
+ /**
+ * java.util.IdentityHashMap#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.IdentityHashMap.containsKey(java.lang.Object)
+ assertTrue("Returned false for valid key", hm
+ .containsKey(objArray2[23]));
+ assertTrue("Returned true for copy of valid key", !hm
+ .containsKey(new Integer(23).toString()));
+ assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ 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)));
+ }
+
+ /**
+ * java.util.IdentityHashMap#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.IdentityHashMap.containsValue(java.lang.Object)
+ assertTrue("Returned false for valid value", hm
+ .containsValue(objArray[19]));
+ assertTrue("Returned true for invalid valie", !hm
+ .containsValue(new Integer(-9)));
+ }
+
+ /**
+ * java.util.IdentityHashMap#entrySet()
+ */
+ public void test_entrySet() {
+ // Test for method java.util.Set java.util.IdentityHashMap.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()));
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.get(java.lang.Object)
+ assertNull("Get returned non-null for non existent key",
+ hm.get("T"));
+ hm.put("T", "HELLO");
+ assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
+ );
+
+ IdentityHashMap m = new IdentityHashMap();
+ 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)));
+ }
+
+ /**
+ * java.util.IdentityHashMap#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.IdentityHashMap.isEmpty()
+ assertTrue("Returned false for new map", new IdentityHashMap()
+ .isEmpty());
+ assertTrue("Returned true for non-empty", !hm.isEmpty());
+ }
+
+ /**
+ * java.util.IdentityHashMap#keySet()
+ */
+ public void test_keySet() {
+ // Test for method java.util.Set java.util.IdentityHashMap.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(objArray2[i]));
+ }
+
+ IdentityHashMap m = new IdentityHashMap();
+ 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 IdentityHashMap(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 IdentityHashMap(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));
+ }
+
+ /**
+ * java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object)
+ hm.put("KEY", "VALUE");
+ assertEquals("Failed to install key/value pair",
+ "VALUE", hm.get("KEY"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ Short s0 = new Short((short) 0);
+ m.put(s0, "short");
+ m.put(null, "test");
+ Integer i0 = new Integer(0);
+ m.put(i0, "int");
+ assertEquals("Failed adding to bucket containing null",
+ "short", m.get(s0));
+ assertEquals("Failed adding to bucket containing null2", "int", m.get(i0)
+ );
+
+ IdentityHashMap<Object, Object> map = new IdentityHashMap<Object, Object>();
+
+ // Test null as a key.
+ Object value = "Some value";
+ map.put(null, value);
+ assertSame("Assert 0: Failure getting null key", value, map.get(null));
+
+ // Test null as a value
+ Object key = "Some key";
+ map.put(key, null);
+ assertNull("Assert 1: Failure getting null value", map.get(key));
+ }
+
+ /**
+ * java.util.IdentityHashMap#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ // Test for method void java.util.IdentityHashMap.putAll(java.util.Map)
+ IdentityHashMap hm2 = new IdentityHashMap();
+ hm2.putAll(hm);
+ for (int i = 0; i < 1000; i++)
+ assertTrue("Failed to clear all elements", hm2.get(objArray2[i])
+ .equals((new Integer(i))));
+
+ hm2 = new IdentityHashMap();
+ Map mockMap = new MockMap();
+ hm2.putAll(mockMap);
+ assertEquals("Size should be 0", 0, hm2.size());
+
+ try {
+ hm2.putAll(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.IdentityHashMap.remove(java.lang.Object)
+ int size = hm.size();
+ Integer x = ((Integer) hm.remove(objArray2[9]));
+ assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
+ assertNull("Failed to remove given key", hm.get(objArray2[9]));
+ assertTrue("Failed to decrement size", hm.size() == (size - 1));
+ assertNull("Remove of non-existent key returned non-null", hm
+ .remove("LCLCLC"));
+
+ IdentityHashMap m = new IdentityHashMap();
+ m.put(null, "test");
+ assertNull("Failed with same hash as null",
+ m.remove(objArray[0]));
+ assertEquals("Failed with null key", "test", m.remove(null));
+
+ // Regression for HARMONY-37
+ IdentityHashMap<String, String> hashMap = new IdentityHashMap<String, String>();
+ hashMap.remove("absent");
+ assertEquals("Assert 0: Size is incorrect", 0, hashMap.size());
+
+ hashMap.put("key", "value");
+ hashMap.remove("key");
+ assertEquals("Assert 1: After removing non-null element size is incorrect", 0, hashMap.size());
+
+ hashMap.put(null, null);
+ assertEquals("Assert 2: adding literal null failed", 1, hashMap.size());
+ hashMap.remove(null);
+ assertEquals("Assert 3: After removing null element size is incorrect", 0, hashMap.size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.IdentityHashMap.size()
+ assertEquals("Returned incorrect size, ", (objArray.length + 2), hm
+ .size());
+ }
+
+ /**
+ * java.util.IdentityHashMap#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ IdentityHashMap mapOne = new IdentityHashMap();
+ IdentityHashMap mapTwo = new IdentityHashMap();
+ IdentityHashMap mapThree = new IdentityHashMap();
+ IdentityHashMap mapFour = new IdentityHashMap();
+
+ String one = "one";
+ String alsoOne = new String(one); // use the new operator to ensure a
+ // new reference is constructed
+ String two = "two";
+ String alsoTwo = new String(two); // use the new operator to ensure a
+ // new reference is constructed
+
+ mapOne.put(one, two);
+ mapFour.put(one, two);
+
+ // these two are not equal to the above two
+ mapTwo.put(alsoOne, two);
+ mapThree.put(one, alsoTwo);
+
+ assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour);
+ assertTrue("failure of non-equality of IdentityHashMaps one and two",
+ !mapOne.equals(mapTwo));
+ assertTrue("failure of non-equality of IdentityHashMaps one and three",
+ !mapOne.equals(mapThree));
+ assertTrue("failure of non-equality of IdentityHashMaps two and three",
+ !mapTwo.equals(mapThree));
+
+ HashMap hashMapTwo = new HashMap();
+ HashMap hashMapThree = new HashMap();
+ hashMapTwo.put(alsoOne, two);
+ hashMapThree.put(one, alsoTwo);
+
+ assertTrue(
+ "failure of non-equality of IdentityHashMaps one and Hashmap two",
+ !mapOne.equals(hashMapTwo));
+ assertTrue(
+ "failure of non-equality of IdentityHashMaps one and Hashmap three",
+ !mapOne.equals(hashMapThree));
+ }
+
+ /**
+ * java.util.IdentityHashMap#Serialization()
+ */
+ public void test_Serialization() throws Exception {
+ IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
+ map.put(ID, "world");
+ // BEGIN android-added
+ // Regression test for null key in serialized IdentityHashMap (1178549)
+ // Together with this change the IdentityHashMap.golden.ser resource
+ // was replaced by a version that contains a map with a null key.
+ map.put(null, "null");
+ // END android-added
+ SerializationTest.verifySelf(map, comparator);
+ SerializationTest.verifyGolden(this, map, comparator);
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ objArray = new Object[hmSize];
+ objArray2 = new Object[hmSize];
+ for (int i = 0; i < objArray.length; i++) {
+ objArray[i] = new Integer(i);
+ // android-changed: the containsKey test requires unique strings.
+ objArray2[i] = new String(objArray[i].toString());
+ }
+
+ hm = new IdentityHashMap();
+ for (int i = 0; i < objArray.length; i++)
+ hm.put(objArray2[i], objArray[i]);
+ hm.put("test", null);
+ hm.put(null, "test");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ objArray = null;
+ objArray2 = null;
+ hm = null;
+ }
+
+ private static final SerializationTest.SerializableAssert comparator = new
+ SerializationTest.SerializableAssert() {
+
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial;
+ IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized;
+ assertEquals("should be equal", initialMap.size(), deseriaMap.size());
+ }
+
+ };
+
+ /**
+ * java.util.IdentityHashMap#containsKey(java.lang.Object)
+ * java.util.IdentityHashMap#containsValue(java.lang.Object)
+ * java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
+ * 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));
+ }
+
+ /**
+ * java.util.IdentityHashMap#remove(java.lang.Object)
+ * 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));
+ }
+
+ /**
+ * java.util.IdentityHashMap#entrySet()
+ * java.util.IdentityHashMap#keySet()
+ * 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()));
+ }
+ }
+
+ /**
+ * java.util.IdentityHashMap#entrySet()
+ * 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());
+ }
+
+ /**
+ * java.util.IdentityHashMap#keySet()
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.IdentityHashMap#keySet()
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.IdentityHashMap#keySet()
+ * 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());
+ }
+
+ 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());
+ }
+
+ 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());
+ }
+
+ 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));
+ }
+
+ 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));
+ }
+
+ /*
+ * Regression test for HARMONY-6419
+ */
+ public void test_underlyingMap() {
+ IdentityHashMap<String, String> ihm = new IdentityHashMap<String, String>();
+ String key = "key";
+ String value = "value";
+ ihm.put(key, value);
+
+ Set<Map.Entry<String, String>> set = ihm.entrySet();
+ assertEquals(1, set.size());
+
+ Map.Entry<String, String> entry = set.iterator().next();
+
+ String newValue = "newvalue";
+ entry.setValue(newValue);
+ assertSame(newValue, ihm.get(key));
+ }
+
+ // comparator for IdentityHashMap objects
+ private static final SerializableAssert COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ IdentityHashMap init = (IdentityHashMap) initial;
+ IdentityHashMap desr = (IdentityHashMap) deserialized;
+
+ assertEquals("Size", init.size(), desr.size());
+ }
+ };
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatCodePointExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatCodePointExceptionTest.java
new file mode 100644
index 0000000..ac67e81
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatCodePointExceptionTest.java
@@ -0,0 +1,91 @@
+/* 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.tests.java.util;
+
+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;
+
+public class IllegalFormatCodePointExceptionTest extends TestCase {
+
+ /**
+ * java.util.IllegalFormatCodePointException.IllegalFormatCodePointException(int)
+ */
+ public void test_illegalFormatCodePointException() {
+ IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
+ -1);
+ assertTrue(null != illegalFormatCodePointException);
+ }
+
+ /**
+ * java.util.IllegalFormatCodePointException.getCodePoint()
+ */
+ public void test_getCodePoint() {
+ int codePoint = 12345;
+ IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
+ codePoint);
+ assertEquals(codePoint, illegalFormatCodePointException.getCodePoint());
+ }
+
+ /**
+ * java.util.IllegalFormatCodePointException.getMessage()
+ */
+ public void test_getMessage() {
+ int codePoint = 12345;
+ IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
+ codePoint);
+ assertTrue(null != illegalFormatCodePointException.getMessage());
+ }
+
+ // comparator for IllegalFormatCodePointException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ IllegalFormatCodePointException initEx = (IllegalFormatCodePointException) initial;
+ IllegalFormatCodePointException desrEx = (IllegalFormatCodePointException) deserialized;
+
+ assertEquals("CodePoint", initEx.getCodePoint(), desrEx
+ .getCodePoint());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(
+ new IllegalFormatCodePointException(12345), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new IllegalFormatCodePointException(12345), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatConversionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatConversionExceptionTest.java
new file mode 100644
index 0000000..2277825
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatConversionExceptionTest.java
@@ -0,0 +1,115 @@
+/* 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.tests.java.util;
+
+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;
+
+public class IllegalFormatConversionExceptionTest extends TestCase {
+
+ /**
+ * java.util.IllegalFormatConversionException#IllegalFormatConversionException(char,
+ *Class)
+ */
+ public void test_illegalFormatConversionException() {
+ try {
+ new IllegalFormatConversionException(' ', null);
+ fail("should throw NullPointerExcetpion.");
+ } catch (NullPointerException e) {
+ // desired
+ }
+ }
+
+ /**
+ * java.util.IllegalFormatConversionException#getArgumentClass()
+ */
+ public void test_getArgumentClass() {
+ char c = '*';
+ Class<String> argClass = String.class;
+ IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
+ c, argClass);
+ assertEquals(argClass, illegalFormatConversionException
+ .getArgumentClass());
+
+ }
+
+ /**
+ * java.util.IllegalFormatConversionException#getConversion()
+ */
+ public void test_getConversion() {
+ char c = '*';
+ Class<String> argClass = String.class;
+ IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
+ c, argClass);
+ assertEquals(c, illegalFormatConversionException.getConversion());
+
+ }
+
+ /**
+ * java.util.IllegalFormatConversionException#getMessage()
+ */
+ public void test_getMessage() {
+ char c = '*';
+ Class<String> argClass = String.class;
+ IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
+ c, argClass);
+ assertTrue(null != illegalFormatConversionException.getMessage());
+
+ }
+
+ // comparator for IllegalFormatConversionException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ IllegalFormatConversionException initEx = (IllegalFormatConversionException) initial;
+ IllegalFormatConversionException desrEx = (IllegalFormatConversionException) deserialized;
+
+ assertEquals("ArgumentClass", initEx.getArgumentClass(), desrEx
+ .getArgumentClass());
+ assertEquals("Conversion", initEx.getConversion(), desrEx
+ .getConversion());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalFormatConversionException('*',
+ String.class), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new IllegalFormatConversionException('*', String.class),
+ exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatFlagsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatFlagsExceptionTest.java
new file mode 100644
index 0000000..1611028
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatFlagsExceptionTest.java
@@ -0,0 +1,94 @@
+/* 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.tests.java.util;
+
+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;
+
+public class IllegalFormatFlagsExceptionTest extends TestCase {
+
+ /**
+ * java.util.IllegalFormatFlagsException#IllegalFormatFlagsException(String)
+ */
+ public void test_illegalFormatFlagsException() {
+ try {
+ new IllegalFormatFlagsException(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.IllegalFormatFlagsException.getFlags()
+ */
+ public void test_getFlags() {
+ String flags = "TESTFLAGS";
+ IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException(
+ flags);
+ assertEquals(flags, illegalFormatFlagsException.getFlags());
+ }
+
+ /**
+ * java.util.IllegalFormatFlagsException.getMessage()
+ */
+ public void test_getMessage() {
+ String flags = "TESTFLAGS";
+ IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException(
+ flags);
+ assertTrue(null != illegalFormatFlagsException.getMessage());
+
+ }
+
+ // comparator for IllegalFormatFlagsException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ IllegalFormatFlagsException initEx = (IllegalFormatFlagsException) initial;
+ IllegalFormatFlagsException desrEx = (IllegalFormatFlagsException) deserialized;
+
+ assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalFormatFlagsException(
+ "TESTFLAGS"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new IllegalFormatFlagsException(
+ "TESTFLAGS"), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatPrecisionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatPrecisionExceptionTest.java
new file mode 100644
index 0000000..b290b48
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatPrecisionExceptionTest.java
@@ -0,0 +1,92 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.tests.java.util;
+
+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;
+
+public class IllegalFormatPrecisionExceptionTest extends TestCase {
+
+ /**
+ * java.util.IllegalFormatPrecisionException#IllegalFormatPrecisionException(int)
+ */
+ public void test_illegalFormatPrecisionException() {
+ IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
+ Integer.MIN_VALUE);
+ assertEquals(Integer.MIN_VALUE, illegalFormatPrecisionException
+ .getPrecision());
+ }
+
+ /**
+ * java.util.IllegalFormatPrecisionException#getPrecision()
+ */
+ public void test_getPrecision() {
+ int precision = 12345;
+ IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
+ precision);
+ assertEquals(precision, illegalFormatPrecisionException.getPrecision());
+ }
+
+ /**
+ * method for 'java.util.IllegalFormatPrecisionException#getMessage()
+ */
+ public void test_getMessage() {
+ int precision = 12345;
+ IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
+ precision);
+ assertTrue(null != illegalFormatPrecisionException.getMessage());
+
+ }
+
+ // comparator for IllegalFormatPrecisionException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ IllegalFormatPrecisionException initEx = (IllegalFormatPrecisionException) initial;
+ IllegalFormatPrecisionException desrEx = (IllegalFormatPrecisionException) deserialized;
+
+ assertEquals("Precision", initEx.getPrecision(), desrEx
+ .getPrecision());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(
+ new IllegalFormatPrecisionException(12345), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new IllegalFormatPrecisionException(12345), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatWidthExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatWidthExceptionTest.java
new file mode 100644
index 0000000..8d5ed0e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/IllegalFormatWidthExceptionTest.java
@@ -0,0 +1,93 @@
+/* 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.tests.java.util;
+
+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;
+
+public class IllegalFormatWidthExceptionTest extends TestCase {
+
+ /**
+ * java.util.IllegalFormatWidthException#IllegalFormatWidthException(int)
+ */
+ public void test_illegalFormatWidthException() {
+ int width = Integer.MAX_VALUE;
+ IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
+ width);
+ assertEquals(width, illegalFormatWidthException.getWidth());
+
+ }
+
+ /**
+ * java.util.IllegalFormatWidthException#getWidth()
+ */
+ public void test_getWidth() {
+ int width = 12345;
+ IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
+ width);
+ assertEquals(width, illegalFormatWidthException.getWidth());
+
+ }
+
+ /**
+ * java.util.IllegalFormatWidthException#getMessage()
+ */
+ public void test_getMessage() {
+ int width = 12345;
+ IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
+ width);
+ assertTrue(null != illegalFormatWidthException.getMessage());
+
+ }
+
+ // comparator for IllegalFormatWidthException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ IllegalFormatWidthException initEx = (IllegalFormatWidthException) initial;
+ IllegalFormatWidthException desrEx = (IllegalFormatWidthException) deserialized;
+
+ assertEquals("Width", initEx.getWidth(), desrEx.getWidth());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalFormatWidthException(12345),
+ exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new IllegalFormatWidthException(
+ 12345), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InputMismatchExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InputMismatchExceptionTest.java
new file mode 100644
index 0000000..30291b3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InputMismatchExceptionTest.java
@@ -0,0 +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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.tests.java.util;
+
+import java.io.Serializable;
+import java.util.InputMismatchException;
+import java.util.NoSuchElementException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class InputMismatchExceptionTest extends TestCase {
+
+ private static final String ERROR_MESSAGE = "for serialization test"; //$NON-NLS-1$
+
+ /**
+ * java.util.InputMismatchException#InputMismatchException()
+ */
+ @SuppressWarnings("cast")
+ public void test_Constructor() {
+ InputMismatchException exception = new InputMismatchException();
+ assertNotNull(exception);
+ assertTrue(exception instanceof NoSuchElementException);
+ assertTrue(exception instanceof Serializable);
+ }
+
+ /**
+ * java.util.InputMismatchException#InputMismatchException(String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ InputMismatchException exception = new InputMismatchException(
+ ERROR_MESSAGE);
+ assertNotNull(exception);
+ assertEquals(ERROR_MESSAGE, exception.getMessage());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new InputMismatchException(ERROR_MESSAGE));
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new InputMismatchException(
+ ERROR_MESSAGE));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InvalidPropertiesFormatExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InvalidPropertiesFormatExceptionTest.java
new file mode 100644
index 0000000..10bb50e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/InvalidPropertiesFormatExceptionTest.java
@@ -0,0 +1,50 @@
+/* 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.tests.java.util;
+
+import java.io.NotSerializableException;
+import java.util.InvalidPropertiesFormatException;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class InvalidPropertiesFormatExceptionTest extends
+ junit.framework.TestCase {
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * {@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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashMapTest.java
new file mode 100644
index 0000000..8565b8e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashMapTest.java
@@ -0,0 +1,736 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import tests.support.Support_MapTest2;
+import tests.support.Support_UnmodifiableCollectionTest;
+
+/**
+ * java.util.LinkedHashMap
+ */
+public class LinkedHashMapTest extends junit.framework.TestCase {
+
+ LinkedHashMap hm;
+
+ final static int hmSize = 1000;
+
+ Object[] objArray;
+
+ Object[] objArray2;
+
+ static final class CacheMap extends LinkedHashMap {
+ protected boolean removeEldestEntry(Map.Entry e) {
+ return size() > 5;
+ }
+ }
+
+ private static class MockMapNull extends AbstractMap {
+ @Override
+ public Set entrySet() {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 10;
+ }
+ }
+
+ /**
+ * java.util.LinkedHashMap#LinkedHashMap()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.LinkedHashMap()
+ new Support_MapTest2(new LinkedHashMap()).runTest();
+
+ LinkedHashMap hm2 = new LinkedHashMap();
+ assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
+ }
+
+ /**
+ * java.util.LinkedHashMap#LinkedHashMap(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.LinkedHashMap(int)
+ LinkedHashMap hm2 = new LinkedHashMap(5);
+ assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
+ try {
+ new LinkedHashMap(-1);
+ fail("Failed to throw IllegalArgumentException for initial " +
+ "capacity < 0");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ LinkedHashMap empty = new LinkedHashMap(0);
+ assertNull("Empty LinkedHashMap access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * java.util.LinkedHashMap#LinkedHashMap(int, float)
+ */
+ public void test_ConstructorIF() {
+ // Test for method java.util.LinkedHashMap(int, float)
+ LinkedHashMap hm2 = new LinkedHashMap(5, (float) 0.5);
+ assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
+ try {
+ new LinkedHashMap(0, 0);
+ fail("Failed to throw IllegalArgumentException for initial " +
+ "load factor <= 0");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ LinkedHashMap empty = new LinkedHashMap(0, 0.75f);
+ assertNull("Empty hashtable access", empty.get("nothing"));
+ empty.put("something", "here");
+ assertTrue("cannot get element", empty.get("something") == "here");
+ }
+
+ /**
+ * java.util.LinkedHashMap#LinkedHashMap(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ // Test for method java.util.LinkedHashMap(java.util.Map)
+ Map myMap = new TreeMap();
+ for (int counter = 0; counter < hmSize; counter++)
+ myMap.put(objArray2[counter], objArray[counter]);
+ LinkedHashMap hm2 = new LinkedHashMap(myMap);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Failed to construct correct LinkedHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+ }
+
+ /**
+ * java.util.LinkedHashMap#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.LinkedHashMap.get(java.lang.Object)
+ assertNull("Get returned non-null for non existent key",
+ hm.get("T"));
+ hm.put("T", "HELLO");
+ assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
+ );
+
+ LinkedHashMap m = new LinkedHashMap();
+ 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)));
+ }
+
+ /**
+ * java.util.LinkedHashMap#put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.LinkedHashMap.put(java.lang.Object, java.lang.Object)
+ hm.put("KEY", "VALUE");
+ assertEquals("Failed to install key/value pair",
+ "VALUE", hm.get("KEY"));
+
+ LinkedHashMap m = new LinkedHashMap();
+ 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)));
+ }
+
+
+ public void test_putPresent() {
+ Map<String, String> m = new LinkedHashMap<String, String>(8, .75f, true);
+ m.put("KEY", "VALUE");
+ m.put("WOMBAT", "COMBAT");
+ m.put("KEY", "VALUE");
+ Map.Entry newest = null;
+ for (Map.Entry<String, String> e : m.entrySet()) {
+ newest = e;
+ }
+ assertEquals("KEY", newest.getKey());
+ assertEquals("VALUE", newest.getValue());
+ }
+
+ /**
+ * java.util.LinkedHashMap#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ // Test for method void java.util.LinkedHashMap.putAll(java.util.Map)
+ LinkedHashMap hm2 = new LinkedHashMap();
+ 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))));
+ }
+
+ /**
+ * java.util.LinkedHashMap#putAll(java.util.Map)
+ */
+ public void test_putAll_Ljava_util_Map_Null() {
+ LinkedHashMap linkedHashMap = new LinkedHashMap();
+ try {
+ linkedHashMap.putAll(new MockMapNull());
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected.
+ }
+
+ try {
+ linkedHashMap = new LinkedHashMap(new MockMapNull());
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected.
+ }
+ }
+
+ /**
+ * java.util.LinkedHashMap#entrySet()
+ */
+ public void test_entrySet() {
+ // Test for method java.util.Set java.util.LinkedHashMap.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()));
+ }
+ }
+
+ public void test_entrySetRemove() {
+ entrySetRemoveHelper("military", "intelligence");
+ entrySetRemoveHelper(null, "hypothesis");
+ }
+ private void entrySetRemoveHelper(String key, String value) {
+ Map<String, String> m1 = new LinkedHashMap<String, String>();
+ m1.put(key, value);
+ m1.put("jumbo", "shrimp");
+ LinkedHashMap<String, String> m2 = new LinkedHashMap<String, String>(m1);
+ Set<Map.Entry<String, String>> s1 = m1.entrySet();
+ s1.remove(m2.entrySet().iterator().next());
+ assertEquals("jumbo", s1.iterator().next().getKey());
+ }
+
+ /**
+ * java.util.LinkedHashMap#keySet()
+ */
+ public void test_keySet() {
+ // Test for method java.util.Set java.util.LinkedHashMap.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()));
+
+ LinkedHashMap m = new LinkedHashMap();
+ 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 LinkedHashMap(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 LinkedHashMap(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));
+ }
+
+ /**
+ * java.util.LinkedHashMap#values()
+ */
+ public void test_values() {
+ // Test for method java.util.Collection java.util.LinkedHashMap.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]));
+
+ LinkedHashMap myLinkedHashMap = new LinkedHashMap();
+ for (int i = 0; i < 100; i++)
+ myLinkedHashMap.put(objArray2[i], objArray[i]);
+ Collection values = myLinkedHashMap.values();
+ new Support_UnmodifiableCollectionTest(
+ "Test Returned Collection From LinkedHashMap.values()", values)
+ .runTest();
+ values.remove(new Integer(0));
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myLinkedHashMap.containsValue(new Integer(0)));
+
+ }
+
+ /**
+ * java.util.LinkedHashMap#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.LinkedHashMap.remove(java.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"));
+
+ LinkedHashMap m = new LinkedHashMap();
+ 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));
+ }
+
+ /**
+ * java.util.LinkedHashMap#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.LinkedHashMap.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]));
+
+ }
+
+ /**
+ * java.util.LinkedHashMap#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.LinkedHashMap.clone()
+ LinkedHashMap hm2 = (LinkedHashMap) hm.clone();
+ assertTrue("Clone answered equivalent LinkedHashMap", hm2 != hm);
+ for (int counter = 0; counter < hmSize; counter++)
+ assertTrue("Clone answered unequal LinkedHashMap", hm
+ .get(objArray2[counter]) == hm2.get(objArray2[counter]));
+
+ LinkedHashMap map = new LinkedHashMap();
+ 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());
+ }
+
+ /**
+ * java.util.LinkedHashMap#clone()
+ */
+ public void test_clone_ordered() {
+ // Test for method java.lang.Object java.util.LinkedHashMap.clone()
+ LinkedHashMap<String, String> hm1 = new LinkedHashMap<String, String>(10, 0.75f, true);
+ hm1.put("a", "a");
+ hm1.put("b", "b");
+ hm1.put("c", "c");
+ LinkedHashMap<String, String> hm2 = (LinkedHashMap<String, String>) hm1.clone();
+ hm1.get("a");
+
+ Map.Entry<String, String>[] set = new Map.Entry[3];
+ Iterator<Map.Entry<String,String>> iterator = hm1.entrySet().iterator();
+
+ assertEquals("b", iterator.next().getKey());
+ assertEquals("c", iterator.next().getKey());
+ assertEquals("a", iterator.next().getKey());
+
+ iterator = hm2.entrySet().iterator();
+ assertEquals("a", iterator.next().getKey());
+ assertEquals("b", iterator.next().getKey());
+ assertEquals("c", iterator.next().getKey());
+ }
+
+ // regresion test for HARMONY-4603
+ public void test_clone_Mock() {
+ LinkedHashMap hashMap = new MockMap();
+ String value = "value a";
+ hashMap.put("key", value);
+ MockMap cloneMap = (MockMap) hashMap.clone();
+ assertEquals(value, cloneMap.get("key"));
+ assertEquals(hashMap, cloneMap);
+ assertEquals(1, cloneMap.num);
+
+ hashMap.put("key", "value b");
+ assertFalse(hashMap.equals(cloneMap));
+ }
+
+ class MockMap extends LinkedHashMap {
+ int num;
+
+ public Object put(Object k, Object v) {
+ num++;
+ return super.put(k, v);
+ }
+
+ protected boolean removeEldestEntry(Map.Entry e) {
+ return num > 1;
+ }
+ }
+
+ /**
+ * put/get interaction in access-order map where removeEldest
+ * returns true.
+ */
+ public void test_removeEldestFromSameBucketAsNewEntry() {
+ LinkedHashMap<String, String> map
+ = new LinkedHashMap<String, String>(6, 0.75F, true) {
+ @Override
+ protected boolean removeEldestEntry(Entry<String, String> e) {
+ return true;
+ }
+ };
+ map.put("N", "E");
+ map.put("F", "I");
+ assertEquals(null, map.get("N"));
+ }
+
+ /**
+ * java.util.LinkedHashMap#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.LinkedHashMap.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"));
+
+ LinkedHashMap m = new LinkedHashMap();
+ 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)));
+ }
+
+ /**
+ * java.util.LinkedHashMap#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.LinkedHashMap.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)));
+ }
+
+ /**
+ * java.util.LinkedHashMap#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.LinkedHashMap.isEmpty()
+ assertTrue("Returned false for new map", new LinkedHashMap().isEmpty());
+ assertTrue("Returned true for non-empty", !hm.isEmpty());
+ }
+
+ /**
+ * java.util.LinkedHashMap#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.LinkedHashMap.size()
+ assertTrue("Returned incorrect size",
+ hm.size() == (objArray.length + 2));
+ }
+
+ /**
+ * java.util.LinkedHashMap#entrySet()
+ */
+ public void test_ordered_entrySet() {
+ int i;
+ int sz = 100;
+ LinkedHashMap lhm = new LinkedHashMap();
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lhm.put(ii, ii.toString());
+ }
+
+ Set s1 = lhm.entrySet();
+ Iterator it1 = s1.iterator();
+ assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
+ for (i = 0; it1.hasNext(); i++) {
+ Map.Entry m = (Map.Entry) it1.next();
+ Integer jj = (Integer) m.getKey();
+ assertTrue("Returned incorrect entry set 1", jj.intValue() == i);
+ }
+
+ LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lruhm.put(ii, ii.toString());
+ }
+
+ Set s3 = lruhm.entrySet();
+ Iterator it3 = s3.iterator();
+ assertTrue("Returned set of incorrect size 2", lruhm.size() == s3
+ .size());
+ for (i = 0; i < sz && it3.hasNext(); i++) {
+ Map.Entry m = (Map.Entry) it3.next();
+ Integer jj = (Integer) m.getKey();
+ assertTrue("Returned incorrect entry set 2", jj.intValue() == i);
+ }
+
+ /* fetch the even numbered entries to affect traversal order */
+ int p = 0;
+ for (i = 0; i < sz; i += 2) {
+ String ii = (String) lruhm.get(new Integer(i));
+ p = p + Integer.parseInt(ii);
+ }
+ assertEquals("invalid sum of even numbers", 2450, p);
+
+ Set s2 = lruhm.entrySet();
+ Iterator it2 = s2.iterator();
+ assertTrue("Returned set of incorrect size 3", lruhm.size() == s2
+ .size());
+ for (i = 1; i < sz && it2.hasNext(); i += 2) {
+ Map.Entry m = (Map.Entry) it2.next();
+ Integer jj = (Integer) m.getKey();
+ assertTrue("Returned incorrect entry set 3", jj.intValue() == i);
+ }
+ for (i = 0; i < sz && it2.hasNext(); i += 2) {
+ Map.Entry m = (Map.Entry) it2.next();
+ Integer jj = (Integer) m.getKey();
+ assertTrue("Returned incorrect entry set 4", jj.intValue() == i);
+ }
+ assertTrue("Entries left to iterate on", !it2.hasNext());
+ }
+
+ /**
+ * java.util.LinkedHashMap#keySet()
+ */
+ public void test_ordered_keySet() {
+ int i;
+ int sz = 100;
+ LinkedHashMap lhm = new LinkedHashMap();
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lhm.put(ii, ii.toString());
+ }
+
+ Set s1 = lhm.keySet();
+ Iterator it1 = s1.iterator();
+ assertTrue("Returned set of incorrect size", lhm.size() == s1.size());
+ for (i = 0; it1.hasNext(); i++) {
+ Integer jj = (Integer) it1.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i);
+ }
+
+ LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lruhm.put(ii, ii.toString());
+ }
+
+ Set s3 = lruhm.keySet();
+ Iterator it3 = s3.iterator();
+ assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
+ for (i = 0; i < sz && it3.hasNext(); i++) {
+ Integer jj = (Integer) it3.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i);
+ }
+
+ /* fetch the even numbered entries to affect traversal order */
+ int p = 0;
+ for (i = 0; i < sz; i += 2) {
+ String ii = (String) lruhm.get(new Integer(i));
+ p = p + Integer.parseInt(ii);
+ }
+ assertEquals("invalid sum of even numbers", 2450, p);
+
+ Set s2 = lruhm.keySet();
+ Iterator it2 = s2.iterator();
+ assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
+ for (i = 1; i < sz && it2.hasNext(); i += 2) {
+ Integer jj = (Integer) it2.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i);
+ }
+ for (i = 0; i < sz && it2.hasNext(); i += 2) {
+ Integer jj = (Integer) it2.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i);
+ }
+ assertTrue("Entries left to iterate on", !it2.hasNext());
+ }
+
+ /**
+ * java.util.LinkedHashMap#values()
+ */
+ public void test_ordered_values() {
+ int i;
+ int sz = 100;
+ LinkedHashMap lhm = new LinkedHashMap();
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lhm.put(ii, new Integer(i * 2));
+ }
+
+ Collection s1 = lhm.values();
+ Iterator it1 = s1.iterator();
+ assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
+ for (i = 0; it1.hasNext(); i++) {
+ Integer jj = (Integer) it1.next();
+ assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
+ }
+
+ LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lruhm.put(ii, new Integer(i * 2));
+ }
+
+ Collection s3 = lruhm.values();
+ Iterator it3 = s3.iterator();
+ assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
+ for (i = 0; i < sz && it3.hasNext(); i++) {
+ Integer jj = (Integer) it3.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
+ }
+
+ // fetch the even numbered entries to affect traversal order
+ int p = 0;
+ for (i = 0; i < sz; i += 2) {
+ Integer ii = (Integer) lruhm.get(new Integer(i));
+ p = p + ii.intValue();
+ }
+ assertTrue("invalid sum of even numbers", p == 2450 * 2);
+
+ Collection s2 = lruhm.values();
+ Iterator it2 = s2.iterator();
+ assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
+ for (i = 1; i < sz && it2.hasNext(); i += 2) {
+ Integer jj = (Integer) it2.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
+ }
+ for (i = 0; i < sz && it2.hasNext(); i += 2) {
+ Integer jj = (Integer) it2.next();
+ assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
+ }
+ assertTrue("Entries left to iterate on", !it2.hasNext());
+ }
+
+ /**
+ * java.util.LinkedHashMap#removeEldestEntry(java.util.Map$Entry)
+ */
+ public void test_remove_eldest() {
+ int i;
+ int sz = 10;
+ CacheMap lhm = new CacheMap();
+ for (i = 0; i < sz; i++) {
+ Integer ii = new Integer(i);
+ lhm.put(ii, new Integer(i * 2));
+ }
+
+ Collection s1 = lhm.values();
+ Iterator it1 = s1.iterator();
+ assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
+ for (i = 5; it1.hasNext(); i++) {
+ Integer jj = (Integer) it1.next();
+ assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
+ }
+ assertTrue("Entries left in map", !it1.hasNext());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ 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();
+ }
+
+ hm = new LinkedHashMap();
+ for (int i = 0; i < objArray.length; i++)
+ hm.put(objArray2[i], objArray[i]);
+ hm.put("test", null);
+ hm.put(null, "test");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ objArray = null;
+ objArray2 = null;
+ hm = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashSetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashSetTest.java
new file mode 100644
index 0000000..721a879
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedHashSetTest.java
@@ -0,0 +1,351 @@
+/* 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.tests.java.util;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.Vector;
+
+/**
+ * java.util.LinkedHashSet
+ */
+
+public class LinkedHashSetTest extends junit.framework.TestCase {
+
+ LinkedHashSet hs;
+
+ Object[] objArray;
+
+ /**
+ * java.util.LinkedHashSet#LinkedHashSet()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.LinkedHashSet()
+ LinkedHashSet hs2 = new LinkedHashSet();
+ assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
+ }
+
+ /**
+ * java.util.LinkedHashSet#LinkedHashSet(int)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.LinkedHashSet(int)
+ LinkedHashSet hs2 = new LinkedHashSet(5);
+ assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
+ try {
+ new LinkedHashSet(-1);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedHashSet#LinkedHashSet(int, float)
+ */
+ public void test_ConstructorIF() {
+ // Test for method java.util.LinkedHashSet(int, float)
+ LinkedHashSet hs2 = new LinkedHashSet(5, (float) 0.5);
+ assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
+
+ try {
+ new LinkedHashSet(-1, 0.5f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new LinkedHashSet(1, -0.5f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new LinkedHashSet(1, 0f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedHashSet#LinkedHashSet(java.util.Collection)
+ */
+ public void test_ConstructorLjava_util_Collection() {
+ // Test for method java.util.LinkedHashSet(java.util.Collection)
+ LinkedHashSet hs2 = new LinkedHashSet(Arrays.asList(objArray));
+ for (int counter = 0; counter < objArray.length; counter++)
+ assertTrue("LinkedHashSet does not contain correct elements", hs
+ .contains(objArray[counter]));
+ assertTrue("LinkedHashSet created from collection incorrect size", hs2
+ .size() == objArray.length);
+
+ try {
+ new LinkedHashSet(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedHashSet#add(java.lang.Object)
+ */
+ public void test_addLjava_lang_Object() {
+ // Test for method boolean java.util.LinkedHashSet.add(java.lang.Object)
+ int size = hs.size();
+ hs.add(new Integer(8));
+ assertTrue("Added element already contained by set", hs.size() == size);
+ hs.add(new Integer(-9));
+ assertTrue("Failed to increment set size after add",
+ hs.size() == size + 1);
+ assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
+ }
+
+ /**
+ * java.util.LinkedHashSet#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.LinkedHashSet.clear()
+ Set orgSet = (Set) hs.clone();
+ hs.clear();
+ Iterator i = orgSet.iterator();
+ assertEquals("Returned non-zero size after clear", 0, hs.size());
+ while (i.hasNext())
+ assertTrue("Failed to clear set", !hs.contains(i.next()));
+ }
+
+ /**
+ * java.util.LinkedHashSet#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.LinkedHashSet.clone()
+ LinkedHashSet hs2 = (LinkedHashSet) hs.clone();
+ assertTrue("clone returned an equivalent LinkedHashSet", hs != hs2);
+ assertTrue("clone did not return an equal LinkedHashSet", hs
+ .equals(hs2));
+ }
+
+ /**
+ * java.util.LinkedHashSet#contains(java.lang.Object)
+ */
+ public void test_containsLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.LinkedHashSet.contains(java.lang.Object)
+ assertTrue("Returned false for valid object", hs.contains(objArray[90]));
+ assertTrue("Returned true for invalid Object", !hs
+ .contains(new Object()));
+
+ LinkedHashSet s = new LinkedHashSet();
+ s.add(null);
+ assertTrue("Cannot handle null", s.contains(null));
+ }
+
+ /**
+ * java.util.LinkedHashSet#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.LinkedHashSet.isEmpty()
+ assertTrue("Empty set returned false", new LinkedHashSet().isEmpty());
+ assertTrue("Non-empty set returned true", !hs.isEmpty());
+ }
+
+ /**
+ * java.util.LinkedHashSet#iterator()
+ */
+ public void test_iterator() {
+ // Test for method java.util.Iterator java.util.LinkedHashSet.iterator()
+ Iterator i = hs.iterator();
+ int x = 0;
+ int j;
+ for (j = 0; i.hasNext(); j++) {
+ Object oo = i.next();
+ if (oo != null) {
+ Integer ii = (Integer) oo;
+ assertTrue("Incorrect element found", ii.intValue() == j);
+ } else {
+ assertTrue("Cannot find null", hs.contains(oo));
+ }
+ ++x;
+ }
+ assertTrue("Returned iteration of incorrect size", hs.size() == x);
+
+ LinkedHashSet s = new LinkedHashSet();
+ s.add(null);
+ assertNull("Cannot handle null", s.iterator().next());
+ }
+
+ /**
+ * java.util.LinkedHashSet#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.LinkedHashSet.remove(java.lang.Object)
+ int size = hs.size();
+ hs.remove(new Integer(98));
+ assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
+ assertTrue("Failed to decrement set size", hs.size() == size - 1);
+
+ LinkedHashSet s = new LinkedHashSet();
+ s.add(null);
+ assertTrue("Cannot handle null", s.remove(null));
+ }
+
+ /**
+ * java.util.LinkedHashSet#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.LinkedHashSet.size()
+ assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
+ hs.clear();
+ assertEquals("Cleared set returned non-zero size", 0, hs.size());
+ }
+
+ class Mock_LinkedHashSet extends LinkedHashSet {
+ @Override
+ public boolean retainAll(Collection c) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public void test_retainAllLjava_util_Collection() {
+ LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
+ Vector v = new Vector<Float>();
+ v.add(new Float(3.14));
+ lhs.add(new Integer(1));
+ assertEquals(1, lhs.size());
+ lhs.retainAll(v);
+ assertEquals(0, lhs.size());
+ v = new Vector<Integer>();
+ v.add(new Integer(1));
+ v.add(new Integer(2));
+ v.add(new Integer(3));
+ v.add(new Integer(4));
+ v.add(new Integer(5));
+ v.add(new Integer(6));
+ lhs.add(new Integer(1));
+ lhs.add(new Integer(6));
+ lhs.add(new Integer(7));
+ lhs.add(new Integer(8));
+ lhs.add(new Integer(9));
+ lhs.add(new Integer(10));
+ lhs.add(new Integer(11));
+ lhs.add(new Integer(12));
+ lhs.add(new Integer(13));
+ assertEquals(9, lhs.size());
+ lhs.retainAll(v);
+ assertEquals(2, lhs.size());
+
+ try {
+ lhs.retainAll(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ lhs = new Mock_LinkedHashSet();
+
+ try {
+ lhs.retainAll(v);
+ fail("UnsupportedOperationException expected");
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void test_toArray() {
+ LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
+ lhs.add(new Integer(1));
+ lhs.add(new Integer(6));
+ lhs.add(new Integer(7));
+ lhs.add(new Integer(8));
+ lhs.add(new Integer(9));
+ lhs.add(new Integer(10));
+ lhs.add(new Integer(11));
+ lhs.add(new Integer(12));
+ lhs.add(new Integer(13));
+
+ Object[] o = lhs.toArray();
+ for (int i = 0; i < o.length; i++) {
+ assertTrue(lhs.contains(o[i]));
+ }
+ assertEquals(lhs.size(), o.length);
+ }
+
+ public void test_toArray$Ljava_lang_Object() {
+ LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
+ lhs.add(new Integer(1));
+ lhs.add(new Integer(6));
+ lhs.add(new Integer(7));
+ lhs.add(new Integer(8));
+ lhs.add(new Integer(9));
+ lhs.add(new Integer(10));
+ lhs.add(new Integer(11));
+ lhs.add(new Integer(12));
+ lhs.add(new Integer(13));
+
+ Object[] o1 = new Object[lhs.size()];
+ Object[] o2 = new Double[lhs.size()];
+ lhs.toArray(o1);
+ for (int i = 0; i < o1.length; i++) {
+ assertTrue(lhs.contains(o1[i]));
+ }
+
+ try {
+ lhs.toArray(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ try {
+ lhs.toArray(o2);
+ fail("ArrayStoreException expected");
+ } catch (ArrayStoreException e) {
+ //expected
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ objArray = new Object[1000];
+ for (int i = 0; i < objArray.length; i++)
+ objArray[i] = new Integer(i);
+
+ hs = new LinkedHashSet();
+ for (int i = 0; i < objArray.length; i++)
+ hs.add(objArray[i]);
+ hs.add(null);
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ objArray = null;
+ hs = null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedListTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedListTest.java
new file mode 100644
index 0000000..79607f1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedListTest.java
@@ -0,0 +1,983 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+import tests.support.Support_ListTest;
+
+public class LinkedListTest extends junit.framework.TestCase {
+
+ LinkedList ll;
+
+ LinkedList<Object> testList;
+
+ private Object testObjOne;
+
+ private Object testObjTwo;
+
+ private Object testObjThree;
+
+ private Object testObjFour;
+
+ private Object testObjLast;
+
+ Object[] objArray;
+
+ /**
+ * java.util.LinkedList#LinkedList()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.LinkedList()
+ new Support_ListTest("", ll).runTest();
+
+ LinkedList subList = new LinkedList();
+ for (int i = -50; i < 150; i++)
+ subList.add(new Integer(i));
+ new Support_ListTest("", subList.subList(50, 150)).runTest();
+ }
+
+ /**
+ * java.util.LinkedList#LinkedList(java.util.Collection)
+ */
+ public void test_ConstructorLjava_util_Collection() {
+ // Test for method java.util.LinkedList(java.util.Collection)
+ assertTrue("Incorrect LinkedList constructed", new LinkedList(ll)
+ .equals(ll));
+
+ try {
+ new LinkedList(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedList#add(int, java.lang.Object)
+ */
+ public void test_addILjava_lang_Object() {
+ // Test for method void java.util.LinkedList.add(int, java.lang.Object)
+ Object o;
+ ll.add(50, o = "Test");
+ assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll
+ .get(50) == o);
+ assertTrue("Failed to fix up list after insert",
+ ll.get(51) == objArray[50] && (ll.get(52) == objArray[51]));
+ ll.add(50, null);
+ assertNull("Did not add null correctly", ll.get(50));
+
+ try {
+ ll.add(-1, "Test");
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ ll.add(-1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ ll.add(ll.size() + 1, "Test");
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ ll.add(ll.size() + 1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * java.util.LinkedList#add(java.lang.Object)
+ */
+ public void test_addLjava_lang_Object() {
+ // Test for method boolean java.util.LinkedList.add(java.lang.Object)
+ Object o;
+ ll.add(o = new Object());
+ assertTrue("Failed to add Object", ll.getLast() == o);
+ ll.add(null);
+ assertNull("Did not add null correctly", ll.get(ll.size() - 1));
+ }
+
+ /**
+ * java.util.LinkedList#addAll(int, java.util.Collection)
+ */
+ public void test_addAllILjava_util_Collection() {
+ // Test for method boolean java.util.LinkedList.addAll(int,
+ // java.util.Collection)
+ ll.addAll(50, (Collection) ll.clone());
+ assertEquals("Returned incorrect size after adding to existing list", 200, ll
+ .size());
+ for (int i = 0; i < 50; i++)
+ assertTrue("Manipulated elements < index", ll.get(i) == objArray[i]);
+ for (int i = 0; i >= 50 && (i < 150); i++)
+ assertTrue("Failed to ad elements properly",
+ ll.get(i) == objArray[i - 50]);
+ for (int i = 0; i >= 150 && (i < 200); i++)
+ assertTrue("Failed to ad elements properly",
+ ll.get(i) == objArray[i - 100]);
+ List myList = new LinkedList();
+ myList.add(null);
+ myList.add("Blah");
+ myList.add(null);
+ myList.add("Booga");
+ myList.add(null);
+ ll.addAll(50, myList);
+ assertNull("a) List w/nulls not added correctly", ll.get(50));
+ assertEquals("b) List w/nulls not added correctly",
+ "Blah", ll.get(51));
+ assertNull("c) List w/nulls not added correctly", ll.get(52));
+ assertEquals("d) List w/nulls not added correctly",
+ "Booga", ll.get(53));
+ assertNull("e) List w/nulls not added correctly", ll.get(54));
+
+ try {
+ ll.addAll(-1, (Collection) null);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ ll.addAll(ll.size() + 1, (Collection) null);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ ll.addAll(0, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedList#addAll(int, java.util.Collection)
+ */
+ public void test_addAllILjava_util_Collection_2() {
+ // Regression for HARMONY-467
+ LinkedList obj = new LinkedList();
+ try {
+ obj.addAll(-1, (Collection) null);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ /**
+ * java.util.LinkedList#addAll(java.util.Collection)
+ */
+ public void test_addAllLjava_util_Collection() {
+ // Test for method boolean
+ // java.util.LinkedList.addAll(java.util.Collection)
+ List l = new ArrayList();
+ l.addAll((Collection) ll.clone());
+ for (int i = 0; i < ll.size(); i++)
+ assertTrue("Failed to add elements properly", l.get(i).equals(
+ ll.get(i)));
+ ll.addAll((Collection) ll.clone());
+ assertEquals("Returned incorrect siZe after adding to existing list", 200, ll
+ .size());
+ for (int i = 0; i < 100; i++) {
+ assertTrue("Added to list in incorrect order", ll.get(i).equals(
+ l.get(i)));
+ assertTrue("Failed to add to existing list", ll.get(i + 100)
+ .equals(l.get(i)));
+ }
+ List myList = new LinkedList();
+ myList.add(null);
+ myList.add("Blah");
+ myList.add(null);
+ myList.add("Booga");
+ myList.add(null);
+ ll.addAll(myList);
+ assertNull("a) List w/nulls not added correctly", ll.get(200));
+ assertEquals("b) List w/nulls not added correctly",
+ "Blah", ll.get(201));
+ assertNull("c) List w/nulls not added correctly", ll.get(202));
+ assertEquals("d) List w/nulls not added correctly",
+ "Booga", ll.get(203));
+ assertNull("e) List w/nulls not added correctly", ll.get(204));
+
+ try {
+ ll.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Excepted
+ }
+ }
+
+ public void test_addAll_Self_Ljava_util_Collection() {
+ LinkedList linkedList = new LinkedList();
+ linkedList.addLast(1);
+ assertEquals(1, linkedList.size());
+ assertTrue(linkedList.addAll(linkedList));
+ assertEquals(2, linkedList.size());
+ }
+
+ public void test_addAll_Self_ILjava_util_Collection() {
+ LinkedList linkedList = new LinkedList();
+ linkedList.addLast(1);
+ assertEquals(1, linkedList.size());
+ assertTrue(linkedList.addAll(1, linkedList));
+ assertEquals(2, linkedList.size());
+ }
+
+ /**
+ * java.util.LinkedList#addFirst(java.lang.Object)
+ */
+ public void test_addFirstLjava_lang_Object() {
+ // Test for method void java.util.LinkedList.addFirst(java.lang.Object)
+ Object o;
+ ll.addFirst(o = new Object());
+ assertTrue("Failed to add Object", ll.getFirst() == o);
+ ll.addFirst(null);
+ assertNull("Failed to add null", ll.getFirst());
+ }
+
+ /**
+ * java.util.LinkedList#addLast(java.lang.Object)
+ */
+ public void test_addLastLjava_lang_Object() {
+ // Test for method void java.util.LinkedList.addLast(java.lang.Object)
+ Object o;
+ ll.addLast(o = new Object());
+ assertTrue("Failed to add Object", ll.getLast() == o);
+ ll.addLast(null);
+ assertNull("Failed to add null", ll.getLast());
+ }
+
+ /**
+ * java.util.LinkedList#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.LinkedList.clear()
+ ll.clear();
+ for (int i = 0; i < ll.size(); i++)
+ assertNull("Failed to clear list", ll.get(i));
+ }
+
+ /**
+ * java.util.LinkedList#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.LinkedList.clone()
+ Object x = ll.clone();
+ assertTrue("Cloned list was inequal to cloned", x.equals(ll));
+ for (int i = 0; i < ll.size(); i++)
+ assertTrue("Cloned list contains incorrect elements", ll.get(i)
+ .equals(((LinkedList) x).get(i)));
+ ll.addFirst(null);
+ x = ll.clone();
+ assertTrue("List with a null did not clone properly", ll.equals(x));
+ }
+
+ /**
+ * java.util.LinkedList#contains(java.lang.Object)
+ */
+ public void test_containsLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.LinkedList.contains(java.lang.Object)
+ assertTrue("Returned false for valid element", ll
+ .contains(objArray[99]));
+ assertTrue("Returned false for equal element", ll.contains(new Integer(
+ 8)));
+ assertTrue("Returned true for invalid element", !ll
+ .contains(new Object()));
+ assertTrue("Should not contain null", !ll.contains(null));
+ ll.add(25, null);
+ assertTrue("Should contain null", ll.contains(null));
+ }
+
+ /**
+ * java.util.LinkedList#get(int)
+ */
+ public void test_getI() {
+ // Test for method java.lang.Object java.util.LinkedList.get(int)
+ assertTrue("Returned incorrect element", ll.get(22) == objArray[22]);
+ try {
+ ll.get(8765);
+ fail("Failed to throw expected exception for index > size");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ /**
+ * {@link java.util.LinkedList#peek()}
+ */
+ public void test_peek() {
+ LinkedList list = new LinkedList();
+
+ assertNull("Should return null if this list is empty", list.peek());
+
+ assertEquals("Returned incorrect first element", ll.peek(), objArray[0]);
+ assertEquals("Peek remove the head (first element) of this list", ll.getFirst(), objArray[0]);
+ }
+
+ /**
+ * java.util.LinkedList#getFirst()
+ */
+ public void test_getFirst() {
+ // Test for method java.lang.Object java.util.LinkedList.getFirst()
+ assertTrue("Returned incorrect first element", ll.getFirst().equals(
+ objArray[0]));
+
+ LinkedList list = new LinkedList();
+ try {
+ list.getFirst();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * java.util.LinkedList#getLast()
+ */
+ public void test_getLast() {
+ // Test for method java.lang.Object java.util.LinkedList.getLast()
+ assertTrue("Returned incorrect first element", ll.getLast().equals(
+ objArray[objArray.length - 1]));
+
+ LinkedList list = new LinkedList();
+ try {
+ list.getLast();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * java.util.LinkedList#indexOf(java.lang.Object)
+ */
+ public void test_indexOfLjava_lang_Object() {
+ // Test for method int java.util.LinkedList.indexOf(java.lang.Object)
+ assertEquals("Returned incorrect index", 87, ll.indexOf(objArray[87]));
+ assertEquals("Returned index for invalid Object", -1, ll
+ .indexOf(new Object()));
+ ll.add(20, null);
+ ll.add(24, null);
+ assertTrue("Index of null should be 20, but got: " + ll.indexOf(null),
+ ll.indexOf(null) == 20);
+ }
+
+ /**
+ * java.util.LinkedList#lastIndexOf(java.lang.Object)
+ */
+ public void test_lastIndexOfLjava_lang_Object() {
+ // Test for method int
+ // java.util.LinkedList.lastIndexOf(java.lang.Object)
+ ll.add(new Integer(99));
+ assertEquals("Returned incorrect index",
+ 100, ll.lastIndexOf(objArray[99]));
+ assertEquals("Returned index for invalid Object", -1, ll
+ .lastIndexOf(new Object()));
+ ll.add(20, null);
+ ll.add(24, null);
+ assertTrue("Last index of null should be 20, but got: "
+ + ll.lastIndexOf(null), ll.lastIndexOf(null) == 24);
+ }
+
+ /**
+ * java.util.LinkedList#listIterator(int)
+ */
+ public void test_listIteratorI() {
+ // Test for method java.util.ListIterator
+ // java.util.LinkedList.listIterator(int)
+ ListIterator i1 = ll.listIterator();
+ ListIterator i2 = ll.listIterator(0);
+ Object elm;
+ int n = 0;
+ while (i2.hasNext()) {
+ if (n == 0 || n == objArray.length - 1) {
+ if (n == 0)
+ assertTrue("First element claimed to have a previous", !i2
+ .hasPrevious());
+ if (n == objArray.length)
+ assertTrue("Last element claimed to have next", !i2
+ .hasNext());
+ }
+ elm = i2.next();
+ assertTrue("Iterator returned elements in wrong order",
+ elm == objArray[n]);
+ if (n > 0 && n < objArray.length - 1) {
+ assertTrue("Next index returned incorrect value",
+ i2.nextIndex() == n + 1);
+ assertTrue("previousIndex returned incorrect value : "
+ + i2.previousIndex() + ", n val: " + n, i2
+ .previousIndex() == n);
+ }
+ elm = i1.next();
+ assertTrue("Iterator returned elements in wrong order",
+ elm == objArray[n]);
+ ++n;
+ }
+
+ i2 = ll.listIterator(ll.size()/2);
+ assertTrue((Integer)i2.next() == ll.size()/2);
+ List myList = new LinkedList();
+ myList.add(null);
+ myList.add("Blah");
+ myList.add(null);
+ myList.add("Booga");
+ myList.add(null);
+ ListIterator li = myList.listIterator();
+ assertTrue("li.hasPrevious() should be false", !li.hasPrevious());
+ assertNull("li.next() should be null", li.next());
+ assertTrue("li.hasPrevious() should be true", li.hasPrevious());
+ assertNull("li.prev() should be null", li.previous());
+ assertNull("li.next() should be null", li.next());
+ assertEquals("li.next() should be Blah", "Blah", li.next());
+ assertNull("li.next() should be null", li.next());
+ assertEquals("li.next() should be Booga", "Booga", li.next());
+ assertTrue("li.hasNext() should be true", li.hasNext());
+ assertNull("li.next() should be null", li.next());
+ assertTrue("li.hasNext() should be false", !li.hasNext());
+
+ try {
+ ll.listIterator(-1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ ll.listIterator(ll.size() + 1);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedList#remove(int)
+ */
+ public void test_removeI() {
+ // Test for method java.lang.Object java.util.LinkedList.remove(int)
+ ll.remove(10);
+ assertEquals("Failed to remove element", -1, ll.indexOf(objArray[10]));
+ try {
+ ll.remove(999);
+ fail("Failed to throw expected exception when index out of range");
+ } catch (IndexOutOfBoundsException e) {
+ // Correct
+ }
+
+ ll.add(20, null);
+ ll.remove(20);
+ assertNotNull("Should have removed null", ll.get(20));
+ }
+
+ /**
+ * java.util.LinkedList#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method boolean java.util.LinkedList.remove(java.lang.Object)
+ assertTrue("Failed to remove valid Object", ll.remove(objArray[87]));
+ assertTrue("Removed invalid object", !ll.remove(new Object()));
+ assertEquals("Found Object after removal", -1, ll.indexOf(objArray[87]));
+ ll.add(null);
+ ll.remove(null);
+ assertTrue("Should not contain null afrer removal", !ll.contains(null));
+ }
+
+ /**
+ * java.util.LinkedList#removeFirst()
+ */
+ public void test_removeFirst() {
+ // Test for method java.lang.Object java.util.LinkedList.removeFirst()
+ ll.removeFirst();
+ assertTrue("Failed to remove first element",
+ ll.getFirst() != objArray[0]);
+
+ LinkedList list = new LinkedList();
+ try {
+ list.removeFirst();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * java.util.LinkedList#removeLast()
+ */
+ public void test_removeLast() {
+ // Test for method java.lang.Object java.util.LinkedList.removeLast()
+ ll.removeLast();
+ assertTrue("Failed to remove last element",
+ ll.getLast() != objArray[objArray.length - 1]);
+
+ LinkedList list = new LinkedList();
+ try {
+ list.removeLast();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * java.util.LinkedList#set(int, java.lang.Object)
+ */
+ public void test_setILjava_lang_Object() {
+ // Test for method java.lang.Object java.util.LinkedList.set(int,
+ // java.lang.Object)
+ Object obj;
+ ll.set(65, obj = new Object());
+ assertTrue("Failed to set object", ll.get(65) == obj);
+
+ try {
+ ll.set(-1, obj = new Object());
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ ll.set(ll.size() + 1, obj = new Object());
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.LinkedList#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.LinkedList.size()
+ assertTrue("Returned incorrect size", ll.size() == objArray.length);
+ ll.removeFirst();
+ assertTrue("Returned incorrect size", ll.size() == objArray.length - 1);
+ }
+
+ /**
+ * java.util.LinkedList#toArray()
+ */
+ public void test_toArray() {
+ // Test for method java.lang.Object [] java.util.LinkedList.toArray()
+ ll.add(null);
+ Object[] obj = ll.toArray();
+ assertEquals("Returned array of incorrect size", objArray.length + 1, obj.length);
+
+ for (int i = 0; i < obj.length - 1; i++)
+ assertTrue("Returned incorrect array: " + i, obj[i] == objArray[i]);
+ assertNull("Returned incorrect array--end isn't null",
+ obj[obj.length - 1]);
+ }
+
+ /**
+ * java.util.LinkedList#toArray(java.lang.Object[])
+ */
+ public void test_toArray$Ljava_lang_Object() {
+ // Test for method java.lang.Object []
+ // java.util.LinkedList.toArray(java.lang.Object [])
+ Integer[] argArray = new Integer[100];
+ Object[] retArray;
+ retArray = ll.toArray(argArray);
+ assertTrue("Returned different array than passed", retArray == argArray);
+ List retList = new LinkedList(Arrays.asList(retArray));
+ Iterator li = ll.iterator();
+ Iterator ri = retList.iterator();
+ while (li.hasNext())
+ assertTrue("Lists are not equal", li.next() == ri.next());
+ argArray = new Integer[1000];
+ retArray = ll.toArray(argArray);
+ assertNull("Failed to set first extra element to null", argArray[ll
+ .size()]);
+ for (int i = 0; i < ll.size(); i++)
+ assertTrue("Returned incorrect array: " + i,
+ retArray[i] == objArray[i]);
+ ll.add(50, null);
+ argArray = new Integer[101];
+ retArray = ll.toArray(argArray);
+ assertTrue("Returned different array than passed", retArray == argArray);
+ retArray = ll.toArray(argArray);
+ assertTrue("Returned different array than passed", retArray == argArray);
+ retList = new LinkedList(Arrays.asList(retArray));
+ li = ll.iterator();
+ ri = retList.iterator();
+ while (li.hasNext())
+ assertTrue("Lists are not equal", li.next() == ri.next());
+
+ try {
+ ll.toArray(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ LinkedList<String> lls = new LinkedList<String>();
+ lls.add("First");
+ lls.add("Second");
+
+ try {
+ lls.toArray(argArray);
+ fail("ArrayStoreException expected");
+ } catch (ArrayStoreException e) {
+ //expected
+ }
+ }
+
+ public void test_offer() {
+ int origSize = ll.size();
+ assertTrue("offer() should return true'", ll.offer(objArray[0]));
+ assertEquals("offer() should add an element as the last one", origSize, ll.lastIndexOf(objArray[0]));
+ }
+
+ public void test_poll() {
+ for (int i = 0; i < objArray.length; i++) {
+ assertEquals("should remove the head", objArray[i], ll.poll());
+ }
+ assertEquals("should be empty", 0, ll.size());
+ assertNull("should return 'null' if list is empty", ll.poll());
+ }
+
+ public void test_remove() {
+ for (int i = 0; i < objArray.length; i++) {
+ assertEquals("should remove the head", objArray[i], ll.remove());
+ }
+ assertEquals("should be empty", 0, ll.size());
+ try {
+ ll.remove();
+ fail("NoSuchElementException is expected when removing from the empty list");
+ } catch (NoSuchElementException e) {
+ //-- expected
+ }
+ }
+
+ public void test_element() {
+ assertEquals("should return the head", objArray[0], ll.element());
+ assertEquals("element() should remove nothing", objArray.length, ll.size());
+ try {
+ new LinkedList().remove();
+ fail("NoSuchElementException is expected when the list is empty");
+ } catch (NoSuchElementException e) {
+ //-- expected
+ }
+ }
+
+ /**
+ * {@link java.util.LinkedList#removeFirstOccurrence(Object)}
+ */
+ public void test_removeFirstOccurrence() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjThree));
+ assertTrue(testList.offerLast(testObjOne));
+ assertEquals(5, testList.size());
+ assertTrue(testList.removeFirstOccurrence(testObjOne));
+ assertFalse(testList.removeFirstOccurrence(testObjFour));
+ assertEquals(testObjTwo, testList.peekFirst());
+ assertEquals(testObjOne, testList.peekLast());
+ assertEquals(4, testList.size());
+ assertTrue(testList.removeFirstOccurrence(testObjOne));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.peekLast());
+ assertTrue(testList.removeFirstOccurrence(testObjOne));
+ assertEquals(2, testList.size());
+ assertEquals(testObjThree, testList.peekLast());
+ assertFalse(testList.removeFirstOccurrence(testObjOne));
+ }
+
+ /**
+ * {@link java.util.LinkedList#removeLastOccurrence(Object)}
+ */
+ public void test_removeLastOccurrence() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjThree));
+ assertTrue(testList.offerLast(testObjOne));
+ assertEquals(5, testList.size());
+ assertTrue(testList.removeLastOccurrence(testObjOne));
+ assertFalse(testList.removeLastOccurrence(testObjFour));
+ assertEquals(testObjOne, testList.peekFirst());
+ assertEquals(testObjThree, testList.peekLast());
+ assertEquals(4, testList.size());
+ assertTrue(testList.removeLastOccurrence(testObjOne));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.peekFirst());
+ assertEquals(testObjThree, testList.peekLast());
+ assertTrue(testList.removeLastOccurrence(testObjOne));
+ assertEquals(2, testList.size());
+ assertEquals(testObjThree, testList.peekLast());
+ assertFalse(testList.removeLastOccurrence(testObjOne));
+ }
+
+ /**
+ * {@link java.util.LinkedList#offerFirst(Object)}
+ */
+ public void test_offerFirst() throws Exception {
+ assertTrue(testList.offerFirst(testObjOne));
+ assertEquals(1, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ assertTrue(testList.offerFirst(testObjOne));
+ assertEquals(2, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ assertTrue(testList.offerFirst(testObjTwo));
+ assertEquals(3, testList.size());
+ assertEquals(testObjTwo, testList.peek());
+ assertEquals(testObjOne, testList.getLast());
+ assertTrue(testList.offerFirst(null));
+ assertEquals(4, testList.size());
+ }
+
+ /**
+ * {@link java.util.LinkedList#offerLast(Object)}
+ */
+ public void test_offerLast() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertEquals(1, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ assertTrue(testList.offerLast(testObjOne));
+ assertEquals(2, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ assertTrue(testList.offerLast(testObjTwo));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ assertEquals(testObjTwo, testList.getLast());
+ assertTrue(testList.offerLast(null));
+ assertEquals(4, testList.size());
+ }
+
+ /**
+ * {@link java.util.LinkedList#push(Object)}
+ */
+ public void test_push() throws Exception {
+ testList.push(testObjOne);
+ assertEquals(1, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ testList.push(testObjOne);
+ assertEquals(2, testList.size());
+ assertEquals(testObjOne, testList.peek());
+ testList.push(testObjTwo);
+ assertEquals(3, testList.size());
+ assertEquals(testObjTwo, testList.peek());
+ assertEquals(testObjOne, testList.getLast());
+ testList.push(null);
+ assertEquals(4, testList.size());
+ }
+
+ /**
+ * {@link java.util.LinkedList#pop()}
+ */
+ public void test_pop() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjThree));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.pop());
+ assertEquals(2, testList.size());
+ assertEquals(testObjTwo, testList.pop());
+ assertEquals(testObjThree, testList.pop());
+ assertEquals(0, testList.size());
+ testList.push(null);
+ assertEquals(1, testList.size());
+ assertNull(testList.pop());
+ try {
+ testList.pop();
+ fail("should throw NoSuchElementException ");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.LinkedList#descendingIterator()}
+ */
+ public void test_descendingIterator() throws Exception {
+ assertFalse(testList.descendingIterator().hasNext());
+ assertTrue(testList.add(testObjOne));
+ assertTrue(testList.add(testObjTwo));
+ assertTrue(testList.add(testObjOne));
+ assertTrue(testList.add(testObjThree));
+ assertTrue(testList.add(testObjLast));
+ Iterator result = testList.descendingIterator();
+ assertEquals(5, testList.size());
+ try {
+ result.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ assertTrue(testList.add(testObjFour));
+
+ try {
+ assertEquals(testObjLast, result.next());
+ fail("should throw ConcurrentModificationException");
+ } catch (ConcurrentModificationException e) {
+ // expected
+ }
+
+ result = testList.descendingIterator();
+ assertEquals(testObjFour, result.next());
+ assertEquals(testObjLast, result.next());
+ assertEquals(testObjThree, result.next());
+ assertEquals(testObjOne, result.next());
+ assertEquals(testObjTwo, result.next());
+ assertTrue(result.hasNext());
+ result.remove();
+ assertEquals(testObjOne, result.next());
+ assertFalse(result.hasNext());
+ try {
+ result.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.LinkedList#pollFirst()}
+ */
+ public void test_pollFirst() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjThree));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.pollFirst());
+ assertEquals(2, testList.size());
+ assertEquals(testObjTwo, testList.pollFirst());
+ assertEquals(testObjThree, testList.pollFirst());
+ assertEquals(0, testList.size());
+ assertNull(testList.pollFirst());
+ }
+
+ /**
+ * {@link java.util.LinkedList#pollLast()}
+ */
+ public void test_pollLast() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjThree));
+ assertEquals(3, testList.size());
+ assertEquals(testObjThree, testList.pollLast());
+ assertEquals(2, testList.size());
+ assertEquals(testObjTwo, testList.pollLast());
+ assertEquals(testObjOne, testList.pollLast());
+ assertEquals(0, testList.size());
+ assertNull(testList.pollFirst());
+ }
+
+ /**
+ * {@link java.util.LinkedList#peekFirst()}
+ */
+ public void test_peekFirst() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjThree));
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.peekFirst());
+ assertEquals(3, testList.size());
+ assertEquals(testObjOne, testList.pollFirst());
+ assertEquals(testObjTwo, testList.peekFirst());
+ assertEquals(testObjTwo, testList.pollFirst());
+ assertEquals(testObjThree, testList.pollFirst());
+ assertEquals(0, testList.size());
+ assertEquals(null, testList.peekFirst());
+ }
+
+ /**
+ * {@link java.util.LinkedList#peek()}
+ */
+ public void test_peekLast() throws Exception {
+ assertTrue(testList.offerLast(testObjOne));
+ assertTrue(testList.offerLast(testObjTwo));
+ assertTrue(testList.offerLast(testObjThree));
+ assertEquals(3, testList.size());
+ assertEquals(testObjThree, testList.peekLast());
+ assertEquals(3, testList.size());
+ assertEquals(testObjThree, testList.pollLast());
+ assertEquals(testObjTwo, testList.peekLast());
+ assertEquals(testObjTwo, testList.pollLast());
+ assertEquals(testObjOne, testList.pollLast());
+ assertEquals(0, testList.size());
+ assertNull(testList.peekLast());
+ }
+
+ /**
+ * java.util.LinkedList#Serialization()
+ */
+ public void test_serialization() throws Exception {
+ assertTrue(ll.add(new Integer(1)));
+ assertTrue(ll.add(new Integer(2)));
+ assertTrue(ll.add(new Integer(3)));
+ assertTrue(ll.add(new Integer(4)));
+ assertTrue(ll.add(new Integer(5)));
+ SerializationTest.verifySelf(ll, new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+ LinkedList<Object> formerQue = (LinkedList) initial;
+ LinkedList<Object> deserializedQue = (LinkedList) deserialized;
+ assertEquals(formerQue.remove(), deserializedQue.remove());
+ }
+ });
+ }
+
+ /**
+ * 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();
+
+ objArray = new Object[100];
+ for (int i = 0; i < objArray.length; i++) {
+ objArray[i] = new Integer(i);
+ }
+
+ ll = new LinkedList();
+ for (int i = 0; i < objArray.length; i++) {
+ ll.add(objArray[i]);
+ }
+
+ testList = new LinkedList<Object>();
+ testObjOne = new Object();
+ testObjTwo = new Object();
+ testObjThree = new Object();
+ testObjFour = new Object();
+ testObjLast = new Object();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ListResourceBundleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ListResourceBundleTest.java
new file mode 100644
index 0000000..6a85161
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ListResourceBundleTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Enumeration;
+import java.util.ListResourceBundle;
+import java.util.Locale;
+import java.util.ResourceBundle;
+import java.util.Vector;
+
+public class ListResourceBundleTest extends junit.framework.TestCase {
+ /**
+ * java.util.ListResourceBundle#getKeys()
+ */
+ public void test_getKeys() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ Enumeration<String> keys = bundle.getKeys();
+ Vector<String> result = new Vector<String>();
+ while (keys.hasMoreElements()) {
+ result.addElement(keys.nextElement());
+ }
+ assertTrue("Missing key parent1", result.contains("parent1"));
+ assertTrue("Missing key parent2", result.contains("parent2"));
+ assertTrue("Missing key parent3", result.contains("parent3"));
+ assertTrue("Missing key parent4", result.contains("parent4"));
+ assertTrue("Missing key child1", result.contains("child1"));
+ assertTrue("Missing key child2", result.contains("child2"));
+ assertTrue("Missing key child3", result.contains("child3"));
+ }
+
+ public void test_handleGetObjectLjava_lang_String() {
+ ListResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = (ListResourceBundle) ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ Enumeration keys = bundle.getKeys();
+ String keyValue = null;
+ Vector result = new Vector();
+ while (keys.hasMoreElements()) {
+ result.addElement(bundle.handleGetObject((String)keys.nextElement()));
+ }
+ assertEquals(9, result.size());
+ assertTrue(result.contains(null));
+ assertTrue(result.contains("frFRVARValue4"));
+ assertTrue(result.contains("frFRVARChildValue1"));
+ assertTrue(result.contains("frFRVARChildValue2"));
+ assertTrue(result.contains("frFRVARChildValue3"));
+ assertTrue(result.remove(null));
+ assertTrue(result.remove(null));
+ assertTrue(result.remove(null));
+ }
+
+ protected void setUp() {
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LocaleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LocaleTest.java
new file mode 100644
index 0000000..dfb2d96
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LocaleTest.java
@@ -0,0 +1,449 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+public class LocaleTest extends junit.framework.TestCase {
+
+ Locale testLocale;
+
+ Locale l;
+
+ Locale defaultLocale;
+
+ /**
+ * java.util.Locale#Locale(java.lang.String, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.Locale(java.lang.String)
+ Locale x = new Locale("xx");
+ assertTrue("Failed to create Locale", x.getVariant().equals(""));
+
+ try {
+ new Locale(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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(""));
+
+ try {
+ new Locale("xx", null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ try {
+ new Locale(null, "CV");
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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) {
+ }
+
+ 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) {
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+
+ }
+
+ /**
+ * java.util.Locale#getAvailableLocales()
+ */
+ public void test_getAvailableLocales() {
+// BEGIN android-changed
+ // Test for method java.util.Locale []
+ // java.util.Locale.getAvailableLocales()
+ // Assumes there will generally be about 10+ available locales...
+ // even in minimal configurations for android
+ try {
+ Locale[] locales = Locale.getAvailableLocales();
+ assertTrue("Wrong number of locales: " + locales.length, locales.length > 10);
+ // regression test for HARMONY-1514
+ // HashSet can filter duplicate locales
+ Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales));
+ assertEquals(localesSet.size(), locales.length);
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+// END android-changed
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ Locale l_countryCD = new Locale("", "CD");
+ assertEquals("Congo (DRC)",
+ l_countryCD.getDisplayCountry());
+ }
+
+ public void test_getDisplayCountryLjava_util_Locale() {
+ assertEquals("Italie", Locale.ITALY.getDisplayCountry(new Locale("fr", "CA", "WIN32")));
+ }
+
+ /**
+ * 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", "");
+ assertEquals("Avestan", l_languageAE.getDisplayLanguage());
+
+ // Regression for HARMONY-4402
+ Locale defaultLocale = Locale.getDefault();
+ try {
+ Locale locale = new Locale("no", "NO");
+ Locale.setDefault(locale);
+ assertEquals("norsk", locale.getDisplayLanguage());
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
+ public void test_getDisplayLanguageLjava_util_Locale() {
+ assertEquals("anglais", new Locale("en", "CA", "WIN32").getDisplayLanguage(l));
+ }
+
+ public void test_getDisplayName() {
+ assertEquals("English (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName());
+ }
+
+ public void test_getDisplayNameLjava_util_Locale() {
+ assertEquals("anglais (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName(l));
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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
+ Locale l_CountryCS = new Locale("", "CS");
+ assertEquals("SCG", l_CountryCS.getISO3Country());
+
+ // Regression for Harmony-1129
+ l = new Locale("ak", "");
+ assertEquals("aka", l.getISO3Language());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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;
+
+ // BEGIN android-changed
+ // Language codes are 2- and 3-letter, with preference given
+ // to 2-letter codes where possible. 3-letter codes are used
+ // when lack a 2-letter equivalent.
+ assertTrue("Random element in wrong format.",
+ (isoLang[length / 2].length() == 2 || isoLang[length / 2].length() == 3)
+ && isoLang[length / 2].toLowerCase().equals(isoLang[length / 2]));
+ // END android-changed
+
+ assertTrue("Wrong number of ISOLanguages.", length > 130);
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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);
+
+ try {
+ Locale.setDefault(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Locale#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.util.Locale.toString()
+ assertEquals("en_CA_WIN32", new Locale("en", "CA", "WIN32").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());
+
+ }
+
+ public void test_hashCode() {
+ Locale l1 = new Locale("en", "US");
+ Locale l2 = new Locale("fr", "CA");
+
+ assertTrue(l1.hashCode() != l2.hashCode());
+ }
+
+ /**
+ * {@value java.util.Locale#ROOT}
+ * @since 1.6
+ */
+ public void test_constantROOT() {
+ Locale root = Locale.ROOT;
+ assertEquals("", root.getLanguage());
+ assertEquals("", root.getCountry());
+ assertEquals("", root.getVariant());
+ }
+
+// BEGIN android-removed
+// These locales are not part of the android reference impl
+// // 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"));
+//
+// List<String> countries = Arrays.asList(Locale.getISOCountries());
+// assertTrue(countries.contains("CS"));
+// }
+// END android-removed
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatArgumentExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatArgumentExceptionTest.java
new file mode 100644
index 0000000..464960a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatArgumentExceptionTest.java
@@ -0,0 +1,97 @@
+/* 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.tests.java.util;
+
+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;
+
+public class MissingFormatArgumentExceptionTest extends TestCase {
+
+ /**
+ * java.util.MissingFormatArgumentException#MissingFormatArgumentException(String)
+ */
+ public void test_missingFormatArgumentException() {
+
+ try {
+ new MissingFormatArgumentException(null);
+ fail("should throw NullPointerExcepiton.");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.MissingFormatArgumentException#getFormatSpecifier()
+ */
+ public void test_getFormatSpecifier() {
+ String s = "MYTESTSTRING";
+ MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
+ s);
+ assertEquals(s, missingFormatArgumentException.getFormatSpecifier());
+ }
+
+ /**
+ * java.util.MissingFormatArgumentException#getMessage()
+ */
+ public void test_getMessage() {
+ String s = "MYTESTSTRING";
+ MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
+ s);
+ assertTrue(null != missingFormatArgumentException.getMessage());
+
+ }
+
+ // comparator for comparing MissingFormatArgumentException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ MissingFormatArgumentException initEx = (MissingFormatArgumentException) initial;
+ MissingFormatArgumentException desrEx = (MissingFormatArgumentException) deserialized;
+
+ assertEquals("FormatSpecifier", initEx.getFormatSpecifier(), desrEx
+ .getFormatSpecifier());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new MissingFormatArgumentException(
+ "MYTESTSTRING"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new MissingFormatArgumentException("MYTESTSTRING"),
+ exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatWidthExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatWidthExceptionTest.java
new file mode 100644
index 0000000..cf3d25f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingFormatWidthExceptionTest.java
@@ -0,0 +1,95 @@
+/* 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.tests.java.util;
+
+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;
+
+public class MissingFormatWidthExceptionTest extends TestCase {
+
+ /**
+ * java.util.MissingFormatWidthException#MissingFormatWidthException(String)
+ */
+ public void test_missingFormatWidthException() {
+ try {
+ new MissingFormatWidthException(null);
+ fail("should throw NullPointerExcepiton");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.MissingFormatWidthException#getFormatSpecifier()
+ */
+ public void test_getFormatSpecifier() {
+ String s = "MYTESTSTRING";
+ MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
+ s);
+ assertEquals(s, missingFormatWidthException.getFormatSpecifier());
+
+ }
+
+ /**
+ * java.util.MissingFormatWidthException#getMessage()
+ */
+ public void test_getMessage() {
+ String s = "MYTESTSTRING";
+ MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
+ s);
+ assertTrue(null != missingFormatWidthException.getMessage());
+
+ }
+
+ // comparator for comparing MissingFormatWidthException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ MissingFormatWidthException initEx = (MissingFormatWidthException) initial;
+ MissingFormatWidthException desrEx = (MissingFormatWidthException) deserialized;
+
+ assertEquals("FormatSpecifier", initEx.getFormatSpecifier(), desrEx
+ .getFormatSpecifier());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new MissingFormatWidthException(
+ "MYTESTSTRING"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new MissingFormatWidthException(
+ "MYTESTSTRING"), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingResourceExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingResourceExceptionTest.java
new file mode 100644
index 0000000..3eb9bac
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/MissingResourceExceptionTest.java
@@ -0,0 +1,85 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class MissingResourceExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.MissingResourceException#MissingResourceException(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
+ // Test for method java.util.MissingResourceException(java.lang.String,
+ // java.lang.String, java.lang.String)
+ assertNotNull(new MissingResourceException("Detail string", "Class name string", "Key string"));
+ assertNotNull(new MissingResourceException(null, "Class name string", "Key string"));
+ assertNotNull(new MissingResourceException("Detail string", null, "Key string"));
+ assertNotNull(new MissingResourceException("Detail string", "Class name string", null));
+ try {
+ ResourceBundle.getBundle("Non-ExistentBundle");
+ } catch (MissingResourceException e) {
+ return;
+ }
+ fail("Failed to generate expected exception");
+ }
+
+ /**
+ * java.util.MissingResourceException#getClassName()
+ */
+ public void test_getClassName() {
+ // Test for method java.lang.String
+ // java.util.MissingResourceException.getClassName()
+ try {
+ ResourceBundle.getBundle("Non-ExistentBundle");
+ } catch (MissingResourceException e) {
+ assertEquals("Returned incorrect class name", "Non-ExistentBundle"
+ + '_' + Locale.getDefault(), e.getClassName());
+ }
+ }
+
+ /**
+ * java.util.MissingResourceException#getKey()
+ */
+ public void test_getKey() {
+ // Test for method java.lang.String
+ // java.util.MissingResourceException.getKey()
+ try {
+ ResourceBundle.getBundle("Non-ExistentBundle");
+ } catch (MissingResourceException e) {
+ assertTrue("Returned incorrect class name", e.getKey().equals(""));
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/NoSuchElementExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/NoSuchElementExceptionTest.java
new file mode 100644
index 0000000..7727f3f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/NoSuchElementExceptionTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.NoSuchElementException;
+import java.util.Vector;
+
+public class NoSuchElementExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.NoSuchElementException#NoSuchElementException()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.NoSuchElementException()
+
+ assertNotNull(new NoSuchElementException());
+
+ try {
+ Vector v = new Vector();
+ v.elements().nextElement();
+ fail("NoSuchElementException expected");
+ } catch (NoSuchElementException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.NoSuchElementException#NoSuchElementException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.NoSuchElementException(java.lang.String)
+
+ assertNotNull(new NoSuchElementException("String"));
+ assertNotNull(new NoSuchElementException(null));
+
+ try {
+ Vector v = new Vector();
+ v.firstElement();
+ fail("NoSuchElementException expected");
+ } catch (NoSuchElementException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ObservableTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ObservableTest.java
new file mode 100644
index 0000000..b13a876
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ObservableTest.java
@@ -0,0 +1,246 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Observable;
+import java.util.Observer;
+import java.util.Vector;
+
+public class ObservableTest extends junit.framework.TestCase {
+
+ static class TestObserver implements Observer {
+ public Vector objv = new Vector();
+
+ int updateCount = 0;
+
+ public void update(Observable observed, Object arg) {
+ ++updateCount;
+ objv.add(arg);
+ }
+
+ public int updateCount() {
+ return updateCount;
+ }
+
+ }
+
+ static class DeleteTestObserver implements Observer {
+ int updateCount = 0;
+
+ boolean deleteAll = false;
+
+ public DeleteTestObserver(boolean all) {
+ deleteAll = all;
+ }
+
+ public void update(Observable observed, Object arg) {
+ ++updateCount;
+ if (deleteAll)
+ observed.deleteObservers();
+ else
+ observed.deleteObserver(this);
+ }
+
+ public int updateCount() {
+ return updateCount;
+ }
+
+ }
+
+ static class TestObservable extends Observable {
+ public void doChange() {
+ setChanged();
+ }
+
+ public void clearChange() {
+ clearChanged();
+ }
+ }
+
+ Observer observer;
+
+ TestObservable observable;
+
+ /**
+ * java.util.Observable#Observable()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.Observable()
+ try {
+ Observable ov = new Observable();
+ assertTrue("Wrong initial values.", !ov.hasChanged());
+ assertEquals("Wrong initial values.", 0, ov.countObservers());
+ } catch (Exception e) {
+ fail("Exception during test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * java.util.Observable#addObserver(java.util.Observer)
+ */
+ public void test_addObserverLjava_util_Observer() {
+ // Test for method void
+ // java.util.Observable.addObserver(java.util.Observer)
+ TestObserver test = new TestObserver();
+ observable.addObserver(test);
+ assertEquals("Failed to add observer", 1, observable.countObservers());
+ observable.addObserver(test);
+ assertEquals("Duplicate observer", 1, observable.countObservers());
+
+ Observable o = new Observable();
+ try {
+ o.addObserver(null);
+ fail("Expected adding a null observer to throw a NPE.");
+ } catch (NullPointerException ex) {
+ // expected;
+ } catch (Throwable ex) {
+ fail("Did not expect adding a new observer to throw a "
+ + ex.getClass().getName());
+ }
+ }
+
+ /**
+ * java.util.Observable#countObservers()
+ */
+ public void test_countObservers() {
+ // Test for method int java.util.Observable.countObservers()
+ assertEquals("New observable had > 0 observers", 0, observable
+ .countObservers());
+ observable.addObserver(new TestObserver());
+ assertEquals("Observable with observer returned other than 1", 1, observable
+ .countObservers());
+ }
+
+ /**
+ * java.util.Observable#deleteObserver(java.util.Observer)
+ */
+ public void test_deleteObserverLjava_util_Observer() {
+ // Test for method void
+ // java.util.Observable.deleteObserver(java.util.Observer)
+ observable.addObserver(observer = new TestObserver());
+ observable.deleteObserver(observer);
+ assertEquals("Failed to delete observer",
+ 0, observable.countObservers());
+ observable.deleteObserver(observer);
+ observable.deleteObserver(null);
+ }
+
+ /**
+ * java.util.Observable#deleteObservers()
+ */
+ public void test_deleteObservers() {
+ // Test for method void java.util.Observable.deleteObservers()
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.addObserver(new TestObserver());
+ observable.deleteObservers();
+ assertEquals("Failed to delete observers",
+ 0, observable.countObservers());
+ }
+
+ /**
+ * java.util.Observable#hasChanged()
+ */
+ public void test_hasChanged() {
+ assertFalse(observable.hasChanged());
+ observable.addObserver(observer = new TestObserver());
+ observable.doChange();
+ assertTrue(observable.hasChanged());
+ }
+
+ public void test_clearChanged() {
+ assertFalse(observable.hasChanged());
+ observable.addObserver(observer = new TestObserver());
+ observable.doChange();
+ assertTrue(observable.hasChanged());
+ observable.clearChange();
+ assertFalse(observable.hasChanged());
+ }
+
+ /**
+ * java.util.Observable#notifyObservers()
+ */
+ public void test_notifyObservers() {
+ // Test for method void java.util.Observable.notifyObservers()
+ observable.addObserver(observer = new TestObserver());
+ observable.notifyObservers();
+ assertEquals("Notified when unchnaged", 0, ((TestObserver) observer)
+ .updateCount());
+ ((TestObservable) observable).doChange();
+ observable.notifyObservers();
+ assertEquals("Failed to notify",
+ 1, ((TestObserver) observer).updateCount());
+
+ DeleteTestObserver observer1, observer2;
+ observable.deleteObservers();
+ observable.addObserver(observer1 = new DeleteTestObserver(false));
+ observable.addObserver(observer2 = new DeleteTestObserver(false));
+ observable.doChange();
+ observable.notifyObservers();
+ assertTrue("Failed to notify all", observer1.updateCount() == 1
+ && observer2.updateCount() == 1);
+ assertEquals("Failed to delete all", 0, observable.countObservers());
+
+ observable.addObserver(observer1 = new DeleteTestObserver(false));
+ observable.addObserver(observer2 = new DeleteTestObserver(false));
+ observable.doChange();
+ observable.notifyObservers();
+ assertTrue("Failed to notify all 2", observer1.updateCount() == 1
+ && observer2.updateCount() == 1);
+ assertEquals("Failed to delete all 2", 0, observable.countObservers());
+ }
+
+ /**
+ * java.util.Observable#notifyObservers(java.lang.Object)
+ */
+ public void test_notifyObserversLjava_lang_Object() {
+ // Test for method void
+ // java.util.Observable.notifyObservers(java.lang.Object)
+ Object obj;
+ observable.addObserver(observer = new TestObserver());
+ observable.notifyObservers();
+ assertEquals("Notified when unchanged", 0, ((TestObserver) observer)
+ .updateCount());
+ ((TestObservable) observable).doChange();
+ observable.notifyObservers(obj = new Object());
+ assertEquals("Failed to notify",
+ 1, ((TestObserver) observer).updateCount());
+ assertTrue("Failed to pass Object arg", ((TestObserver) observer).objv
+ .elementAt(0).equals(obj));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ observable = new TestObservable();
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PriorityQueueTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PriorityQueueTest.java
new file mode 100644
index 0000000..9c9d4fe
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PriorityQueueTest.java
@@ -0,0 +1,823 @@
+/* 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.tests.java.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.PriorityQueue;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import junit.framework.TestCase;
+import tests.util.SerializationTester;
+
+public class PriorityQueueTest extends TestCase {
+
+ private static final String SERIALIZATION_FILE_NAME = "serialization/org/apache/harmony/tests/java/util/PriorityQueue.golden.ser";
+
+ /**
+ * java.util.PriorityQueue#iterator()
+ */
+ public void test_iterator() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ Iterator<Integer> iter = integerQueue.iterator();
+ assertNotNull(iter);
+ ArrayList<Integer> iterResult = new ArrayList<Integer>();
+ while (iter.hasNext()) {
+ iterResult.add(iter.next());
+ }
+ Object[] resultArray = iterResult.toArray();
+ Arrays.sort(array);
+ Arrays.sort(resultArray);
+ assertTrue(Arrays.equals(array, resultArray));
+ }
+
+ /**
+ * java.util.PriorityQueue#iterator()
+ */
+ public void test_iterator_empty() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Iterator<Integer> iter = integerQueue.iterator();
+ try {
+ iter.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ iter = integerQueue.iterator();
+ try {
+ iter.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#iterator()
+ */
+ public void test_iterator_outofbound() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ integerQueue.offer(0);
+ Iterator<Integer> iter = integerQueue.iterator();
+ iter.next();
+ try {
+ iter.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+
+ iter = integerQueue.iterator();
+ iter.next();
+ iter.remove();
+ try {
+ iter.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#iterator()
+ */
+ public void test_iterator_remove() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ Iterator<Integer> iter = integerQueue.iterator();
+ assertNotNull(iter);
+ for (int i = 0; i < array.length; i++) {
+ iter.next();
+ if (2 == i) {
+ iter.remove();
+ }
+ }
+ assertEquals(array.length - 1, integerQueue.size());
+
+ iter = integerQueue.iterator();
+ Integer[] newArray = new Integer[array.length - 1];
+ for (int i = 0; i < newArray.length; i++) {
+ newArray[i] = iter.next();
+ }
+
+ Arrays.sort(newArray);
+ for (int i = 0; i < integerQueue.size(); i++) {
+ assertEquals(newArray[i], integerQueue.poll());
+ }
+ }
+
+ public void test_iterator_removeEquals() {
+ PriorityQueue<String> integerQueue = new PriorityQueue<String>(10, new MockComparatorStringByLength());
+ String[] array = { "ONE", "TWO", "THREE", "FOUR", "FIVE" };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ // Try removing an entry that the comparator says is equal
+ assertFalse(integerQueue.remove("123"));
+ assertFalse(integerQueue.remove("one"));
+ assertTrue(integerQueue.remove("THREE"));
+ }
+
+ /**
+ * java.util.PriorityQueue#iterator()
+ */
+ public void test_iterator_remove_illegalState() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ Iterator<Integer> iter = integerQueue.iterator();
+ assertNotNull(iter);
+ try {
+ iter.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ iter.next();
+ iter.remove();
+ try {
+ iter.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * java.util.PriorityQueue.size()
+ */
+ public void test_size() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ assertEquals(0, integerQueue.size());
+ int[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ assertEquals(array.length, integerQueue.size());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue()
+ */
+ public void test_Constructor() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ assertNotNull(queue);
+ assertEquals(0, queue.size());
+ assertNull(queue.comparator());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(int)
+ */
+ public void test_ConstructorI() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>(100);
+ assertNotNull(queue);
+ assertEquals(0, queue.size());
+ assertNull(queue.comparator());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
+ */
+ public void test_ConstructorILjava_util_Comparator() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>(100,
+ (Comparator<Object>) null);
+ assertNotNull(queue);
+ assertEquals(0, queue.size());
+ assertNull(queue.comparator());
+
+ MockComparator<Object> comparator = new MockComparator<Object>();
+ queue = new PriorityQueue<Object>(100, comparator);
+ assertNotNull(queue);
+ assertEquals(0, queue.size());
+ assertEquals(comparator, queue.comparator());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
+ */
+ public void test_ConstructorILjava_util_Comparator_illegalCapacity() {
+ try {
+ new PriorityQueue<Object>(0, new MockComparator<Object>());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ new PriorityQueue<Object>(-1, new MockComparator<Object>());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
+ */
+ public void test_ConstructorILjava_util_Comparator_cast() {
+ MockComparatorCast<Object> objectComparator = new MockComparatorCast<Object>();
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(100,
+ objectComparator);
+ assertNotNull(integerQueue);
+ assertEquals(0, integerQueue.size());
+ assertEquals(objectComparator, integerQueue.comparator());
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ List<Integer> list = Arrays.asList(array);
+ integerQueue.addAll(list);
+ assertEquals(list.size(), integerQueue.size());
+ // just test here no cast exception raises.
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(Collection)
+ */
+ public void test_ConstructorLjava_util_Colleciton() {
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
+ assertEquals(array.length, integerQueue.size());
+ assertNull(integerQueue.comparator());
+ Arrays.sort(array);
+ for (int i = 0; i < array.length; i++) {
+ assertEquals(array[i], integerQueue.poll());
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(Collection)
+ */
+ public void test_ConstructorLjava_util_Colleciton_null() {
+ ArrayList<Object> list = new ArrayList<Object>();
+ list.add(new Float(11));
+ list.add(null);
+ list.add(new Integer(10));
+ try {
+ new PriorityQueue<Object>(list);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(Collection)
+ */
+ public void test_ConstructorLjava_util_Colleciton_non_comparable() {
+ ArrayList<Object> list = new ArrayList<Object>();
+ list.add(new Float(11));
+ list.add(new Integer(10));
+ try {
+ new PriorityQueue<Object>(list);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(Collection)
+ */
+ public void test_ConstructorLjava_util_Colleciton_from_priorityqueue() {
+ String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
+ PriorityQueue<String> queue = new PriorityQueue<String>(4,
+ new MockComparatorStringByLength());
+ for (int i = 0; i < array.length; i++) {
+ queue.offer(array[i]);
+ }
+ Collection<String> c = queue;
+ PriorityQueue<String> constructedQueue = new PriorityQueue<String>(c);
+ assertEquals(queue.comparator(), constructedQueue.comparator());
+ while (queue.size() > 0) {
+ assertEquals(queue.poll(), constructedQueue.poll());
+ }
+ assertEquals(0, constructedQueue.size());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(Collection)
+ */
+ public void test_ConstructorLjava_util_Colleciton_from_sortedset() {
+ int[] array = { 3, 5, 79, -17, 5 };
+ TreeSet<Integer> treeSet = new TreeSet<Integer>(new MockComparator<Integer>());
+ for (int i = 0; i < array.length; i++) {
+ treeSet.add(array[i]);
+ }
+ Collection<? extends Integer> c = treeSet;
+ PriorityQueue<Integer> queue = new PriorityQueue<Integer>(c);
+ assertEquals(treeSet.comparator(), queue.comparator());
+ Iterator<Integer> iter = treeSet.iterator();
+ while (iter.hasNext()) {
+ assertEquals(iter.next(), queue.poll());
+ }
+ assertEquals(0, queue.size());
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(PriorityQueue<? * extends
+ *E>)
+ */
+ public void test_ConstructorLjava_util_PriorityQueue() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ int[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ PriorityQueue<Object> objectQueue = new PriorityQueue<Object>(
+ integerQueue);
+ assertEquals(integerQueue.size(), objectQueue.size());
+ assertEquals(integerQueue.comparator(), objectQueue.comparator());
+ Arrays.sort(array);
+ for (int i = 0; i < array.length; i++) {
+ assertEquals(array[i], objectQueue.poll());
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(PriorityQueue<? * extends
+ *E>)
+ */
+ public void test_ConstructorLjava_util_PriorityQueue_null() {
+ try {
+ new PriorityQueue<Object>((PriorityQueue<Integer>) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(SortedSet<? extends E>)
+ */
+ public void test_ConstructorLjava_util_SortedSet() {
+ int[] array = { 3, 5, 79, -17, 5 };
+ TreeSet<Integer> treeSet = new TreeSet<Integer>();
+ for (int i = 0; i < array.length; i++) {
+ treeSet.add(array[i]);
+ }
+ PriorityQueue<Integer> queue = new PriorityQueue<Integer>(treeSet);
+ Iterator<Integer> iter = treeSet.iterator();
+ while (iter.hasNext()) {
+ assertEquals(iter.next(), queue.poll());
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#PriorityQueue(SortedSet<? extends E>)
+ */
+ public void test_ConstructorLjava_util_SortedSet_null() {
+ try {
+ new PriorityQueue<Integer>((SortedSet<? extends Integer>) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#offer(Object)
+ */
+ public void test_offerLjava_lang_Object() {
+ PriorityQueue<String> queue = new PriorityQueue<String>(10,
+ new MockComparatorStringByLength());
+ String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
+ for (int i = 0; i < array.length; i++) {
+ queue.offer(array[i]);
+ }
+ String[] sortedArray = { "AA", "AAAA", "AAAAA", "AAAAAAAA" };
+ for (int i = 0; i < sortedArray.length; i++) {
+ assertEquals(sortedArray[i], queue.poll());
+ }
+ assertEquals(0, queue.size());
+ assertNull(queue.poll());
+ }
+
+ /**
+ * java.util.PriorityQueue#offer(Object)
+ */
+ public void test_offerLjava_lang_Object_null() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ try {
+ queue.offer(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#offer(Object)
+ */
+ public void test_offer_Ljava_lang_Object_non_Comparable() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ queue.offer(new Integer(10));
+ try {
+ queue.offer(new Float(1.3));
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ queue = new PriorityQueue<Object>();
+ queue.offer(new Integer(10));
+ try {
+ queue.offer(new Object());
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#poll()
+ */
+ public void test_poll() {
+ PriorityQueue<String> stringQueue = new PriorityQueue<String>();
+ String[] array = { "MYTESTSTRING", "AAAAA", "BCDEF", "ksTRD", "AAAAA" };
+ for (int i = 0; i < array.length; i++) {
+ stringQueue.offer(array[i]);
+ }
+ Arrays.sort(array);
+ for (int i = 0; i < array.length; i++) {
+ assertEquals(array[i], stringQueue.poll());
+ }
+ assertEquals(0, stringQueue.size());
+ assertNull(stringQueue.poll());
+ }
+
+ /**
+ * java.util.PriorityQueue#poll()
+ */
+ public void test_poll_empty() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ assertEquals(0, queue.size());
+ assertNull(queue.poll());
+ }
+
+ /**
+ * java.util.PriorityQueue#peek()
+ */
+ public void test_peek() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ int[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.add(array[i]);
+ }
+ Arrays.sort(array);
+ assertEquals(new Integer(array[0]), integerQueue.peek());
+ assertEquals(new Integer(array[0]), integerQueue.peek());
+ }
+
+ /**
+ * java.util.PriorityQueue#peek()
+ */
+ public void test_peek_empty() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ assertEquals(0, queue.size());
+ assertNull(queue.peek());
+ assertNull(queue.peek());
+ }
+
+ /**
+ * java.util.PriorityQueue#Clear()
+ */
+ public void test_clear() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ int[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.offer(array[i]);
+ }
+ integerQueue.clear();
+ assertTrue(integerQueue.isEmpty());
+ }
+
+ /**
+ * java.util.PriorityQueue#add(Object)
+ */
+ public void test_add_Ljava_lang_Object() {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.add(array[i]);
+ }
+ Arrays.sort(array);
+ assertEquals(array.length, integerQueue.size());
+ for (int i = 0; i < array.length; i++) {
+ assertEquals(array[i], integerQueue.poll());
+ }
+ assertEquals(0, integerQueue.size());
+ }
+
+ /**
+ * java.util.PriorityQueue#add(Object)
+ */
+ public void test_add_Ljava_lang_Object_null() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ try {
+ queue.add(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#add(Object)
+ */
+ public void test_add_Ljava_lang_Object_non_Comparable() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ queue.add(new Integer(10));
+ try {
+ queue.add(new Float(1.3));
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ queue = new PriorityQueue<Object>();
+ queue.add(new Integer(10));
+ try {
+ queue.add(new Object());
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PriorityQueue#remove(Object)
+ */
+ public void test_remove_Ljava_lang_Object() {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
+ assertTrue(integerQueue.remove(16));
+ Integer[] newArray = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 39 };
+ Arrays.sort(newArray);
+ for (int i = 0; i < newArray.length; i++) {
+ assertEquals(newArray[i], integerQueue.poll());
+ }
+ assertEquals(0, integerQueue.size());
+ }
+
+ /**
+ * java.util.PriorityQueue#remove(Object)
+ */
+ public void test_remove_Ljava_lang_Object_using_comparator() {
+ PriorityQueue<String> queue = new PriorityQueue<String>(10,
+ new MockComparatorStringByLength());
+ String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
+ for (int i = 0; i < array.length; i++) {
+ queue.offer(array[i]);
+ }
+ assertFalse(queue.contains("BB"));
+ assertTrue(queue.remove("AA"));
+ }
+
+ /**
+ * java.util.PriorityQueue#remove(Object)
+ */
+ public void test_remove_Ljava_lang_Object_not_exists() {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
+ assertFalse(integerQueue.remove(111));
+ assertFalse(integerQueue.remove(null));
+ assertFalse(integerQueue.remove(""));
+ }
+
+ /**
+ * java.util.PriorityQueue#remove(Object)
+ */
+ public void test_remove_Ljava_lang_Object_null() {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
+ assertFalse(integerQueue.remove(null));
+ }
+
+ /**
+ * java.util.PriorityQueue#remove(Object)
+ */
+ public void test_remove_Ljava_lang_Object_not_Compatible() {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
+ assertFalse(integerQueue.remove(new Float(1.3F)));
+
+ // although argument element type is not compatible with those in queue,
+ // but comparator supports it.
+ MockComparator<Object> comparator = new MockComparator<Object>();
+ PriorityQueue<Integer> integerQueue1 = new PriorityQueue<Integer>(100,
+ comparator);
+ integerQueue1.offer(1);
+ assertFalse(integerQueue1.remove(new Float(1.3F)));
+
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ Object o = new Object();
+ queue.offer(o);
+ assertTrue(queue.remove(o));
+ }
+
+ /**
+ * java.util.PriorityQueue#comparator()
+ */
+ public void test_comparator() {
+ PriorityQueue<Object> queue = new PriorityQueue<Object>();
+ assertNull(queue.comparator());
+
+ MockComparator<Object> comparator = new MockComparator<Object>();
+ queue = new PriorityQueue<Object>(100, comparator);
+ assertEquals(comparator, queue.comparator());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void test_Serialization() throws Exception {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
+ list);
+ PriorityQueue<Integer> destIntegerQueue = (PriorityQueue<Integer>) SerializationTester
+ .getDeserilizedObject(srcIntegerQueue);
+ Arrays.sort(array);
+ for (int i = 0; i < array.length; i++) {
+ assertEquals(array[i], destIntegerQueue.poll());
+ }
+ assertEquals(0, destIntegerQueue.size());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ public void test_Serialization_casting() throws Exception {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
+ list);
+ PriorityQueue<String> destStringQueue = (PriorityQueue<String>) SerializationTester
+ .getDeserilizedObject(srcIntegerQueue);
+ // will not incur class cast exception.
+ Object o = destStringQueue.peek();
+ Arrays.sort(array);
+ Integer I = (Integer) o;
+ assertEquals(array[0], I);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void test_SerializationCompatibility_cast() throws Exception {
+ Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
+ List<Integer> list = Arrays.asList(array);
+ PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
+ list);
+ PriorityQueue<String> destStringQueue = (PriorityQueue<String>) SerializationTester
+ .readObject(srcIntegerQueue, SERIALIZATION_FILE_NAME);
+
+ // will not incur class cast exception.
+ Object o = destStringQueue.peek();
+ Arrays.sort(array);
+ Integer I = (Integer) o;
+ assertEquals(array[0], I);
+ }
+
+ /**
+ * {@link PriorityQueue#contains(Object)}
+ */
+ public void test_contains() throws Exception {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.add(array[i]);
+ }
+ for (int i = 0; i < array.length; i++) {
+ assertTrue(integerQueue.contains(array[i]));
+ }
+ assertFalse(integerQueue.contains(null));
+ }
+
+ /**
+ * {@link PriorityQueue#toArray()}
+ */
+ public void test_toArray() throws Exception {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.add(array[i]);
+ }
+ Object[] returnArray = integerQueue.toArray();
+ assertEquals(returnArray.length, integerQueue.size());
+ for (int i = 0; i < returnArray.length; i++) {
+ assertTrue(integerQueue.contains(returnArray[i]));
+ }
+ }
+
+ /**
+ * {@link PriorityQueue#toArray(T[])}
+ */
+ public void test_toArray_$T() throws Exception {
+ PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
+ Integer[] array = { 2, 45, 7, -12, 9 };
+ for (int i = 0; i < array.length; i++) {
+ integerQueue.add(array[i]);
+ }
+ Object[] returnArray = integerQueue.toArray(new Integer[0]);
+ assertEquals(returnArray.length, integerQueue.size());
+ for (int i = 0; i < returnArray.length; i++) {
+ assertTrue(integerQueue.contains(returnArray[i]));
+ }
+ returnArray = integerQueue.toArray(new Integer[10]);
+ assertEquals(10, returnArray.length);
+ for (int i = 0; i < array.length; i++) {
+ assertTrue(integerQueue.contains(returnArray[i]));
+ }
+ for (int i = array.length; i < 10; i++) {
+ assertNull(returnArray[i]);
+ }
+ try {
+ integerQueue.toArray(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ integerQueue.toArray(new String[1]);
+ fail("should throw ArrayStoreException");
+ } catch (ArrayStoreException e) {
+ // expected
+ }
+ }
+
+ private static class MockComparator<E> implements Comparator<E> {
+
+ public int compare(E object1, E object2) {
+ int hashcode1 = object1.hashCode();
+ int hashcode2 = object2.hashCode();
+ if (hashcode1 > hashcode2) {
+ return 1;
+ } else if (hashcode1 == hashcode2) {
+ return 0;
+ } else {
+ return -1;
+ }
+ }
+ }
+
+ private static class MockComparatorStringByLength implements
+ Comparator<String> {
+
+ public int compare(String object1, String object2) {
+ int length1 = object1.length();
+ int length2 = object2.length();
+ if (length1 > length2) {
+ return 1;
+ } else if (length1 == length2) {
+ return 0;
+ } else {
+ return -1;
+ }
+ }
+
+ }
+
+ private static class MockComparatorCast<E> implements Comparator<E> {
+
+ public int compare(E object1, E object2) {
+ return 0;
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertiesTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertiesTest.java
new file mode 100644
index 0000000..27cae4e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertiesTest.java
@@ -0,0 +1,1157 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.BufferedReader;
+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.PrintStream;
+import java.io.PrintWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.InvalidPropertiesFormatException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Scanner;
+import java.util.Set;
+import tests.support.resource.Support_Resources;
+
+public class PropertiesTest extends junit.framework.TestCase {
+
+ Properties tProps;
+
+ byte[] propsFile;
+
+ /**
+ * java.util.Properties#Properties()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.Properties()
+ Properties p = new Properties();
+ // do something to avoid getting a variable unused warning
+ p.clear();
+ assertTrue("Created incorrect Properties", true);
+ }
+
+ public void test_loadLjava_io_InputStream_NPE() throws Exception {
+ Properties p = new Properties();
+ try {
+ p.load((InputStream) null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void test_loadsave() throws Exception {
+ Properties p = new Properties();
+ try {
+ p.load((InputStream) null);
+ fail("should throw NPE");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Properties#Properties(java.util.Properties)
+ */
+ public void test_ConstructorLjava_util_Properties() {
+ Properties systemProperties = System.getProperties();
+ Properties properties = new Properties(systemProperties);
+ Enumeration<?> propertyNames = systemProperties.propertyNames();
+ String propertyName = null;
+ while (propertyNames.hasMoreElements()) {
+ propertyName = (String) propertyNames.nextElement();
+ assertEquals("failed to construct correct properties",
+ systemProperties.getProperty(propertyName),
+ properties.getProperty(propertyName));
+ }
+ }
+
+ /**
+ * java.util.Properties#getProperty(java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.util.Properties.getProperty(java.lang.String)
+ assertEquals("Did not retrieve property", "this is a test property",
+ ((String) tProps.getProperty("test.prop")));
+ }
+
+ /**
+ * java.util.Properties#getProperty(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_StringLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.util.Properties.getProperty(java.lang.String, java.lang.String)
+ assertEquals("Did not retrieve property", "this is a test property",
+ ((String) tProps.getProperty("test.prop", "Blarg")));
+ assertEquals("Did not return default value", "Gabba", ((String) tProps
+ .getProperty("notInThere.prop", "Gabba")));
+ }
+
+ /**
+ * java.util.Properties#getProperty(java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_String2() {
+ // regression test for HARMONY-3518
+ MyProperties props = new MyProperties();
+ assertNull(props.getProperty("key"));
+ }
+
+ /**
+ * java.util.Properties#getProperty(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_getPropertyLjava_lang_StringLjava_lang_String2() {
+ // regression test for HARMONY-3518
+ MyProperties props = new MyProperties();
+ assertEquals("defaultValue", props.getProperty("key", "defaultValue"));
+ }
+
+ // regression testing for HARMONY-3518
+ static class MyProperties extends Properties {
+ public synchronized Object get(Object key) {
+ return getProperty((String) key); // assume String
+ }
+ }
+
+ /**
+ * java.util.Properties#list(java.io.PrintStream)
+ */
+ public void test_listLjava_io_PrintStream() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(baos);
+ Properties myProps = new Properties();
+ myProps.setProperty("Abba", "Cadabra");
+ myProps.setProperty("Open", "Sesame");
+ myProps.setProperty("LongProperty",
+ "a long long long long long long long property");
+ myProps.list(ps);
+ ps.flush();
+ String propList = baos.toString();
+ assertTrue("Property list innacurate",
+ propList.indexOf("Abba=Cadabra") >= 0);
+ assertTrue("Property list innacurate",
+ propList.indexOf("Open=Sesame") >= 0);
+ assertTrue("property list do not conatins \"...\"", propList
+ .indexOf("...") != -1);
+
+ ps = null;
+ try {
+ myProps.list(ps);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Properties#list(java.io.PrintWriter)
+ */
+ public void test_listLjava_io_PrintWriter() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ PrintWriter pw = new PrintWriter(baos);
+ Properties myProps = new Properties();
+ myProps.setProperty("Abba", "Cadabra");
+ myProps.setProperty("Open", "Sesame");
+ myProps.setProperty("LongProperty",
+ "a long long long long long long long property");
+ myProps.list(pw);
+ pw.flush();
+ String propList = baos.toString();
+ assertTrue("Property list innacurate",
+ propList.indexOf("Abba=Cadabra") >= 0);
+ assertTrue("Property list innacurate",
+ propList.indexOf("Open=Sesame") >= 0);
+ pw = null;
+ try {
+ myProps.list(pw);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Properties#load(java.io.InputStream)
+ */
+ public void test_loadLjava_io_InputStream() {
+ // Test for method void java.util.Properties.load(java.io.InputStream)
+ Properties prop = null;
+ try {
+ InputStream is;
+ prop = new Properties();
+ prop.load(is = new ByteArrayInputStream(writeProperties()));
+ is.close();
+ } catch (Exception e) {
+ fail("Exception during load test : " + e.getMessage());
+ }
+ assertEquals("Failed to load correct properties", "harmony.tests", prop
+ .getProperty("test.pkg"));
+ assertNull("Load failed to parse incorrectly", prop
+ .getProperty("commented.entry"));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream("=".getBytes()));
+ } catch (IOException e) {
+ // expected
+ }
+ assertTrue("Failed to add empty key", prop.get("").equals(""));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream(" = ".getBytes()));
+ } catch (IOException e) {
+ // expected
+ }
+ assertTrue("Failed to add empty key2", prop.get("").equals(""));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream(" a= b".getBytes()));
+ } catch (IOException e) {
+ // expected
+ }
+ assertEquals("Failed to ignore whitespace", "b", prop.get("a"));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream(" a b".getBytes()));
+ } catch (IOException e) {
+ // expected
+ }
+ assertEquals("Failed to interpret whitespace as =", "b", prop.get("a"));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream("#\u008d\u00d2\na=\u008d\u00d3"
+ .getBytes("ISO8859_1")));
+ } catch (IOException e) {
+ // expected
+ }
+ assertEquals("Failed to parse chars >= 0x80", "\u008d\u00d3", prop
+ .get("a"));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream(
+ "#properties file\r\nfred=1\r\n#last comment"
+ .getBytes("ISO8859_1")));
+ } catch (IOException e) {
+ // expected
+ } catch (IndexOutOfBoundsException e) {
+ fail("IndexOutOfBoundsException when last line is a comment with no line terminator");
+ }
+ assertEquals("Failed to load when last line contains a comment", "1",
+ prop.get("fred"));
+ }
+
+ /**
+ * java.util.Properties#load(java.io.InputStream)
+ */
+ public void test_loadLjava_io_InputStream_subtest0() {
+ try {
+ InputStream is = Support_Resources
+ .getStream("hyts_PropertiesTest.properties");
+ Properties props = new Properties();
+ props.load(is);
+ is.close();
+ assertEquals("1", "\n \t \f", props.getProperty(" \r"));
+ assertEquals("2", "a", props.getProperty("a"));
+ assertEquals("3", "bb as,dn ", props.getProperty("b"));
+ assertEquals("4", ":: cu", props.getProperty("c\r \t\nu"));
+ assertEquals("5", "bu", props.getProperty("bu"));
+ assertEquals("6", "d\r\ne=e", props.getProperty("d"));
+ assertEquals("7", "fff", props.getProperty("f"));
+ assertEquals("8", "g", props.getProperty("g"));
+ assertEquals("9", "", props.getProperty("h h"));
+ assertEquals("10", "i=i", props.getProperty(" "));
+ assertEquals("11", " j", props.getProperty("j"));
+ assertEquals("12", " c", props.getProperty("space"));
+ assertEquals("13", "\\", props.getProperty("dblbackslash"));
+ } catch (IOException e) {
+ fail("Unexpected: " + e);
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.Properties#load(java.io.Reader)
+ * @since 1.6
+ */
+ public void test_loadLjava_io_Reader() throws IOException {
+ Properties prop = null;
+ try {
+ InputStream is;
+ prop = new Properties();
+ is = new ByteArrayInputStream(writeProperties());
+ prop.load(new InputStreamReader(is));
+ is.close();
+ } catch (Exception e) {
+ fail("Exception during load test : " + e.getMessage());
+ }
+ assertEquals("Failed to load correct properties", "harmony.tests", prop
+ .getProperty("test.pkg"));
+ assertNull("Load failed to parse incorrectly", prop
+ .getProperty("commented.entry"));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("=".getBytes()));
+ assertEquals("Failed to add empty key", "", prop.get(""));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream(" = ".getBytes()));
+ assertEquals("Failed to add empty key2", "", prop.get(""));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream(" a= b".getBytes()));
+ assertEquals("Failed to ignore whitespace", "b", prop.get("a"));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream(" a b".getBytes()));
+ assertEquals("Failed to interpret whitespace as =", "b", prop.get("a"));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("#comment\na=value"
+ .getBytes("UTF-8")));
+ assertEquals("value", prop.getProperty("a"));
+
+ prop = new Properties();
+ prop.load(new InputStreamReader(new ByteArrayInputStream(
+ "#\u008d\u00d2\na=\u008d\u00d3".getBytes("UTF-8"))));
+ try {
+ prop
+ .load(new InputStreamReader(new ByteArrayInputStream(
+ "#\u008d\u00d2\na=\\\\u008d\\\\\\uu00d3"
+ .getBytes("UTF-8"))));
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ prop = new Properties();
+ try {
+ prop.load(new InputStreamReader(new ByteArrayInputStream(
+ "#properties file\r\nfred=1\r\n#last comment"
+ .getBytes("ISO8859_1"))));
+ } catch (IndexOutOfBoundsException e) {
+ fail("IndexOutOfBoundsException when last line is a comment with no line terminator");
+ }
+ assertEquals("Failed to load when last line contains a comment", "1",
+ prop.get("fred"));
+
+ // Regression tests for HARMONY-5414
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("a=\\u1234z".getBytes()));
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream("a=\\u123".getBytes()));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ prop = new Properties();
+ try {
+ prop.load(new ByteArrayInputStream("a=\\u123z".getBytes()));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // Expected
+ }
+
+ prop = new Properties();
+ Properties expected = new Properties();
+ expected.put("a", "\u0000");
+ prop.load(new ByteArrayInputStream("a=\\".getBytes()));
+ assertEquals("Failed to read trailing slash value", expected, prop);
+
+ prop = new Properties();
+ expected = new Properties();
+ expected.put("a", "\u1234\u0000");
+ prop.load(new ByteArrayInputStream("a=\\u1234\\".getBytes()));
+ assertEquals("Failed to read trailing slash value #2", expected, prop);
+
+ prop = new Properties();
+ expected = new Properties();
+ expected.put("a", "q");
+ prop.load(new ByteArrayInputStream("a=\\q".getBytes()));
+ assertEquals("Failed to read slash value #3", expected, prop);
+ }
+
+ /**
+ * java.util.Properties#load(java.io.InputStream)
+ */
+ public void test_loadLjava_io_InputStream_Special() throws IOException {
+ // Test for method void java.util.Properties.load(java.io.InputStream)
+ Properties prop = null;
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("=".getBytes()));
+ assertTrue("Failed to add empty key", prop.get("").equals(""));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("=\r\n".getBytes()));
+ assertTrue("Failed to add empty key", prop.get("").equals(""));
+
+ prop = new Properties();
+ prop.load(new ByteArrayInputStream("=\n\r".getBytes()));
+ assertTrue("Failed to add empty key", prop.get("").equals(""));
+ }
+
+ /**
+ * @throws IOException
+ * java.util.Properties#load(java.io.Reader)
+ * @since 1.6
+ */
+ public void test_loadLjava_io_Reader_subtest0() throws IOException {
+ InputStream is = Support_Resources
+ .getStream("hyts_PropertiesTest.properties");
+ Properties props = new Properties();
+ props.load(new InputStreamReader(is));
+ is.close();
+ assertEquals("1", "\n \t \f", props.getProperty(" \r"));
+ assertEquals("2", "a", props.getProperty("a"));
+ assertEquals("3", "bb as,dn ", props.getProperty("b"));
+ assertEquals("4", ":: cu", props.getProperty("c\r \t\nu"));
+ assertEquals("5", "bu", props.getProperty("bu"));
+ assertEquals("6", "d\r\ne=e", props.getProperty("d"));
+ assertEquals("7", "fff", props.getProperty("f"));
+ assertEquals("8", "g", props.getProperty("g"));
+ assertEquals("9", "", props.getProperty("h h"));
+ assertEquals("10", "i=i", props.getProperty(" "));
+ assertEquals("11", " j", props.getProperty("j"));
+ assertEquals("12", " c", props.getProperty("space"));
+ assertEquals("13", "\\", props.getProperty("dblbackslash"));
+ }
+
+ /**
+ * {@link java.util.Properties#stringPropertyNames()}
+ * @since 1.6
+ */
+ public void test_stringPropertyNames() {
+ Set<String> set = tProps.stringPropertyNames();
+ assertEquals(2, set.size());
+ assertTrue(set.contains("test.prop"));
+ assertTrue(set.contains("bogus.prop"));
+ assertNotSame(set, tProps.stringPropertyNames());
+
+ set = new Properties().stringPropertyNames();
+ assertEquals(0, set.size());
+
+ set = new Properties(System.getProperties()).stringPropertyNames();
+ assertTrue(set.size() > 0);
+
+ tProps = new Properties(tProps);
+ tProps.put("test.prop", "anotherValue");
+ tProps.put("3rdKey", "3rdValue");
+ set = tProps.stringPropertyNames();
+ assertEquals(3, set.size());
+ assertTrue(set.contains("test.prop"));
+ assertTrue(set.contains("bogus.prop"));
+ assertTrue(set.contains("3rdKey"));
+
+ tProps.put(String.class, "valueOfNonStringKey");
+ set = tProps.stringPropertyNames();
+ assertEquals(3, set.size());
+ assertTrue(set.contains("test.prop"));
+ assertTrue(set.contains("bogus.prop"));
+ assertTrue(set.contains("3rdKey"));
+
+ tProps.put("4thKey", "4thValue");
+ assertEquals(4, tProps.size());
+ assertEquals(3, set.size());
+
+ try {
+ set.add("another");
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ /**
+ * {@link java.util.Properties#stringPropertyNames()}
+ * @since 1.6
+ */
+ public void test_stringPropertyNames_scenario1() {
+ String[] keys = new String[] { "key1", "key2", "key3" };
+ String[] values = new String[] { "value1", "value2", "value3" };
+ List<String> keyList = Arrays.asList(keys);
+
+ Properties properties = new Properties();
+ for (int index = 0; index < keys.length; index++) {
+ properties.setProperty(keys[index], values[index]);
+ }
+
+ properties = new Properties(properties);
+ Set<String> nameSet = properties.stringPropertyNames();
+ assertEquals(keys.length, nameSet.size());
+ Iterator<String> iterator = nameSet.iterator();
+ while (iterator.hasNext()) {
+ assertTrue(keyList.contains(iterator.next()));
+ }
+
+ Enumeration<?> nameEnum = properties.propertyNames();
+ int count = 0;
+ while (nameEnum.hasMoreElements()) {
+ count++;
+ assertTrue(keyList.contains(nameEnum.nextElement()));
+ }
+ assertEquals(keys.length, count);
+
+ properties = new Properties(properties);
+ nameSet = properties.stringPropertyNames();
+ assertEquals(keys.length, nameSet.size());
+ iterator = nameSet.iterator();
+ while (iterator.hasNext()) {
+ assertTrue(keyList.contains(iterator.next()));
+ }
+
+ nameEnum = properties.propertyNames();
+ count = 0;
+ while (nameEnum.hasMoreElements()) {
+ count++;
+ assertTrue(keyList.contains(nameEnum.nextElement()));
+ }
+ assertEquals(keys.length, count);
+ }
+
+ /**
+ * {@link java.util.Properties#stringPropertyNames()}
+ * @since 1.6
+ */
+ public void test_stringPropertyNames_scenario2() {
+ String[] defaultKeys = new String[] { "defaultKey1", "defaultKey2",
+ "defaultKey3", "defaultKey4", "defaultKey5", "defaultKey6" };
+ String[] defaultValues = new String[] { "defaultValue1",
+ "defaultValue2", "defaultValue3", "defaultValue4",
+ "defaultValue5", "defaultValue6" };
+ List<String> keyList = new ArrayList<String>();
+ Properties defaults = new Properties();
+ for (int index = 0; index < 3; index++) {
+ defaults.setProperty(defaultKeys[index], defaultValues[index]);
+ keyList.add(defaultKeys[index]);
+ }
+
+ String[] keys = new String[] { "key1", "key2", "key3" };
+ String[] values = new String[] { "value1", "value2", "value3" };
+ Properties properties = new Properties(defaults);
+ for (int index = 0; index < keys.length; index++) {
+ properties.setProperty(keys[index], values[index]);
+ keyList.add(keys[index]);
+ }
+
+ Set<String> nameSet = properties.stringPropertyNames();
+ assertEquals(keyList.size(), nameSet.size());
+ Iterator<String> iterator = nameSet.iterator();
+ while (iterator.hasNext()) {
+ assertTrue(keyList.contains(iterator.next()));
+ }
+
+ Enumeration<?> nameEnum = properties.propertyNames();
+ int count = 0;
+ while (nameEnum.hasMoreElements()) {
+ count++;
+ assertTrue(keyList.contains(nameEnum.nextElement()));
+ }
+ assertEquals(keyList.size(), count);
+
+ for (int index = 3; index < defaultKeys.length; index++) {
+ defaults.setProperty(defaultKeys[index], defaultValues[index]);
+ keyList.add(defaultKeys[index]);
+ }
+
+ nameSet = properties.stringPropertyNames();
+ assertEquals(keyList.size(), nameSet.size());
+ iterator = nameSet.iterator();
+ while (iterator.hasNext()) {
+ assertTrue(keyList.contains(iterator.next()));
+ }
+
+ nameEnum = properties.propertyNames();
+ count = 0;
+ while (nameEnum.hasMoreElements()) {
+ count++;
+ assertTrue(keyList.contains(nameEnum.nextElement()));
+ }
+ assertEquals(keyList.size(), count);
+ }
+
+ /**
+ * java.util.Properties#save(java.io.OutputStream, java.lang.String)
+ */
+ public void test_saveLjava_io_OutputStreamLjava_lang_String() {
+ // Test for method void java.util.Properties.save(java.io.OutputStream,
+ // java.lang.String)
+ Properties myProps = new Properties();
+ Properties myProps2 = new Properties();
+
+ myProps.setProperty("Property A", "aye");
+ myProps.setProperty("Property B", "bee");
+ myProps.setProperty("Property C", "see");
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ myProps.save(out, "A Header");
+ out.close();
+ ByteArrayInputStream in = new ByteArrayInputStream(out
+ .toByteArray());
+ myProps2.load(in);
+ in.close();
+ } catch (IOException ioe) {
+ fail("IOException occurred reading/writing file : "
+ + ioe.getMessage());
+ }
+
+ Enumeration e = myProps.propertyNames();
+ String nextKey;
+ while (e.hasMoreElements()) {
+ nextKey = (String) e.nextElement();
+ assertEquals("Stored property list not equal to original", myProps
+ .getProperty(nextKey), myProps2.getProperty(nextKey));
+ }
+ }
+
+ /**
+ * java.util.Properties#setProperty(java.lang.String,
+ *java.lang.String)
+ */
+ public void test_setPropertyLjava_lang_StringLjava_lang_String() {
+ // Test for method java.lang.Object
+ // java.util.Properties.setProperty(java.lang.String, java.lang.String)
+ Properties myProps = new Properties();
+ myProps.setProperty("Yoink", "Yabba");
+ assertEquals("Failed to set property", "Yabba", myProps
+ .getProperty("Yoink"));
+ myProps.setProperty("Yoink", "Gab");
+ assertEquals("Failed to reset property", "Gab", myProps
+ .getProperty("Yoink"));
+ }
+
+ /**
+ * java.util.Properties#store(java.io.OutputStream, java.lang.String)
+ */
+ public void test_storeLjava_io_OutputStreamLjava_lang_String() {
+ // Test for method void java.util.Properties.store(java.io.OutputStream,
+ // java.lang.String)
+ Properties myProps = new Properties();
+ Properties myProps2 = new Properties();
+ Enumeration e;
+ String nextKey;
+
+ myProps.put("Property A", " aye\\\f\t\n\r\b");
+ myProps.put("Property B", "b ee#!=:");
+ myProps.put("Property C", "see");
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ myProps.store(out, "A Header");
+ out.close();
+ ByteArrayInputStream in = new ByteArrayInputStream(out
+ .toByteArray());
+ myProps2.load(in);
+ in.close();
+ } catch (IOException ioe) {
+ fail("IOException occurred reading/writing file : "
+ + ioe.getMessage());
+ }
+
+ e = myProps.propertyNames();
+ while (e.hasMoreElements()) {
+ nextKey = (String) e.nextElement();
+ assertTrue("Stored property list not equal to original", myProps2
+ .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
+ }
+
+ }
+
+ /**
+ * @throws IOException
+ * java.util.Properties#store(java.io.Writer, java.lang.String)
+ * @since 1.6
+ */
+ public void test_storeLjava_io_WriterLjava_lang_String() throws IOException {
+ Properties myProps = new Properties();
+ Properties myProps2 = new Properties();
+
+ myProps.put("Property A", " aye\\\f\t\n\r\b");
+ myProps.put("Property B", "b ee#!=:");
+ myProps.put("Property C", "see");
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ myProps.store(new OutputStreamWriter(out), "A Header");
+ Scanner scanner = new Scanner(out.toString());
+ assertTrue(scanner.nextLine().startsWith("#A Header"));
+ assertTrue(scanner.nextLine().startsWith("#"));
+ out.close();
+ ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+ myProps2.load(in);
+ in.close();
+
+ Enumeration e = myProps.propertyNames();
+ String nextKey;
+ while (e.hasMoreElements()) {
+ nextKey = (String) e.nextElement();
+ assertTrue("Stored property list not equal to original", myProps2
+ .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
+ }
+
+ try {
+ myProps.store((Writer) null, "some comments");
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e1) {
+ // expected
+ }
+
+ myProps.put(String.class, "wrong type");
+ try {
+ myProps.store(new OutputStreamWriter(new ByteArrayOutputStream()),
+ "some comments");
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e1) {
+ // expected
+ }
+ myProps.remove(String.class);
+ myProps.store(new OutputStreamWriter(new ByteArrayOutputStream()),
+ "some comments");
+ // it is OK
+ myProps.put("wrong type", String.class);
+ try {
+ myProps.store(new OutputStreamWriter(new ByteArrayOutputStream()),
+ "some comments");
+ fail("Should throw ClassCastException");
+ } catch (ClassCastException e1) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Properties#loadFromXML(java.io.InputStream)
+ */
+ public void test_loadFromXMLLjava_io_InputStream() throws Exception {
+ // Test for method void
+ // java.util.Properties.loadFromXML(java.io.InputStream)
+ Properties prop = null;
+ try {
+ InputStream is;
+ prop = new Properties();
+ prop.loadFromXML(is = new ByteArrayInputStream(
+ writePropertiesXMLUTF_8()));
+ is.close();
+ } catch (Exception e) {
+ fail("Exception during load test : " + e.getMessage());
+ }
+ assertEquals("Failed to load correct properties", "value3", prop
+ .getProperty("key3"));
+ assertEquals("Failed to load correct properties", "value1", prop
+ .getProperty("key1"));
+
+ try {
+ InputStream is;
+ prop = new Properties();
+ prop.loadFromXML(is = new ByteArrayInputStream(
+ writePropertiesXMLISO_8859_1()));
+ is.close();
+ } catch (Exception e) {
+ fail("Exception during load test : " + e.getMessage());
+ }
+ assertEquals("Failed to load correct properties", "value2", prop
+ .getProperty("key2"));
+ assertEquals("Failed to load correct properties", "value1", prop
+ .getProperty("key1"));
+
+ try {
+ prop.loadFromXML(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.Properties#storeToXML(java.io.OutputStream,
+ *java.lang.String, java.lang.String)
+ */
+ public void test_storeToXMLLjava_io_OutputStreamLjava_lang_StringLjava_lang_String()
+ throws Exception {
+ // Test for method void
+ // java.util.Properties.storeToXML(java.io.OutputStream,
+ // java.lang.String, java.lang.String)
+ Properties myProps = new Properties();
+ Properties myProps2 = new Properties();
+ Enumeration e;
+ String nextKey;
+
+ myProps.setProperty("key1", "value1");
+ myProps.setProperty("key2", "value2");
+ myProps.setProperty("key3", "value3");
+ myProps.setProperty("<a>key4</a>", "\"value4");
+ myProps.setProperty("key5 ", "<h>value5</h>");
+ myProps.setProperty("<a>key6</a>", " <h>value6</h> ");
+ myProps.setProperty("<comment>key7</comment>", "value7");
+ myProps.setProperty(" key8 ", "<comment>value8</comment>");
+ myProps.setProperty("&lt;key9&gt;", "\u0027value9");
+ myProps.setProperty("key10\"", "&lt;value10&gt;");
+ myProps.setProperty("&amp;key11&amp;", "value11");
+ myProps.setProperty("key12", "&amp;value12&amp;");
+ myProps.setProperty("<a>&amp;key13&lt;</a>",
+ "&amp;&value13<b>&amp;</b>");
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ // store in UTF-8 encoding
+ myProps.storeToXML(out, "comment");
+ out.close();
+ ByteArrayInputStream in = new ByteArrayInputStream(out
+ .toByteArray());
+ myProps2.loadFromXML(in);
+ in.close();
+ } catch (InvalidPropertiesFormatException ipfe) {
+ fail("InvalidPropertiesFormatException occurred reading file: "
+ + ipfe.getMessage());
+ } catch (IOException ioe) {
+ fail("IOException occurred reading/writing file : "
+ + ioe.getMessage());
+ }
+
+ e = myProps.propertyNames();
+ while (e.hasMoreElements()) {
+ nextKey = (String) e.nextElement();
+ assertTrue("Stored property list not equal to original", myProps2
+ .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
+ }
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ // store in ISO-8859-1 encoding
+ myProps.storeToXML(out, "comment", "ISO-8859-1");
+ out.close();
+ ByteArrayInputStream in = new ByteArrayInputStream(out
+ .toByteArray());
+ myProps2 = new Properties();
+ myProps2.loadFromXML(in);
+ in.close();
+ } catch (InvalidPropertiesFormatException ipfe) {
+ fail("InvalidPropertiesFormatException occurred reading file: "
+ + ipfe.getMessage());
+ } catch (IOException ioe) {
+ fail("IOException occurred reading/writing file : "
+ + ioe.getMessage());
+ }
+
+ e = myProps.propertyNames();
+ while (e.hasMoreElements()) {
+ nextKey = (String) e.nextElement();
+ assertTrue("Stored property list not equal to original", myProps2
+ .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
+ }
+
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ myProps.storeToXML(out, null, null);
+ fail("should throw nullPointerException");
+ } catch (NullPointerException ne) {
+ // expected
+ }
+ }
+
+ /**
+ * if loading from single line like "hello" without "\n\r" neither "=", it
+ * should be same as loading from "hello="
+ */
+ public void testLoadSingleLine() throws Exception {
+ Properties props = new Properties();
+ InputStream sr = new ByteArrayInputStream("hello".getBytes());
+ props.load(sr);
+ assertEquals(1, props.size());
+ }
+
+ public void test_propertyNames() {
+ Properties parent = new Properties();
+ parent.setProperty("parent.a.key", "parent.a.value");
+ parent.setProperty("parent.b.key", "parent.b.value");
+
+ Enumeration<?> names = parent.propertyNames();
+ assertPropertyEnumeration(names, "parent.a.key", "parent.b.key");
+
+ Properties current = new Properties(parent);
+ current.setProperty("current.a.key", "current.a.value");
+ current.setProperty("current.b.key", "current.b.value");
+
+ names = current.propertyNames();
+ assertPropertyEnumeration(names,
+ "parent.a.key",
+ "parent.b.key",
+ "current.a.key",
+ "current.b.key");
+
+ Properties child = new Properties(current);
+ child.setProperty("child.a.key", "child.a.value");
+ child.setProperty("child.b.key", "child.b.value");
+
+ names = child.propertyNames();
+ assertPropertyEnumeration(names,
+ "parent.a.key",
+ "parent.b.key",
+ "current.a.key",
+ "current.b.key",
+ "child.a.key",
+ "child.b.key");
+ }
+
+ public void assertPropertyEnumeration(Enumeration<?> propNames,
+ String... expected) {
+ Set<String> propsSet = new HashSet<String>();
+ while (propNames.hasMoreElements()) {
+ String next = (String) propNames.nextElement();
+ assertFalse(propsSet.contains(next));
+ propsSet.add(next);
+ }
+
+ assertEquals(expected.length, propsSet.size());
+ assertTrue(propsSet.containsAll(Arrays.asList(expected)));
+ }
+
+ private String comment1 = "comment1";
+
+ private String comment2 = "comment2";
+
+ private void validateOutput(String[] expectStrings, byte[] output)
+ throws IOException {
+ ByteArrayInputStream bais = new ByteArrayInputStream(output);
+ BufferedReader br = new BufferedReader(new InputStreamReader(bais,
+ "ISO8859_1"));
+ for (String expectString : expectStrings) {
+ assertEquals(expectString, br.readLine());
+ }
+ br.readLine();
+ assertNull(br.readLine());
+ br.close();
+ }
+
+ public void testStore_scenario0() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario1() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario2() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + '\n' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario3() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + '\r' + comment2);
+ validateOutput(new String[] { "#comment1", "#", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario4() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + '#' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario5() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + '!' + comment2);
+ validateOutput(new String[] { "#comment1", "!comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario6() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + '#' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario7() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + '!' + comment2);
+ validateOutput(new String[] { "#comment1", "!comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario8() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + '\n' + '#' + comment2);
+ validateOutput(new String[] { "#comment1", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario9() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + '\r' + '#' + comment2);
+ validateOutput(new String[] { "#comment1", "#", "#comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario10() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\r' + '\n' + '!' + comment2);
+ validateOutput(new String[] { "#comment1", "!comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testStore_scenario11() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Properties props = new Properties();
+ props.store(baos, comment1 + '\n' + '\r' + '!' + comment2);
+ validateOutput(new String[] { "#comment1", "#", "!comment2" },
+ baos.toByteArray());
+ baos.close();
+ }
+
+ public void testLoadReader() throws IOException {
+ InputStream inputStream = new ByteArrayInputStream(
+ "\u3000key=value".getBytes("UTF-8"));
+ Properties props = new Properties();
+ props.load(inputStream);
+ Enumeration<Object> keyEnum = props.keys();
+ assertFalse("\u3000key".equals(keyEnum.nextElement()));
+ assertFalse(keyEnum.hasMoreElements());
+ inputStream.close();
+
+ inputStream = new ByteArrayInputStream(
+ "\u3000key=value".getBytes("UTF-8"));
+ props = new Properties();
+ props.load(new InputStreamReader(inputStream, "UTF-8"));
+ keyEnum = props.keys();
+ assertEquals("key", keyEnum.nextElement());
+ assertFalse(keyEnum.hasMoreElements());
+ inputStream.close();
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+
+ tProps = new Properties();
+ tProps.put("test.prop", "this is a test property");
+ tProps.put("bogus.prop", "bogus");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected byte[] writeProperties() throws IOException {
+ PrintStream ps = null;
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ ps = new PrintStream(bout);
+ ps.println("#commented.entry=Bogus");
+ ps.println("test.pkg=harmony.tests");
+ ps.println("test.proj=Automated Tests");
+ ps.close();
+ return bout.toByteArray();
+ }
+
+ protected byte[] writePropertiesXMLUTF_8() throws IOException {
+ PrintStream ps = null;
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ ps = new PrintStream(bout, true, "UTF-8");
+ ps.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+ ps
+ .println("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");
+ ps.println("<properties>");
+ ps.println("<comment>comment</comment>");
+ ps.println("<entry key=\"key4\">value4</entry>");
+ ps.println("<entry key=\"key3\">value3</entry>");
+ ps.println("<entry key=\"key2\">value2</entry>");
+ ps.println("<entry key=\"key1\"><!-- xml comment -->value1</entry>");
+ ps.println("</properties>");
+ ps.close();
+ return bout.toByteArray();
+ }
+
+ protected byte[] writePropertiesXMLISO_8859_1() throws IOException {
+ PrintStream ps = null;
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ ps = new PrintStream(bout, true, "ISO-8859-1");
+ ps.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
+ ps
+ .println("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");
+ ps.println("<properties>");
+ ps.println("<comment>comment</comment>");
+ ps.println("<entry key=\"key4\">value4</entry>");
+ ps.println("<entry key=\"key3\">value3</entry>");
+ ps.println("<entry key=\"key2\">value2</entry>");
+ ps.println("<entry key=\"key1\"><!-- xml comment -->value1</entry>");
+ ps.println("</properties>");
+ ps.close();
+ return bout.toByteArray();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertyResourceBundleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertyResourceBundleTest.java
new file mode 100644
index 0000000..2306ec1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/PropertyResourceBundleTest.java
@@ -0,0 +1,201 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.CharArrayReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.util.Enumeration;
+import java.util.MissingResourceException;
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+import java.util.Vector;
+
+public class PropertyResourceBundleTest extends junit.framework.TestCase {
+
+ static PropertyResourceBundle prb;
+
+ /**
+ * @throws IOException
+ * java.util.PropertyResourceBundle#PropertyResourceBundle(java.io.InputStream)
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ InputStream propertiesStream = new ByteArrayInputStream(
+ "p1=one\ncharset=iso-8859-1".getBytes("ISO-8859-1"));
+ prb = new PropertyResourceBundle(propertiesStream);
+ assertEquals(2, prb.keySet().size());
+ assertEquals("one", prb.getString("p1"));
+ assertEquals("iso-8859-1", prb.getString("charset"));
+
+ propertiesStream = new ByteArrayInputStream("p1=one\ncharset=UTF-8"
+ .getBytes("UTF-8"));
+ prb = new PropertyResourceBundle(propertiesStream);
+ assertEquals(2, prb.keySet().size());
+ assertEquals("UTF-8", prb.getString("charset"));
+
+ try {
+ new PropertyResourceBundle((InputStream) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @throws IOException
+ * {@link java.util.PropertyResourceBundle#PropertyResourceBundle(java.io.Reader)}
+ * @since 1.6
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_io_Reader() throws IOException {
+ Charset charset = Charset.forName("ISO-8859-1");
+ String content = "p1=one\nfeature=good_feature";
+ CharBuffer cbuffer = charset.decode(ByteBuffer.wrap(content
+ .getBytes("ISO-8859-1")));
+ char[] chars = new char[cbuffer.limit()];
+ cbuffer.get(chars);
+
+ prb = new PropertyResourceBundle(new CharArrayReader(chars));
+ assertEquals(2, prb.keySet().size());
+ assertEquals("one", prb.getString("p1"));
+ assertEquals("good_feature", prb.getString("feature"));
+
+ charset = Charset.forName("UTF-8");
+ cbuffer = charset.decode(ByteBuffer.wrap(content.getBytes("UTF-8")));
+ chars = new char[cbuffer.limit()];
+ cbuffer.get(chars);
+
+ prb = new PropertyResourceBundle(new CharArrayReader(chars));
+ assertEquals(2, prb.keySet().size());
+ assertEquals("one", prb.getString("p1"));
+ assertEquals("good_feature", prb.getString("feature"));
+
+ try {
+ new PropertyResourceBundle((Reader) null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.PropertyResourceBundle#getKeys()
+ */
+ public void test_getKeys() {
+ Enumeration keyEnum = prb.getKeys();
+ Vector<Object> test = new Vector<Object>();
+ int keyCount = 0;
+ while (keyEnum.hasMoreElements()) {
+ test.addElement(keyEnum.nextElement());
+ keyCount++;
+ }
+
+ assertEquals("Returned the wrong number of keys", 2, keyCount);
+ assertTrue("Returned the wrong keys", test.contains("p1")
+ && test.contains("p2"));
+ }
+
+ /**
+ * java.util.PropertyResourceBundle#handleGetObject(java.lang.String)
+ */
+ public void test_handleGetObjectLjava_lang_String() {
+ // Test for method java.lang.Object
+ // java.util.PropertyResourceBundle.handleGetObject(java.lang.String)
+ try {
+ assertTrue("Returned incorrect objects", prb.getObject("p1")
+ .equals("one")
+ && prb.getObject("p2").equals("two"));
+ } catch (MissingResourceException e) {
+ fail(
+ "Threw MisingResourceException for a key contained in the bundle");
+ }
+ try {
+ prb.getObject("Not in the bundle");
+ } catch (MissingResourceException e) {
+ return;
+ }
+ fail(
+ "Failed to throw MissingResourceException for object not in the bundle");
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ *
+ * @throws UnsupportedEncodingException
+ */
+ protected void setUp() throws UnsupportedEncodingException {
+ InputStream propertiesStream = new ByteArrayInputStream(
+ "p1=one\np2=two".getBytes("ISO-8859-1"));
+ try {
+ prb = new PropertyResourceBundle(propertiesStream);
+ } catch (java.io.IOException e) {
+ fail(
+ "Construction of PropertyResourceBundle threw IOException");
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+
+ /**
+ * {@link java.util.PropertyResourceBundle#Enumeration}
+ */
+ public void test_access$0_Enumeration() throws IOException {
+ class MockResourceBundle extends PropertyResourceBundle {
+ MockResourceBundle(java.io.InputStream stream) throws IOException {
+ super(stream);
+ }
+
+ @Override
+ protected void setParent(ResourceBundle bundle) {
+ super.setParent(bundle);
+ }
+ }
+
+ java.io.InputStream localStream = new java.io.ByteArrayInputStream(
+ "p3=three\np4=four".getBytes());
+ MockResourceBundle localPrb = new MockResourceBundle(localStream);
+ localPrb.setParent(prb);
+ Enumeration<String> keys = localPrb.getKeys();
+ Vector<String> contents = new Vector<String>();
+ while (keys.hasMoreElements()) {
+ contents.add(keys.nextElement());
+ }
+
+ assertEquals("did not get the right number of properties", 4, contents
+ .size());
+ assertTrue("did not get the parent property p1", contents
+ .contains("p1"));
+ assertTrue("did not get the parent property p2", contents
+ .contains("p2"));
+ assertTrue("did not get the local property p3", contents.contains("p3"));
+ assertTrue("did not get the local property p4", contents.contains("p4"));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RandomTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RandomTest.java
new file mode 100644
index 0000000..d51d8ab
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RandomTest.java
@@ -0,0 +1,320 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.Serializable;
+import java.util.Random;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class RandomTest extends junit.framework.TestCase {
+
+ Random r;
+
+ /**
+ * java.util.Random#Random()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.Random()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * java.util.Random#Random(long)
+ */
+ public void test_ConstructorJ() {
+ Random r = new Random(8409238L);
+ Random r2 = new Random(8409238L);
+ for (int i = 0; i < 100; i++)
+ assertTrue("Values from randoms with same seed don't match", r
+ .nextInt() == r2.nextInt());
+ }
+
+ /**
+ * java.util.Random#nextBoolean()
+ */
+ public void test_nextBoolean() {
+ // Test for method boolean java.util.Random.nextBoolean()
+ boolean falseAppeared = false, trueAppeared = false;
+ for (int counter = 0; counter < 100; counter++)
+ if (r.nextBoolean())
+ trueAppeared = true;
+ else
+ falseAppeared = true;
+ assertTrue("Calling nextBoolean() 100 times resulted in all trues",
+ falseAppeared);
+ assertTrue("Calling nextBoolean() 100 times resulted in all falses",
+ trueAppeared);
+ }
+
+ /**
+ * java.util.Random#nextBytes(byte[])
+ */
+ public void test_nextBytes$B() {
+ // Test for method void java.util.Random.nextBytes(byte [])
+ boolean someDifferent = false;
+ byte[] randomBytes = new byte[100];
+ r.nextBytes(randomBytes);
+ byte firstByte = randomBytes[0];
+ for (int counter = 1; counter < randomBytes.length; counter++)
+ if (randomBytes[counter] != firstByte)
+ someDifferent = true;
+ assertTrue(
+ "nextBytes() returned an array of length 100 of the same byte",
+ someDifferent);
+ }
+
+ /**
+ * java.util.Random#nextDouble()
+ */
+ public void test_nextDouble() {
+ // Test for method double java.util.Random.nextDouble()
+ double lastNum = r.nextDouble();
+ double nextNum;
+ boolean someDifferent = false;
+ boolean inRange = true;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextDouble();
+ if (nextNum != lastNum)
+ someDifferent = true;
+ if (!(0 <= nextNum && nextNum < 1.0))
+ inRange = false;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextDouble 100 times resulted in same number",
+ someDifferent);
+ assertTrue(
+ "Calling nextDouble resulted in a number out of range [0,1)",
+ inRange);
+ }
+
+ /**
+ * java.util.Random#nextFloat()
+ */
+ public void test_nextFloat() {
+ // Test for method float java.util.Random.nextFloat()
+ float lastNum = r.nextFloat();
+ float nextNum;
+ boolean someDifferent = false;
+ boolean inRange = true;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextFloat();
+ if (nextNum != lastNum)
+ someDifferent = true;
+ if (!(0 <= nextNum && nextNum < 1.0))
+ inRange = false;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextFloat 100 times resulted in same number",
+ someDifferent);
+ assertTrue("Calling nextFloat resulted in a number out of range [0,1)",
+ inRange);
+ }
+
+ /**
+ * java.util.Random#nextGaussian()
+ */
+ public void test_nextGaussian() {
+ // Test for method double java.util.Random.nextGaussian()
+ double lastNum = r.nextGaussian();
+ double nextNum;
+ boolean someDifferent = false;
+ boolean someInsideStd = false;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextGaussian();
+ if (nextNum != lastNum)
+ someDifferent = true;
+ if (-1.0 <= nextNum && nextNum <= 1.0)
+ someInsideStd = true;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextGaussian 100 times resulted in same number",
+ someDifferent);
+ assertTrue(
+ "Calling nextGaussian 100 times resulted in no number within 1 std. deviation of mean",
+ someInsideStd);
+ }
+
+ /**
+ * java.util.Random#nextInt()
+ */
+ public void test_nextInt() {
+ // Test for method int java.util.Random.nextInt()
+ int lastNum = r.nextInt();
+ int nextNum;
+ boolean someDifferent = false;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextInt();
+ if (nextNum != lastNum)
+ someDifferent = true;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextInt 100 times resulted in same number",
+ someDifferent);
+ }
+
+ /**
+ * java.util.Random#nextInt(int)
+ */
+ public void test_nextIntI() {
+ // Test for method int java.util.Random.nextInt(int)
+ final int range = 10;
+ int lastNum = r.nextInt(range);
+ int nextNum;
+ boolean someDifferent = false;
+ boolean inRange = true;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextInt(range);
+ if (nextNum != lastNum)
+ someDifferent = true;
+ if (!(0 <= nextNum && nextNum < range))
+ inRange = false;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextInt (range) 100 times resulted in same number",
+ someDifferent);
+ assertTrue(
+ "Calling nextInt (range) resulted in a number outside of [0, range)",
+ inRange);
+
+ }
+
+ /**
+ * java.util.Random#nextLong()
+ */
+ public void test_nextLong() {
+ // Test for method long java.util.Random.nextLong()
+ long lastNum = r.nextLong();
+ long nextNum;
+ boolean someDifferent = false;
+ for (int counter = 0; counter < 100; counter++) {
+ nextNum = r.nextLong();
+ if (nextNum != lastNum)
+ someDifferent = true;
+ lastNum = nextNum;
+ }
+ assertTrue("Calling nextLong 100 times resulted in same number",
+ someDifferent);
+ }
+
+ /**
+ * java.util.Random#setSeed(long)
+ */
+ public void test_setSeedJ() {
+ // Test for method void java.util.Random.setSeed(long)
+ long[] randomArray = new long[100];
+ boolean someDifferent = false;
+ final long firstSeed = 1000;
+ long aLong, anotherLong, yetAnotherLong;
+ Random aRandom = new Random();
+ Random anotherRandom = new Random();
+ Random yetAnotherRandom = new Random();
+ aRandom.setSeed(firstSeed);
+ anotherRandom.setSeed(firstSeed);
+ for (int counter = 0; counter < randomArray.length; counter++) {
+ aLong = aRandom.nextLong();
+ anotherLong = anotherRandom.nextLong();
+ assertTrue(
+ "Two randoms with same seeds gave differing nextLong values",
+ aLong == anotherLong);
+ yetAnotherLong = yetAnotherRandom.nextLong();
+ randomArray[counter] = aLong;
+ if (aLong != yetAnotherLong)
+ someDifferent = true;
+ }
+ assertTrue(
+ "Two randoms with the different seeds gave the same chain of values",
+ someDifferent);
+ aRandom.setSeed(firstSeed);
+ for (int counter = 0; counter < randomArray.length; counter++)
+ assertTrue(
+ "Reseting a random to its old seed did not result in the same chain of values as it gave before",
+ aRandom.nextLong() == randomArray[counter]);
+ }
+
+ class Mock_Random extends Random {
+ boolean nextCalled = false;
+
+ public boolean getFlag () {
+ boolean retVal = nextCalled;
+ nextCalled = false;
+ return retVal;
+ }
+
+ @Override
+ protected int next(int bits) {
+ nextCalled = true;
+ return super.next(bits);
+ }
+ }
+
+ public void test_next() {
+ Mock_Random mr = new Mock_Random();
+ assertFalse(mr.getFlag());
+ mr.nextBoolean();
+ assertTrue(mr.getFlag());
+ mr.nextBytes(new byte[10]);
+ assertTrue(mr.getFlag());
+ mr.nextDouble();
+ assertTrue(mr.getFlag());
+ mr.nextFloat();
+ assertTrue(mr.getFlag());
+ mr.nextGaussian();
+ assertTrue(mr.getFlag());
+ mr.nextInt();
+ assertTrue(mr.getFlag());
+ mr.nextInt(10);
+ assertTrue(mr.getFlag());
+ mr.nextLong();
+ assertTrue(mr.getFlag());
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ r = new Random();
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+
+ public void testSerializationCompatibility() throws Exception {
+ Random rand = new Random(0x8123aea6267e055dL);
+ rand.nextGaussian();
+ // SerializationTest.createGoldenFile("/tmp", this, rand);
+ SerializationTest.verifyGolden(this, rand, comparator);
+
+ rand = new Random(0x8123aea6267e055dL);
+ rand.nextGaussian();
+ SerializationTest.verifySelf(rand, comparator);
+ }
+
+ public static final SerializationTest.SerializableAssert comparator =
+ new SerializationTest.SerializableAssert() {
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ Random initialRand = (Random) initial;
+ Random deserializedRand = (Random) deserialized;
+ assertEquals("should be equal", initialRand.nextInt(), deserializedRand.nextInt());
+ }
+ };
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RefSortedMap.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RefSortedMap.java
new file mode 100644
index 0000000..4b829af
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/RefSortedMap.java
@@ -0,0 +1,402 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.AbstractSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.SortedMap;
+
+public class RefSortedMap<K, V> extends java.util.AbstractMap<K, V>
+ implements SortedMap<K, V>, Cloneable, Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final class MapEntry<K, V> implements Map.Entry<K, V> {
+
+ final K key;
+ V value;
+
+ MapEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public V setValue(V v) {
+ V res = value;
+ value = v;
+ return res;
+ }
+
+ public int hashCode() {
+ return (getKey() == null ? 0 : getKey().hashCode())
+ ^ (getValue() == null ? 0 : getValue().hashCode());
+ }
+
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (object instanceof Map.Entry) {
+ Map.Entry<?, ?> entry = (Map.Entry<?, ?>) object;
+ return (getKey() == null ? entry.getKey() == null : getKey().equals(entry
+ .getKey()))
+ && (getValue() == null ? entry.getValue() == null : getValue()
+ .equals(entry.getValue()));
+ }
+ return false;
+ }
+ }
+
+ transient ArrayList<MapEntry<K, V>> entries = new ArrayList<MapEntry<K, V>>();
+ transient int modCnt;
+
+ private final Comparator<? super K> comparator;
+
+ class SubMap extends java.util.AbstractMap<K, V>
+ implements SortedMap<K, V>, Cloneable {
+
+ final boolean hasStart, hasEnd;
+ final K start, end;
+
+ SubMap(boolean hasFirst, K first, boolean hasLast, K last) {
+ this.hasStart = hasFirst;
+ this.start = first;
+ this.hasEnd = hasLast;
+ this.end = last;
+ if (hasStart && hasEnd && compare(start, end) >= 0) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ @Override
+ public Set<java.util.Map.Entry<K, V>> entrySet() {
+ return new AbstractSet<Entry<K, V>>() {
+
+ @Override
+ public Iterator<java.util.Map.Entry<K, V>> iterator() {
+ return new Iterator<Entry<K, V>>() {
+ int modCnt = RefSortedMap.this.modCnt;
+ int offset = SubMap.this.size() > 0 ?
+ bsearch(SubMap.this.firstKey()) - 1 :
+ entries.size();
+
+ public boolean hasNext() {
+ if (modCnt != RefSortedMap.this.modCnt) {
+ throw new ConcurrentModificationException();
+ }
+ return offset + 1 < entries.size()
+ && isInRange(entries.get(offset + 1).getKey());
+ }
+
+ public Map.Entry<K, V> next() {
+ if (modCnt != RefSortedMap.this.modCnt) {
+ throw new ConcurrentModificationException();
+ }
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ offset++;
+ return entries.get(offset);
+ }
+
+ public void remove() {
+ if (modCnt != RefSortedMap.this.modCnt) {
+ throw new ConcurrentModificationException();
+ }
+ modCnt++;
+ RefSortedMap.this.modCnt++;
+ RefSortedMap.this.entries.remove(offset);
+ offset--;
+ }
+
+ };
+ }
+
+ @Override
+ public int size() {
+ try {
+ int lastIdx = bsearch(SubMap.this.lastKey());
+ int firstIdx = bsearch(SubMap.this.firstKey());
+ return lastIdx - firstIdx + 1;
+ } catch (NoSuchElementException e) {
+ return 0;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ return 0;
+ }
+ }
+
+ };
+ }
+
+ public Comparator<? super K> comparator() {
+ return RefSortedMap.this.comparator();
+ }
+
+ public K firstKey() {
+ if (!hasStart) {
+ K res = RefSortedMap.this.firstKey();
+ if (!isInRange(res)) {
+ throw new NoSuchElementException();
+ }
+ return res;
+ }
+ int idx = bsearch(start);
+ if (idx >= 0) {
+ return start;
+ }
+ if (-idx - 1 >= entries.size() || !isInRange(entries.get(-idx - 1).getKey())) {
+ throw new NoSuchElementException();
+ }
+ return entries.get(-idx - 1).getKey();
+ }
+
+ public SortedMap<K, V> headMap(K key) {
+ if (!isInRange(key)) {
+ throw new IllegalArgumentException();
+ }
+ return new SubMap(hasStart, start, true, key);
+ }
+
+ public K lastKey() {
+ if (!hasEnd) {
+ K res = RefSortedMap.this.lastKey();
+ if (!isInRange(res)) {
+ throw new NoSuchElementException();
+ }
+ return res;
+ }
+ int idx = bsearch(end);
+ idx = idx >= 0 ? idx - 1 : -idx - 2;
+ if (idx < 0 || !isInRange(entries.get(idx).getKey())) {
+ throw new NoSuchElementException();
+ }
+ return entries.get(idx).getKey();
+ }
+
+ public SortedMap<K, V> subMap(K startKey, K endKey) {
+ if (!isInRange(startKey)) {
+ throw new IllegalArgumentException();
+ }
+ if (!isInRange(endKey)) {
+ throw new IllegalArgumentException();
+ }
+ return new SubMap(true, startKey, true, endKey);
+ }
+
+ public SortedMap<K, V> tailMap(K key) {
+ if (!isInRange(key)) {
+ throw new IllegalArgumentException();
+ }
+ return new SubMap(true, key, hasEnd, end);
+ }
+
+ private boolean isInRange(K key) {
+ if (hasStart && compare(key, start) < 0) {
+ return false;
+ }
+ if (hasEnd && compare(key, end) >= 0) {
+ return false;
+ }
+ return true;
+ }
+
+ }
+
+ public RefSortedMap() {
+ this((Comparator<? super K>) null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public int compare(K start, K end) {
+ return comparator != null ? comparator.compare(start, end)
+ : ((Comparable<K>) start).compareTo(end);
+ }
+
+ @SuppressWarnings("unchecked")
+ public RefSortedMap(Comparator<? super K> comparator) {
+ this.comparator = comparator;
+ cmp = createCmp();
+ }
+
+ public RefSortedMap(Map<? extends K, ? extends V> map) {
+ this();
+ putAll(map);
+ }
+
+ public RefSortedMap(SortedMap<K, ? extends V> map) {
+ this(map.comparator());
+ putAll(map);
+ }
+
+ public Comparator<? super K> comparator() {
+ return comparator;
+ }
+
+ public Set<Map.Entry<K, V>> entrySet() {
+ return tailMap(firstKey()).entrySet();
+ }
+
+ public K firstKey() {
+ return entries.get(0).getKey();
+ }
+
+ public SortedMap<K, V> headMap(K key) {
+ return new SubMap(false, null, true, key);
+ }
+
+ public Set<K> keySet() {
+ return tailMap(firstKey()).keySet();
+ }
+
+ public K lastKey() {
+ return entries.get(entries.size() - 1).getKey();
+ }
+
+ public SortedMap<K, V> subMap(K startKey, K endKey) {
+ return new SubMap(true, startKey, true, endKey);
+ }
+
+ public SortedMap<K, V> tailMap(K key) {
+ return new SubMap(true, key, false, null);
+ }
+
+ public Collection<V> values() {
+ return tailMap(firstKey()).values();
+ }
+
+ public void clear() {
+ entries.clear();
+ }
+
+ public boolean containsKey(Object arg0) {
+ return bsearch(arg0) >= 0;
+ }
+
+ public boolean containsValue(Object arg0) {
+ for (V v : values()) {
+ if (arg0.equals(v)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @SuppressWarnings("unchecked")
+ public V get(Object arg0) {
+ int idx = bsearch(arg0);
+ return idx >= 0 ? entries.get(idx).getValue() : null;
+ }
+
+ public boolean isEmpty() {
+ return entries.isEmpty();
+ }
+
+ public V put(K arg0, V arg1) {
+ modCnt++;
+ int idx = bsearch(arg0);
+ if (idx >= 0) {
+ return entries.get(idx).setValue(arg1);
+ }
+ entries.add(-idx - 1, new MapEntry<K, V>(arg0, arg1));
+ return null;
+ }
+
+ public void putAll(Map<? extends K, ? extends V> arg0) {
+ for (Map.Entry<? extends K, ? extends V> e : arg0.entrySet()) {
+ put(e.getKey(), e.getValue());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public V remove(Object arg0) {
+ modCnt++;
+ int idx = bsearch(arg0);
+ if (idx < 0) {
+ return null;
+ }
+ return entries.remove(idx).getValue();
+ }
+
+ transient private Comparator<MapEntry<K, V>> cmp = createCmp();
+
+ Comparator<MapEntry<K, V>> createCmp() {
+ return new Comparator<MapEntry<K, V>>() {
+
+ public int compare(MapEntry<K, V> arg0, MapEntry<K, V> arg1) {
+ return RefSortedMap.this.compare(arg0.getKey(), arg1.getKey());
+ }
+
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ private int bsearch(Object arg0) {
+ return Collections.binarySearch(entries, new MapEntry<K, V>((K) arg0, null), cmp);
+ }
+
+ public int size() {
+ return entries.size();
+ }
+
+ public RefSortedMap<K, V> clone() {
+ return new RefSortedMap<K, V>(this);
+ }
+
+ private void writeObject(ObjectOutputStream stream) throws IOException {
+ stream.defaultWriteObject();
+ stream.writeInt(size());
+ for (Map.Entry<K, V> e : entrySet()) {
+ stream.writeObject(e.getKey());
+ stream.writeObject(e.getValue());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void readObject(ObjectInputStream stream) throws IOException,
+ ClassNotFoundException {
+
+ cmp = createCmp();
+ stream.defaultReadObject();
+ int size = stream.readInt();
+ entries = new ArrayList<MapEntry<K, V>>(size);
+ for (int i = 0; i < size; i++) {
+ put((K) stream.readObject(), (V) stream.readObject());
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ResourceBundleTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ResourceBundleTest.java
new file mode 100644
index 0000000..11be2fe
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ResourceBundleTest.java
@@ -0,0 +1,398 @@
+/*
+ * 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.tests.java.util;
+
+import dalvik.annotation.KnownFailure;
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.StringTokenizer;
+import java.util.Vector;
+import org.apache.harmony.tests.java.util.support.B;
+import tests.support.resource.Support_Resources;
+
+public class ResourceBundleTest extends junit.framework.TestCase {
+
+ public void test_getCandidateLocales() throws Exception {
+ ResourceBundle.Control c = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT);
+ assertEquals("[en_US, en, ]", c.getCandidateLocales("base", Locale.US).toString());
+ assertEquals("[de_CH, de, ]", c.getCandidateLocales("base", new Locale("de", "CH")).toString());
+ }
+
+ /**
+ * java.util.ResourceBundle#getBundle(java.lang.String,
+ * java.util.Locale)
+ */
+ public void test_getBundleLjava_lang_StringLjava_util_Locale() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale defLocale = Locale.getDefault();
+
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ assertEquals("Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString("parent4"));
+
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
+ assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
+
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
+ assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
+
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
+ assertEquals("Wrong bundle de_FR_var", "enUSValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("fr", "FR", "VAR"));
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
+ assertEquals("Wrong bundle de_FR_var 2", "frFRVARValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("de", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
+ assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
+ );
+
+ try {
+ ResourceBundle.getBundle(null, Locale.US);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+ try {
+ ResourceBundle.getBundle("blah", (Locale) null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+
+ try {
+ ResourceBundle.getBundle("", new Locale("xx", "yy"));
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.ResourceBundle#getBundle(java.lang.String,
+ * java.util.Locale, java.lang.ClassLoader)
+ */
+ @KnownFailure("It's not allowed to pass null as parent class loader to"
+ + " a new ClassLoader anymore. Maybe we need to change"
+ + " URLClassLoader to allow this? It's not specified.")
+ public void test_getBundleLjava_lang_StringLjava_util_LocaleLjava_lang_ClassLoader() {
+ String classPath = System.getProperty("java.class.path");
+ StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
+ Vector<URL> urlVec = new Vector<URL>();
+ String resPackage = Support_Resources.RESOURCE_PACKAGE;
+ try {
+ while (tok.hasMoreTokens()) {
+ String path = tok.nextToken();
+ String url;
+ if (new File(path).isDirectory())
+ url = "file:" + path + resPackage + "subfolder/";
+ else
+ url = "jar:file:" + path + "!" + resPackage + "subfolder/";
+ urlVec.addElement(new URL(url));
+ }
+ } catch (MalformedURLException e) {
+ }
+ URL[] urls = new URL[urlVec.size()];
+ for (int i = 0; i < urlVec.size(); i++)
+ urls[i] = urlVec.elementAt(i);
+ URLClassLoader loader = new URLClassLoader(urls, null);
+
+ String name = Support_Resources.RESOURCE_PACKAGE_NAME
+ + ".hyts_resource";
+ ResourceBundle bundle = ResourceBundle.getBundle(name, Locale
+ .getDefault());
+ assertEquals("Wrong value read", "parent", bundle.getString("property"));
+ bundle = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
+ assertEquals("Wrong cached value",
+ "resource", bundle.getString("property"));
+
+ try {
+ ResourceBundle.getBundle(null, Locale.getDefault(), loader);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ ResourceBundle.getBundle(name, null, loader);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ ResourceBundle.getBundle(name, Locale.getDefault(), (ClassLoader) null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ ResourceBundle.getBundle("", Locale.getDefault(), loader);
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+
+ // Regression test for Harmony-3823
+ B bb = new B();
+ String s = bb.find("nonexistent");
+ s = bb.find("name");
+ assertEquals("Wrong property got", "Name", s);
+ }
+
+ /**
+ * java.util.ResourceBundle#getString(java.lang.String)
+ */
+ public void test_getStringLjava_lang_String() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ assertEquals("Wrong value parent4",
+ "frFRVARValue4", bundle.getString("parent4"));
+ assertEquals("Wrong value parent3",
+ "frFRValue3", bundle.getString("parent3"));
+ assertEquals("Wrong value parent2",
+ "frValue2", bundle.getString("parent2"));
+ assertEquals("Wrong value parent1",
+ "parentValue1", bundle.getString("parent1"));
+ assertEquals("Wrong value child3",
+ "frFRVARChildValue3", bundle.getString("child3"));
+ assertEquals("Wrong value child2",
+ "frFRVARChildValue2", bundle.getString("child2"));
+ assertEquals("Wrong value child1",
+ "frFRVARChildValue1", bundle.getString("child1"));
+
+ try {
+ bundle.getString(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ bundle.getString("");
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+
+ try {
+ bundle.getString("IntegerVal");
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expected
+ }
+ }
+ public void test_getBundle_getClassName() {
+ // Regression test for Harmony-1759
+ Locale locale = Locale.GERMAN;
+ String nonExistentBundle = "Non-ExistentBundle";
+ try {
+ ResourceBundle.getBundle(nonExistentBundle, locale, this.getClass()
+ .getClassLoader());
+ fail("MissingResourceException expected!");
+ } catch (MissingResourceException e) {
+ assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
+ }
+
+ try {
+ ResourceBundle.getBundle(nonExistentBundle, locale);
+ fail("MissingResourceException expected!");
+ } catch (MissingResourceException e) {
+ assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
+ }
+
+ locale = Locale.getDefault();
+ try {
+ ResourceBundle.getBundle(nonExistentBundle);
+ fail("MissingResourceException expected!");
+ } catch (MissingResourceException e) {
+ assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
+ }
+ }
+
+ class Mock_ResourceBundle extends ResourceBundle {
+ @Override
+ public Enumeration<String> getKeys() {
+ return null;
+ }
+
+ @Override
+ protected Object handleGetObject(String key) {
+ return null;
+ }
+ }
+
+ public void test_constructor() {
+ assertNotNull(new Mock_ResourceBundle());
+ }
+
+ public void test_getLocale() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale loc = Locale.getDefault();
+ Locale.setDefault(new Locale("en", "US"));
+
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ assertEquals("fr_FR_VAR", bundle.getLocale().toString());
+
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
+ assertEquals("fr_FR", bundle.getLocale().toString());
+
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
+ assertEquals("fr", bundle.getLocale().toString());
+
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
+ assertEquals("en_US", bundle.getLocale().toString());
+
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
+ assertEquals("en_US", bundle.getLocale().toString());
+
+ bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
+ assertEquals("en_US", bundle.getLocale().toString());
+
+ Locale.setDefault(loc);
+ }
+
+ public void test_getObjectLjava_lang_String() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+ assertEquals("Wrong value parent4",
+ "frFRVARValue4", (String)bundle.getObject("parent4"));
+ assertEquals("Wrong value parent3",
+ "frFRValue3", (String)bundle.getObject("parent3"));
+ assertEquals("Wrong value parent2",
+ "frValue2", (String) bundle.getObject("parent2"));
+ assertEquals("Wrong value parent1",
+ "parentValue1", (String)bundle.getObject("parent1"));
+ assertEquals("Wrong value child3",
+ "frFRVARChildValue3", (String)bundle.getObject("child3"));
+ assertEquals("Wrong value child2",
+ "frFRVARChildValue2", (String) bundle.getObject("child2"));
+ assertEquals("Wrong value child1",
+ "frFRVARChildValue1", (String)bundle.getObject("child1"));
+ assertEquals("Wrong value IntegerVal",
+ 1, bundle.getObject("IntegerVal"));
+
+ try {
+ bundle.getObject(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ bundle.getObject("");
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+ }
+
+ public void test_getStringArrayLjava_lang_String() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
+
+ String[] array = bundle.getStringArray("StringArray");
+ for(int i = 0; i < array.length; i++) {
+ assertEquals("Str" + (i + 1), array[i]);
+ }
+
+ try {
+ bundle.getStringArray(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ bundle.getStringArray("");
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+
+ try {
+ bundle.getStringArray("IntegerVal");
+ fail("ClassCastException expected");
+ } catch (ClassCastException ee) {
+ //expected
+ }
+ }
+
+ public void test_getBundleLjava_lang_String() {
+ ResourceBundle bundle;
+ String name = "tests.support.Support_TestResource";
+ Locale defLocale = Locale.getDefault();
+
+ Locale.setDefault(new Locale("en", "US"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("enUSValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("fr", "FR", "v1"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("fr", "US", "VAR"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("de", "FR", "VAR"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("Wrong bundle de_FR_var", "parentValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("de", "FR", "v1"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
+
+ Locale.setDefault(new Locale("de", "FR", "var"));
+ bundle = ResourceBundle.getBundle(name);
+ assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
+
+ try {
+ ResourceBundle.getBundle(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ //expected
+ }
+
+ try {
+ ResourceBundle.getBundle("");
+ fail("MissingResourceException expected");
+ } catch (MissingResourceException ee) {
+ //expected
+ }
+
+ Locale.setDefault(defLocale);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SampleBundleClass.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SampleBundleClass.java
new file mode 100644
index 0000000..394291b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SampleBundleClass.java
@@ -0,0 +1,43 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.util;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * Part of the ResourceBundleTest
+ */
+public class SampleBundleClass {
+
+ private static SampleBundleClass singleton;
+ private static ResourceBundle bundle;
+
+ public SampleBundleClass() {
+ super();
+ if (singleton != null) {
+ throw new RuntimeException();
+ }
+ singleton = this;
+ try {
+ bundle = ResourceBundle.getBundle("tests.api.simple.SampleBundleClass");
+ } catch (MissingResourceException x) {
+ System.out.println("Missing resource");
+ bundle = null;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerParseLargeFileBenchmarkTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerParseLargeFileBenchmarkTest.java
index 117f211..c0f9e58 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerParseLargeFileBenchmarkTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerParseLargeFileBenchmarkTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.luni.tests.java.util;
+package org.apache.harmony.tests.java.util;
import java.io.IOException;
import java.io.Reader;
@@ -24,11 +24,11 @@ import junit.framework.TestCase;
public class ScannerParseLargeFileBenchmarkTest extends TestCase {
/**
- * This test will check when parse a large file like more than 200M bytes if
- * the Scanner will exhaust all heap memory
+ * Check whether the Scanner will exhaust all heap memory when parsing a
+ * large file.
*/
public void testParseLargeFile() throws Exception {
- MyReader reader = new MyReader();
+ FakeLargeFile reader = new FakeLargeFile();
String delimiter = "\r?\n";
Scanner scanner = new Scanner(reader).useDelimiter(delimiter);
@@ -39,14 +39,9 @@ public class ScannerParseLargeFileBenchmarkTest extends TestCase {
reader.close();
}
- private static class MyReader extends Reader {
- static final char[] CONTENT = "large file!\n".toCharArray();
-
- static long fileLength = (8 << 21) * 12;
-
- static boolean first = true;
-
- static int position = 0;
+ private static class FakeLargeFile extends Reader {
+ private static final char[] CONTENT = "large file!\n".toCharArray();
+ private static final int FILE_LENGTH = 192 * 1024 * 1024; // 192 MB
private int count = 0;
@@ -55,22 +50,24 @@ public class ScannerParseLargeFileBenchmarkTest extends TestCase {
}
@Override
- public int read(char[] buf, int offset, int length) {
- if (count >= fileLength) {
+ public int read(char[] buffer, int offset, int length) {
+ if (count >= FILE_LENGTH) {
return -1;
}
- if (first == true) {
- position = 0;
- first = false;
- }
- for (int i = offset; i < length; i++) {
- buf[i] = CONTENT[(i + position) % CONTENT.length];
- count++;
- }
-
- position = (length + position) % CONTENT.length;
- return length - offset;
+ final int charsToRead = Math.min(FILE_LENGTH - count, length);
+ int bufferIndex = offset;
+ int contentIndex = count % CONTENT.length;
+ int charsRead = 0;
+ while (charsRead < charsToRead) {
+ buffer[bufferIndex++] = CONTENT[contentIndex++];
+ if (contentIndex == CONTENT.length) {
+ contentIndex = 0;
+ }
+ charsRead++;
+ }
+ count += charsRead;
+ return charsToRead;
}
}
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerTest.java
index b3e1abc..cc6a0f0 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/ScannerTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ScannerTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.luni.tests.java.util;
+package org.apache.harmony.tests.java.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -25,9 +25,9 @@ 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.InputStreamReader;
-import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
@@ -39,12 +39,12 @@ import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
+import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
-import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
@@ -52,10 +52,9 @@ import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
+import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
-import java.util.Scanner;
-
import junit.framework.TestCase;
public class ScannerTest extends TestCase {
@@ -1058,27 +1057,20 @@ public class ScannerTest extends TestCase {
s.useLocale(Locale.CHINESE);
assertEquals(12300, s.nextInt(10));
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
+ s = new Scanner("-123 123-");
+ s.useLocale(new Locale("ar", "AE"));
+ assertEquals(-123, s.nextInt());
+ try {
+ s.nextInt();
+ fail();
+ } catch (InputMismatchException expected) {
+ }
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
+ s = new Scanner("-123 -123-");
s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextInt(10));
- // The following test case fails on RI
- assertEquals(-123, s.nextInt(10));
+ assertEquals(-123, s.nextInt());
try {
- s.nextInt(10);
+ s.nextInt();
fail();
} catch (InputMismatchException expected) {
}
@@ -1244,24 +1236,17 @@ public class ScannerTest extends TestCase {
s.useLocale(Locale.CHINESE);
assertEquals(12300, s.nextInt());
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
+ s = new Scanner("-123 123-");
s.useLocale(new Locale("ar", "AE"));
assertEquals(-123, s.nextInt());
- // The following test case fails on RI
+ try {
+ s.nextInt();
+ fail();
+ } catch (InputMismatchException expected) {
+ }
+
+ s = new Scanner("-123 -123-");
+ s.useLocale(new Locale("ar", "AE"));
assertEquals(-123, s.nextInt());
try {
s.nextInt();
@@ -3259,26 +3244,19 @@ public class ScannerTest extends TestCase {
assertTrue(s.hasNextInt(10));
assertEquals(12300, s.nextInt(10));
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used together. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) should be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
+ s = new Scanner("-123 123-");
s.useLocale(new Locale("ar", "AE"));
assertTrue(s.hasNextInt(10));
assertEquals(-123, s.nextInt(10));
- // The following test case fails on RI
- assertTrue(s.hasNextInt(10));
+ assertFalse(s.hasNextInt(10));
+ try {
+ s.nextInt(10);
+ fail();
+ } catch (InputMismatchException expected) {
+ }
+
+ s = new Scanner("-123 -123-");
+ s.useLocale(new Locale("ar", "AE"));
assertEquals(-123, s.nextInt(10));
assertFalse(s.hasNextInt(10));
try {
@@ -3452,25 +3430,19 @@ public class ScannerTest extends TestCase {
assertTrue(s.hasNextInt());
assertEquals(12300, s.nextInt());
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
+ s = new Scanner("-123 123-");
s.useLocale(new Locale("ar", "AE"));
assertTrue(s.hasNextInt());
assertEquals(-123, s.nextInt());
- // The following test case fails on RI
+ assertFalse(s.hasNextInt());
+ try {
+ s.nextInt();
+ fail();
+ } catch (InputMismatchException expected) {
+ }
+
+ s = new Scanner("-123 -123-");
+ s.useLocale(new Locale("ar", "AE"));
assertTrue(s.hasNextInt());
assertEquals(-123, s.nextInt());
assertFalse(s.hasNextInt());
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ServiceConfigurationErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ServiceConfigurationErrorTest.java
new file mode 100644
index 0000000..870ef1e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ServiceConfigurationErrorTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.ServiceConfigurationError;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for java.util.ServiceConfigurationError
+ *
+ * @since 1.6
+ */
+public class ServiceConfigurationErrorTest extends TestCase {
+
+ /**
+ * {@link java.util.ServiceConfigurationError#ServiceConfigurationError(String)}
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_lang_String() {
+ ServiceConfigurationError e = new ServiceConfigurationError("fixture");
+ assertEquals("fixture", e.getMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * {@link java.util.ServiceConfigurationError#ServiceConfigurationError(String, Throwable)}
+ */
+ @SuppressWarnings("nls")
+ public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
+ IllegalArgumentException iae = new IllegalArgumentException(
+ "info in the IAE");
+ ServiceConfigurationError e = new ServiceConfigurationError("fixture",
+ iae);
+ assertEquals("fixture", e.getMessage());
+ assertEquals(iae, e.getCause());
+ assertEquals("info in the IAE", e.getCause().getMessage());
+ }
+
+ /**
+ * @throws Exception
+ * serialization/deserialization.
+ */
+ @SuppressWarnings("nls")
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new ServiceConfigurationError("fixture"));
+ SerializationTest.verifySelf(new ServiceConfigurationError("fixture",
+ new IllegalArgumentException("info in the IAE")));
+ }
+
+ /**
+ * @throws Exception
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings("nls")
+ public void testSerializationCompatibility() throws Exception {
+ ServiceConfigurationError e = new ServiceConfigurationError("fixture",
+ new IllegalArgumentException("info in the IAE"));
+ SerializationTest.verifyGolden(this, e);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleEntryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleEntryTest.java
new file mode 100644
index 0000000..3f0847f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleEntryTest.java
@@ -0,0 +1,133 @@
+/*
+ * 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.tests.java.util;
+
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.util.SerializationTester;
+import java.util.AbstractMap;
+import java.util.AbstractMap.SimpleEntry;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+public class SimpleEntryTest extends TestCase {
+ public void test_SimpleEntry_Constructor_K_V() throws Exception {
+ new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ new AbstractMap.SimpleEntry(null, null);
+ }
+
+ static class NullEntry implements Entry {
+
+ public Object getKey() {
+ return null;
+ }
+
+ public Object getValue() {
+ return null;
+ }
+
+ public Object setValue(Object object) {
+ return null;
+ }
+ }
+
+ public void test_SimpleEntry_Constructor_LEntry() throws Exception {
+ Map map = new TreeMap();
+ map.put(1, "test");
+ Entry entryToPut = (Entry) map.entrySet().iterator().next();
+ Entry testEntry = new AbstractMap.SimpleEntry(entryToPut);
+ assertEquals(1, testEntry.getKey());
+ assertEquals("test", testEntry.getValue());
+ map.clear();
+
+ testEntry = new AbstractMap.SimpleEntry(new NullEntry());
+ assertNull(testEntry.getKey());
+ assertNull(testEntry.getValue());
+ try {
+ new AbstractMap.SimpleEntry(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ public void test_SimpleEntry_getKey() throws Exception {
+ Entry entry = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ assertEquals(1, entry.getKey());
+ entry = new AbstractMap.SimpleEntry(null, null);
+ assertNull(entry.getKey());
+ }
+
+ public void test_SimpleEntry_getValue() throws Exception {
+ Entry entry = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ assertEquals("test", entry.getValue());
+ entry = new AbstractMap.SimpleEntry(null, null);
+ assertNull(entry.getValue());
+ }
+
+ public void test_SimpleEntry_setValue() throws Exception {
+ Entry entry = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ assertEquals("test", entry.getValue());
+ entry.setValue("Another String");
+ assertEquals("Another String", entry.getValue());
+ entry = new AbstractMap.SimpleEntry(null, null);
+ assertNull(entry.getKey());
+ }
+
+ public void test_SimpleEntry_equals() throws Exception {
+ Entry entry = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ Map map = new TreeMap();
+ map.put(1, "test");
+ Entry entryToPut = (Entry) map.entrySet().iterator().next();
+ Entry testEntry = new AbstractMap.SimpleEntry(entryToPut);
+ assertEquals(entry, testEntry);
+ Entry ent = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals(entry, ent);
+ }
+
+ public void test_SimpleEntry_hashCode() throws Exception {
+ Entry e = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ assertEquals((e.getKey() == null ? 0 : e.getKey().hashCode())
+ ^ (e.getValue() == null ? 0 : e.getValue().hashCode()), e
+ .hashCode());
+ }
+
+ public void test_SimpleEntry_toString() throws Exception {
+ Entry e = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ assertEquals(e.getKey() + "=" + e.getValue(), e.toString());
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationSelf_SimpleEntry() throws Exception {
+ Entry e = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ SerializationTest.verifySelf(e);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationCompatibility_SimpleEntry() throws Exception {
+ SimpleEntry e = new AbstractMap.SimpleEntry<Integer, String>(1, "test");
+ SerializationTester.assertCompabilityEquals(e, "serialization/org/apache/harmony/tests/java/util/AbstractMapTest_SimpleEntry.golden.ser");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleImmutableEntryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleImmutableEntryTest.java
new file mode 100644
index 0000000..b83468e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleImmutableEntryTest.java
@@ -0,0 +1,146 @@
+/*
+ * 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.tests.java.util;
+
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.util.SerializationTester;
+import java.lang.reflect.Array;
+import java.util.AbstractMap;
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+public class SimpleImmutableEntryTest extends TestCase {
+ public void test_SimpleImmutableEntry_Constructor_K_V() throws Exception {
+ new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ new AbstractMap.SimpleImmutableEntry(null, null);
+ }
+
+ static class NullEntry implements Entry {
+
+ public Object getKey() {
+ return null;
+ }
+
+ public Object getValue() {
+ return null;
+ }
+
+ public Object setValue(Object object) {
+ return null;
+ }
+ }
+
+ public void test_SimpleImmutableEntry_Constructor_LEntry() throws Exception {
+ Map map = new TreeMap();
+ map.put(1, "test");
+ Entry entryToPut = (Entry) map.entrySet().iterator().next();
+ Entry testEntry = new AbstractMap.SimpleImmutableEntry(entryToPut);
+ assertEquals(1, testEntry.getKey());
+ assertEquals("test", testEntry.getValue());
+ map.clear();
+
+ testEntry = new AbstractMap.SimpleImmutableEntry(new NullEntry());
+ assertNull(testEntry.getKey());
+ assertNull(testEntry.getValue());
+ try {
+ new AbstractMap.SimpleImmutableEntry(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ }
+
+ public void test_SimpleImmutableEntry_getKey() throws Exception {
+ Entry entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals(1, entry.getKey());
+ entry = new AbstractMap.SimpleImmutableEntry(null, null);
+ assertNull(entry.getKey());
+ }
+
+ public void test_SimpleImmutableEntry_getValue() throws Exception {
+ Entry entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals("test", entry.getValue());
+ entry = new AbstractMap.SimpleImmutableEntry(null, null);
+ assertNull(entry.getValue());
+ }
+
+ public void test_SimpleImmutableEntry_setValue() throws Exception {
+ Entry entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals("test", entry.getValue());
+ try {
+ entry.setValue("Another String");
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ assertEquals("test", entry.getValue());
+ try {
+ entry.setValue(null);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ public void test_SimpleImmutableEntry_equals() throws Exception {
+ Entry entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ Map map = new TreeMap();
+ map.put(1, "test");
+ Entry entryToPut = (Entry) map.entrySet().iterator().next();
+ Entry testEntry = new AbstractMap.SimpleImmutableEntry(entryToPut);
+ assertEquals(entry, testEntry);
+ }
+
+ public void test_SimpleImmutableEntry_hashCode() throws Exception {
+ Entry e = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals((e.getKey() == null ? 0 : e.getKey().hashCode())
+ ^ (e.getValue() == null ? 0 : e.getValue().hashCode()), e
+ .hashCode());
+ }
+
+ public void test_SimpleImmutableEntry_toString() throws Exception {
+ Entry e = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ assertEquals(e.getKey() + "=" + e.getValue(), e.toString());
+ Object array = Array.newInstance((byte[].class).getComponentType(), 10);
+ assertEquals(10, ((byte[]) array).length);
+ }
+
+ /**
+ * serialization/deserialization.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationSelf_SimpleImmutableEntry() throws Exception {
+ Entry e = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ SerializationTest.verifySelf(e);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ @SuppressWarnings({ "unchecked", "boxing" })
+ public void testSerializationCompatibility_SimpleImmutableEntry() throws Exception {
+ SimpleImmutableEntry e = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "test");
+ if (!(SerializationTester.readObject(e, "serialization/org/apache/harmony/tests/java/util/AbstractMapTest_SimpleImmutableEntry.golden.ser") instanceof SimpleImmutableEntry)) {
+ fail("should be SimpleImmutableEntry");
+ }
+ SerializationTester.assertCompabilityEquals(e, "serialization/org/apache/harmony/tests/java/util/AbstractMapTest_SimpleImmutableEntry.golden.ser");
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleTimeZoneTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleTimeZoneTest.java
new file mode 100644
index 0000000..0fbe7ac
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SimpleTimeZoneTest.java
@@ -0,0 +1,838 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+
+public class SimpleTimeZoneTest extends junit.framework.TestCase {
+
+ SimpleTimeZone st1;
+
+ SimpleTimeZone st2;
+
+ /**
+ * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String)
+ */
+ public void test_ConstructorILjava_lang_String() {
+ // Test for method java.util.SimpleTimeZone(int, java.lang.String)
+
+ SimpleTimeZone st = new SimpleTimeZone(1000, "TEST");
+ assertEquals("Incorrect TZ constructed", "TEST", st.getID());
+ assertTrue("Incorrect TZ constructed: " + "returned wrong offset", st
+ .getRawOffset() == 1000);
+ assertTrue("Incorrect TZ constructed" + "using daylight savings", !st
+ .useDaylightTime());
+ }
+
+ /**
+ * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
+ * int, int, int, int, int, int, int, int)
+ */
+ public void test_ConstructorILjava_lang_StringIIIIIIII() {
+ // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
+ // int, int, int, int, int, int, int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0);
+ assertTrue("Incorrect TZ constructed", st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime()));
+ assertTrue("Incorrect TZ constructed", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+ assertEquals("Incorrect TZ constructed", "TEST", st.getID());
+ assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
+ assertTrue("Incorrect TZ constructed", st.useDaylightTime());
+
+ try {
+ new SimpleTimeZone(1000, "TEST", 12,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
+ 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
+ * int, int, int, int, int, int, int, int, int)
+ */
+ public void test_ConstructorILjava_lang_StringIIIIIIIII() {
+ // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
+ // int, int, int, int, int, int, int, int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, 1000 * 60 * 60);
+ assertTrue("Incorrect TZ constructed", st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime()));
+ assertTrue("Incorrect TZ constructed", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+ assertEquals("Incorrect TZ constructed", "TEST", st.getID());
+ assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
+ assertTrue("Incorrect TZ constructed", st.useDaylightTime());
+ assertTrue("Incorrect TZ constructed",
+ st.getDSTSavings() == 1000 * 60 * 60);
+
+ try {
+ new SimpleTimeZone(1000, "TEST", 12,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
+ 0, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
+ * int, int, int, int, int, int, int, int, int, int, int)
+ */
+ public void test_ConstructorILjava_lang_StringIIIIIIIIIII() {
+ // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
+ // int, int, int, int, int, int, int, int, int, int)
+ // TODO : Implement test
+ //Regression for HARMONY-1241
+ assertNotNull(new SimpleTimeZone(
+ TimeZone.LONG,
+ "Europe/Paris",
+ SimpleTimeZone.STANDARD_TIME,
+ SimpleTimeZone.STANDARD_TIME,
+ SimpleTimeZone.UTC_TIME,
+ SimpleTimeZone.WALL_TIME,
+ SimpleTimeZone.WALL_TIME,
+ TimeZone.SHORT,
+ SimpleTimeZone.STANDARD_TIME,
+ TimeZone.LONG,
+ SimpleTimeZone.UTC_TIME,
+ SimpleTimeZone.STANDARD_TIME,
+ TimeZone.LONG));
+ //seems RI doesn't check the startTimeMode and endTimeMode at all
+ //this behavior is contradicts with spec
+ assertNotNull(new SimpleTimeZone(
+ TimeZone.LONG,
+ "Europe/Paris",
+ SimpleTimeZone.STANDARD_TIME,
+ SimpleTimeZone.STANDARD_TIME,
+ SimpleTimeZone.UTC_TIME,
+ SimpleTimeZone.WALL_TIME,
+ Integer.MAX_VALUE,
+ TimeZone.SHORT,
+ SimpleTimeZone.STANDARD_TIME,
+ TimeZone.LONG,
+ SimpleTimeZone.UTC_TIME,
+ Integer.MIN_VALUE,
+ TimeZone.LONG));
+
+ try {
+ new SimpleTimeZone(1000, "TEST", 12,
+ 1, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, Integer.MAX_VALUE, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 10, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0, Integer.MAX_VALUE, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, 10, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -1, Calendar.SUNDAY,
+ 0, Integer.MAX_VALUE, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -10, Calendar.SUNDAY,
+ 0, Integer.MAX_VALUE, 1000 * 60 * 60);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.SimpleTimeZone.clone()
+ SimpleTimeZone st1 = new SimpleTimeZone(1000, "TEST",
+ Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
+ -1, Calendar.SUNDAY, 0);
+ SimpleTimeZone stA = new SimpleTimeZone(1, "Gah");
+ assertTrue("Clone resulted in same reference", st1.clone() != st1);
+ assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) st1
+ .clone()).equals(st1));
+ assertTrue("Clone resulted in same reference", stA.clone() != stA);
+ assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) stA
+ .clone()).equals(stA));
+ }
+
+ /**
+ * java.util.SimpleTimeZone#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.SimpleTimeZone.equals(java.lang.Object)
+ TimeZone tz = TimeZone.getTimeZone("EST");
+ st1 = new SimpleTimeZone(tz.getRawOffset(), "EST");
+ st2 = new SimpleTimeZone(0, "EST");
+ assertFalse(st1.equals(st2));
+ st1.setRawOffset(st2.getRawOffset());
+ assertTrue(st1.equals(st2));
+ }
+
+ /**
+ * java.util.SimpleTimeZone#getDSTSavings()
+ */
+ public void test_getDSTSavings() {
+ // Test for method int java.util.SimpleTimeZone.getDSTSavings()
+ st1 = new SimpleTimeZone(0, "TEST");
+
+ assertEquals("Non-zero default daylight savings",
+ 0, st1.getDSTSavings());
+ st1.setStartRule(0, 1, 1, 1);
+ st1.setEndRule(11, 1, 1, 1);
+
+ assertEquals("Incorrect default daylight savings",
+ 3600000, st1.getDSTSavings());
+ st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
+ -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
+ Calendar.SUNDAY, 2 * 3600000, 7200000);
+ assertEquals("Incorrect daylight savings from constructor", 7200000, st1
+ .getDSTSavings());
+
+ }
+
+ /**
+ * java.util.SimpleTimeZone#getOffset(int, int, int, int, int, int)
+ */
+ public void test_getOffsetIIIIII() {
+ // Test for method int java.util.SimpleTimeZone.getOffset(int, int, int,
+ // int, int, int)
+// TimeZone st1 = TimeZone.getTimeZone("EST");
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ assertTrue("Incorrect offset returned", st1.getOffset(
+ GregorianCalendar.AD, 1998, Calendar.NOVEMBER, 11,
+ Calendar.WEDNESDAY, 0) == -(5 * 60 * 60 * 1000));
+
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
+ .getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 11,
+ Calendar.THURSDAY, 0));
+
+ // Regression for HARMONY-5459
+ st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
+ int fourHours = 4*60*60*1000;
+ st1.setRawOffset(fourHours);
+ assertEquals(fourHours, st1.getOffset(1, 2099, 01, 1, 5, 0));
+
+ try {
+ st1.getOffset(-1, 2099, 01, 1, 5, 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ st1.getOffset(1, 2099, 15, 1, 5, 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ st1.getOffset(1, 2099, 01, 100, 5, 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ st1.getOffset(1, 2099, 01, 1, 50, 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try {
+ st1.getOffset(1, 2099, 01, 1, 5, -10);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#getRawOffset()
+ */
+ public void test_getRawOffset() {
+ // Test for method int java.util.SimpleTimeZone.getRawOffset()
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ assertTrue("Incorrect offset returned",
+ st1.getRawOffset() == -(5 * 60 * 60 * 1000));
+
+ }
+
+ /**
+ * java.util.SimpleTimeZone#hashCode()
+ */
+ public void test_hashCode() {
+ // Test for method int java.util.SimpleTimeZone.hashCode()
+ // For lack of a better test.
+ st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
+ -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
+ Calendar.SUNDAY, 2 * 3600000);
+ assertTrue(TimeZone.getTimeZone("EST").hashCode() != 0);
+ assertTrue(st1.hashCode() != 0);
+ }
+
+ /**
+ * java.util.SimpleTimeZone#hasSameRules(java.util.TimeZone)
+ */
+ public void test_hasSameRulesLjava_util_TimeZone() {
+ // Test for method boolean
+ // java.util.SimpleTimeZone.hasSameRules(java.util.TimeZone)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
+ 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
+ 0);
+ SimpleTimeZone sameAsSt = new SimpleTimeZone(1000, "REST",
+ Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
+ -1, Calendar.SUNDAY, 0);
+ SimpleTimeZone notSameAsSt = new SimpleTimeZone(1000, "PEST",
+ Calendar.NOVEMBER, 2, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
+ -1, Calendar.SUNDAY, 0);
+ assertTrue("Time zones have same rules but return false", st
+ .hasSameRules(sameAsSt));
+ assertTrue("Time zones have different rules but return true", !st
+ .hasSameRules(notSameAsSt));
+ }
+
+ /**
+ * java.util.SimpleTimeZone#inDaylightTime(java.util.Date)
+ */
+ public void test_inDaylightTimeLjava_util_Date() {
+ // Test for method boolean
+ // java.util.SimpleTimeZone.inDaylightTime(java.util.Date)
+ TimeZone tz = TimeZone.getTimeZone("EST");
+ SimpleTimeZone zone = new SimpleTimeZone(tz.getRawOffset(), "EST",
+ Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000);
+ GregorianCalendar gc = new GregorianCalendar(1998, Calendar.JUNE, 11);
+
+ assertTrue("Returned incorrect daylight value1", zone.inDaylightTime(gc
+ .getTime()));
+ gc = new GregorianCalendar(1998, Calendar.NOVEMBER, 11);
+ assertTrue("Returned incorrect daylight value2", !(zone
+ .inDaylightTime(gc.getTime())));
+ gc = new GregorianCalendar(zone);
+ gc.set(1999, Calendar.APRIL, 4, 1, 59, 59);
+ assertTrue("Returned incorrect daylight value3", !(zone
+ .inDaylightTime(gc.getTime())));
+ Date date = new Date(gc.getTime().getTime() + 1000);
+ assertTrue("Returned incorrect daylight value4", zone
+ .inDaylightTime(date));
+ gc.set(1999, Calendar.OCTOBER, 31, 1, 0, 0);
+ assertTrue("Returned incorrect daylight value5", !(zone
+ .inDaylightTime(gc.getTime())));
+ date = new Date(gc.getTime().getTime() - 1000);
+ assertTrue("Returned incorrect daylight value6", zone
+ .inDaylightTime(date));
+
+ assertTrue("Returned incorrect daylight value7", !zone
+ .inDaylightTime(new Date(891752400000L + 7200000 - 1)));
+ assertTrue("Returned incorrect daylight value8", zone
+ .inDaylightTime(new Date(891752400000L + 7200000)));
+ assertTrue("Returned incorrect daylight value9", zone
+ .inDaylightTime(new Date(909288000000L + 7200000 - 1)));
+ assertTrue("Returned incorrect daylight value10", !zone
+ .inDaylightTime(new Date(909288000000L + 7200000)));
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setDSTSavings(int)
+ */
+ public void test_setDSTSavingsI() {
+ // Test for method void java.util.SimpleTimeZone.setDSTSavings(int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ st.setStartRule(0, 1, 1, 1);
+ st.setEndRule(11, 1, 1, 1);
+ st.setDSTSavings(1);
+ assertEquals(1, st.getDSTSavings());
+ try {
+ st.setDSTSavings(0);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ st.setDSTSavings(-1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setEndRule(int, int, int)
+ */
+ public void test_setEndRuleIII() {
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ st.setStartRule(Calendar.NOVEMBER, 1, 0);
+ st.setEndRule(Calendar.NOVEMBER, 20, 0);
+ assertTrue("StartRule improperly set1", st.useDaylightTime());
+ assertTrue("StartRule improperly set2", st.inDaylightTime(
+ new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime()));
+ assertTrue("StartRule improperly set3", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+
+ try {
+ st.setEndRule(13, 20, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(1, 32, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(1, 30, 10);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setEndRule(int, int, int, int)
+ */
+ public void test_setEndRuleIIII() {
+ // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
+ // int, int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
+ st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
+ assertTrue("StartRule improperly set1", st.useDaylightTime());
+ assertTrue("StartRule improperly set2", st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime()));
+ assertTrue("StartRule improperly set3", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+
+ try {
+ st.setEndRule(12, -1, Calendar.SUNDAY, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, -1, 8, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setEndRule(int, int, int, int, boolean)
+ */
+ public void test_setEndRuleIIIIZ() {
+ // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
+ // int, int, boolean)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 8, Calendar.SUNDAY, 1, false);
+ st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, true);
+ assertTrue("StartRule improperly set1", st.useDaylightTime());
+ assertTrue("StartRule improperly set2", st
+ .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 7, 12, 0).getTime())));
+ assertTrue("StartRule improperly set3", st
+ .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 20, 12, 0).getTime())));
+ assertTrue("StartRule improperly set4", !(st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 6, 12, 0).getTime())));
+ assertTrue("StartRule improperly set5", !(st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 21, 12, 0).getTime())));
+
+ try {
+ st.setEndRule(20, 15, Calendar.SUNDAY, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, 15, 12, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setRawOffset(int)
+ */
+ public void test_setRawOffsetI() {
+ // Test for method void java.util.SimpleTimeZone.setRawOffset(int)
+
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ int off = st1.getRawOffset();
+ st1.setRawOffset(1000);
+ boolean val = st1.getRawOffset() == 1000;
+ st1.setRawOffset(off);
+ assertTrue("Incorrect offset set", val);
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setStartRule(int, int, int)
+ */
+ public void test_setStartRuleIII() {
+ // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
+ // int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 1, 1);
+ st.setEndRule(Calendar.DECEMBER, 1, 1);
+ assertTrue("StartRule improperly set", st.useDaylightTime());
+ assertTrue("StartRule improperly set", st
+ .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime())));
+ assertTrue("StartRule improperly set", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+
+ try {
+ st.setStartRule(13, 20, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(1, 32, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(1, 30, 10);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setStartRule(int, int, int, int)
+ */
+ public void test_setStartRuleIIII() {
+ // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
+ // int, int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
+ st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
+ assertTrue("StartRule improperly set1", st.useDaylightTime());
+ assertTrue("StartRule improperly set2", st
+ .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
+ 13).getTime())));
+ assertTrue("StartRule improperly set3", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+
+ try {
+ st.setStartRule(12, -1, Calendar.SUNDAY, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, -1, 8, 0);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setStartRule(int, int, int, int, boolean)
+ */
+ public void test_setStartRuleIIIIZ() {
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
+ // int, int, boolean)
+ SimpleTimeZone st = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 1, true);
+ st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, false);
+ assertTrue("StartRule improperly set1", st.useDaylightTime());
+ assertTrue("StartRule improperly set2", st
+ .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 7, 12, 0).getTime())));
+ assertTrue("StartRule improperly set3", st
+ .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 13, 12, 0).getTime())));
+ assertTrue("StartRule improperly set4", !(st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 6, 12, 0).getTime())));
+ assertTrue("StartRule improperly set5", !(st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 14, 12, 0).getTime())));
+
+ try {
+ st.setStartRule(20, 15, Calendar.SUNDAY, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, 15, 12, 1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ st.setStartRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
+ fail("IllegalArgumentException is not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.SimpleTimeZone#setStartYear(int)
+ */
+ public void test_setStartYearI() {
+ // Test for method void java.util.SimpleTimeZone.setStartYear(int)
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
+ st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
+ st.setStartYear(1999);
+ assertTrue("set year improperly set1", !(st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.JULY, 12)
+ .getTime())));
+ assertTrue("set year improperly set2", !(st
+ .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
+ 13).getTime())));
+ assertTrue("set year improperly set3", (st
+ .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
+ 13).getTime())));
+ }
+
+ /**
+ * java.util.SimpleTimeZone#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.util.SimpleTimeZone.toString()
+ String string = TimeZone.getTimeZone("EST").toString();
+ assertNotNull("toString() returned null", string);
+ assertTrue("toString() is empty", string.length() != 0);
+ }
+
+ /**
+ * java.util.SimpleTimeZone#useDaylightTime()
+ */
+ public void test_useDaylightTime() {
+ // Test for method boolean java.util.SimpleTimeZone.useDaylightTime()
+ SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
+ assertTrue("useDaylightTime returned incorrect value", !st
+ .useDaylightTime());
+ // Spec indicates that both end and start must be set or result is
+ // undefined
+ st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
+ st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
+ assertTrue("useDaylightTime returned incorrect value", st
+ .useDaylightTime());
+ }
+
+ public void test_getOffsetJ() {
+ Calendar cal = Calendar.getInstance();
+ cal.set(1998, Calendar.NOVEMBER, 11, 0, 0);
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+
+ assertTrue("Incorrect offset returned", st1.getOffset(cal.getTimeInMillis()) ==
+ -(5 * 60 * 60 * 1000));
+
+ st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
+ cal.set(1998, Calendar.JUNE, 11, 0, 0);
+ assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
+ .getOffset(cal.getTimeInMillis()));
+
+ // Regression for HARMONY-5459
+ st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
+ int fourHours = 4*60*60*1000;
+ st1.setRawOffset(fourHours);
+ cal.set(2099, 01, 1, 0, 0);
+
+ assertEquals(fourHours, st1.getOffset(cal.getTimeInMillis()));
+
+ }
+
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SortedMapTestBase.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SortedMapTestBase.java
new file mode 100644
index 0000000..f1fb1e4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/SortedMapTestBase.java
@@ -0,0 +1,369 @@
+/*
+ * 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.tests.java.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import junit.framework.TestCase;
+
+public abstract class SortedMapTestBase extends TestCase {
+
+ final int N = 1000;
+ final int TRIES = 100;
+
+ SortedMap<Integer, Integer> map;
+ SortedMap<Integer, Integer> ref;
+
+ Random rnd;
+
+ protected void setUp() throws Exception {
+ rnd = new Random(-1);
+ for (int i = 0; i < N; i++) {
+ ref.put(rnd.nextInt(N) * 2, rnd.nextBoolean() ? null : rnd.nextInt(N) * 2);
+ }
+ }
+
+ public final void testClear() {
+ map.clear();
+ assertTrue(map.isEmpty());
+ }
+
+ public final void testContainsKey() {
+ for (int i = 0; i < TRIES; i++) {
+ int key = rnd.nextInt(N);
+ assertEquals(ref.containsKey(key), map.containsKey(key));
+ }
+ }
+
+
+ public final void testContainsValue() {
+ for (int i = 0; i < TRIES; i++) {
+ int value = rnd.nextInt(N);
+ assertEquals(ref.containsValue(value), map.containsValue(value));
+ }
+ }
+
+
+ public final void testEntrySet() {
+ Set<Map.Entry<Integer, Integer>> refSet = ref.entrySet();
+ Set<Map.Entry<Integer, Integer>> mapSet = map.entrySet();
+ for (Map.Entry<Integer, Integer> e : refSet) {
+ assertTrue(mapSet.contains(e));
+ }
+ for (Map.Entry<Integer, Integer> e : mapSet) {
+ assertTrue(refSet.contains(e));
+ }
+ assertEquals(ref.entrySet(), map.entrySet());
+ }
+
+
+ public final void testGet() {
+ for (int i = 0; i < TRIES; i++) {
+ int key = rnd.nextInt(N);
+ assertEquals(ref.get(key), map.get(key));
+ }
+ }
+
+
+ public final void testKeySet() {
+ assertEquals(ref.keySet(), map.keySet());
+ Iterator<Integer> i = ref.keySet().iterator();
+ Iterator<Integer> j = map.keySet().iterator();
+ while (i.hasNext()) {
+ assertEquals(i.next(), j.next());
+ if (rnd.nextBoolean()) {
+ j.remove();
+ i.remove();
+ }
+ }
+ }
+
+
+ public final void testPut() {
+ for (int i = 0; i < TRIES; i++) {
+ int key = rnd.nextInt(N);
+ int value = rnd.nextInt(N);
+ assertEquals(ref.put(key, value), map.put(key, value));
+ assertEquals(ref.get(key), map.get(key));
+ assertEquals(ref, map);
+ }
+ }
+
+ public final void testPut0() {
+ ref.clear();
+ map.clear();
+ for (int i = 0; i < N; i++) {
+ int key = rnd.nextInt(N);
+ int value = rnd.nextInt(N);
+ assertEquals(ref.put(key, value), map.put(key, value));
+ assertEquals(ref.get(key), map.get(key));
+ }
+ }
+
+ public final void testPutAll() {
+ Map<Integer, Integer> mixin = new HashMap<Integer, Integer>(TRIES);
+ for (int i = 0; i < TRIES; i++) {
+ mixin.put(rnd.nextInt(N), rnd.nextInt(N));
+ }
+ ref.putAll(mixin);
+ map.putAll(mixin);
+ assertEquals(ref, map);
+ }
+
+
+ public final void testRemove() {
+ for (int i = 0; i < N; i++) {
+ int key = rnd.nextInt(N);
+ assertEquals(ref.remove(key), map.remove(key));
+ if (i % (N / TRIES) == 0) {
+ assertEquals(ref, map);
+ }
+ }
+ }
+
+ public final void testRemove0() {
+ while (!ref.isEmpty()) {
+ int key = ref.tailMap((ref.firstKey() + ref.lastKey()) / 2)
+ .firstKey();
+ assertEquals(ref.remove(key), map.remove(key));
+ }
+ }
+
+ public final void testSize() {
+ assertEquals(ref.size(), map.size());
+ }
+
+
+ public final void testValues() {
+ assertEquals(ref.values().size(), map.values().size());
+ assertTrue(ref.values().containsAll(map.values()));
+ assertTrue(map.values().containsAll(ref.values()));
+
+ Iterator<Integer> i = ref.values().iterator();
+ Iterator<Integer> j = map.values().iterator();
+ while (i.hasNext()) {
+ assertEquals(i.next(), j.next());
+ if (rnd.nextBoolean()) {
+ j.remove();
+ i.remove();
+ }
+ }
+ }
+
+ public final void testComparator() {
+ assertEquals(ref.comparator(), map.comparator());
+ }
+
+
+ public final void testFirstKey() {
+ assertEquals(ref.firstKey(), map.firstKey());
+ }
+
+
+ public final void testHeadMap() {
+ for (int i = 0; i < TRIES; i++) {
+ int key = rnd.nextInt(N);
+ checkSubMap(ref.headMap(key), map.headMap(key));
+ }
+ checkSubMap(ref.headMap(-1), map.headMap(-1));
+ }
+
+ public final void testLastKey() {
+ assertEquals(ref.lastKey(), map.lastKey());
+ }
+
+ public final void testSubMap() {
+ for (int i = 0; i < TRIES; i++) {
+ int key0 = rnd.nextInt(N / 2);
+ int key1 = rnd.nextInt(N / 2) + N / 2;
+ if (ref.comparator() != null &&
+ ref.comparator().compare(key0, key1) > 0) {
+
+ int tmp = key0;
+ key0 = key1;
+ key1 = tmp;
+ }
+ checkSubMap(ref.subMap(key0, key1), map.subMap(key0, key1));
+ }
+ boolean caught = false;
+ try {
+ if (ref.comparator() != null && ref.comparator().compare(100, 0) < 0) {
+ map.subMap(0, 100);
+ } else {
+ map.subMap(100, 0);
+ }
+ } catch (IllegalArgumentException e) {
+ caught = true;
+ }
+ assertTrue(caught);
+
+ int firstKey = ref.firstKey();
+ Map.Entry<Integer, Integer> refE = ref.entrySet().iterator().next();
+ Map.Entry<Integer, Integer> mapE = map.entrySet().iterator().next();
+ mapE.setValue(-1);
+ refE.setValue(-1);
+ assertEquals(ref.get(firstKey), map.get(firstKey));
+ }
+
+
+ public final void testTailMap() {
+ for (int i = 0; i < TRIES; i++) {
+ int key = rnd.nextInt(2 * N);
+ checkSubMap(ref.tailMap(key), map.tailMap(key));
+ }
+ checkSubMap(ref.tailMap(2 * N + 1), map.tailMap(2 * N + 1));
+ }
+
+
+ public final void testHashCode() {
+ assertEquals(ref.hashCode(), map.hashCode());
+ }
+
+ public final void testEqualsObject() {
+ assertTrue(map.equals(ref));
+ map.put(N + 1, N + 1);
+ assertFalse(map.equals(ref));
+ }
+
+
+ public final void testIsEmpty() {
+ assertEquals(ref.isEmpty(), map.isEmpty());
+ }
+
+ public final void testIsEmpty2() {
+ TreeMap<String, String> map = new TreeMap<String, String>();
+ map.put("one", "1");
+ assertEquals("size should be one", 1, map.size());
+ map.clear();
+ assertEquals("size should be zero", 0, map.size());
+ assertTrue("Should not have entries", !map.entrySet().iterator()
+ .hasNext());
+
+ map.put("one", "1");
+ assertEquals("size should be one", 1, map.size());
+ map.remove("one");
+ assertEquals("size should be zero", 0, map.size());
+ assertTrue("Should not have entries", !map.entrySet().iterator()
+ .hasNext());
+
+ map.clear();
+ map.put("0", "1");
+ map.clear();
+ assertTrue(map.isEmpty());
+ assertFalse(map.entrySet().iterator().hasNext());
+ assertFalse(map.keySet().iterator().hasNext());
+ assertFalse(map.values().iterator().hasNext());
+ }
+
+ public final void testToString() {
+ assertEquals(ref.toString(), map.toString());
+ }
+
+ private void checkSubMap(SortedMap<Integer, Integer> ref,
+ SortedMap<Integer, Integer> map) {
+
+ assertEquals(ref.size(), map.size());
+ assertEquals(ref, map);
+ assertEquals(ref.isEmpty(), map.isEmpty());
+ if (!ref.isEmpty()) {
+ assertEquals(ref.firstKey(), map.firstKey());
+ assertEquals(ref.lastKey(), map.lastKey());
+
+ testViews(ref, map);
+ } else {
+ boolean caught = false;
+ try {
+ map.firstKey();
+ } catch (NoSuchElementException e) {
+ caught = true;
+ }
+ caught = false;
+ try {
+ map.lastKey();
+ } catch (NoSuchElementException e) {
+ caught = true;
+ }
+ assertTrue(caught);
+ }
+
+ }
+
+ public final void testViews() {
+ testViews(ref, map);
+ }
+
+ private void testViews(SortedMap<Integer, Integer> ref, SortedMap<Integer, Integer> map) {
+ assertEquals(ref.keySet().size(), map.keySet().size());
+ assertEquals(ref.keySet(), map.keySet());
+ compareIterators(ref.keySet(), map.keySet());
+
+ assertEquals(ref.values().size(), map.values().size());
+ compareIterators(ref.values(), map.values());
+
+ assertEquals(ref.entrySet(), map.entrySet());
+ compareIterators(ref.entrySet(), map.entrySet());
+ }
+
+ private void compareIterators(Collection ref, Collection map) {
+ Iterator i = ref.iterator();
+ Iterator j = map.iterator();
+ while (i.hasNext()) {
+ assertEquals(i.next(), j.next());
+ if (rnd.nextBoolean()) {
+ j.remove();
+ i.remove();
+ assertEquals(ref.size(), map.size());
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public final void testSerialization() throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(map);
+ oos.close();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+ Object read = ois.readObject();
+ assertEquals(ref, read);
+ }
+
+ public final void testClone() throws Exception {
+ Method refClone = ref.getClass().getMethod("clone", new Class[0]);
+ Method mapClone = map.getClass().getMethod("clone", new Class[0]);
+ SortedMap<Integer, Integer> map2 = (SortedMap<Integer, Integer>) mapClone.invoke(map, new Object[0]);
+ assertEquals(refClone.invoke(ref, new Object[0]), map2);
+ map2.remove(map2.lastKey());
+ assertFalse(ref.equals(map2));
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StackTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StackTest.java
new file mode 100644
index 0000000..7be5a56
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StackTest.java
@@ -0,0 +1,214 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.EmptyStackException;
+import java.util.Stack;
+
+public class StackTest extends junit.framework.TestCase {
+
+ Stack s;
+
+ /**
+ * java.util.Stack#Stack()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.Stack()
+ assertEquals("Stack creation failed", 0, s.size());
+ }
+
+ /**
+ * java.util.Stack#empty()
+ */
+ public void test_empty() {
+ // Test for method boolean java.util.Stack.empty()
+ assertTrue("New stack answers non-empty", s.empty());
+ s.push("blah");
+ assertTrue("Stack should not be empty but answers empty", !s.empty());
+ s.pop();
+ assertTrue("Stack should be empty but answers non-empty", s.empty());
+ s.push(null);
+ assertTrue("Stack with null should not be empty but answers empty", !s
+ .empty());
+ }
+
+ /**
+ * java.util.Stack#peek()
+ */
+ public void test_peek() {
+ // Test for method java.lang.Object java.util.Stack.peek()
+ String item1 = "Ichi";
+ String item2 = "Ni";
+ String item3 = "San";
+ s.push(item1);
+ assertTrue("Peek did not return top item when it was the only item", s
+ .peek() == item1);
+ s.push(item2);
+ s.push(item3);
+ assertTrue("Peek did not return top item amoung many other items", s
+ .peek() == item3);
+ s.pop();
+ assertTrue("Peek did not return top item after a pop", s.pop() == item2);
+ s.push(null);
+ assertNull("Peek did not return top item (wanted: null)",
+ s.peek());
+ s.pop();
+ s.pop();
+ try {
+ s.pop();
+ fail("EmptyStackException expected");
+ } catch (EmptyStackException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.Stack#pop()
+ */
+ public void test_pop() {
+ // Test for method java.lang.Object java.util.Stack.pop()
+ String item1 = "Ichi";
+ String item2 = "Ni";
+ Object lastPopped;
+ s.push(item1);
+ s.push(item2);
+
+ try {
+ lastPopped = s.pop();
+ assertTrue("a) Pop did not return top item", lastPopped == item2);
+ } catch (EmptyStackException e) {
+ fail(
+ "a) Pop threw EmptyStackException when stack should not have been empty");
+ }
+
+ try {
+ lastPopped = s.pop();
+ assertTrue("b) Pop did not return top item", lastPopped == item1);
+ } catch (EmptyStackException e) {
+ fail(
+ "b) Pop threw EmptyStackException when stack should not have been empty");
+ }
+
+ s.push(null);
+ try {
+ lastPopped = s.pop();
+ assertNull("c) Pop did not return top item", lastPopped);
+ } catch (EmptyStackException e) {
+ fail(
+ "c) Pop threw EmptyStackException when stack should not have been empty");
+ }
+
+ try {
+ lastPopped = s.pop();
+ fail(
+ "d) Pop did not throw EmptyStackException when stack should have been empty");
+ } catch (EmptyStackException e) {
+ return;
+ }
+
+ }
+
+ /**
+ * java.util.Stack#push(java.lang.Object)
+ */
+ public void test_pushLjava_lang_Object() {
+ Object [] array = {new Integer(0), new Object(),
+ new Float(0), new String()};
+
+ Stack<Object> stack = new Stack<Object>();
+ for(int i = 0; i < array.length; i++) {
+ stack.push(array[i]);
+ }
+ for(int i = 0; i < array.length; i++) {
+ assertEquals(array.length - i, stack.search(array[i]));
+ }
+ }
+
+ /**
+ * java.util.Stack#search(java.lang.Object)
+ */
+ public void test_searchLjava_lang_Object() {
+ // Test for method int java.util.Stack.search(java.lang.Object)
+ String item1 = "Ichi";
+ String item2 = "Ni";
+ String item3 = "San";
+ s.push(item1);
+ s.push(item2);
+ s.push(item3);
+ assertEquals("Search returned incorrect value for equivalent object", 3, s
+ .search(item1));
+ assertEquals("Search returned incorrect value for equal object", 3, s
+ .search("Ichi"));
+ s.pop();
+ assertEquals("Search returned incorrect value for equivalent object at top of stack",
+ 1, s.search(item2));
+ assertEquals("Search returned incorrect value for equal object at top of stack",
+ 1, s.search("Ni"));
+ s.push(null);
+ assertEquals("Search returned incorrect value for search for null at top of stack",
+ 1, s.search(null));
+ s.push("Shi");
+ assertEquals("Search returned incorrect value for search for null", 2, s
+ .search(null));
+ s.pop();
+ s.pop();
+ assertEquals("Search returned incorrect value for search for null--wanted -1",
+ -1, s.search(null));
+ }
+
+ static class BugStack<E> extends Stack<E> {
+ public void setLength(int elementCount) {
+ this.elementCount = elementCount;
+ }
+
+ public int getLength() {
+ return elementCount;
+ }
+ }
+
+ //test for wrong exception threw by pop method
+ public void test_pop_modify_elementCount() {
+ BugStack<String> testStack = new BugStack<String>();
+ testStack.push("A");
+ testStack.push("B");
+ testStack.setLength(20);
+ try {
+ testStack.pop();
+ fail("Should throw ArrayIndexOutOfBoundsException here");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ //Expected to throw ArrayIndexOutOfBoundsException here
+ } catch (EmptyStackException e) {
+ fail("Should throw ArrayIndexOutOfBoundsException here");
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ s = new Stack();
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StringTokenizerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StringTokenizerTest.java
new file mode 100644
index 0000000..eeed19f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/StringTokenizerTest.java
@@ -0,0 +1,311 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+public class StringTokenizerTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.StringTokenizer#StringTokenizer(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.StringTokenizer(java.lang.String)
+ try {
+ new StringTokenizer(null);
+ fail("NullPointerException is not thrown.");
+ } catch(NullPointerException npe) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.StringTokenizer#StringTokenizer(java.lang.String,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() {
+ // Test for method java.util.StringTokenizer(java.lang.String,
+ // java.lang.String)
+ StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":");
+ assertTrue("Created incorrect tokenizer", st.countTokens() == 5
+ && (st.nextElement().equals("This")));
+ st = new StringTokenizer("This:is:a:test:String", null);
+
+ try {
+ new StringTokenizer(null, ":");
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.StringTokenizer#StringTokenizer(java.lang.String,
+ * java.lang.String, boolean)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringZ() {
+ // Test for method java.util.StringTokenizer(java.lang.String,
+ // java.lang.String, boolean)
+ StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":",
+ true);
+ st.nextElement();
+ assertTrue("Created incorrect tokenizer", st.countTokens() == 8
+ && (st.nextElement().equals(":")));
+ st = new StringTokenizer("This:is:a:test:String", null, true);
+ st = new StringTokenizer("This:is:a:test:String", null, false);
+
+ try {
+ new StringTokenizer(null, ":", true);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.StringTokenizer#countTokens()
+ */
+ public void test_countTokens() {
+ // Test for method int java.util.StringTokenizer.countTokens()
+ StringTokenizer st = new StringTokenizer("This is a test String");
+
+ assertEquals("Incorrect token count returned", 5, st.countTokens());
+ }
+
+ /**
+ * java.util.StringTokenizer#hasMoreElements()
+ */
+ public void test_hasMoreElements() {
+ // Test for method boolean java.util.StringTokenizer.hasMoreElements()
+
+ StringTokenizer st = new StringTokenizer("This is a test String");
+ st.nextElement();
+ assertTrue("hasMoreElements returned incorrect value", st
+ .hasMoreElements());
+ st.nextElement();
+ st.nextElement();
+ st.nextElement();
+ st.nextElement();
+ assertTrue("hasMoreElements returned incorrect value", !st
+ .hasMoreElements());
+ }
+
+ /**
+ * java.util.StringTokenizer#hasMoreTokens()
+ */
+ public void test_hasMoreTokens() {
+ // Test for method boolean java.util.StringTokenizer.hasMoreTokens()
+ StringTokenizer st = new StringTokenizer("This is a test String");
+ for (int counter = 0; counter < 5; counter++) {
+ assertTrue(
+ "StringTokenizer incorrectly reports it has no more tokens",
+ st.hasMoreTokens());
+ st.nextToken();
+ }
+ assertTrue("StringTokenizer incorrectly reports it has more tokens",
+ !st.hasMoreTokens());
+ }
+
+ /**
+ * java.util.StringTokenizer#nextElement()
+ */
+ public void test_nextElement() {
+ // Test for method java.lang.Object
+ // java.util.StringTokenizer.nextElement()
+ StringTokenizer st = new StringTokenizer("This is a test String");
+ assertEquals("nextElement returned incorrect value", "This", ((String) st
+ .nextElement()));
+ assertEquals("nextElement returned incorrect value", "is", ((String) st
+ .nextElement()));
+ assertEquals("nextElement returned incorrect value", "a", ((String) st
+ .nextElement()));
+ assertEquals("nextElement returned incorrect value", "test", ((String) st
+ .nextElement()));
+ assertEquals("nextElement returned incorrect value", "String", ((String) st
+ .nextElement()));
+ try {
+ st.nextElement();
+ fail(
+ "nextElement failed to throw a NoSuchElementException when it should have been out of elements");
+ } catch (NoSuchElementException e) {
+ return;
+ }
+ }
+
+ /**
+ * java.util.StringTokenizer#nextToken()
+ */
+ public void test_nextToken() {
+ // Test for method java.lang.String
+ // java.util.StringTokenizer.nextToken()
+ StringTokenizer st = new StringTokenizer("This is a test String");
+ assertEquals("nextToken returned incorrect value",
+ "This", st.nextToken());
+ assertEquals("nextToken returned incorrect value",
+ "is", st.nextToken());
+ assertEquals("nextToken returned incorrect value",
+ "a", st.nextToken());
+ assertEquals("nextToken returned incorrect value",
+ "test", st.nextToken());
+ assertEquals("nextToken returned incorrect value",
+ "String", st.nextToken());
+ try {
+ st.nextToken();
+ fail(
+ "nextToken failed to throw a NoSuchElementException when it should have been out of elements");
+ } catch (NoSuchElementException e) {
+ return;
+ }
+ }
+
+ /**
+ * java.util.StringTokenizer#nextToken(java.lang.String)
+ */
+ public void test_nextTokenLjava_lang_String() {
+ // Test for method java.lang.String
+ // java.util.StringTokenizer.nextToken(java.lang.String)
+ StringTokenizer st = new StringTokenizer("This is a test String");
+ assertEquals("nextToken(String) returned incorrect value with normal token String",
+ "This", st.nextToken(" "));
+ assertEquals("nextToken(String) returned incorrect value with custom token String",
+ " is a ", st.nextToken("tr"));
+ assertEquals("calling nextToken() did not use the new default delimiter list",
+ "es", st.nextToken());
+ st = new StringTokenizer("This:is:a:test:String", " ");
+ assertTrue(st.nextToken(":").equals("This"));
+ assertTrue(st.nextToken(":").equals("is"));
+ assertTrue(st.nextToken(":").equals("a"));
+ assertTrue(st.nextToken(":").equals("test"));
+ assertTrue(st.nextToken(":").equals("String"));
+
+ try {
+ st.nextToken(":");
+ fail("NoSuchElementException expected");
+ } catch (NoSuchElementException e) {
+ //expected
+ }
+
+ try {
+ st.nextToken(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ public void test_hasMoreElements_NPE() {
+ StringTokenizer stringTokenizer = new StringTokenizer(new String(),
+ (String) null, true);
+ try {
+ stringTokenizer.hasMoreElements();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ stringTokenizer = new StringTokenizer(new String(), (String) null);
+ try {
+ stringTokenizer.hasMoreElements();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void test_hasMoreTokens_NPE() {
+ StringTokenizer stringTokenizer = new StringTokenizer(new String(),
+ (String) null, true);
+ try {
+ stringTokenizer.hasMoreTokens();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ stringTokenizer = new StringTokenizer(new String(), (String) null);
+ try {
+ stringTokenizer.hasMoreTokens();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void test_nextElement_NPE() {
+ StringTokenizer stringTokenizer = new StringTokenizer(new String(),
+ (String) null, true);
+ try {
+ stringTokenizer.nextElement();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ stringTokenizer = new StringTokenizer(new String(), (String) null);
+ try {
+ stringTokenizer.nextElement();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void test_nextToken_NPE() {
+ StringTokenizer stringTokenizer = new StringTokenizer(new String(),
+ (String) null, true);
+ try {
+ stringTokenizer.nextToken();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ stringTokenizer = new StringTokenizer(new String(), (String) null);
+ try {
+ stringTokenizer.nextToken();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void test_nextTokenLjava_lang_String_NPE() {
+ StringTokenizer stringTokenizer = new StringTokenizer(new String());
+ try {
+ stringTokenizer.nextToken(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimeZoneTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimeZoneTest.java
new file mode 100644
index 0000000..0d16786
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimeZoneTest.java
@@ -0,0 +1,301 @@
+/*
+ * 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.tests.java.util;
+
+import tests.support.Support_TimeZone;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Locale;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+
+public class TimeZoneTest extends junit.framework.TestCase {
+
+ private static final int ONE_HOUR = 3600000;
+
+ private TimeZone processDefault;
+
+ /**
+ * java.util.TimeZone#getDefault()
+ */
+ public void test_getDefault() {
+ assertNotSame("returns identical",
+ TimeZone.getDefault(), TimeZone.getDefault());
+ }
+
+ /**
+ * java.util.TimeZone#getDSTSavings()
+ */
+ public void test_getDSTSavings() {
+ // Test for method int java.util.TimeZone.getDSTSavings()
+
+ // test on subclass SimpleTimeZone
+ TimeZone st1 = TimeZone.getTimeZone("America/New_York");
+ assertEquals("T1A. Incorrect daylight savings returned",
+ ONE_HOUR, st1.getDSTSavings());
+
+ // a SimpleTimeZone with daylight savings different then 1 hour
+ st1 = TimeZone.getTimeZone("Australia/Lord_Howe");
+ assertEquals("T1B. Incorrect daylight savings returned",
+ 1800000, st1.getDSTSavings());
+
+ // test on subclass Support_TimeZone, an instance with daylight savings
+ TimeZone tz1 = new Support_TimeZone(-5 * ONE_HOUR, true);
+ assertEquals("T2. Incorrect daylight savings returned",
+ ONE_HOUR, tz1.getDSTSavings());
+
+ // an instance without daylight savings
+ tz1 = new Support_TimeZone(3 * ONE_HOUR, false);
+ assertEquals("T3. Incorrect daylight savings returned, ",
+ 0, tz1.getDSTSavings());
+ }
+
+ /**
+ * java.util.TimeZone#getOffset(long)
+ */
+ public void test_getOffset_long() {
+ // Test for method int java.util.TimeZone.getOffset(long time)
+
+ // test on subclass SimpleTimeZone
+ TimeZone st1 = TimeZone.getTimeZone("EST");
+ long time1 = new GregorianCalendar(1998, Calendar.NOVEMBER, 11)
+ .getTimeInMillis();
+ assertEquals("T1. Incorrect offset returned",
+ -(5 * ONE_HOUR), st1.getOffset(time1));
+
+ long time2 = new GregorianCalendar(1998, Calendar.JUNE, 11)
+ .getTimeInMillis();
+ st1 = TimeZone.getTimeZone("EST");
+ assertEquals("T2. Incorrect offset returned",
+ -(5 * ONE_HOUR), st1.getOffset(time2));
+
+ // test on subclass Support_TimeZone, an instance with daylight savings
+ TimeZone tz1 = new Support_TimeZone(-5 * ONE_HOUR, true);
+ assertEquals("T3. Incorrect offset returned, ",
+ -(5 * ONE_HOUR), tz1.getOffset(time1));
+ assertEquals("T4. Incorrect offset returned, ",
+ -(4 * ONE_HOUR), tz1.getOffset(time2));
+
+ // an instance without daylight savings
+ tz1 = new Support_TimeZone(3 * ONE_HOUR, false);
+ assertEquals("T5. Incorrect offset returned, ",
+ (3 * ONE_HOUR), tz1.getOffset(time1));
+ assertEquals("T6. Incorrect offset returned, ",
+ (3 * ONE_HOUR), tz1.getOffset(time2));
+ }
+
+ /**
+ * java.util.TimeZone#getTimeZone(java.lang.String)
+ */
+ public void test_getTimeZoneLjava_lang_String() {
+ assertEquals("Must return GMT when given an invalid TimeZone id SMT-8.",
+ "GMT", TimeZone.getTimeZone("SMT-8").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+28:70.",
+ "GMT", TimeZone.getTimeZone("GMT+28:70").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+28:30.",
+ "GMT", TimeZone.getTimeZone("GMT+28:30").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+8:70.",
+ "GMT", TimeZone.getTimeZone("GMT+8:70").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+3:.",
+ "GMT", TimeZone.getTimeZone("GMT+3:").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+3:0.",
+ "GMT", TimeZone.getTimeZone("GMT+3:0").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+2360.",
+ "GMT", TimeZone.getTimeZone("GMT+2360").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+892.",
+ "GMT", TimeZone.getTimeZone("GMT+892").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+082.",
+ "GMT", TimeZone.getTimeZone("GMT+082").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+28.",
+ "GMT", TimeZone.getTimeZone("GMT+28").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT+30.",
+ "GMT", TimeZone.getTimeZone("GMT+30").getID());
+ assertEquals("Must return GMT when given TimeZone GMT.",
+ "GMT", TimeZone.getTimeZone("GMT").getID());
+ assertEquals("Must return GMT when given TimeZone GMT+.",
+ "GMT", TimeZone.getTimeZone("GMT+").getID());
+ assertEquals("Must return GMT when given TimeZone GMT-.",
+ "GMT", TimeZone.getTimeZone("GMT-").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT-8.45.",
+ "GMT", TimeZone.getTimeZone("GMT-8.45").getID());
+ assertEquals("Must return GMT when given an invalid TimeZone time GMT-123:23.",
+ "GMT", TimeZone.getTimeZone("GMT-123:23").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+8:30 (eg. GMT+08:20).",
+ "GMT+08:30", TimeZone.getTimeZone("GMT+8:30").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+3 (eg. GMT+08:20).",
+ "GMT+03:00", TimeZone.getTimeZone("GMT+3").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+3:02 (eg. GMT+08:20).",
+ "GMT+03:02", TimeZone.getTimeZone("GMT+3:02").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+2359 (eg. GMT+08:20).",
+ "GMT+23:59", TimeZone.getTimeZone("GMT+2359").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+520 (eg. GMT+08:20).",
+ "GMT+05:20", TimeZone.getTimeZone("GMT+520").getID());
+ assertEquals("Must return proper GMT formatted string for GMT+052 (eg. GMT+08:20).",
+ "GMT+00:52", TimeZone.getTimeZone("GMT+052").getID());
+ // GMT-0 is an available ID in ICU, so replace it with GMT-00
+ assertEquals("Must return proper GMT formatted string for GMT-00 (eg. GMT+08:20).",
+ "GMT-00:00", TimeZone.getTimeZone("GMT-00").getID());
+ }
+
+ /**
+ * java.util.TimeZone#setDefault(java.util.TimeZone)
+ */
+ public void test_setDefaultLjava_util_TimeZone() {
+ // NOTE: Required to get tests passing under vogar. Vogar sets
+ // a hardcoded timezone before running every test, so we have to
+ // set it back to the "real" default before we run the test.
+ TimeZone.setDefault(null);
+
+ TimeZone oldDefault = TimeZone.getDefault();
+ TimeZone zone = new SimpleTimeZone(45, "TEST");
+ TimeZone.setDefault(zone);
+ assertEquals("timezone not set", zone, TimeZone.getDefault());
+ TimeZone.setDefault(null);
+ assertEquals("default not restored",
+ oldDefault, TimeZone.getDefault());
+ }
+
+ /**
+ * java.util.TimeZone#getDisplayName(java.util.Locale)
+ */
+ public void test_getDisplayNameLjava_util_Locale() {
+ TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");
+ assertEquals("\u4e2d\u56fd\u6807\u51c6\u65f6\u95f4", timezone
+ .getDisplayName(Locale.CHINA));
+ }
+
+ /**
+ * java.util.TimeZone#getDisplayName(boolean, int, java.util.Locale)
+ */
+ public void test_getDisplayNameZILjava_util_Locale() {
+ TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");
+ /* Time zone data was changed in ICU49.2. Many common short names were removed. */
+ assertEquals("中国标准时间",
+ timezone.getDisplayName(false, TimeZone.LONG, Locale.CHINA));
+ assertEquals("GMT+08:00",
+ timezone.getDisplayName(false, TimeZone.SHORT, Locale.CHINA));
+ try {
+ timezone.getDisplayName(false, 100, Locale.CHINA);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Regression for HARMONY-5860
+ */
+ public void test_GetTimezoneOffset() {
+ // America/Toronto is lazy initialized
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Toronto"));
+ Date date = new Date(07, 2, 24);
+ assertEquals(300, date.getTimezoneOffset());
+ date = new Date(99, 8, 1);
+ assertEquals(240, date.getTimezoneOffset());
+ }
+
+ protected void setUp() {
+ processDefault = TimeZone.getDefault();
+ }
+
+ protected void tearDown() {
+ TimeZone.setDefault(processDefault);
+ }
+
+ public void test_getAvailableIDs_I_16947622() {
+ TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
+ int rawOffset = tz.getRawOffset();
+ assertEquals(-8 * 60 * 60 * 1000, rawOffset);
+ List<String> ids = Arrays.asList(TimeZone.getAvailableIDs(rawOffset));
+
+ // Obviously, for all time zones, the time zone whose raw offset we started with
+ // should be one of the available ids for that offset.
+ assertTrue(ids.toString(), ids.contains("America/Los_Angeles"));
+
+ // Any one of these might legitimately change its raw offset, though that's
+ // fairly unlikely, and the chances of more than one changing are very slim.
+ assertTrue(ids.toString(), ids.contains("America/Dawson"));
+ assertTrue(ids.toString(), ids.contains("America/Tijuana"));
+ assertTrue(ids.toString(), ids.contains("America/Vancouver"));
+ assertTrue(ids.toString(), ids.contains("Canada/Pacific"));
+ assertTrue(ids.toString(), ids.contains("Canada/Yukon"));
+ assertTrue(ids.toString(), ids.contains("Pacific/Pitcairn"));
+ }
+
+ public void test_getAvailableIDs_I() {
+ TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
+ int rawoffset = tz.getRawOffset();
+ String[] ids = TimeZone.getAvailableIDs(rawoffset);
+ List<String> idList = Arrays.asList(ids);
+ assertTrue(idList.toString(), idList.contains("Asia/Hong_Kong"));
+ }
+
+ /**
+ * @add test {@link java.util.TimeZone#getDisplayName()}
+ */
+ public void test_getDisplayName() {
+ TimeZone defaultZone = TimeZone.getDefault();
+ Locale defaulLocal = Locale.getDefault();
+ String defaultName = defaultZone.getDisplayName();
+ String expectedName = defaultZone.getDisplayName(defaulLocal);
+ assertEquals(
+ "getDispalyName() did not return the default Locale suitable name",
+ expectedName, defaultName);
+ }
+
+ /**
+ * @add test {@link java.util.TimeZone#getDisplayName(boolean, int)}
+ */
+ public void test_getDisplayName_ZI() {
+ TimeZone defaultZone = TimeZone.getDefault();
+ Locale defaultLocale = Locale.getDefault();
+ String actualName = defaultZone.getDisplayName(false, TimeZone.LONG);
+ String expectedName = defaultZone.getDisplayName(false, TimeZone.LONG,
+ defaultLocale);
+ assertEquals(
+ "getDisplayName(daylight,style) did not return the default locale suitable name",
+ expectedName, actualName);
+ }
+
+ /**
+ * @add test {@link java.util.TimeZone#hasSameRules(TimeZone)}
+ */
+ public void test_hasSameRules_Ljava_util_TimeZone() {
+ TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
+ int offset = tz.getRawOffset();
+
+ String[] ids = TimeZone.getAvailableIDs(offset);
+ int i = 0;
+ if (ids.length != 0) {
+ while (true) {
+ if (!(ids[i].equalsIgnoreCase(tz.getID()))) {
+ TimeZone sameZone = TimeZone.getTimeZone(ids[i]);
+ assertTrue(tz.hasSameRules(sameZone));
+ break;
+ } else {
+ i++;
+ }
+ }
+ }
+ assertFalse("should return false when parameter is null", tz
+ .hasSameRules(null));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTaskTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTaskTest.java
new file mode 100644
index 0000000..3e072e7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTaskTest.java
@@ -0,0 +1,248 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+public class TimerTaskTest extends junit.framework.TestCase {
+ /**
+ * Warning: These tests have the possibility to leave a VM hanging if the
+ * Timer is not cancelled.
+ */
+ class TimerTestTask extends TimerTask {
+
+ private final Object sync = new Object();
+ private final Object start = new Object();
+
+ private int wasRun = 0;
+
+ // Set this to true to see normal tests fail (or hang possibly)
+ // The default is false and needs to be set by some tests
+ private boolean sleepInRun = false;
+
+ public void run() {
+ synchronized (this) {
+ wasRun++;
+ }
+ synchronized (start) {
+ start.notify();
+ }
+ if (sleepInRun) {
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ }
+ }
+ synchronized (sync) {
+ sync.notify();
+ }
+ }
+
+ public synchronized int wasRun() {
+ return wasRun;
+ }
+
+ public void sleepInRun(boolean value) {
+ sleepInRun = value;
+ }
+ }
+
+ /**
+ * java.util.TimerTask#TimerTask()
+ */
+ public void test_Constructor() {
+ // Ensure the constructor does not fail
+ new TimerTestTask();
+ }
+
+ /**
+ * java.util.TimerTask#cancel()
+ */
+ public void test_cancel() {
+ Timer t = null;
+ try {
+ // Ensure cancel returns false if never scheduled
+ TimerTestTask testTask = new TimerTestTask();
+ assertTrue("Unsheduled tasks should return false for cancel()",
+ !testTask.cancel());
+
+ // Ensure cancelled task never runs
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 500);
+ assertTrue("TimerTask should not have run yet", testTask.cancel());
+ t.cancel();
+
+ // Ensure cancelling a task which has already run returns true
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 50);
+ while (testTask.wasRun() == 0) {
+ try {
+ Thread.sleep(150);
+ } catch (InterruptedException e) {
+ }
+ }
+ assertFalse(
+ "TimerTask.cancel() should return false if task has run",
+ testTask.cancel());
+ assertFalse(
+ "TimerTask.cancel() should return false if called a second time",
+ testTask.cancel());
+ t.cancel();
+
+ // Ensure cancelling a repeated execution task which has never run
+ // returns true
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 500, 500); // should never run
+ assertTrue(
+ "TimerTask.cancel() should return true if sheduled for repeated execution even if not run",
+ testTask.cancel());
+ t.cancel();
+
+ // Ensure cancelling a repeated execution task which HAS run returns
+ // true
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 50, 50);
+ while (testTask.wasRun() == 0) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ }
+ }
+ assertTrue(
+ "TimerTask.cancel() should return true if sheduled for repeated execution and run",
+ testTask.cancel());
+ t.cancel();
+
+ // Ensure calling cancel a second returns false
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 5000); // Should never run
+ assertTrue(
+ "TimerTask.cancel() should return true if task has never run",
+ testTask.cancel());
+ assertFalse(
+ "TimerTask.cancel() should return false if called a second time",
+ testTask.cancel());
+ t.cancel();
+
+ // Ensure cancelling a task won't cause deadlock
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.sleepInRun(true);
+ synchronized (testTask.start) {
+ t.schedule(testTask, 0);
+ try {
+ testTask.start.wait();
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ }
+ }
+ assertFalse("TimerTask should have been cancelled", testTask
+ .cancel());
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.TimerTask#scheduledExecutionTime()
+ */
+ public void test_scheduledExecutionTime() {
+ Timer t = null;
+ try {
+ // Ensure scheduledExecutionTime is roughly right
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.schedule(testTask, 100);
+ long time = System.currentTimeMillis() + 100;
+ synchronized (testTask.sync) {
+ try {
+ testTask.sync.wait(500);
+ } catch (InterruptedException e) {
+ }
+ }
+ long scheduledExecutionTime = testTask.scheduledExecutionTime();
+ assertTrue(scheduledExecutionTime <= time);
+ t.cancel();
+
+ // Ensure scheduledExecutionTime is the last scheduled time
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 100, 500);
+ long estNow = System.currentTimeMillis() + 100;
+ // Will wake in 100, and every 500 run again
+ // We want to try to get it after it's run at least once but not
+ // twice
+ synchronized (testTask.sync) {
+ try {
+ testTask.sync.wait(500);
+ } catch (InterruptedException e) {
+ }
+ }
+ scheduledExecutionTime = testTask.scheduledExecutionTime();
+ assertTrue(scheduledExecutionTime <= estNow);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ }
+
+ /**
+ * java.util.TimerTask#run()
+ */
+ public void test_run() {
+ Timer t = null;
+ try {
+ // Ensure a new task is never run
+ TimerTestTask testTask = new TimerTestTask();
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ }
+ assertEquals("TimerTask.run() method should not have been called",
+ 0, testTask.wasRun());
+
+ // Ensure a task is run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ while(testTask.wasRun() < 1) {
+ try {
+ Thread.sleep(400);
+ } catch (InterruptedException e) {
+ }
+ }
+ assertFalse(testTask.cancel());
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTest.java
new file mode 100644
index 0000000..85e7c6a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TimerTest.java
@@ -0,0 +1,986 @@
+/*
+ * 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.tests.java.util;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.Date;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicReference;
+import junit.framework.TestCase;
+
+public class TimerTest extends TestCase {
+
+ int timerCounter = 0;
+
+ private final Object sync = new Object();
+
+ /**
+ * Warning: These tests have the possibility to leave a VM hanging if the
+ * Timer is not cancelled.
+ */
+ class TimerTestTask extends TimerTask {
+ int wasRun = 0;
+
+ // Should we sleep for 200 ms each run()?
+ boolean sleepInRun = false;
+
+ // Should we increment the timerCounter?
+ boolean incrementCount = false;
+
+ // Should we terminate the timer at a specific timerCounter?
+ int terminateCount = -1;
+
+ // The timer we belong to
+ Timer timer = null;
+
+ public TimerTestTask() {
+ }
+
+ public TimerTestTask(Timer t) {
+ timer = t;
+ }
+
+ public void run() {
+ synchronized (this) {
+ wasRun++;
+ }
+ if (incrementCount) {
+ timerCounter++;
+ }
+ if (terminateCount == timerCounter && timer != null) {
+ timer.cancel();
+ }
+ if (sleepInRun) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ synchronized (sync) {
+ sync.notify();
+ }
+ }
+
+ public synchronized int wasRun() {
+ return wasRun;
+ }
+
+ public void sleepInRun(boolean sleepInRun) {
+ this.sleepInRun = sleepInRun;
+ }
+
+ public void incrementCount(boolean incrementCount) {
+ this.incrementCount = incrementCount;
+ }
+
+ public void terminateCount(int terminateCount) {
+ this.terminateCount = terminateCount;
+ }
+ }
+
+ private void awaitRun(TimerTestTask task) throws Exception {
+ while (task.wasRun() == 0) {
+ Thread.sleep(150);
+ }
+ }
+
+ /**
+ * java.util.Timer#Timer(boolean)
+ */
+ public void test_ConstructorZ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a task is run
+ t = new Timer(true);
+ TimerTestTask testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ awaitRun(testTask);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ }
+
+ /**
+ * java.util.Timer#Timer()
+ */
+ public void test_Constructor() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a task is run
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ awaitRun(testTask);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ }
+
+ /**
+ * java.util.Timer#Timer(String, boolean)
+ */
+ public void test_ConstructorSZ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a task is run
+ t = new Timer("test_ConstructorSZThread", true);
+ TimerTestTask testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ awaitRun(testTask);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ try {
+ new Timer(null, true);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ new Timer(null, false);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * java.util.Timer#Timer(String)
+ */
+ public void test_ConstructorS() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a task is run
+ t = new Timer("test_ConstructorSThread");
+ TimerTestTask testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ awaitRun(testTask);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ try {
+ new Timer(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * java.util.Timer#cancel()
+ */
+ public void test_cancel() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a task throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.cancel();
+ try {
+ t.schedule(testTask, 100, 200);
+ fail("Scheduling a task after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a task is run but not after cancel
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 100, 500);
+ awaitRun(testTask);
+ t.cancel();
+ synchronized (sync) {
+ sync.wait(500);
+ }
+ assertEquals("TimerTask.run() method should not have been called after cancel",
+ 1, testTask.wasRun());
+
+ // Ensure you can call cancel more than once
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 100, 500);
+ awaitRun(testTask);
+ t.cancel();
+ t.cancel();
+ t.cancel();
+ synchronized (sync) {
+ sync.wait(500);
+ }
+ assertEquals("TimerTask.run() method should not have been called after cancel",
+ 1, testTask.wasRun());
+
+ // Ensure that a call to cancel from within a timer ensures no more
+ // run
+ t = new Timer();
+ testTask = new TimerTestTask(t);
+ testTask.incrementCount(true);
+ testTask.terminateCount(5); // Terminate after 5 runs
+ t.schedule(testTask, 100, 100);
+ synchronized (sync) {
+ sync.wait(200);
+ assertEquals(1, testTask.wasRun());
+ sync.wait(200);
+ assertEquals(2, testTask.wasRun());
+ sync.wait(200);
+ assertEquals(3, testTask.wasRun());
+ sync.wait(200);
+ assertEquals(4, testTask.wasRun());
+ sync.wait(200);
+ assertEquals(5, testTask.wasRun());
+ sync.wait(200);
+ assertEquals(5, testTask.wasRun());
+ }
+ t.cancel();
+ Thread.sleep(200);
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+
+ }
+
+ /**
+ * java.util.Timer#purge()
+ */
+ public void test_purge() throws Exception {
+ Timer t = null;
+ try {
+ t = new Timer();
+ assertEquals(0, t.purge());
+
+ TimerTestTask[] tasks = new TimerTestTask[100];
+ int[] delayTime = { 50, 80, 20, 70, 40, 10, 90, 30, 60 };
+
+ int j = 0;
+ for (int i = 0; i < 100; i++) {
+ tasks[i] = new TimerTestTask();
+ t.schedule(tasks[i], delayTime[j++], 200);
+ if (j == 9) {
+ j = 0;
+ }
+ }
+
+ for (int i = 0; i < 50; i++) {
+ tasks[i].cancel();
+ }
+
+ assertTrue(t.purge() <= 50);
+ assertEquals(0, t.purge());
+ } finally {
+ if (t != null) {
+ t.cancel();
+ }
+ }
+ }
+
+ /**
+ * java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
+ */
+ public void test_scheduleLjava_util_TimerTaskLjava_util_Date() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ Date d = new Date(System.currentTimeMillis() + 100);
+ t.cancel();
+ try {
+ t.schedule(testTask, d);
+ fail("Scheduling a task after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalStateException if task already
+ // cancelled
+ t = new Timer();
+ testTask = new TimerTestTask();
+ d = new Date(System.currentTimeMillis() + 100);
+ testTask.cancel();
+ try {
+ t.schedule(testTask, d);
+ fail("Scheduling a task after cancelling it should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ d = new Date(-100);
+ try {
+ t.schedule(testTask, d);
+ fail("Scheduling a task with negative date should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the task is null
+ t = new Timer();
+ d = new Date(System.currentTimeMillis() + 100);
+ try {
+ t.schedule(null, d);
+ fail("Scheduling a null task should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the date is null
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, null);
+ fail("Scheduling a null date should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ d = new Date(-100);
+ try {
+ t.schedule(null, d);
+ fail("Scheduling a null task with negative date should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ d = new Date(System.currentTimeMillis() + 200);
+ t.schedule(testTask, d);
+ awaitRun(testTask);
+ t.cancel();
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 100);
+ t.schedule(testTask, d);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 150);
+ t.schedule(testTask, d);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 70);
+ t.schedule(testTask, d);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 10);
+ t.schedule(testTask, d);
+ Thread.sleep(400);
+ assertTrue("Multiple tasks should have incremented counter 4 times not "
+ + timerCounter, timerCounter == 4);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.Timer#schedule(java.util.TimerTask, long)
+ */
+ public void test_scheduleLjava_util_TimerTaskJ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.cancel();
+ try {
+ t.schedule(testTask, 100);
+ fail("Scheduling a task after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalStateException if task already
+ // cancelled
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.cancel();
+ try {
+ t.schedule(testTask, 100);
+ fail("Scheduling a task after cancelling it should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, -100);
+ fail("Scheduling a task with negative delay should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the task is null
+ t = new Timer();
+ try {
+ t.schedule(null, 10);
+ fail("Scheduling a null task should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ try {
+ t.schedule(null, -10);
+ fail("Scheduling a null task with negative delays should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 200);
+ awaitRun(testTask);
+ t.cancel();
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 100);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 150);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 70);
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 10);
+ Thread.sleep(400);
+ assertTrue("Multiple tasks should have incremented counter 4 times not "
+ + timerCounter, timerCounter == 4);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.Timer#schedule(java.util.TimerTask, long, long)
+ */
+ public void test_scheduleLjava_util_TimerTaskJJ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.cancel();
+ try {
+ t.schedule(testTask, 100, 100);
+ fail("Scheduling a task after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalStateException if task already
+ // cancelled
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.cancel();
+ try {
+ t.schedule(testTask, 100, 100);
+ fail("Scheduling a task after cancelling it should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, -100, 100);
+ fail("Scheduling a task with negative delay should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if period is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, 100, -100);
+ fail("Scheduling a task with negative period should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if period is
+ // zero
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, 100, 0);
+ fail("Scheduling a task with 0 period should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the task is null
+ t = new Timer();
+ try {
+ t.schedule(null, 10, 10);
+ fail("Scheduling a null task should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ try {
+ t.schedule(null, -10, -10);
+ fail("Scheduling a null task with negative delays should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run at least twice
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.schedule(testTask, 100, 100);
+ Thread.sleep(400);
+ assertTrue("TimerTask.run() method should have been called at least twice ("
+ + testTask.wasRun() + ")", testTask.wasRun() >= 2);
+ t.cancel();
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 100, 100); // at least 9 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 200, 100); // at least 7 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 300, 200); // at least 4 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ t.schedule(testTask, 100, 200); // at least 4 times
+ Thread.sleep(1200); // Allowed more room for error
+ assertTrue("Multiple tasks should have incremented counter 24 times not "
+ + timerCounter, timerCounter >= 24);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.Timer#schedule(java.util.TimerTask, java.util.Date,
+ * long)
+ */
+ public void test_scheduleLjava_util_TimerTaskLjava_util_DateJ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ Date d = new Date(System.currentTimeMillis() + 100);
+ t.cancel();
+ try {
+ t.schedule(testTask, d, 100);
+ fail("Scheduling a task after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalStateException if task already
+ // cancelled
+ t = new Timer();
+ d = new Date(System.currentTimeMillis() + 100);
+ testTask = new TimerTestTask();
+ testTask.cancel();
+ try {
+ t.schedule(testTask, d, 100);
+ fail("Scheduling a task after cancelling it should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ d = new Date(-100);
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, d, 100);
+ fail("Scheduling a task with negative delay should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if period is
+ // negative
+ t = new Timer();
+ d = new Date(System.currentTimeMillis() + 100);
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, d, -100);
+ fail("Scheduling a task with negative period should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the task is null
+ t = new Timer();
+ d = new Date(System.currentTimeMillis() + 100);
+ try {
+ t.schedule(null, d, 10);
+ fail("Scheduling a null task should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws a NullPointerException if the date is null
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.schedule(testTask, null, 10);
+ fail("Scheduling a null task should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ d = new Date(-100);
+ try {
+ t.schedule(null, d, 10);
+ fail("Scheduling a null task with negative dates should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run at least twice
+ t = new Timer();
+ d = new Date(System.currentTimeMillis() + 100);
+ testTask = new TimerTestTask();
+ t.schedule(testTask, d, 100);
+ Thread.sleep(800);
+ assertTrue("TimerTask.run() method should have been called at least twice ("
+ + testTask.wasRun() + ")", testTask.wasRun() >= 2);
+ t.cancel();
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 100);
+ t.schedule(testTask, d, 100); // at least 9 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 200);
+ t.schedule(testTask, d, 100); // at least 7 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 300);
+ t.schedule(testTask, d, 200); // at least 4 times
+ testTask = new TimerTestTask();
+ testTask.incrementCount(true);
+ d = new Date(System.currentTimeMillis() + 100);
+ t.schedule(testTask, d, 200); // at least 4 times
+ Thread.sleep(3000);
+ assertTrue("Multiple tasks should have incremented counter 24 times not "
+ + timerCounter, timerCounter >= 24);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long,
+ * long)
+ */
+ public void test_scheduleAtFixedRateLjava_util_TimerTaskJJ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.cancel();
+ try {
+ t.scheduleAtFixedRate(testTask, 100, 100);
+ fail("scheduleAtFixedRate after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.scheduleAtFixedRate(testTask, -100, 100);
+ fail("scheduleAtFixedRate with negative delay should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if period is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.scheduleAtFixedRate(testTask, 100, -100);
+ fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run at least twice
+ t = new Timer();
+ testTask = new TimerTestTask();
+ t.scheduleAtFixedRate(testTask, 100, 100);
+ Thread.sleep(400);
+ assertTrue("TimerTask.run() method should have been called at least twice ("
+ + testTask.wasRun() + ")", testTask.wasRun() >= 2);
+ t.cancel();
+
+ class SlowThenFastTask extends TimerTask {
+ int wasRun = 0;
+
+ long startedAt;
+
+ long lastDelta;
+
+ public void run() {
+ if (wasRun == 0)
+ startedAt = System.currentTimeMillis();
+ lastDelta = System.currentTimeMillis()
+ - (startedAt + (100 * wasRun));
+ wasRun++;
+ if (wasRun == 2) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ public long lastDelta() {
+ return lastDelta;
+ }
+
+ public int wasRun() {
+ return wasRun;
+ }
+ }
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
+
+ // at least 9 times even when asleep
+ t.scheduleAtFixedRate(slowThenFastTask, 100, 100);
+ Thread.sleep(1000);
+ long lastDelta = slowThenFastTask.lastDelta();
+ assertTrue("Fixed Rate Schedule should catch up, but is off by "
+ + lastDelta + " ms", slowThenFastTask.lastDelta < 300);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,
+ * java.util.Date, long)
+ */
+ public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() throws Exception {
+ Timer t = null;
+ try {
+ // Ensure a Timer throws an IllegalStateException after cancelled
+ t = new Timer();
+ TimerTestTask testTask = new TimerTestTask();
+ t.cancel();
+ Date d = new Date(System.currentTimeMillis() + 100);
+ try {
+ t.scheduleAtFixedRate(testTask, d, 100);
+ fail("scheduleAtFixedRate after Timer.cancel() should throw exception");
+ } catch (IllegalStateException expected) {
+ }
+
+ // Ensure a Timer throws an IllegalArgumentException if delay is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ d = new Date(-100);
+ try {
+ t.scheduleAtFixedRate(testTask, d, 100);
+ fail("scheduleAtFixedRate with negative Date should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an IllegalArgumentException if period is
+ // negative
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.scheduleAtFixedRate(testTask, d, -100);
+ fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a Timer throws an NullPointerException if date is Null
+ t = new Timer();
+ testTask = new TimerTestTask();
+ try {
+ t.scheduleAtFixedRate(testTask, null, 100);
+ fail("scheduleAtFixedRate with null date should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ d = new Date(-100);
+ try {
+ t.scheduleAtFixedRate(null, d, 10);
+ fail("Scheduling a null task with negative date should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure proper sequence of exceptions
+ t = new Timer();
+ try {
+ t.scheduleAtFixedRate(null, null, -10);
+ fail("Scheduling a null task & null date & negative period should throw IllegalArgumentException first");
+ } catch (IllegalArgumentException expected) {
+ }
+ t.cancel();
+
+ // Ensure a task is run at least twice
+ t = new Timer();
+ testTask = new TimerTestTask();
+ d = new Date(System.currentTimeMillis() + 100);
+ t.scheduleAtFixedRate(testTask, d, 100);
+ Thread.sleep(400);
+ assertTrue("TimerTask.run() method should have been called at least twice ("
+ + testTask.wasRun() + ")", testTask.wasRun() >= 2);
+ t.cancel();
+
+ class SlowThenFastTask extends TimerTask {
+ int wasRun = 0;
+
+ long startedAt;
+
+ long lastDelta;
+
+ public void run() {
+ if (wasRun == 0)
+ startedAt = System.currentTimeMillis();
+ lastDelta = System.currentTimeMillis()
+ - (startedAt + (100 * wasRun));
+ wasRun++;
+ if (wasRun == 2) {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ public long lastDelta() {
+ return lastDelta;
+ }
+
+ public int wasRun() {
+ return wasRun;
+ }
+ }
+
+ // Ensure multiple tasks are run
+ t = new Timer();
+ SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
+ d = new Date(System.currentTimeMillis() + 100);
+
+ // at least 9 times even when asleep
+ t.scheduleAtFixedRate(slowThenFastTask, d, 100);
+ Thread.sleep(1000);
+ long lastDelta = slowThenFastTask.lastDelta();
+ assertTrue("Fixed Rate Schedule should catch up, but is off by "
+ + lastDelta + " ms", lastDelta < 300);
+ t.cancel();
+ } finally {
+ if (t != null)
+ t.cancel();
+ }
+ }
+
+ /**
+ * We used to swallow RuntimeExceptions thrown by tasks. Instead, we need to
+ * let those exceptions bubble up, where they will both notify the thread's
+ * uncaught exception handler and terminate the timer's thread.
+ */
+ public void testThrowingTaskKillsTimerThread() throws Exception {
+ final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
+ new Timer().schedule(new TimerTask() {
+ @Override public void run() {
+ Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
+ public void uncaughtException(Thread thread, Throwable ex) {}
+ });
+ threadRef.set(Thread.currentThread());
+ throw new RuntimeException("task failure!");
+ }
+ }, 1);
+
+ Thread.sleep(400);
+ Thread timerThread = threadRef.get();
+ assertFalse(timerThread.isAlive());
+ }
+
+ protected void setUp() {
+ timerCounter = 0;
+ }
+
+ protected void tearDown() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TooManyListenersExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TooManyListenersExceptionTest.java
new file mode 100644
index 0000000..6683e96
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TooManyListenersExceptionTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.TooManyListenersException;
+
+public class TooManyListenersExceptionTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.TooManyListenersException#TooManyListenersException()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.TooManyListenersException()
+ try {
+ throw new TooManyListenersException();
+ } catch (TooManyListenersException e) {
+ assertNull(
+ "Message thrown with exception constructed with no message",
+ e.getMessage());
+ }
+ }
+
+ /**
+ * java.util.TooManyListenersException#TooManyListenersException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.TooManyListenersException(java.lang.String)
+ try {
+ throw new TooManyListenersException("Gah");
+ } catch (TooManyListenersException e) {
+ assertEquals("Incorrect message thrown with exception", "Gah", e
+ .getMessage());
+ }
+ }
+
+ /**
+ * 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() {
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapExtendTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapExtendTest.java
new file mode 100644
index 0000000..5754468
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapExtendTest.java
@@ -0,0 +1,13581 @@
+package org.apache.harmony.tests.java.util;
+
+/*
+ * 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.
+ */
+
+import junit.framework.TestCase;
+import org.apache.harmony.tests.java.util.TreeMapTest.MockComparator;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.NavigableMap;
+import java.util.NavigableSet;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+
+//
+public class TreeMapExtendTest extends TestCase {
+
+ TreeMap tm;
+
+ TreeMap tm_comparator;
+
+ SortedMap subMap_default;
+
+ SortedMap subMap_startExcluded_endExcluded;
+
+ SortedMap subMap_startExcluded_endIncluded;
+
+ SortedMap subMap_startIncluded_endExcluded;
+
+ SortedMap subMap_startIncluded_endIncluded;
+
+ SortedMap subMap_default_beforeStart_100;
+
+ SortedMap subMap_default_afterEnd_109;
+
+ NavigableMap navigableMap_startExcluded_endExcluded;
+
+ NavigableMap navigableMap_startExcluded_endIncluded;
+
+ NavigableMap navigableMap_startIncluded_endExcluded;
+
+ NavigableMap navigableMap_startIncluded_endIncluded;
+
+ SortedMap subMap_default_comparator;
+
+ SortedMap subMap_startExcluded_endExcluded_comparator;
+
+ SortedMap subMap_startExcluded_endIncluded_comparator;
+
+ SortedMap subMap_startIncluded_endExcluded_comparator;
+
+ SortedMap subMap_startIncluded_endIncluded_comparator;
+
+ Object objArray[] = new Object[1000];
+
+ public void test_TreeMap_Constructor_Default() {
+ TreeMap treeMap = new TreeMap();
+ assertTrue(treeMap.isEmpty());
+ assertNull(treeMap.comparator());
+ assertEquals(0, treeMap.size());
+
+ try {
+ treeMap.firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ assertNull(treeMap.firstEntry());
+
+ try {
+ treeMap.lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ assertNull(treeMap.lastEntry());
+
+ try {
+ treeMap.ceilingKey(1);
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ assertNull(treeMap.ceilingEntry(1));
+
+ try {
+ treeMap.floorKey(1);
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ assertNull(treeMap.floorEntry(1));
+ assertNull(treeMap.lowerKey(1));
+ assertNull(treeMap.lowerEntry(1));
+ assertNull(treeMap.higherKey(1));
+ assertNull(treeMap.higherEntry(1));
+ assertFalse(treeMap.containsKey(1));
+ assertFalse(treeMap.containsValue(1));
+ assertNull(treeMap.get(1));
+
+ assertNull(treeMap.pollFirstEntry());
+ assertNull(treeMap.pollLastEntry());
+ assertEquals(0, treeMap.values().size());
+ }
+
+ public void test_TreeMap_Constructor_Comparator() {
+ MockComparator mockComparator = new MockComparator();
+ TreeMap treeMap = new TreeMap(mockComparator);
+
+ assertEquals(mockComparator, treeMap.comparator());
+ }
+
+ public void test_TreeMap_Constructor_Map() {
+ TreeMap treeMap = new TreeMap(tm);
+ assertEquals(tm.size(), treeMap.size());
+ assertEquals(tm.firstKey(), treeMap.firstKey());
+ assertEquals(tm.firstEntry(), treeMap.firstEntry());
+ assertEquals(tm.lastKey(), treeMap.lastKey());
+ assertEquals(tm.lastEntry(), treeMap.lastEntry());
+ assertEquals(tm.keySet(), treeMap.keySet());
+
+ String key = new Integer(100).toString();
+ assertEquals(tm.ceilingKey(key), treeMap.ceilingKey(key));
+ assertEquals(tm.ceilingEntry(key), treeMap.ceilingEntry(key));
+ assertEquals(tm.floorKey(key), treeMap.floorKey(key));
+ assertEquals(tm.floorEntry(key), treeMap.floorEntry(key));
+ assertEquals(tm.lowerKey(key), treeMap.lowerKey(key));
+ assertEquals(tm.lowerEntry(key), treeMap.lowerEntry(key));
+ assertEquals(tm.higherKey(key), treeMap.higherKey(key));
+ assertEquals(tm.higherEntry(key), treeMap.higherEntry(key));
+ assertEquals(tm.entrySet(), treeMap.entrySet());
+ }
+
+ public void test_TreeMap_Constructor_SortedMap() {
+ TreeMap treeMap = new TreeMap(subMap_default);
+ assertEquals(subMap_default.size(), treeMap.size());
+ assertEquals(subMap_default.firstKey(), treeMap.firstKey());
+ assertEquals(subMap_default.lastKey(), treeMap.lastKey());
+ assertEquals(subMap_default.keySet(), treeMap.keySet());
+ assertEquals(subMap_default.entrySet(), treeMap.entrySet());
+ }
+
+ public void test_TreeMap_clear() {
+ tm.clear();
+ assertEquals(0, tm.size());
+ }
+
+ public void test_TreeMap_clone() {
+ TreeMap cloneTreeMap = (TreeMap) tm.clone();
+ assertEquals(tm, cloneTreeMap);
+ }
+
+ public void test_SubMap_Constructor() {
+ }
+
+ public void test_SubMap_clear() {
+ subMap_default.clear();
+ assertEquals(0, subMap_default.size());
+ }
+
+ public void test_SubMap_comparator() {
+ assertEquals(tm.comparator(), subMap_default.comparator());
+ }
+
+ public void test_SubMap_containsKey() {
+ String key = null;
+ for (int counter = 101; counter < 109; counter++) {
+ key = objArray[counter].toString();
+ assertTrue("SubMap contains incorrect elements", subMap_default
+ .containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsKey(key));
+ }
+
+ // Check boundary
+ key = objArray[100].toString();
+ assertTrue("SubMap contains incorrect elements", subMap_default
+ .containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsKey(key));
+
+ key = objArray[109].toString();
+ assertFalse("SubMap contains incorrect elements", subMap_default
+ .containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsKey(key));
+
+ // With Comparator
+ for (int counter = 101; counter < 109; counter++) {
+ key = objArray[counter].toString();
+ assertTrue("SubMap contains incorrect elements",
+ subMap_default_comparator.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded_comparator
+ .containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded_comparator
+ .containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded_comparator
+ .containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded_comparator
+ .containsKey(key));
+ }
+
+ // Check boundary
+ key = objArray[100].toString();
+ assertTrue("SubMap contains incorrect elements",
+ subMap_default_comparator.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded_comparator.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded_comparator.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded_comparator.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded_comparator.containsKey(key));
+
+ key = objArray[109].toString();
+ assertFalse("SubMap contains incorrect elements",
+ subMap_default_comparator.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded_comparator.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded_comparator.containsKey(key));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded_comparator.containsKey(key));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded_comparator.containsKey(key));
+ }
+
+ public void test_SubMap_containsValue() {
+ Object value = null;
+ for (int counter = 101; counter < 109; counter++) {
+ value = objArray[counter];
+ assertTrue("SubMap contains incorrect elements", subMap_default
+ .containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsValue(value));
+ }
+
+ // Check boundary
+ value = objArray[100];
+ assertTrue("SubMap contains incorrect elements", subMap_default
+ .containsValue(value));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsValue(value));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsValue(value));
+
+ value = objArray[109];
+ assertFalse("SubMap contains incorrect elements", subMap_default
+ .containsValue(value));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startExcluded_endExcluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startExcluded_endIncluded.containsValue(value));
+ assertFalse("SubMap contains incorrect elements",
+ subMap_startIncluded_endExcluded.containsValue(value));
+ assertTrue("SubMap contains incorrect elements",
+ subMap_startIncluded_endIncluded.containsValue(value));
+
+ assertFalse(subMap_default.containsValue(null));
+
+ TreeMap tm_null = new TreeMap();
+ tm_null.put("0", 1);
+ tm_null.put("1", null);
+ tm_null.put("2", 2);
+ SortedMap subMap = tm_null.subMap("0", "2");
+ assertTrue(subMap.containsValue(null));
+
+ subMap.remove("1");
+ assertFalse(subMap.containsValue(null));
+ }
+
+ public void test_SubMap_entrySet() {
+ Set entrySet = subMap_default.entrySet();
+ assertFalse(entrySet.isEmpty());
+ assertEquals(9, entrySet.size());
+
+ entrySet = subMap_startExcluded_endExcluded.entrySet();
+ assertFalse(entrySet.isEmpty());
+ assertEquals(8, entrySet.size());
+
+ entrySet = subMap_startExcluded_endIncluded.entrySet();
+ assertFalse(entrySet.isEmpty());
+ assertEquals(9, entrySet.size());
+
+ entrySet = subMap_startIncluded_endExcluded.entrySet();
+ assertFalse(entrySet.isEmpty());
+ assertEquals(9, entrySet.size());
+
+ entrySet = subMap_startIncluded_endIncluded.entrySet();
+ assertFalse(entrySet.isEmpty());
+ assertEquals(10, entrySet.size());
+ }
+
+ public void test_SubMap_firstKey() {
+ String firstKey1 = new Integer(100).toString();
+ String firstKey2 = new Integer(101).toString();
+ assertEquals(firstKey1, subMap_default.firstKey());
+ assertEquals(firstKey2, subMap_startExcluded_endExcluded.firstKey());
+ assertEquals(firstKey2, subMap_startExcluded_endIncluded.firstKey());
+ assertEquals(firstKey1, subMap_startIncluded_endExcluded.firstKey());
+ assertEquals(firstKey1, subMap_startIncluded_endIncluded.firstKey());
+
+ try {
+ subMap_default.subMap(firstKey1, firstKey1).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.subMap(firstKey2, firstKey2)
+ .firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.subMap(firstKey2, firstKey2)
+ .firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.subMap(firstKey1, firstKey1)
+ .firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.subMap(firstKey1, firstKey1)
+ .firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ // With Comparator
+ assertEquals(firstKey1, subMap_default_comparator.firstKey());
+ assertEquals(firstKey2, subMap_startExcluded_endExcluded_comparator
+ .firstKey());
+ assertEquals(firstKey2, subMap_startExcluded_endIncluded_comparator
+ .firstKey());
+ assertEquals(firstKey1, subMap_startIncluded_endExcluded_comparator
+ .firstKey());
+ assertEquals(firstKey1, subMap_startIncluded_endIncluded_comparator
+ .firstKey());
+
+ try {
+ subMap_default_comparator.subMap(firstKey1, firstKey1).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator.subMap(firstKey2,
+ firstKey2).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded_comparator.subMap(firstKey2,
+ firstKey2).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded_comparator.subMap(firstKey1,
+ firstKey1).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded_comparator.subMap(firstKey1,
+ firstKey1).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ }
+
+ public void test_SubMap_lastKey() {
+ String lastKey1 = new Integer(108).toString();
+ String lastKey2 = new Integer(109).toString();
+ assertEquals(lastKey1, subMap_default.lastKey());
+ assertEquals(lastKey1, subMap_startExcluded_endExcluded.lastKey());
+ assertEquals(lastKey2, subMap_startExcluded_endIncluded.lastKey());
+ assertEquals(lastKey1, subMap_startIncluded_endExcluded.lastKey());
+ assertEquals(lastKey2, subMap_startIncluded_endIncluded.lastKey());
+
+ try {
+ subMap_default.subMap(lastKey1, lastKey1).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.subMap(lastKey1, lastKey1)
+ .lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.subMap(lastKey2, lastKey2)
+ .lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.subMap(lastKey1, lastKey1)
+ .lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.subMap(lastKey2, lastKey2)
+ .lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ // With Comparator
+ assertEquals(lastKey1, subMap_default_comparator.lastKey());
+ assertEquals(lastKey1, subMap_startExcluded_endExcluded_comparator
+ .lastKey());
+ assertEquals(lastKey2, subMap_startExcluded_endIncluded_comparator
+ .lastKey());
+ assertEquals(lastKey1, subMap_startIncluded_endExcluded_comparator
+ .lastKey());
+ assertEquals(lastKey2, subMap_startIncluded_endIncluded_comparator
+ .lastKey());
+
+ try {
+ subMap_default_comparator.subMap(lastKey1, lastKey1).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator.subMap(lastKey1,
+ lastKey1).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded_comparator.subMap(lastKey2,
+ lastKey2).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded_comparator.subMap(lastKey1,
+ lastKey1).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded_comparator.subMap(lastKey2,
+ lastKey2).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ public void test_SubMap_get() {
+ // left boundary
+ Integer value = new Integer(100);
+ assertEquals(value, subMap_default.get(value.toString()));
+ assertEquals(null, subMap_startExcluded_endExcluded.get(value
+ .toString()));
+ assertEquals(null, subMap_startExcluded_endIncluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startIncluded_endExcluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startIncluded_endIncluded.get(value
+ .toString()));
+
+ // normal value
+ value = new Integer(105);
+ assertEquals(value, subMap_default.get(value.toString()));
+ assertEquals(value, subMap_startExcluded_endExcluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startExcluded_endIncluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startIncluded_endExcluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startIncluded_endIncluded.get(value
+ .toString()));
+
+ // right boundary
+ value = new Integer(109);
+ assertEquals(null, subMap_default.get(value.toString()));
+ assertEquals(null, subMap_startExcluded_endExcluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startExcluded_endIncluded.get(value
+ .toString()));
+ assertEquals(null, subMap_startIncluded_endExcluded.get(value
+ .toString()));
+ assertEquals(value, subMap_startIncluded_endIncluded.get(value
+ .toString()));
+
+ // With Comparator to test inInRange
+ // left boundary
+ value = new Integer(100);
+ assertEquals(value, subMap_default_comparator.get(value.toString()));
+
+ // normal value
+ value = new Integer(105);
+ assertEquals(value, subMap_default_comparator.get(value.toString()));
+
+ // right boundary
+ value = new Integer(109);
+ assertEquals(null, subMap_default_comparator.get(value.toString()));
+ }
+
+ public void test_SubMap_headMap() {
+ String endKey = new Integer(99).toString();
+ try {
+ subMap_default.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ SortedMap headMap = null;
+ endKey = new Integer(100).toString();
+ headMap = subMap_default.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ try {
+ headMap = subMap_startExcluded_endExcluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ headMap = subMap_startExcluded_endIncluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ headMap = subMap_startIncluded_endExcluded.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ for (int i = 0, j = 101; i < 8; i++) {
+ endKey = new Integer(i + j).toString();
+ headMap = subMap_default.headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+
+ headMap = subMap_startExcluded_endExcluded.headMap(endKey);
+ assertEquals(i, headMap.size());
+
+ headMap = subMap_startExcluded_endIncluded.headMap(endKey);
+ assertEquals(i, headMap.size());
+
+ headMap = subMap_startIncluded_endExcluded.headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded.headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+ }
+
+ endKey = new Integer(109).toString();
+ headMap = subMap_default.headMap(endKey);
+ assertEquals(9, headMap.size());
+
+ headMap = subMap_startExcluded_endExcluded.headMap(endKey);
+ assertEquals(8, headMap.size());
+
+ headMap = subMap_startExcluded_endIncluded.headMap(endKey);
+ assertEquals(8, headMap.size());
+
+ headMap = subMap_startIncluded_endExcluded.headMap(endKey);
+ assertEquals(9, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded.headMap(endKey);
+ assertEquals(9, headMap.size());
+
+ endKey = new Integer(110).toString();
+ try {
+ subMap_default.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // With Comparator
+ endKey = new Integer(99).toString();
+ try {
+ subMap_default_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ headMap = null;
+ endKey = new Integer(100).toString();
+ headMap = subMap_default_comparator.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ try {
+ headMap = subMap_startExcluded_endExcluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ headMap = subMap_startExcluded_endIncluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ headMap = subMap_startIncluded_endExcluded_comparator.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded_comparator.headMap(endKey);
+ assertEquals(0, headMap.size());
+
+ for (int i = 0, j = 101; i < 8; i++) {
+ endKey = new Integer(i + j).toString();
+ headMap = subMap_default_comparator.headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+
+ headMap = subMap_startExcluded_endExcluded_comparator
+ .headMap(endKey);
+ assertEquals(i, headMap.size());
+
+ headMap = subMap_startExcluded_endIncluded_comparator
+ .headMap(endKey);
+ assertEquals(i, headMap.size());
+
+ headMap = subMap_startIncluded_endExcluded_comparator
+ .headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded_comparator
+ .headMap(endKey);
+ assertEquals(i + 1, headMap.size());
+ }
+
+ endKey = new Integer(108).toString();
+ headMap = subMap_default_comparator.headMap(endKey);
+ assertEquals(8, headMap.size());
+
+ headMap = subMap_startExcluded_endExcluded_comparator.headMap(endKey);
+ assertEquals(7, headMap.size());
+
+ headMap = subMap_startExcluded_endIncluded_comparator.headMap(endKey);
+ assertEquals(7, headMap.size());
+
+ headMap = subMap_startIncluded_endExcluded_comparator.headMap(endKey);
+ assertEquals(8, headMap.size());
+
+ headMap = subMap_startIncluded_endIncluded_comparator.headMap(endKey);
+ assertEquals(8, headMap.size());
+
+ endKey = new Integer(110).toString();
+ try {
+ subMap_default_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded_comparator.headMap(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_SubMap_isEmpty() {
+ assertFalse(subMap_default.isEmpty());
+ assertFalse(subMap_startExcluded_endExcluded.isEmpty());
+ assertFalse(subMap_startExcluded_endIncluded.isEmpty());
+ assertFalse(subMap_startIncluded_endExcluded.isEmpty());
+ assertFalse(subMap_startIncluded_endIncluded.isEmpty());
+
+ Object startKey = new Integer(100);
+ Object endKey = startKey;
+ SortedMap subMap = tm.subMap(startKey.toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+ subMap = subMap_default.subMap(startKey.toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+ subMap = subMap_startIncluded_endExcluded.subMap(startKey.toString(),
+ endKey.toString());
+ assertTrue(subMap.isEmpty());
+ subMap = subMap_startIncluded_endIncluded.subMap(startKey.toString(),
+ endKey.toString());
+ assertTrue(subMap.isEmpty());
+
+ for (int i = 0, j = 101; i < 8; i++) {
+ startKey = i + j;
+ endKey = startKey;
+
+ subMap = subMap_default.subMap(startKey.toString(), endKey
+ .toString());
+ assertTrue(subMap.isEmpty());
+
+ subMap = subMap_startExcluded_endExcluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+
+ subMap = subMap_startExcluded_endIncluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+
+ subMap = subMap_startIncluded_endExcluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+
+ subMap = subMap_startIncluded_endIncluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+ }
+
+ for (int i = 0, j = 101; i < 5; i++) {
+ startKey = i + j;
+ endKey = i + j + 4;
+
+ subMap = subMap_default.subMap(startKey.toString(), endKey
+ .toString());
+ assertFalse(subMap.isEmpty());
+
+ subMap = subMap_startExcluded_endExcluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertFalse(subMap.isEmpty());
+
+ subMap = subMap_startExcluded_endIncluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertFalse(subMap.isEmpty());
+
+ subMap = subMap_startIncluded_endExcluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertFalse(subMap.isEmpty());
+
+ subMap = subMap_startIncluded_endIncluded.subMap(startKey
+ .toString(), endKey.toString());
+ assertFalse(subMap.isEmpty());
+ }
+
+ startKey = new Integer(109).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey.toString(), endKey.toString());
+ assertTrue(subMap.isEmpty());
+ subMap = subMap_startExcluded_endIncluded.subMap(startKey, endKey);
+ assertTrue(subMap.isEmpty());
+ subMap = subMap_startIncluded_endIncluded.subMap(startKey, endKey);
+ assertTrue(subMap.isEmpty());
+
+ }
+
+ public void test_SubMap_keySet() {
+ Set keySet = subMap_default.keySet();
+ assertFalse(keySet.isEmpty());
+ assertEquals(9, keySet.size());
+
+ keySet = subMap_startExcluded_endExcluded.entrySet();
+ assertFalse(keySet.isEmpty());
+ assertEquals(8, keySet.size());
+
+ keySet = subMap_startExcluded_endIncluded.entrySet();
+ assertFalse(keySet.isEmpty());
+ assertEquals(9, keySet.size());
+
+ keySet = subMap_startIncluded_endExcluded.entrySet();
+ assertFalse(keySet.isEmpty());
+ assertEquals(9, keySet.size());
+
+ keySet = subMap_startIncluded_endIncluded.entrySet();
+ assertFalse(keySet.isEmpty());
+ assertEquals(10, keySet.size());
+ }
+
+ public void test_SubMap_put() {
+ Integer value = new Integer(100);
+ int addValue = 5;
+
+ subMap_default.put(value.toString(), value + addValue);
+ assertEquals(value + addValue, subMap_default.get(value.toString()));
+
+ try {
+ subMap_startExcluded_endExcluded.put(value.toString(), value
+ + addValue);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.put(value.toString(), value
+ + addValue);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subMap_startIncluded_endExcluded
+ .put(value.toString(), value + addValue);
+ assertEquals(value + addValue, subMap_startIncluded_endExcluded
+ .get(value.toString()));
+
+ subMap_startIncluded_endIncluded
+ .put(value.toString(), value + addValue);
+ assertEquals(value + addValue, subMap_startIncluded_endIncluded
+ .get(value.toString()));
+
+ value = new Integer(109);
+ try {
+ subMap_default.put(value.toString(), value + addValue);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.put(value.toString(), value
+ + addValue);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subMap_startExcluded_endIncluded
+ .put(value.toString(), value + addValue);
+ assertEquals(value + addValue, subMap_startExcluded_endIncluded
+ .get(value.toString()));
+
+ try {
+ subMap_startIncluded_endExcluded.put(value.toString(), value
+ + addValue);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subMap_startIncluded_endIncluded
+ .put(value.toString(), value + addValue);
+ assertEquals(value + addValue, subMap_startIncluded_endIncluded
+ .get(value.toString()));
+ }
+
+ public void test_SubMap_remove() {
+ Integer value = new Integer(100);
+
+ subMap_default.remove(value.toString());
+ assertNull(subMap_default.get(value.toString()));
+
+ subMap_startExcluded_endExcluded.remove(value.toString());
+ assertNull(subMap_startExcluded_endExcluded.get(value.toString()));
+
+ subMap_startExcluded_endIncluded.remove(value.toString());
+ assertNull(subMap_startExcluded_endIncluded.get(value.toString()));
+
+ subMap_startIncluded_endExcluded.remove(value.toString());
+ assertNull(subMap_startIncluded_endExcluded.get(value.toString()));
+
+ subMap_startIncluded_endIncluded.remove(value.toString());
+ assertNull(subMap_startIncluded_endIncluded.get(value.toString()));
+
+ value = new Integer(109);
+ subMap_default.remove(value.toString());
+ assertNull(subMap_default.get(value.toString()));
+
+ subMap_startExcluded_endExcluded.remove(value.toString());
+ assertNull(subMap_startExcluded_endExcluded.get(value.toString()));
+
+ subMap_startExcluded_endIncluded.remove(value.toString());
+ assertNull(subMap_startExcluded_endIncluded.get(value.toString()));
+
+ subMap_startIncluded_endExcluded.remove(value.toString());
+ assertNull(subMap_startIncluded_endExcluded.get(value.toString()));
+
+ subMap_startIncluded_endIncluded.remove(value.toString());
+ assertNull(subMap_startIncluded_endIncluded.get(value.toString()));
+ }
+
+ public void test_SubMap_subMap_NoComparator() {
+ String startKey = new Integer[100].toString();
+ String endKey = new Integer[100].toString();
+ try {
+ subMap_default.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ SortedMap subSubMap = null;
+ for (int i = 101; i < 109; i++) {
+ startKey = new Integer(i).toString();
+ endKey = startKey;
+
+ subSubMap = subMap_default.subMap(startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded.subMap(startKey,
+ endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded.subMap(startKey,
+ endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded.subMap(startKey,
+ endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded.subMap(startKey,
+ endKey);
+ assertEquals(0, subSubMap.size());
+ }
+
+ for (int i = 101, j = 5; i < 105; i++) {
+ startKey = new Integer(i).toString();
+ endKey = new Integer(i + j).toString();
+
+ subSubMap = subMap_default.subMap(startKey, endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded.subMap(startKey,
+ endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded.subMap(startKey,
+ endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded.subMap(startKey,
+ endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded.subMap(startKey,
+ endKey);
+ assertEquals(j, subSubMap.size());
+ }
+
+ startKey = new Integer(108).toString();
+ endKey = new Integer(109).toString();
+
+ subSubMap = subMap_default.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ startKey = new Integer(109).toString();
+ endKey = new Integer(109).toString();
+
+ try {
+ subMap_default.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subSubMap = subMap_startExcluded_endIncluded.subMap(startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ try {
+ subMap_startIncluded_endExcluded.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subSubMap = subMap_startIncluded_endIncluded.subMap(startKey, endKey);
+ assertEquals(0, subSubMap.size());
+ }
+
+ public void test_SubMap_subMap_Comparator() {
+ String startKey = new Integer[100].toString();
+ String endKey = new Integer[100].toString();
+ try {
+ subMap_default_comparator.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ SortedMap subSubMap = null;
+ for (int i = 101; i < 109; i++) {
+ startKey = new Integer(i).toString();
+ endKey = startKey;
+
+ subSubMap = subMap_default_comparator.subMap(startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+ }
+
+ for (int i = 101, j = 5; i < 105; i++) {
+ startKey = new Integer(i).toString();
+ endKey = new Integer(i + j).toString();
+
+ subSubMap = subMap_default_comparator.subMap(startKey, endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(j, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(j, subSubMap.size());
+ }
+
+ startKey = new Integer(108).toString();
+ endKey = new Integer(109).toString();
+
+ subSubMap = subMap_default_comparator.subMap(startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startExcluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endExcluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ subSubMap = subMap_startIncluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(1, subSubMap.size());
+
+ startKey = new Integer(109).toString();
+ endKey = new Integer(109).toString();
+
+ try {
+ subMap_default_comparator.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subSubMap = subMap_startExcluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+
+ try {
+ subMap_startIncluded_endExcluded_comparator
+ .subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ subSubMap = subMap_startIncluded_endIncluded_comparator.subMap(
+ startKey, endKey);
+ assertEquals(0, subSubMap.size());
+ }
+
+ public void test_SubMap_tailMap() {
+ String startKey = new Integer(99).toString();
+ try {
+ subMap_default.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startIncluded_endIncluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ SortedMap tailMap = null;
+
+ startKey = new Integer(100).toString();
+ tailMap = subMap_default.tailMap(startKey);
+ assertEquals(9, tailMap.size());
+
+ try {
+ subMap_startExcluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endIncluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ tailMap = subMap_startIncluded_endExcluded.tailMap(startKey);
+ assertEquals(9, tailMap.size());
+
+ tailMap = subMap_startIncluded_endIncluded.tailMap(startKey);
+ assertEquals(10, tailMap.size());
+
+ for (int i = 0, j = 101, end = 8; i < end; i++) {
+ startKey = new Integer(i + j).toString();
+ tailMap = subMap_default.tailMap(startKey);
+ assertEquals(end - i, tailMap.size());
+
+ tailMap = subMap_startExcluded_endExcluded.tailMap(startKey);
+ assertEquals(end - i, tailMap.size());
+
+ tailMap = subMap_startExcluded_endIncluded.tailMap(startKey);
+ assertEquals(end - i + 1, tailMap.size());
+
+ tailMap = subMap_startIncluded_endExcluded.tailMap(startKey);
+ assertEquals(end - i, tailMap.size());
+
+ tailMap = subMap_startIncluded_endIncluded.tailMap(startKey);
+ assertEquals(end - i + 1, tailMap.size());
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ subMap_default.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ subMap_startExcluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ tailMap = subMap_startExcluded_endIncluded.tailMap(startKey);
+ assertEquals(1, tailMap.size());
+
+ try {
+ subMap_startIncluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ tailMap = subMap_startIncluded_endIncluded.tailMap(startKey);
+ assertEquals(1, tailMap.size());
+
+ startKey = new Integer(110).toString();
+ try {
+ subMap_default.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ subMap_startExcluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ subMap_startExcluded_endIncluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ subMap_startIncluded_endExcluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ subMap_startIncluded_endIncluded.tailMap(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_SubMap_values() {
+ Collection values = subMap_default.values();
+
+ assertFalse(values.isEmpty());
+ assertTrue(values.contains(100));
+ for (int i = 101; i < 109; i++) {
+ assertTrue(values.contains(i));
+ }
+ assertFalse(values.contains(109));
+
+ values = subMap_startExcluded_endExcluded.values();
+ assertFalse(values.isEmpty());
+ assertFalse(values.contains(100));
+ for (int i = 101; i < 109; i++) {
+ assertTrue(values.contains(i));
+ }
+ assertFalse(values.contains(109));
+
+ values = subMap_startExcluded_endIncluded.values();
+ assertFalse(values.isEmpty());
+ assertFalse(values.contains(100));
+ for (int i = 101; i < 109; i++) {
+ assertTrue(values.contains(i));
+ }
+ assertTrue(values.contains(109));
+
+ values = subMap_startIncluded_endExcluded.values();
+ assertFalse(values.isEmpty());
+ assertTrue(values.contains(100));
+ for (int i = 101; i < 109; i++) {
+ assertTrue(values.contains(i));
+ }
+ assertFalse(values.contains(109));
+
+ values = subMap_startIncluded_endIncluded.values();
+ assertFalse(values.isEmpty());
+ assertTrue(values.contains(100));
+ for (int i = 100; i < 109; i++) {
+ assertTrue(values.contains(i));
+ }
+ assertTrue(values.contains(109));
+ }
+
+ public void test_SubMap_size() {
+ assertEquals(9, subMap_default.size());
+ assertEquals(8, subMap_startExcluded_endExcluded.size());
+ assertEquals(9, subMap_startExcluded_endIncluded.size());
+ assertEquals(9, subMap_startIncluded_endExcluded.size());
+ assertEquals(10, subMap_startIncluded_endIncluded.size());
+
+ assertEquals(9, subMap_default_comparator.size());
+ assertEquals(8, subMap_startExcluded_endExcluded_comparator.size());
+ assertEquals(9, subMap_startExcluded_endIncluded_comparator.size());
+ assertEquals(9, subMap_startIncluded_endExcluded_comparator.size());
+ assertEquals(10, subMap_startIncluded_endIncluded_comparator.size());
+ }
+
+ public void test_SubMap_readObject() throws Exception {
+ // SerializationTest.verifySelf(subMap_default);
+ // SerializationTest.verifySelf(subMap_startExcluded_endExcluded);
+ // SerializationTest.verifySelf(subMap_startExcluded_endIncluded);
+ // SerializationTest.verifySelf(subMap_startIncluded_endExcluded);
+ // SerializationTest.verifySelf(subMap_startIncluded_endIncluded);
+ }
+
+ public void test_AscendingSubMap_ceilingEntry() {
+ String key = new Integer(99).toString();
+ assertNull(navigableMap_startExcluded_endExcluded.ceilingEntry(key));
+ assertNull(navigableMap_startExcluded_endIncluded.ceilingEntry(key));
+ assertNull(navigableMap_startIncluded_endExcluded.ceilingEntry(key));
+ assertNull(navigableMap_startIncluded_endIncluded.ceilingEntry(key));
+
+ key = new Integer(100).toString();
+ assertEquals(101, navigableMap_startExcluded_endExcluded.ceilingEntry(
+ key).getValue());
+ assertEquals(101, navigableMap_startExcluded_endIncluded.ceilingEntry(
+ key).getValue());
+ assertEquals(100, navigableMap_startIncluded_endExcluded.ceilingEntry(
+ key).getValue());
+ assertEquals(100, navigableMap_startIncluded_endIncluded.ceilingEntry(
+ key).getValue());
+
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, navigableMap_startExcluded_endExcluded
+ .ceilingEntry(key).getValue());
+ assertEquals(i, navigableMap_startExcluded_endIncluded
+ .ceilingEntry(key).getValue());
+ assertEquals(i, navigableMap_startIncluded_endExcluded
+ .ceilingEntry(key).getValue());
+ assertEquals(i, navigableMap_startIncluded_endIncluded
+ .ceilingEntry(key).getValue());
+
+ }
+
+ key = new Integer(109).toString();
+ assertNull(navigableMap_startExcluded_endExcluded.ceilingEntry(key));
+ assertEquals(109, navigableMap_startExcluded_endIncluded.ceilingEntry(
+ key).getValue());
+ assertNull(navigableMap_startIncluded_endExcluded.ceilingEntry(key));
+ assertEquals(109, navigableMap_startIncluded_endIncluded.ceilingEntry(
+ key).getValue());
+
+ key = new Integer(110).toString();
+ assertNull(navigableMap_startExcluded_endExcluded.ceilingEntry(key));
+ assertNull(navigableMap_startExcluded_endIncluded.ceilingEntry(key));
+ assertNull(navigableMap_startIncluded_endExcluded.ceilingEntry(key));
+ assertNull(navigableMap_startIncluded_endIncluded.ceilingEntry(key));
+ }
+
+ public void test_AscendingSubMap_descendingMap() {
+ NavigableMap descendingMap = navigableMap_startExcluded_endExcluded
+ .descendingMap();
+ assertEquals(navigableMap_startExcluded_endExcluded.size(),
+ descendingMap.size());
+ assertNotNull(descendingMap.comparator());
+
+ assertEquals(navigableMap_startExcluded_endExcluded.firstKey(),
+ descendingMap.lastKey());
+ assertEquals(navigableMap_startExcluded_endExcluded.firstEntry(),
+ descendingMap.lastEntry());
+
+ assertEquals(navigableMap_startExcluded_endExcluded.lastKey(),
+ descendingMap.firstKey());
+ assertEquals(navigableMap_startExcluded_endExcluded.lastEntry(),
+ descendingMap.firstEntry());
+
+ descendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ assertEquals(navigableMap_startExcluded_endIncluded.size(),
+ descendingMap.size());
+ assertNotNull(descendingMap.comparator());
+
+ assertEquals(navigableMap_startExcluded_endIncluded.firstKey(),
+ descendingMap.lastKey());
+ assertEquals(navigableMap_startExcluded_endIncluded.firstEntry(),
+ descendingMap.lastEntry());
+
+ assertEquals(navigableMap_startExcluded_endIncluded.lastKey(),
+ descendingMap.firstKey());
+ assertEquals(navigableMap_startExcluded_endIncluded.lastEntry(),
+ descendingMap.firstEntry());
+
+ descendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ assertEquals(navigableMap_startIncluded_endExcluded.size(),
+ descendingMap.size());
+ assertNotNull(descendingMap.comparator());
+
+ assertEquals(navigableMap_startIncluded_endExcluded.firstKey(),
+ descendingMap.lastKey());
+ assertEquals(navigableMap_startIncluded_endExcluded.firstEntry(),
+ descendingMap.lastEntry());
+
+ assertEquals(navigableMap_startIncluded_endExcluded.lastKey(),
+ descendingMap.firstKey());
+ assertEquals(navigableMap_startIncluded_endExcluded.lastEntry(),
+ descendingMap.firstEntry());
+
+ descendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ assertEquals(navigableMap_startIncluded_endIncluded.size(),
+ descendingMap.size());
+ assertNotNull(descendingMap.comparator());
+
+ assertEquals(navigableMap_startIncluded_endIncluded.firstKey(),
+ descendingMap.lastKey());
+ assertEquals(navigableMap_startIncluded_endIncluded.firstEntry(),
+ descendingMap.lastEntry());
+
+ assertEquals(navigableMap_startIncluded_endIncluded.lastKey(),
+ descendingMap.firstKey());
+ assertEquals(navigableMap_startIncluded_endIncluded.lastEntry(),
+ descendingMap.firstEntry());
+ }
+
+ public void test_AscendingSubMap_floorEntry() {
+ String key = new Integer(99).toString();
+ assertEquals(108, navigableMap_startExcluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startExcluded_endIncluded
+ .floorEntry(key).getValue());
+ assertEquals(108, navigableMap_startIncluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startIncluded_endIncluded
+ .floorEntry(key).getValue());
+
+ key = new Integer(100).toString();
+ assertNull(navigableMap_startExcluded_endExcluded.floorEntry(key));
+ assertNull(navigableMap_startExcluded_endIncluded.floorEntry(key));
+ assertEquals(100, navigableMap_startIncluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(100, navigableMap_startIncluded_endIncluded
+ .floorEntry(key).getValue());
+
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, navigableMap_startExcluded_endExcluded.floorEntry(
+ key).getValue());
+ assertEquals(i, navigableMap_startExcluded_endIncluded.floorEntry(
+ key).getValue());
+ assertEquals(i, navigableMap_startIncluded_endExcluded.floorEntry(
+ key).getValue());
+ assertEquals(i, navigableMap_startIncluded_endIncluded.floorEntry(
+ key).getValue());
+
+ }
+
+ key = new Integer(109).toString();
+ assertEquals(108, navigableMap_startExcluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startExcluded_endIncluded
+ .floorEntry(key).getValue());
+ assertEquals(108, navigableMap_startIncluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startIncluded_endIncluded
+ .floorEntry(key).getValue());
+
+ key = new Integer(110).toString();
+ assertEquals(108, navigableMap_startExcluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startExcluded_endIncluded
+ .floorEntry(key).getValue());
+ assertEquals(108, navigableMap_startIncluded_endExcluded
+ .floorEntry(key).getValue());
+ assertEquals(109, navigableMap_startIncluded_endIncluded
+ .floorEntry(key).getValue());
+ }
+
+ public void test_AscendingSubMap_pollFirstEntry() {
+ assertEquals(101, navigableMap_startExcluded_endExcluded
+ .pollFirstEntry().getValue());
+ assertEquals(102, navigableMap_startExcluded_endIncluded
+ .pollFirstEntry().getValue());
+ assertEquals(100, navigableMap_startIncluded_endExcluded
+ .pollFirstEntry().getValue());
+ assertEquals(103, navigableMap_startIncluded_endIncluded
+ .pollFirstEntry().getValue());
+ }
+
+ public void test_AscendingSubMap_pollLastEntry() {
+ assertEquals(108, navigableMap_startExcluded_endExcluded
+ .pollLastEntry().getValue());
+ assertEquals(109, navigableMap_startExcluded_endIncluded
+ .pollLastEntry().getValue());
+ assertEquals(107, navigableMap_startIncluded_endExcluded
+ .pollLastEntry().getValue());
+ assertEquals(106, navigableMap_startIncluded_endIncluded
+ .pollLastEntry().getValue());
+ }
+
+ public void test_AscendingSubMap_entrySet() {
+ assertEquals(8, navigableMap_startExcluded_endExcluded.entrySet()
+ .size());
+ assertEquals(9, navigableMap_startExcluded_endIncluded.entrySet()
+ .size());
+ assertEquals(9, navigableMap_startIncluded_endExcluded.entrySet()
+ .size());
+ assertEquals(10, navigableMap_startIncluded_endIncluded.entrySet()
+ .size());
+ }
+
+ public void test_AscendingSubMap_subMap() {
+ Set entrySet;
+ Entry startEntry, endEntry;
+ int startIndex, endIndex;
+ SortedMap subMap;
+ Iterator subMapSetIterator;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ Iterator startIterator = entrySet.iterator();
+ while (startIterator.hasNext()) {
+ startEntry = (Entry) startIterator.next();
+ startIndex = (Integer) startEntry.getValue();
+ Iterator endIterator = entrySet.iterator();
+ while (endIterator.hasNext()) {
+ endEntry = (Entry) endIterator.next();
+ endIndex = (Integer) endEntry.getValue();
+
+ if (startIndex > endIndex) {
+ try {
+ navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), endEntry.getKey());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), false, endEntry.getKey(),
+ false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), false, endEntry.getKey(),
+ true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), true, endEntry.getKey(),
+ false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), true, endEntry.getKey(),
+ true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subMap = navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), endEntry.getKey());
+ subMapSetIterator = subMap.entrySet().iterator();
+ for (int index = startIndex; index < endIndex; index++) {
+ assertEquals(index, ((Entry) subMapSetIterator.next())
+ .getValue());
+ }
+
+ subMap = navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), false, endEntry.getKey(),
+ false);
+ subMapSetIterator = subMap.entrySet().iterator();
+ for (int index = startIndex + 1; index < endIndex; index++) {
+ assertEquals(index, ((Entry) subMapSetIterator.next())
+ .getValue());
+ }
+
+ subMap = navigableMap_startExcluded_endExcluded
+ .subMap(startEntry.getKey(), false, endEntry
+ .getKey(), true);
+ subMapSetIterator = subMap.entrySet().iterator();
+ for (int index = startIndex + 1; index < endIndex; index++) {
+ assertEquals(index, ((Entry) subMapSetIterator.next())
+ .getValue());
+ }
+
+ subMap = navigableMap_startExcluded_endExcluded
+ .subMap(startEntry.getKey(), true, endEntry
+ .getKey(), false);
+ subMapSetIterator = subMap.entrySet().iterator();
+ for (int index = startIndex; index < endIndex; index++) {
+ assertEquals(index, ((Entry) subMapSetIterator.next())
+ .getValue());
+ }
+
+ subMap = navigableMap_startExcluded_endExcluded.subMap(
+ startEntry.getKey(), true, endEntry.getKey(), true);
+ subMapSetIterator = subMap.entrySet().iterator();
+ for (int index = startIndex; index <= endIndex; index++) {
+ assertEquals(index, ((Entry) subMapSetIterator.next())
+ .getValue());
+ }
+ }
+ }
+ }
+ }
+
+ public void test_DescendingSubMap_ceilingEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ String key = new Integer(-1).toString();
+ assertNull(decendingMap.ceilingEntry(key));
+ for (int i = 0; i < objArray.length; i++) {
+ key = objArray[i].toString();
+ assertEquals(objArray[i], decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(1000).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+ key = new Integer(1001).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ key = new Integer(100).toString();
+ assertNull(decendingMap.ceilingEntry(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(108, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ key = new Integer(100).toString();
+ assertNull(decendingMap.ceilingEntry(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(108, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.ceilingEntry(key).getValue());
+
+ // With Comparator
+ decendingMap = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertNull(decendingMap.ceilingEntry(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(108, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertNull(decendingMap.ceilingEntry(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(108, decendingMap.ceilingEntry(key).getValue());
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.ceilingEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.ceilingEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.ceilingEntry(key).getValue());
+ }
+
+ public void test_DescendingSubMap_descendingMap() {
+ NavigableMap decendingMap = tm.descendingMap();
+ NavigableMap decendingDecendingMap = decendingMap.descendingMap();
+ assertEquals(decendingMap, decendingDecendingMap);
+
+ NavigableMap decendingMapHeadMap = decendingMap.headMap(
+ new Integer(990).toString(), false);
+ NavigableMap decendingDecendingHeadMap = decendingMapHeadMap
+ .descendingMap();
+ assertNotNull(decendingMapHeadMap);
+ assertNotNull(decendingDecendingHeadMap);
+ assertEquals(decendingMapHeadMap, decendingDecendingHeadMap);
+
+ NavigableMap decendingMapTailMap = decendingMap.tailMap(
+ new Integer(990).toString(), false);
+ NavigableMap decendingDecendingTailMap = decendingMapTailMap
+ .descendingMap();
+ assertNotNull(decendingMapTailMap);
+ assertNotNull(decendingDecendingTailMap);
+ // assertEquals(decendingMapTailMap,decendingDecendingTailMap);
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ decendingDecendingMap = decendingMap.descendingMap();
+ assertEquals(decendingMap, decendingDecendingMap);
+
+ decendingMapHeadMap = decendingMap.headMap(new Integer(104).toString(),
+ false);
+ decendingDecendingHeadMap = decendingMapHeadMap.descendingMap();
+ assertEquals(decendingMapHeadMap, decendingDecendingHeadMap);
+
+ decendingMapTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ decendingDecendingTailMap = decendingMapTailMap.descendingMap();
+ assertEquals(decendingMapTailMap, decendingDecendingTailMap);
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ decendingDecendingMap = decendingMap.descendingMap();
+ assertEquals(decendingMap, decendingDecendingMap);
+
+ decendingMapHeadMap = decendingMap.headMap(new Integer(104).toString(),
+ false);
+ decendingDecendingHeadMap = decendingMapHeadMap.descendingMap();
+ assertEquals(decendingMapHeadMap, decendingDecendingHeadMap);
+
+ decendingMapTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ decendingDecendingTailMap = decendingMapTailMap.descendingMap();
+ assertEquals(decendingMapTailMap, decendingDecendingTailMap);
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ decendingDecendingMap = decendingMap.descendingMap();
+ assertEquals(decendingMap, decendingDecendingMap);
+
+ decendingMapHeadMap = decendingMap.headMap(new Integer(104).toString(),
+ false);
+ decendingDecendingHeadMap = decendingMapHeadMap.descendingMap();
+ assertEquals(decendingMapHeadMap, decendingDecendingHeadMap);
+
+ decendingMapTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ decendingDecendingTailMap = decendingMapTailMap.descendingMap();
+ assertEquals(decendingMapTailMap, decendingDecendingTailMap);
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ decendingDecendingMap = decendingMap.descendingMap();
+ assertEquals(decendingMap, decendingDecendingMap);
+
+ decendingMapHeadMap = decendingMap.headMap(new Integer(104).toString(),
+ false);
+ decendingDecendingHeadMap = decendingMapHeadMap.descendingMap();
+ assertEquals(decendingMapHeadMap, decendingDecendingHeadMap);
+
+ decendingMapTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ decendingDecendingTailMap = decendingMapTailMap.descendingMap();
+ assertEquals(decendingMapTailMap, decendingDecendingTailMap);
+ }
+
+ public void test_DescendingSubMap_firstEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ assertEquals(999, decendingMap.firstEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ assertEquals(108, decendingMap.firstEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ assertEquals(109, decendingMap.firstEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ assertEquals(108, decendingMap.firstEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ assertEquals(109, decendingMap.firstEntry().getValue());
+ }
+
+ public void test_DescendingSubMap_floorEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ String key = new Integer(-1).toString();
+ assertEquals(0, decendingMap.floorEntry(key).getValue());
+ for (int i = 0; i < objArray.length; i++) {
+ key = objArray[i].toString();
+ assertEquals(objArray[i], decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(1000).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+ key = new Integer(1001).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertNull(decendingMap.floorEntry(key));
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.floorEntry(key).getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertNull(decendingMap.floorEntry(key));
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.floorEntry(key).getValue());
+
+ // With Comparator
+ decendingMap = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertNull(decendingMap.floorEntry(key));
+
+ decendingMap = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(101, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.floorEntry(key).getValue());
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertNull(decendingMap.floorEntry(key));
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .descendingMap();
+ key = new Integer(100).toString();
+ assertEquals(100, decendingMap.floorEntry(key).getValue());
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertEquals(i, decendingMap.floorEntry(key).getValue());
+ }
+ key = new Integer(109).toString();
+ assertEquals(109, decendingMap.floorEntry(key).getValue());
+ }
+
+ public void test_DescendingSubMap_lastEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ assertEquals(0, decendingMap.lastEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ assertEquals(101, decendingMap.lastEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ assertEquals(101, decendingMap.lastEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ assertEquals(100, decendingMap.lastEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ assertEquals(100, decendingMap.lastEntry().getValue());
+ }
+
+ public void test_DescendingSubMap_higherEntry() {
+ NavigableMap decendingMap;
+ NavigableMap decendingTailMap;
+ Integer value;
+ Entry entry;
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ value = new Integer(101);
+ assertNull(decendingMap.higherEntry(value.toString()));
+
+ for (int i = 108; i > 101; i--) {
+ value = new Integer(i);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(value - 1, entry.getValue());
+ }
+
+ value = new Integer(109);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(108, entry.getValue());
+
+ decendingTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ value = new Integer(109);
+ entry = decendingTailMap.higherEntry(value.toString());
+ assertEquals(103, entry.getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ value = new Integer(100);
+ assertNull(decendingMap.higherEntry(value.toString()));
+
+ for (int i = 108; i > 100; i--) {
+ value = new Integer(i);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(value - 1, entry.getValue());
+ }
+
+ value = new Integer(109);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(108, entry.getValue());
+
+ decendingTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ value = new Integer(109);
+ entry = decendingTailMap.higherEntry(value.toString());
+ assertEquals(103, entry.getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ value = new Integer(101);
+ assertNull(decendingMap.higherEntry(value.toString()));
+
+ for (int i = 109; i > 101; i--) {
+ value = new Integer(i);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(value - 1, entry.getValue());
+ }
+
+ value = new Integer(2);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(109, entry.getValue());
+
+ decendingTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ value = new Integer(109);
+ entry = decendingTailMap.higherEntry(value.toString());
+ assertEquals(103, entry.getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ value = new Integer(100);
+ assertNull(decendingMap.higherEntry(value.toString()));
+
+ for (int i = 109; i > 100; i--) {
+ value = new Integer(i);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(value - 1, entry.getValue());
+ }
+
+ value = new Integer(2);
+ entry = decendingMap.higherEntry(value.toString());
+ assertEquals(109, entry.getValue());
+
+ decendingTailMap = decendingMap.tailMap(new Integer(104).toString(),
+ false);
+ value = new Integer(109);
+ entry = decendingTailMap.higherEntry(value.toString());
+ assertEquals(103, entry.getValue());
+ }
+
+ public void test_DescendingSubMap_lowerEntry() {
+ NavigableMap decendingMap;
+ NavigableMap decendingHeadMap;
+ Integer value;
+ Entry entry;
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ value = new Integer(99);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+ for (int i = 100; i < 108; i++) {
+ value = new Integer(i);
+ entry = decendingMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(109);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+
+ decendingHeadMap = decendingMap.headMap(new Integer(103).toString(),
+ false);
+ for (int i = 104; i < 106; i++) {
+ value = new Integer(i);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(102);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(104, entry.getValue());
+
+ value = new Integer(109);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertNull(entry);
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ value = new Integer(99);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+ for (int i = 100; i < 109; i++) {
+ value = new Integer(i);
+ entry = decendingMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(110);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+
+ decendingHeadMap = decendingMap.headMap(new Integer(103).toString(),
+ false);
+ for (int i = 104; i < 109; i++) {
+ value = new Integer(i);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(102);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(104, entry.getValue());
+
+ value = new Integer(2);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertNull(entry);
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ value = new Integer(99);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+ for (int i = 100; i < 108; i++) {
+ value = new Integer(i);
+ entry = decendingMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(109);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+
+ decendingHeadMap = decendingMap.headMap(new Integer(103).toString(),
+ false);
+ for (int i = 104; i < 107; i++) {
+ value = new Integer(i);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(102);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(104, entry.getValue());
+
+ value = new Integer(2);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertNull(entry);
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ value = new Integer(99);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+ for (int i = 100; i < 109; i++) {
+ value = new Integer(i);
+ entry = decendingMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(110);
+ assertNull(decendingMap.lowerEntry(value.toString()));
+
+ decendingHeadMap = decendingMap.headMap(new Integer(103).toString(),
+ false);
+ for (int i = 104; i < 109; i++) {
+ value = new Integer(i);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(value + 1, entry.getValue());
+ }
+ value = new Integer(102);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertEquals(104, entry.getValue());
+
+ value = new Integer(2);
+ entry = decendingHeadMap.lowerEntry(value.toString());
+ assertNull(entry);
+ }
+
+ public void test_DescendingSubMap_pollFirstEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ assertEquals(999, decendingMap.pollFirstEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ assertEquals(108, decendingMap.pollFirstEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ assertEquals(109, decendingMap.pollFirstEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ assertEquals(107, decendingMap.pollFirstEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ assertEquals(106, decendingMap.pollFirstEntry().getValue());
+ }
+
+ public void test_DescendingSubMap_pollLastEntry() {
+ NavigableMap decendingMap = tm.descendingMap();
+ assertEquals(0, decendingMap.pollLastEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ assertEquals(101, decendingMap.pollLastEntry().getValue());
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ assertEquals(102, decendingMap.pollLastEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ assertEquals(100, decendingMap.pollLastEntry().getValue());
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ assertEquals(103, decendingMap.pollLastEntry().getValue());
+ }
+
+ public void test_DescendingSubMap_values() {
+ NavigableMap decendingMap = tm.descendingMap();
+ Collection values = decendingMap.values();
+ assertFalse(values.isEmpty());
+ assertFalse(values.contains(1000));
+ for (int i = 999; i > 0; i--) {
+ assertTrue(values.contains(i));
+ }
+ assertTrue(values.contains(0));
+
+ String endKey = new Integer(99).toString();
+ NavigableMap headMap = decendingMap.headMap(endKey, false);
+ values = headMap.values();
+ Iterator it = values.iterator();
+ for (int i = 999; i > 990; i--) {
+ assertTrue(values.contains(i));
+ assertEquals(i, it.next());
+ }
+
+ String startKey = new Integer(11).toString();
+ NavigableMap tailMap = decendingMap.tailMap(startKey, false);
+ values = tailMap.values();
+ it = values.iterator();
+ for (int i = 109; i > 100; i--) {
+ assertTrue(values.contains(i));
+ assertEquals(i, it.next());
+ }
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ values = decendingMap.values();
+ assertFalse(values.isEmpty());
+ assertFalse(values.contains(109));
+ for (int i = 108; i > 100; i--) {
+ assertTrue(values.contains(i));
+ }
+ assertFalse(values.contains(100));
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ values = decendingMap.values();
+ assertFalse(values.isEmpty());
+ assertFalse(values.contains(100));
+ for (int i = 108; i > 100; i--) {
+ assertTrue(values.contains(i));
+ }
+ assertTrue(values.contains(109));
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ values = decendingMap.values();
+ assertFalse(values.isEmpty());
+ assertTrue(values.contains(100));
+ for (int i = 108; i > 100; i--) {
+ assertTrue(values.contains(i));
+ }
+ assertFalse(values.contains(109));
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ values = decendingMap.values();
+ assertFalse(values.isEmpty());
+ assertTrue(values.contains(100));
+ for (int i = 108; i > 100; i--) {
+ assertTrue(values.contains(i));
+ }
+ assertTrue(values.contains(109));
+ }
+
+ public void test_DescendingSubMap_headMap() {
+ NavigableMap decendingMap = tm.descendingMap();
+ String endKey = new Integer(0).toString(), key;
+ SortedMap subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ SortedMap subDecendingMap_Excluded = decendingMap
+ .headMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 1; i < 1000; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(1000).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.headMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.headMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ // With Comparator
+
+ decendingMap = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .descendingMap();
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.headMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .descendingMap();
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.headMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .descendingMap();
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .descendingMap();
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.headMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.headMap(endKey, false);
+
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ for (int i = 102; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+
+ public void test_DescendingSubMap_subMap() {
+ NavigableMap descendingMap = tm.descendingMap();
+ String startKey = new Integer(109).toString();
+ String endKey = new Integer(100).toString();
+ try {
+ descendingMap.subMap(endKey, false, startKey, false);
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ SortedMap subDescendingMap = descendingMap.subMap(startKey, false,
+ endKey, false);
+ String key = new Integer(100).toString();
+ assertFalse(subDescendingMap.containsKey(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDescendingMap.containsKey(key));
+
+ subDescendingMap = descendingMap.subMap(startKey, false, endKey, true);
+ key = new Integer(100).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(subDescendingMap.containsKey(key));
+
+ subDescendingMap = descendingMap.subMap(startKey, true, endKey, false);
+ key = new Integer(100).toString();
+ assertFalse(subDescendingMap.containsKey(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+
+ subDescendingMap = descendingMap.subMap(startKey, true, endKey, true);
+ key = new Integer(100).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(subDescendingMap.containsKey(key));
+
+ TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
+ for (int i = -10; i < 10; i++) {
+ treeMap.put(i, String.valueOf(i));
+ }
+ descendingMap = treeMap.descendingMap();
+ subDescendingMap = descendingMap.subMap(5, 0);
+ assertEquals(5, subDescendingMap.size());
+ }
+
+ public void test_DescendingSubMap_tailMap() {
+ // tm
+ NavigableMap decendingMap = tm.descendingMap();
+ String endKey = new Integer(1000).toString(), key;
+ SortedMap subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ SortedMap subDecendingMap_Excluded = decendingMap
+ .tailMap(endKey, false);
+
+ key = endKey;
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ key = new Integer(100).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ key = new Integer(10).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ key = new Integer(1).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ key = new Integer(0).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(999).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 998; i > 0; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(0).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(0).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ assertEquals(1, subDecendingMap_Included.size());
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.isEmpty());
+
+ // navigableMap_startExcluded_endExcluded
+ decendingMap = navigableMap_startExcluded_endExcluded.descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(1, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.isEmpty());
+
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // navigableMap_startExcluded_endIncluded
+ decendingMap = navigableMap_startExcluded_endIncluded.descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(1, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.isEmpty());
+
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // navigableMap_startIncluded_endExcluded
+ decendingMap = navigableMap_startIncluded_endExcluded.descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(2, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // navigableMap_startIncluded_endIncluded
+ decendingMap = navigableMap_startIncluded_endIncluded.descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(2, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // With Comparator
+ decendingMap = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(1, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.isEmpty());
+
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ decendingMap = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertFalse(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(1, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.isEmpty());
+
+ endKey = new Integer(100).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // navigableMap_startIncluded_endExcluded
+ decendingMap = ((NavigableMap) subMap_startIncluded_endExcluded)
+ .descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(2, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ decendingMap = ((NavigableMap) subMap_startIncluded_endIncluded)
+ .descendingMap();
+ endKey = new Integer(110).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(108).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+ for (int i = 107; i > 100; i--) {
+ key = new Integer(i).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Excluded.containsKey(key));
+ }
+ key = new Integer(100).toString();
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertTrue(subDecendingMap_Included.containsKey(key));
+
+ endKey = new Integer(101).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertEquals(2, subDecendingMap_Included.size());
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(100).toString();
+ subDecendingMap_Included = decendingMap.tailMap(endKey, true);
+ subDecendingMap_Excluded = decendingMap.tailMap(endKey, false);
+ key = endKey;
+ assertTrue(subDecendingMap_Included.containsKey(key));
+ assertFalse(subDecendingMap_Excluded.containsKey(key));
+
+ endKey = new Integer(99).toString();
+ try {
+ decendingMap.tailMap(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ decendingMap.tailMap(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_Entry_setValue() {
+ TreeMap treeMap = new TreeMap();
+ Integer value = null;
+ for (int i = 0; i < 50; i++) {
+ value = new Integer(i);
+ treeMap.put(value, value);
+ }
+ Map checkedMap = Collections.checkedMap(treeMap, Integer.class,
+ Integer.class);
+ Set entrySet = checkedMap.entrySet();
+ Iterator iterator = entrySet.iterator();
+ Entry entry;
+ value = new Integer(0);
+ for (; iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.setValue(value + 1));
+ assertEquals(value + 1, entry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_comparator() {
+ Set entrySet;
+ NavigableSet descendingSet;
+ Comparator comparator;
+ Entry[] entryArray;
+ Integer value1, value2;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ assertNull(((NavigableSet) entrySet).comparator());
+ comparator = descendingSet.comparator();
+ assertNotNull(comparator);
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 1; i < entryArray.length; i++) {
+ value1 = (Integer) entryArray[i - 1].getValue();
+ value2 = (Integer) entryArray[i].getValue();
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ assertNull(((NavigableSet) entrySet).comparator());
+ comparator = descendingSet.comparator();
+ assertNotNull(comparator);
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 1; i < entryArray.length; i++) {
+ value1 = (Integer) entryArray[i - 1].getValue();
+ value2 = (Integer) entryArray[i].getValue();
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ assertNull(((NavigableSet) entrySet).comparator());
+ comparator = descendingSet.comparator();
+ assertNotNull(comparator);
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 1; i < entryArray.length; i++) {
+ value1 = (Integer) entryArray[i - 1].getValue();
+ value2 = (Integer) entryArray[i].getValue();
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ assertNull(((NavigableSet) entrySet).comparator());
+ comparator = descendingSet.comparator();
+ assertNotNull(comparator);
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 1; i < entryArray.length; i++) {
+ value1 = (Integer) entryArray[i - 1].getValue();
+ value2 = (Integer) entryArray[i].getValue();
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ assertNotNull(descendingSet.comparator());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_descendingSet() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet, descendingDescedingSet;
+ Entry[] ascendingEntryArray, descendingDescendingArray;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ descendingDescedingSet = descendingSet.descendingSet();
+ ascendingEntryArray = (Entry[]) ascendingSubMapEntrySet
+ .toArray(new Entry[ascendingSubMapEntrySet.size()]);
+
+ descendingDescendingArray = (Entry[]) descendingDescedingSet
+ .toArray(new Entry[descendingDescedingSet.size()]);
+
+ assertEquals(ascendingEntryArray.length,
+ descendingDescendingArray.length);
+ for (int i = 0; i < ascendingEntryArray.length; i++) {
+ assertEquals(ascendingEntryArray[i],
+ descendingDescendingArray[i]);
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ descendingDescedingSet = descendingSet.descendingSet();
+ ascendingEntryArray = (Entry[]) ascendingSubMapEntrySet
+ .toArray(new Entry[ascendingSubMapEntrySet.size()]);
+
+ descendingDescendingArray = (Entry[]) descendingDescedingSet
+ .toArray(new Entry[descendingDescedingSet.size()]);
+
+ assertEquals(ascendingEntryArray.length,
+ descendingDescendingArray.length);
+ for (int i = 0; i < ascendingEntryArray.length; i++) {
+ assertEquals(ascendingEntryArray[i],
+ descendingDescendingArray[i]);
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ descendingDescedingSet = descendingSet.descendingSet();
+ ascendingEntryArray = (Entry[]) ascendingSubMapEntrySet
+ .toArray(new Entry[ascendingSubMapEntrySet.size()]);
+
+ descendingDescendingArray = (Entry[]) descendingDescedingSet
+ .toArray(new Entry[descendingDescedingSet.size()]);
+
+ assertEquals(ascendingEntryArray.length,
+ descendingDescendingArray.length);
+ for (int i = 0; i < ascendingEntryArray.length; i++) {
+ assertEquals(ascendingEntryArray[i],
+ descendingDescendingArray[i]);
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ descendingDescedingSet = descendingSet.descendingSet();
+ ascendingEntryArray = (Entry[]) ascendingSubMapEntrySet
+ .toArray(new Entry[ascendingSubMapEntrySet.size()]);
+
+ descendingDescendingArray = (Entry[]) descendingDescedingSet
+ .toArray(new Entry[descendingDescedingSet.size()]);
+
+ assertEquals(ascendingEntryArray.length,
+ descendingDescendingArray.length);
+ for (int i = 0; i < ascendingEntryArray.length; i++) {
+ assertEquals(ascendingEntryArray[i],
+ descendingDescendingArray[i]);
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();// 0...2
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ // [0...2]
+ descendingDescedingSet = descendingSet.descendingSet();
+ Iterator iterator = descendingDescedingSet.iterator();
+ assertEquals(0, ((Entry) iterator.next()).getValue());
+ }
+
+ String startKey = new Integer(2).toString();
+ entrySet = tm.tailMap(startKey, true).entrySet();// 2...
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ // [0...2]
+ descendingDescedingSet = descendingSet.descendingSet();
+ Iterator iterator = descendingDescedingSet.iterator();
+ assertEquals(2, ((Entry) iterator.next()).getValue());
+ }
+
+ }
+
+ public void test_DescendingSubMapEntrySet_first() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet;
+ Entry entry;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.first();
+ assertEquals(101, entry.getValue());
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.first();
+ assertEquals(101, entry.getValue());
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.first();
+ assertEquals(100, entry.getValue());
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.first();
+ assertEquals(100, entry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_last() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet;
+ Entry entry;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.last();
+ assertEquals(108, entry.getValue());
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.last();
+ assertEquals(109, entry.getValue());
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.last();
+ assertEquals(108, entry.getValue());
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ entry = (Entry) descendingSet.last();
+ assertEquals(109, entry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollFirst_startExcluded_endExcluded() {
+ Set entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(8, descendingSubMapEntrySet.size());
+ for (int i = 101; i < 109; i++) {
+ entry = (Entry) descendingSubMapEntrySet.pollFirst();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollFirst_startExcluded_endIncluded() {
+ Set entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(9, descendingSubMapEntrySet.size());
+ for (int i = 101; i < 110; i++) {
+ entry = (Entry) descendingSubMapEntrySet.pollFirst();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollFirst_startIncluded_endExcluded() {
+ Set entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(9, descendingSubMapEntrySet.size());
+ for (int i = 100; i < 109; i++) {
+ entry = (Entry) descendingSubMapEntrySet.pollFirst();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollFirst_startIncluded_endIncluded() {
+ Set entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(10, descendingSubMapEntrySet.size());
+ for (int i = 100; i < 110; i++) {
+ entry = (Entry) descendingSubMapEntrySet.pollFirst();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollFirst() {
+ String key = new Integer(2).toString();
+ Set entrySet = tm.headMap(key, true).entrySet();// [0...2]
+ NavigableSet descendingEntrySet;
+ Entry entry;
+
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingEntrySet = ((NavigableSet) entrySet).descendingSet();
+ entry = (Entry) descendingEntrySet.pollFirst();
+ assertEquals(0, entry.getValue());
+ }
+
+ entrySet = tm.tailMap(key, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingEntrySet = ((NavigableSet) entrySet).descendingSet();
+ entry = (Entry) descendingEntrySet.pollFirst();
+ assertEquals(2, entry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollLast_startExcluded_endExclued() {
+ Set entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(8, descendingSubMapEntrySet.size());
+ for (int i = 108; i > 100; i--) {
+ entry = (Entry) descendingSubMapEntrySet.pollLast();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollLast_startExcluded_endInclued() {
+ Set entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(9, descendingSubMapEntrySet.size());
+ for (int i = 109; i > 100; i--) {
+ entry = (Entry) descendingSubMapEntrySet.pollLast();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollLast_startIncluded_endExclued() {
+ Set entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(9, descendingSubMapEntrySet.size());
+ for (int i = 108; i > 99; i--) {
+ entry = (Entry) descendingSubMapEntrySet.pollLast();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollLast_startIncluded_endInclued() {
+ Set entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ Entry entry;
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ assertEquals(10, descendingSubMapEntrySet.size());
+ for (int i = 109; i > 99; i--) {
+ entry = (Entry) descendingSubMapEntrySet.pollLast();
+ assertEquals(i, entry.getValue());
+ }
+ assertNull(descendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_pollLast() {
+ String key = new Integer(2).toString();
+ Set entrySet = tm.headMap(key, true).entrySet();// [0...2]
+ NavigableSet descendingEntrySet;
+ Entry entry;
+
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingEntrySet = ((NavigableSet) entrySet).descendingSet();
+ entry = (Entry) descendingEntrySet.pollLast();
+ assertEquals(2, entry.getValue());
+ }
+
+ entrySet = tm.tailMap(key, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingEntrySet = ((NavigableSet) entrySet).descendingSet();
+ entry = (Entry) descendingEntrySet.pollLast();
+ assertEquals(999, entry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_descendingIterator() {
+ Set entrySet;
+ NavigableSet descendingSet;
+ Iterator iterator;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 108; value > 100; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(value, ((Entry) iterator.next()).getValue());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 109; value > 100; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(value, ((Entry) iterator.next()).getValue());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 108; value > 99; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(value, ((Entry) iterator.next()).getValue());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 109; value > 99; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(value, ((Entry) iterator.next()).getValue());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();// 0...2
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ iterator = descendingSet.descendingIterator();
+ assertEquals(0, ((Entry) iterator.next()).getValue());// 0...2
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_headSet() {
+ Set entrySet, headSet;
+ NavigableSet descendingSubMapEntrySet;
+ Iterator iterator, headSetIterator;
+ Entry entry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = descendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = descendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = descendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 108; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = descendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = descendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 109; headSetIterator.hasNext(); value--) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();// 0...2
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ iterator.next();// 2
+ iterator.next();// 199
+ entry = (Entry) iterator.next();// 198
+ headSet = descendingSubMapEntrySet.headSet(entry);
+ assertEquals(2, headSet.size());// 2 199
+ headSetIterator = headSet.iterator();
+ assertEquals(2, ((Entry) headSetIterator.next()).getValue());
+ assertEquals(199, ((Entry) headSetIterator.next()).getValue());
+
+ headSet = descendingSubMapEntrySet.headSet(entry, true);
+ assertEquals(3, headSet.size());// 2 199
+ headSetIterator = headSet.iterator();
+ assertEquals(2, ((Entry) headSetIterator.next()).getValue());
+ assertEquals(199, ((Entry) headSetIterator.next()).getValue());
+ assertEquals(198, ((Entry) headSetIterator.next()).getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_tailSet() {
+ Set entrySet, tailSet;
+ NavigableSet descendingSubMapEntrySet;
+ Iterator iterator, tailSetIterator;
+ Entry entry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = descendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value - 1, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = descendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value - 1, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = descendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value - 1, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = descendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value - 1, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value--) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();// 0...2
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ iterator.next();// 2
+ entry = (Entry) iterator.next();// 199
+ tailSet = descendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ assertEquals(199, ((Entry) tailSetIterator.next()).getValue());
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ assertEquals(198, ((Entry) tailSetIterator.next()).getValue());
+
+ tailSet = descendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ assertEquals(199, ((Entry) tailSetIterator.next()).getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_subSet() {
+ Set entrySet, subSet;
+ NavigableSet descendingSubMapEntrySet;
+ Entry startEntry, endEntry;
+ Iterator subSetIterator;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ Iterator iteratorStart = descendingSubMapEntrySet.iterator();
+ while (iteratorStart.hasNext()) {
+ startEntry = (Entry) iteratorStart.next();
+ Iterator iteratorEnd = descendingSubMapEntrySet.iterator();
+ while (iteratorEnd.hasNext()) {
+ endEntry = (Entry) iteratorEnd.next();
+ int startIndex = (Integer) startEntry.getValue();
+ int endIndex = (Integer) endEntry.getValue();
+ if (startIndex < endIndex) {
+ try {
+ descendingSubMapEntrySet.subSet(startEntry,
+ endEntry);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ endEntry);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator
+ .hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator
+ .hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+ }
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ // [2...0]
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ Iterator iterator = descendingSubMapEntrySet.iterator();
+ startEntry = (Entry) iterator.next();
+ iterator.next();
+ endEntry = (Entry) iterator.next();
+ subSet = descendingSubMapEntrySet.subSet(startEntry, endEntry);
+ assertEquals(2, subSet.size());
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, false);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(199, ((Entry) subSetIterator.next()).getValue());
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, true);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(199, ((Entry) subSetIterator.next()).getValue());
+ assertEquals(198, ((Entry) subSetIterator.next()).getValue());
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, false);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(2, ((Entry) subSetIterator.next()).getValue());
+ assertEquals(199, ((Entry) subSetIterator.next()).getValue());
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, true);
+ assertEquals(3, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(2, ((Entry) subSetIterator.next()).getValue());
+ assertEquals(199, ((Entry) subSetIterator.next()).getValue());
+ assertEquals(198, ((Entry) subSetIterator.next()).getValue());
+ }
+
+ // With Comnparator
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ Iterator iteratorStart = descendingSubMapEntrySet.iterator();
+ while (iteratorStart.hasNext()) {
+ startEntry = (Entry) iteratorStart.next();
+ Iterator iteratorEnd = descendingSubMapEntrySet.iterator();
+ while (iteratorEnd.hasNext()) {
+ endEntry = (Entry) iteratorEnd.next();
+ int startIndex = (Integer) startEntry.getValue();
+ int endIndex = (Integer) endEntry.getValue();
+ if (startIndex < endIndex) {
+ try {
+ descendingSubMapEntrySet.subSet(startEntry,
+ endEntry);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ endEntry);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator
+ .hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator
+ .hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = descendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+ }
+ }
+ }
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_lower() {
+ Set entrySet, subSet;
+ NavigableSet descendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry, lowerEntry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) descendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+
+ // System.out.println(descendingSubMapEntrySet);
+ // System.out.println(tm);
+ Object afterEnd = this.subMap_default_afterEnd_109.entrySet()
+ .iterator().next();
+ // System.out.println("o:" + afterEnd);
+ Object x = descendingSubMapEntrySet.lower(afterEnd);
+ // System.out.println("x:" + x);
+ assertNull(x);
+ Object beforeStart = this.subMap_default_beforeStart_100.entrySet()
+ .iterator().next();
+ // System.out.println("before: " + beforeStart);
+ Object y = descendingSubMapEntrySet.lower(beforeStart);
+ // System.out.println("y: " + y);
+ assertNotNull(y);
+ assertEquals(101, (((Entry) y).getValue()));
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) descendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) descendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) descendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ iterator.next();// 2
+ iterator.next();// 199
+ entry = (Entry) iterator.next();// 198
+ lowerEntry = (Entry) descendingSubMapEntrySet.lower(entry);
+ assertEquals(199, lowerEntry.getValue());
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_higher() {
+ Set entrySet, subSet;
+ NavigableSet descendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry, higherEntry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, higherEntry.getValue());
+ } else {
+ assertNull(higherEntry);
+ }
+ }
+
+ Object afterEnd = this.subMap_default_afterEnd_109.entrySet()
+ .iterator().next();
+ Object x = descendingSubMapEntrySet.higher(afterEnd);
+ assertNotNull(x);
+ assertEquals(108, ((Entry) x).getValue());
+ Object beforeStart = this.subMap_default_beforeStart_100.entrySet()
+ .iterator().next();
+ Object y = descendingSubMapEntrySet.higher(beforeStart);
+ assertNull(y);
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, higherEntry.getValue());
+ } else {
+ assertNull(higherEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, higherEntry.getValue());
+ } else {
+ assertNull(higherEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, higherEntry.getValue());
+ } else {
+ assertNull(higherEntry);
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ iterator.next();// 2
+ iterator.next();// 199
+ entry = (Entry) iterator.next();// 198
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ assertEquals(197, higherEntry.getValue());
+ }
+
+ // With Comparator
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSubMapEntrySet = ((NavigableSet) entrySet)
+ .descendingSet();
+ iterator = descendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ higherEntry = (Entry) descendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, higherEntry.getValue());
+ } else {
+ assertNull(higherEntry);
+ }
+ }
+
+ Object afterEnd = this.subMap_default_afterEnd_109.entrySet()
+ .iterator().next();
+ Object x = descendingSubMapEntrySet.higher(afterEnd);
+ assertNotNull(x);
+ assertEquals(108, ((Entry) x).getValue());
+ Object beforeStart = this.subMap_default_beforeStart_100.entrySet()
+ .iterator().next();
+ Object y = descendingSubMapEntrySet.higher(beforeStart);
+ assertNull(y);
+ }
+ }
+
+ public void test_DescendingSubMapEntrySet_ceiling() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet;
+ Entry entry;
+ Entry[] entryArray;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.ceiling(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+
+ // System.out.println(descendingSet);
+ // System.out.println(tm);
+ Object afterEnd = this.subMap_default_afterEnd_109.entrySet()
+ .iterator().next();
+ // System.out.println("o:" + afterEnd);//110
+ Object x = descendingSet.ceiling(afterEnd);
+ assertNotNull(x);
+ // System.out.println("x:" + x);
+ assertEquals(108, ((Entry) x).getValue());
+ Object beforeStart = this.subMap_default_beforeStart_100.entrySet()
+ .iterator().next();
+ // System.out.println("before: " + beforeStart);//0
+ Object y = descendingSet.ceiling(beforeStart);
+ assertNull(y);
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.ceiling(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.ceiling(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ try {
+ descendingSet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.ceiling(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ try {
+ descendingSet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ Iterator iterator = descendingSet.iterator();
+ Entry ceilingEntry;
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ ceilingEntry = (Entry) descendingSet.ceiling(entry);
+ assertEquals(entry, ceilingEntry);
+ }
+ }
+
+ }
+
+ public void test_DescendingSubMapEntrySet_floor() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet;
+ Entry entry;
+ Entry[] entryArray;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+
+ Object afterEnd = this.subMap_default_afterEnd_109.entrySet()
+ .iterator().next();
+ Object x = descendingSet.floor(afterEnd);
+ assertNull(x);
+
+ Object beforeStart = this.subMap_default_beforeStart_100.entrySet()
+ .iterator().next();
+ Object y = descendingSet.floor(beforeStart);
+ assertNotNull(y);
+ assertEquals(101, (((Entry) y).getValue()));
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+
+ Iterator iterator = descendingSet.iterator();
+ Entry floorEntry;
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) descendingSet.floor(entry);
+ assertEquals(entry, floorEntry);
+ }
+ }
+
+ // With Comparator
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 108; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+
+ entrySet = subMap_startIncluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ descendingSet = ((NavigableSet) entrySet).descendingSet();
+ try {
+ descendingSet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ entryArray = (Entry[]) descendingSet
+ .toArray(new Entry[descendingSet.size()]);
+ for (int i = 0, j = 109; i < entryArray.length; i++) {
+ entry = (Entry) descendingSet.floor(entryArray[i]);
+ assertEquals(j - i, entry.getValue());
+ }
+ }
+ }
+
+ public void test_DescendingSubMapKeySet_comparator() {
+ NavigableSet keySet, descendingKeySet;
+ Comparator comparator;
+ String[] keyArray;
+ Integer value1, value2;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ assertNull(keySet.comparator());
+ descendingKeySet = keySet.descendingSet();
+ comparator = descendingKeySet.comparator();
+ assertNotNull(comparator);
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 1; i < keyArray.length; i++) {
+ value1 = Integer.valueOf(keyArray[i - 1]);
+ value2 = Integer.valueOf(keyArray[i]);
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ assertNull(keySet.comparator());
+ descendingKeySet = keySet.descendingSet();
+ comparator = descendingKeySet.comparator();
+ assertNotNull(comparator);
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 1; i < keyArray.length; i++) {
+ value1 = Integer.valueOf(keyArray[i - 1]);
+ value2 = Integer.valueOf(keyArray[i]);
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ assertNull(keySet.comparator());
+ descendingKeySet = keySet.descendingSet();
+ comparator = descendingKeySet.comparator();
+ assertNotNull(comparator);
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 1; i < keyArray.length; i++) {
+ value1 = Integer.valueOf(keyArray[i - 1]);
+ value2 = Integer.valueOf(keyArray[i]);
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ assertNull(keySet.comparator());
+ descendingKeySet = keySet.descendingSet();
+ comparator = descendingKeySet.comparator();
+ assertNotNull(comparator);
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 1; i < keyArray.length; i++) {
+ value1 = Integer.valueOf(keyArray[i - 1]);
+ value2 = Integer.valueOf(keyArray[i]);
+ assertTrue(value1 > value2);
+ assertTrue(comparator.compare(value1, value2) < 0);
+ }
+
+ String endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ assertNull(keySet.comparator());
+ descendingKeySet = keySet.descendingSet();
+ assertNotNull(descendingKeySet.comparator());
+ }
+
+ public void test_AscendingSubMapKeySet_first() {
+ NavigableSet keySet;
+ String firstKey1 = new Integer(100).toString();
+ String firstKey2 = new Integer(101).toString();
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ assertEquals(firstKey2, keySet.first());
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ assertEquals(firstKey2, keySet.first());
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ assertEquals(firstKey1, keySet.first());
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ assertEquals(firstKey1, keySet.first());
+ }
+
+ public void test_DescendingSubMapKeySet_pollFirst_startExcluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endExcluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(8, keySet.size());
+ for (int value = 101; value < 109; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollFirst_startExcluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endIncluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 101; value < 110; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollFirst_startIncluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endExcluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 100; value < 109; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollFirst_startIncluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endIncluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(10, keySet.size());
+ for (int value = 100; value < 110; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollFirst() {
+ String endKey = new Integer(2).toString();
+ NavigableSet keySet = tm.headMap(endKey, true).navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ assertEquals(endKey, descendingKeySet.pollFirst());
+ }
+
+ public void test_DescendingSubMapKeySet_pollLast_startExcluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endExcluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(8, keySet.size());
+ for (int value = 108; value > 100; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollLast_startExcluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endIncluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 109; value > 100; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollLast_startIncluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endExcluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 108; value > 99; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollLast_startIncluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endIncluded
+ .navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(10, keySet.size());
+ for (int value = 109; value > 99; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_pollLast() {
+ String endKey = new Integer(2).toString();
+ NavigableSet keySet = tm.headMap(endKey, true).navigableKeySet();
+ NavigableSet descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(0).toString(), descendingKeySet.pollLast());
+ }
+
+ public void test_DescendingSubMapKeySet_headSet() {
+ NavigableSet keySet, descendingKeySet;
+ SortedSet headSet;
+ String endKey, key;
+ Iterator iterator;
+ int index;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ endKey = new Integer(99).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i - 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ try {
+ headSet = descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ endKey = new Integer(99).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i - 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(108, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ endKey = new Integer(99).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ endKey = new Integer(101).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 108; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 108; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i - 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ endKey = new Integer(99).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ endKey = new Integer(101).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 109; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i - 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = descendingKeySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(108, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ descendingKeySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ iterator.next();
+ endKey = (String) iterator.next();
+
+ headSet = descendingKeySet.headSet(endKey);
+ assertEquals(1, headSet.size());
+
+ headSet = descendingKeySet.headSet(endKey, false);
+ assertEquals(1, headSet.size());
+
+ headSet = descendingKeySet.headSet(endKey, true);
+ assertEquals(2, headSet.size());
+
+ key = new Integer(2).toString();
+ keySet = tm.tailMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ iterator.next();
+ endKey = (String) iterator.next();
+ headSet = descendingKeySet.headSet(endKey);
+ assertEquals(1, headSet.size());
+ iterator = headSet.iterator();
+ assertEquals(999, Integer.parseInt((String) iterator.next()));
+ }
+
+ public void test_DescendingSubMapKeySet_tailSet() {
+ NavigableSet keySet, descendingKeySet;
+ SortedSet tailSet;
+ String startKey, key;
+ Iterator iterator;
+ int index;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startKey = new Integer(99).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(101).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(100, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(100, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j - 1).toString(), key);
+ }
+ assertEquals(101, j);
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(101, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startKey = new Integer(99).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(101).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(100, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(100, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j - 1).toString(), key);
+ }
+ assertEquals(101, j);
+ }
+
+ startKey = new Integer(109).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(100, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(101, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startKey = new Integer(99).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ assertEquals(1, tailSet.size());
+ iterator = tailSet.iterator();
+ assertEquals(startKey, iterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ assertEquals(1, tailSet.size());
+ iterator = tailSet.iterator();
+ assertEquals(startKey, iterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ assertEquals(0, tailSet.size());
+
+ startKey = new Integer(101).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(99, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(99, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j - 1).toString(), key);
+ }
+ assertEquals(100, j);
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(100, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startKey = new Integer(99).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ assertEquals(1, tailSet.size());
+ iterator = tailSet.iterator();
+ assertEquals(startKey, iterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ assertEquals(1, tailSet.size());
+ iterator = tailSet.iterator();
+ assertEquals(startKey, iterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ assertEquals(0, tailSet.size());
+
+ startKey = new Integer(101).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(100, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(99, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(99, j);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j - 1).toString(), key);
+ }
+ assertEquals(100, j);
+ }
+
+ startKey = new Integer(109).toString();
+ tailSet = descendingKeySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(99, index);
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index--) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index - 1).toString(), key);
+ }
+ assertEquals(100, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ descendingKeySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ descendingKeySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ iterator.next();
+ startKey = (String) iterator.next();
+
+ tailSet = descendingKeySet.tailSet(startKey);
+ assertEquals(112, tailSet.size());
+ Iterator tailIterator = tailSet.iterator();
+ assertEquals(new Integer(199).toString(), tailIterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, true);
+ assertEquals(112, tailSet.size());
+ tailIterator = tailSet.iterator();
+ assertEquals(new Integer(199).toString(), tailIterator.next());
+
+ tailSet = descendingKeySet.tailSet(startKey, false);
+ assertEquals(111, tailSet.size());
+ tailIterator = tailSet.iterator();
+ assertEquals(new Integer(198).toString(), tailIterator.next());
+ }
+
+ public void test_DescendingSubMapKeySet_subSet() {
+ NavigableSet keySet, descendingKeySet;
+ SortedSet subSet;
+ String startKey, endKey, key;
+ Iterator startIterator, endIterator, subSetIterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startIterator = descendingKeySet.iterator();
+ while (startIterator.hasNext()) {
+ startKey = (String) startIterator.next();
+ endIterator = descendingKeySet.iterator();
+ while (endIterator.hasNext()) {
+ endKey = (String) endIterator.next();
+ int startIndex = Integer.valueOf(startKey);
+ int endIndex = Integer.valueOf(endKey);
+ if (startIndex < endIndex) {
+ try {
+ descendingKeySet.subSet(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, false, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, false, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, true, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, true, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = descendingKeySet.subSet(startKey, endKey);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey,
+ false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey,
+ true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey,
+ false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey,
+ true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+ }
+ }
+ }
+
+ endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+
+ startKey = (String) iterator.next();
+ iterator.next();
+ endKey = (String) iterator.next();
+
+ subSet = descendingKeySet.subSet(startKey, endKey);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(startKey, subSetIterator.next());
+ subSetIterator.next();
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey, false);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ subSetIterator.next();
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey, true);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ subSetIterator.next();
+ assertEquals(endKey, subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey, false);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(startKey, subSetIterator.next());
+ subSetIterator.next();
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey, true);
+ assertEquals(3, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(startKey, subSetIterator.next());
+ subSetIterator.next();
+ assertEquals(endKey, subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ startIterator = descendingKeySet.iterator();
+ while (startIterator.hasNext()) {
+ startKey = (String) startIterator.next();
+ endIterator = descendingKeySet.iterator();
+ while (endIterator.hasNext()) {
+ endKey = (String) endIterator.next();
+ int startIndex = Integer.valueOf(startKey);
+ int endIndex = Integer.valueOf(endKey);
+ if (startIndex < endIndex) {
+ try {
+ descendingKeySet.subSet(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, false, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, false, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, true, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ descendingKeySet.subSet(startKey, true, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = descendingKeySet.subSet(startKey, endKey);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey,
+ false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, false, endKey,
+ true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex - 1; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey,
+ false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = descendingKeySet.subSet(startKey, true, endKey,
+ true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index--) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+ }
+ }
+ }
+ }
+
+ public void test_DescendingSubMapKeySet_descendingSet() {
+ NavigableSet keySet, descendingSet, descendingDescendingSet;
+ int value;
+ Iterator iterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ iterator = descendingDescendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 101; iterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertEquals(109, value);
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ iterator = descendingDescendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 101; iterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertEquals(110, value);
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ iterator = descendingDescendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 100; iterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertEquals(109, value);
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ iterator = descendingDescendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 100; iterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertEquals(110, value);
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ String endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ assertEquals(keySet, descendingDescendingSet);
+
+ String startKey = new Integer(2).toString();
+ keySet = tm.tailMap(startKey, true).navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingDescendingSet = descendingSet.descendingSet();
+ assertEquals(keySet, descendingDescendingSet);
+ }
+
+ public void test_DescendingSubMapKeySet_descendingIterator() {
+ NavigableSet keySet, descendingSet;
+ int value;
+ Iterator iterator, descendingIterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+ assertTrue(descendingIterator.hasNext());
+ for (value = 101; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+ assertEquals(109, value);
+ try {
+ descendingIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ descendingSet = descendingSet
+ .headSet(new Integer(105).toString(), true);
+ descendingIterator = descendingSet.descendingIterator();
+ for (value = 105; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+
+ descendingSet = keySet.descendingSet();
+ descendingSet = descendingSet
+ .tailSet(new Integer(105).toString(), true);
+ descendingIterator = descendingSet.descendingIterator();
+ for (value = 101; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+ assertTrue(descendingIterator.hasNext());
+ for (value = 101; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+ assertEquals(110, value);
+ try {
+ descendingIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ descendingSet = descendingSet
+ .headSet(new Integer(105).toString(), true);
+ descendingIterator = descendingSet.descendingIterator();
+ for (value = 105; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+
+ descendingSet = keySet.descendingSet();
+ descendingSet = descendingSet
+ .tailSet(new Integer(105).toString(), true);
+ descendingIterator = descendingSet.descendingIterator();
+ for (value = 101; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+ assertTrue(descendingIterator.hasNext());
+ for (value = 100; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+ assertEquals(109, value);
+ try {
+ descendingIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+ assertTrue(descendingIterator.hasNext());
+ for (value = 100; descendingIterator.hasNext(); value++) {
+ assertEquals(new Integer(value).toString(), descendingIterator
+ .next());
+ }
+ assertEquals(110, value);
+ try {
+ descendingIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ String endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ iterator = keySet.iterator();
+
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+
+ while (iterator.hasNext()) {
+ assertEquals(iterator.next(), descendingIterator.next());
+ }
+
+ String startKey = new Integer(2).toString();
+ keySet = tm.tailMap(startKey, true).navigableKeySet();
+ iterator = keySet.iterator();
+ descendingSet = keySet.descendingSet();
+ descendingIterator = descendingSet.descendingIterator();
+
+ while (iterator.hasNext()) {
+ assertEquals(iterator.next(), descendingIterator.next());
+ }
+ }
+
+ public void test_DescendingSubMapKeySet_lower() {
+ NavigableSet keySet, descendingKeySet;
+ Iterator iterator;
+ String key, lowerKey;
+ int value, lowerValue;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(101, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(101, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(100, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(100, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ iterator.next();
+ iterator.next();
+ key = (String) iterator.next();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(new Integer(199).toString(), lowerKey);
+ try {
+ descendingKeySet.lower(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ String endKey = key;
+
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.lower(endKey));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.lower(endKey));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.lower(endKey));
+ assertEquals(new Integer(1).toString(), descendingKeySet.lower(key));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.lower(endKey));
+ assertEquals(new Integer(1).toString(), descendingKeySet.lower(key));
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(101, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(101, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(0).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertEquals(100, Integer.parseInt(lowerKey));
+
+ key = new Integer(2).toString();
+ lowerKey = (String) descendingKeySet.lower(key);
+ assertNull(lowerKey);
+
+ keySet = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) descendingKeySet.lower(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+ }
+
+ public void test_DescendingSubMapKeySet_higher() {
+ NavigableSet keySet, descendingKeySet;
+ Iterator iterator;
+ String key, higherKey;
+ int value, higherValue;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 101) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("108", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(0).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(108, Integer.parseInt(higherKey));
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 101) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("109", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(109, Integer.parseInt(higherKey));
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 100) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("108", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(108, Integer.parseInt(higherKey));
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 100) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("109", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(109, Integer.parseInt(higherKey));
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ key = (String) iterator.next();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(new Integer(199).toString(), higherKey);
+ try {
+ descendingKeySet.higher(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ String endKey = key;
+
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.higher(endKey));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.higher(endKey));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(998).toString(), descendingKeySet
+ .higher(endKey));
+ assertNull(descendingKeySet.higher(key));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(998).toString(), descendingKeySet
+ .higher(endKey));
+ assertNull(descendingKeySet.higher(key));
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 101) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("108", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(0).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(108, Integer.parseInt(higherKey));
+
+ keySet = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 101) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("109", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(109, Integer.parseInt(higherKey));
+
+ keySet = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 100) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("108", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(108, Integer.parseInt(higherKey));
+
+ keySet = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ higherKey = (String) descendingKeySet.higher(key);
+ if (value > 100) {
+ higherValue = Integer.valueOf(higherKey);
+ assertEquals(value - 1, higherValue);
+ } else {
+ assertNull(higherKey);
+ }
+ }
+
+ key = new Integer(99999).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals("109", higherKey);
+
+ key = new Integer(-1).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(100).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertNull(higherKey);
+
+ key = new Integer(2).toString();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(109, Integer.parseInt(higherKey));
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ iterator = descendingKeySet.iterator();
+ key = (String) iterator.next();
+ higherKey = (String) descendingKeySet.higher(key);
+ assertEquals(new Integer(199).toString(), higherKey);
+ try {
+ descendingKeySet.higher(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ endKey = key;
+
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.higher(endKey));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.higher(endKey));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(998).toString(), descendingKeySet
+ .higher(endKey));
+ assertNull(descendingKeySet.higher(key));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(998).toString(), descendingKeySet
+ .higher(endKey));
+ assertNull(descendingKeySet.higher(key));
+ }
+
+ public void test_DescendingSubMapKeySet_ceiling() {
+ NavigableSet keySet, descendingKeySet;
+ String[] keyArray;
+ String key, ceilingKey;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ key = new Integer(2).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertEquals(108, Integer.parseInt(ceilingKey));
+
+ key = new Integer(0).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertNull(ceilingKey);
+
+ key = new Integer(-1).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertNull(ceilingKey);
+
+ key = new Integer(99999).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertEquals(108, Integer.parseInt(ceilingKey));
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(key, descendingKeySet.ceiling(iterator.next()));
+ try {
+ descendingKeySet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ String endKey = key;
+
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(key, descendingKeySet.ceiling(endKey));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.ceiling(endKey));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(999).toString(), descendingKeySet
+ .ceiling(endKey));
+ assertEquals(key, descendingKeySet.ceiling(key));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(998).toString(), descendingKeySet
+ .ceiling(endKey));
+ assertEquals(key, descendingKeySet.ceiling(key));
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ key = new Integer(2).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertEquals(108, Integer.parseInt(ceilingKey));
+
+ key = new Integer(0).toString();
+ ceilingKey = (String) descendingKeySet.ceiling(key);
+ assertNull(ceilingKey);
+
+ keySet = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ keySet = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+
+ keySet = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ ceilingKey = (String) descendingKeySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), ceilingKey);
+ }
+ }
+
+ public void test_DescendingSubMapKeySet_floor() {
+ NavigableSet keySet, descendingKeySet;
+ String[] keyArray;
+ String floorKey;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ String key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(101, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(101, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(100, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(100, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ Iterator iterator = descendingKeySet.iterator();
+ assertEquals(key, descendingKeySet.floor(iterator.next()));
+ try {
+ descendingKeySet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ String endKey = key;
+
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(key, descendingKeySet.floor(endKey));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.floor(endKey));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertEquals(new Integer(999).toString(), descendingKeySet
+ .floor(endKey));
+ assertEquals(key, descendingKeySet.floor(key));
+
+ endKey = new Integer(999).toString();
+ keySet = tm.headMap(endKey, false).navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ assertNull(descendingKeySet.floor(endKey));
+ assertEquals(key, descendingKeySet.floor(key));
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(101, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(101, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 108; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(100, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+
+ keySet = ((NavigableMap) subMap_startIncluded_endIncluded)
+ .navigableKeySet();
+ descendingKeySet = keySet.descendingSet();
+ keyArray = (String[]) descendingKeySet
+ .toArray(new String[descendingKeySet.size()]);
+ for (int i = 0, j = 109; i < keyArray.length; i++) {
+ floorKey = (String) descendingKeySet.floor(keyArray[i]);
+ assertEquals(new Integer(j - i).toString(), floorKey);
+ }
+
+ key = new Integer(0).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertEquals(100, Integer.parseInt(floorKey));
+
+ key = new Integer(2).toString();
+ floorKey = (String) descendingKeySet.floor(key);
+ assertNull(floorKey);
+ }
+
+ public void test_AscendingSubMapKeySet_last() {
+ NavigableSet keySet;
+ String firstKey1 = new Integer(108).toString();
+ String firstKey2 = new Integer(109).toString();
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ assertEquals(firstKey1, keySet.last());
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ assertEquals(firstKey2, keySet.last());
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ assertEquals(firstKey1, keySet.last());
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ assertEquals(firstKey2, keySet.last());
+ }
+
+ public void test_AscendingSubMapKeySet_comparator() {
+ NavigableSet keySet;
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ assertNull(keySet.comparator());
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ assertNull(keySet.comparator());
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ assertNull(keySet.comparator());
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ assertNull(keySet.comparator());
+
+ String endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ assertNull(keySet.comparator());
+ }
+
+ public void test_AscendingSubMapKeySet_pollFirst_startExcluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endExcluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(8, keySet.size());
+ for (int value = 101; value < 109; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollFirst());
+ }
+
+ public void test_AscendingSubMapKeySet_pollFirst_startExcluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endIncluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 101; value < 110; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollFirst());
+ }
+
+ public void test_AscendingSubMapKeySet_pollFirst_startIncluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endExcluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 100; value < 109; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollFirst());
+ }
+
+ public void test_AscendingSubMapKeySet_pollFirst_startIncluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endIncluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(10, keySet.size());
+ for (int value = 100; value < 110; value++) {
+ assertEquals(new Integer(value).toString(), keySet.pollFirst());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollFirst());
+ }
+
+ public void test_AscendingSubMapKeySet_pollFirst() {
+ String endKey = new Integer(2).toString();
+ NavigableSet keySet = tm.headMap(endKey, true).navigableKeySet();
+ assertEquals(new Integer(0).toString(), keySet.pollFirst());
+
+ keySet = tm.tailMap(endKey, true).navigableKeySet();
+ assertEquals(new Integer(2).toString(), keySet.pollFirst());
+ }
+
+ public void test_AscendingSubMapKeySet_pollLast_startExcluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endExcluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(8, keySet.size());
+ for (int value = 108; value > 100; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_AscendingSubMapKeySet_pollLast_startExcluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startExcluded_endIncluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 109; value > 100; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_AscendingSubMapKeySet_pollLast_startIncluded_endExcluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endExcluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(9, keySet.size());
+ for (int value = 108; value > 99; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_AscendingSubMapKeySet_pollLast_startIncluded_endIncluded() {
+ NavigableSet keySet = navigableMap_startIncluded_endIncluded
+ .navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ assertEquals(10, keySet.size());
+ for (int value = 109; value > 99; value--) {
+ assertEquals(new Integer(value).toString(), keySet.pollLast());
+ }
+ assertEquals(0, keySet.size());
+ assertNull(keySet.pollLast());
+ }
+
+ public void test_AscendingSubMapKeySet_pollLast() {
+ String endKey = new Integer(2).toString();
+ NavigableSet keySet = tm.headMap(endKey, true).navigableKeySet();
+ assertEquals(new Integer(2).toString(), keySet.pollLast());
+
+ keySet = tm.tailMap(endKey, true).navigableKeySet();
+ assertEquals(new Integer(999).toString(), keySet.pollLast());
+ }
+
+ public void test_AscendingSubMapKeySet_descendingIterator() {
+ NavigableSet keySet;
+ Iterator iterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ iterator = keySet.descendingIterator();
+ for (int value = 108; value > 100; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ iterator = keySet.descendingIterator();
+ for (int value = 109; value > 100; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ iterator = keySet.descendingIterator();
+ for (int value = 108; value > 99; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ iterator = keySet.descendingIterator();
+ for (int value = 109; value > 99; value--) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ String endKey = new Integer(2).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ iterator = keySet.descendingIterator();
+ assertEquals(new Integer(2).toString(), iterator.next());
+ assertEquals(new Integer(199).toString(), iterator.next());
+ }
+
+ public void test_AscendingSubMapKeySet_descendingSet() {
+ NavigableSet keySet, descendingSet;
+ Iterator iterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet()
+ .descendingSet();
+ descendingSet = keySet.descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 101; value < 109; value++) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet()
+ .descendingSet();
+ descendingSet = keySet.descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 101; value < 110; value++) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet()
+ .descendingSet();
+ descendingSet = keySet.descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 100; value < 109; value++) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet()
+ .descendingSet();
+ descendingSet = keySet.descendingSet();
+ iterator = descendingSet.iterator();
+ for (int value = 100; value < 110; value++) {
+ assertTrue(iterator.hasNext());
+ assertEquals(new Integer(value).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ String endKey = new Integer(1).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ descendingSet = keySet.descendingSet();
+ iterator = descendingSet.iterator();
+ assertEquals(new Integer(1).toString(), iterator.next());
+ assertEquals(new Integer(0).toString(), iterator.next());
+ }
+
+ public void test_AscendingSubMapKeySet_headSet() {
+ NavigableSet keySet;
+ SortedSet headSet;
+ String endKey, key;
+ Iterator iterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int index;
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ endKey = new Integer(101).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(102, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ endKey = new Integer(101).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(102, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ key = new Integer(1).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ iterator = keySet.iterator();
+ iterator.next();
+ endKey = (String) iterator.next();
+ headSet = keySet.headSet(endKey, false);
+ assertEquals(1, headSet.size());
+ Iterator headSetIterator = headSet.iterator();
+ assertEquals(new Integer(0).toString(), headSetIterator.next());
+ assertFalse(headSetIterator.hasNext());
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ headSet = keySet.headSet(endKey, true);
+ assertEquals(2, headSet.size());
+ headSetIterator = headSet.iterator();
+ assertEquals(new Integer(0).toString(), headSetIterator.next());
+ assertEquals(new Integer(1).toString(), headSetIterator.next());
+ assertFalse(headSetIterator.hasNext());
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ try {
+ keySet.headSet(endKey).size();
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, false).size();
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true).size();
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = ((NavigableMap) subMap_startExcluded_endIncluded_comparator)
+ .navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(101).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 101; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = ((NavigableMap) subMap_startIncluded_endExcluded_comparator)
+ .navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ endKey = new Integer(101).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(102, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = ((NavigableMap) subMap_startIncluded_endIncluded_comparator)
+ .navigableKeySet();
+ endKey = new Integer(99).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ endKey = new Integer(100).toString();
+ assertEquals(0, keySet.headSet(endKey).size());
+ assertEquals(0, keySet.headSet(endKey, false).size());
+ assertEquals(1, keySet.headSet(endKey, true).size());
+
+ endKey = new Integer(101).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(101, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(102, index);
+
+ for (int i = 102; i < 109; i++) {
+ endKey = new Integer(i).toString();
+
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ int j;
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i, j);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (j = 100; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(i + 1, j);
+ }
+
+ endKey = new Integer(109).toString();
+ headSet = keySet.headSet(endKey);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, false);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ headSet = keySet.headSet(endKey, true);
+ iterator = headSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ endKey = new Integer(110).toString();
+ try {
+ keySet.headSet(endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(endKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ key = new Integer(1).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ iterator = keySet.iterator();
+ iterator.next();
+ endKey = (String) iterator.next();
+ headSet = keySet.headSet(endKey, false);
+ assertEquals(1, headSet.size());
+ headSetIterator = headSet.iterator();
+ assertEquals(new Integer(0).toString(), headSetIterator.next());
+ assertFalse(headSetIterator.hasNext());
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ headSet = keySet.headSet(endKey, true);
+ assertEquals(2, headSet.size());
+ headSetIterator = headSet.iterator();
+ assertEquals(new Integer(0).toString(), headSetIterator.next());
+ assertEquals(new Integer(1).toString(), headSetIterator.next());
+ assertFalse(headSetIterator.hasNext());
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.headSet(null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ }
+
+ public void test_AscendingSubMapKeySet_remove() {
+ TreeMap tm_rm = new TreeMap(tm);
+ SortedMap subMap_startExcluded_endExcluded_rm = tm_rm.subMap(
+ objArray[100].toString(), false, objArray[109].toString(),
+ false);
+ assertNull(subMap_startExcluded_endExcluded_rm.remove("0"));
+ try {
+ subMap_startExcluded_endExcluded_rm.remove(null);
+ fail("should throw NPE");
+ } catch (Exception e) {
+ // Expected
+ }
+ for (int i = 101; i < 108; i++) {
+ assertNotNull(subMap_startExcluded_endExcluded_rm
+ .remove(new Integer(i).toString()));
+ }
+ }
+
+ public void test_AscendingSubMapKeySet_tailSet() {
+ NavigableSet keySet;
+ SortedSet tailSet;
+ String startKey, key;
+ Iterator iterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ int index;
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; index < 109; index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+
+ startKey = new Integer(101).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(108, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(108, j);
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(109, j);
+ }
+
+ startKey = new Integer(109).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(108, index);
+
+ startKey = new Integer(101).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(108, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(108, j);
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ startKey = new Integer(100).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ startKey = new Integer(101).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(109, j);
+ }
+
+ startKey = new Integer(109).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ String endKey = new Integer(1).toString();
+ keySet = tm.headMap(endKey, true).navigableKeySet();
+ iterator = keySet.iterator();
+ iterator.next();
+ startKey = (String) iterator.next();
+ tailSet = keySet.tailSet(startKey);
+ assertEquals(1, tailSet.size());
+ Iterator tailSetIterator = tailSet.iterator();
+ assertEquals(endKey, tailSetIterator.next());
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ tailSet = keySet.tailSet(startKey, true);
+ assertEquals(1, tailSet.size());
+ tailSetIterator = tailSet.iterator();
+ assertEquals(endKey, tailSetIterator.next());
+
+ tailSet = keySet.tailSet(startKey, false);
+ assertEquals(0, tailSet.size());
+ tailSetIterator = tailSet.iterator();
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; index < 109; index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+
+ startKey = new Integer(101).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(109, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 101; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(108, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(109, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(108, j);
+ }
+
+ startKey = new Integer(109).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ startKey = new Integer(99).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ startKey = new Integer(100).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 100; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ for (int i = 102; i < 109; i++) {
+ startKey = new Integer(i).toString();
+
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ int j;
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j).toString(), key);
+ }
+ assertEquals(110, j);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (j = i; iterator.hasNext(); j++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(j + 1).toString(), key);
+ }
+ assertEquals(109, j);
+ }
+
+ startKey = new Integer(109).toString();
+ tailSet = keySet.tailSet(startKey);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, true);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index).toString(), key);
+ }
+ assertEquals(110, index);
+
+ tailSet = keySet.tailSet(startKey, false);
+ iterator = tailSet.iterator();
+ for (index = 109; iterator.hasNext(); index++) {
+ key = (String) iterator.next();
+ assertEquals(new Integer(index + 1).toString(), key);
+ }
+ assertEquals(109, index);
+
+ startKey = new Integer(110).toString();
+ try {
+ keySet.tailSet(startKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ keySet.tailSet(startKey, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_AscendingSubMapKeySet_subSet() {
+ NavigableSet keySet;
+ SortedSet subSet;
+ String startKey, endKey, key;
+ Iterator startIterator, endIterator, subSetIterator;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ startIterator = keySet.iterator();
+ while (startIterator.hasNext()) {
+ startKey = (String) startIterator.next();
+ endIterator = keySet.iterator();
+ while (endIterator.hasNext()) {
+ endKey = (String) endIterator.next();
+ int startIndex = Integer.valueOf(startKey);
+ int endIndex = Integer.valueOf(endKey);
+ if (startIndex > endIndex) {
+ try {
+ keySet.subSet(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = keySet.subSet(startKey, endKey);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+ }
+ }
+ }
+
+ key = new Integer(1).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ startKey = (String) iterator.next();
+ endKey = (String) iterator.next();
+
+ subSet = keySet.subSet(startKey, endKey);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, false);
+ assertEquals(0, subSet.size());
+
+ subSet = keySet.subSet(startKey, false, endKey, true);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(1).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, false);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, true);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ assertEquals(new Integer(1).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, endKey);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, endKey, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, endKey, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, endKey, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, endKey, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // With Comparator
+ keySet = ((NavigableMap) subMap_startExcluded_endExcluded_comparator)
+ .navigableKeySet();
+ startIterator = keySet.iterator();
+ while (startIterator.hasNext()) {
+ startKey = (String) startIterator.next();
+ endIterator = keySet.iterator();
+ while (endIterator.hasNext()) {
+ endKey = (String) endIterator.next();
+ int startIndex = Integer.valueOf(startKey);
+ int endIndex = Integer.valueOf(endKey);
+ if (startIndex > endIndex) {
+ try {
+ keySet.subSet(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, endKey, false);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, endKey, true);
+ fail("shoudl throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = keySet.subSet(startKey, endKey);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(new Integer(index).toString(),
+ subSetIterator.next());
+ }
+ }
+ }
+ }
+
+ key = new Integer(1).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ iterator = keySet.iterator();
+ startKey = (String) iterator.next();
+ endKey = (String) iterator.next();
+
+ subSet = keySet.subSet(startKey, endKey);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, false, endKey, false);
+ assertEquals(0, subSet.size());
+
+ subSet = keySet.subSet(startKey, false, endKey, true);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(1).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, false);
+ assertEquals(1, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ subSet = keySet.subSet(startKey, true, endKey, true);
+ assertEquals(2, subSet.size());
+ subSetIterator = subSet.iterator();
+ assertEquals(new Integer(0).toString(), subSetIterator.next());
+ assertEquals(new Integer(1).toString(), subSetIterator.next());
+ try {
+ subSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, endKey);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, endKey, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, false, endKey, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, endKey, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(null, true, endKey, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, false, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, null, false);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ keySet.subSet(startKey, true, null, true);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ }
+
+ public void test_AscendingSubMapKeySet_lower() {
+ NavigableSet keySet;
+ Iterator iterator;
+ String key, lowerKey;
+ int value, lowerValue;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.lower(key);
+ if (value > 101) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value - 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.lower(key);
+ if (value > 101) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value - 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.lower(key);
+ if (value > 100) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value - 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.lower(key);
+ if (value > 100) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value - 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ iterator = keySet.iterator();
+ iterator.next();// 0
+ String expectedLowerKey = (String) iterator.next();// 1
+ assertEquals(expectedLowerKey, keySet.lower(iterator.next()));
+
+ try {
+ keySet.lower(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertNull(keySet.lower(key));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.lower(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertNotNull(keySet.lower(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNotNull(keySet.lower(key));
+ }
+
+ public void test_AscendingSubMapKeySet_higher() {
+ NavigableSet keySet;
+ Iterator iterator;
+ String key, lowerKey;
+ int value, lowerValue;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.higher(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.higher(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.higher(key);
+ if (value < 108) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ iterator = keySet.iterator();
+ while (iterator.hasNext()) {
+ key = (String) iterator.next();
+ value = Integer.valueOf(key);
+ lowerKey = (String) keySet.higher(key);
+ if (value < 109) {
+ lowerValue = Integer.valueOf(lowerKey);
+ assertEquals(value + 1, lowerValue);
+ } else {
+ assertNull(lowerKey);
+ }
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ iterator = keySet.iterator();
+ iterator.next();// 0
+ iterator.next();// 1
+ lowerKey = (String) keySet.higher(iterator.next());
+ String expectedLowerKey = (String) iterator.next();
+ assertEquals(expectedLowerKey, lowerKey);
+
+ try {
+ keySet.higher(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertNull(keySet.higher(key));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.higher(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertNull(keySet.higher(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.higher(key));
+ }
+
+ public void test_AscendingSubMapKeySet_ceiling() {
+ NavigableSet keySet;
+ String key;
+ String[] keyArray;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 101; i < keyArray.length; i++) {
+ key = (String) keySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 101; i < keyArray.length; i++) {
+ key = (String) keySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 100; i < keyArray.length; i++) {
+ key = (String) keySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 100; i < keyArray.length; i++) {
+ key = (String) keySet.ceiling(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ iterator.next();
+ assertEquals(new Integer(1).toString(), keySet.ceiling(iterator.next()));
+
+ try {
+ keySet.ceiling(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertEquals(key, keySet.ceiling(key));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.higher(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertNull(keySet.higher(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.higher(key));
+ }
+
+ public void test_AscendingSubMapKeySet_floor() {
+ NavigableSet keySet;
+ String key;
+ String[] keyArray;
+
+ keySet = navigableMap_startExcluded_endExcluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 101; i < keyArray.length; i++) {
+ key = (String) keySet.floor(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startExcluded_endIncluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 101; i < keyArray.length; i++) {
+ key = (String) keySet.floor(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startIncluded_endExcluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 100; i < keyArray.length; i++) {
+ key = (String) keySet.floor(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ keySet = navigableMap_startIncluded_endIncluded.navigableKeySet();
+ keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
+ for (int i = 0, j = 100; i < keyArray.length; i++) {
+ key = (String) keySet.floor(keyArray[i]);
+ assertEquals(new Integer(i + j).toString(), key);
+ }
+
+ key = new Integer(2).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ Iterator iterator = keySet.iterator();
+ iterator.next();
+ assertEquals(new Integer(1).toString(), keySet.floor(iterator.next()));
+
+ try {
+ keySet.floor(null);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertEquals(key, keySet.floor(key));
+
+ key = new Integer(0).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertNull(keySet.floor(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, true).navigableKeySet();
+ assertEquals(key, keySet.floor(key));
+
+ key = new Integer(999).toString();
+ keySet = tm.headMap(key, false).navigableKeySet();
+ assertEquals(new Integer(998).toString(), keySet.floor(key));
+ }
+
+ public void test_BoundedEntryIterator_next() {
+ Iterator iterator = subMap_default.entrySet().iterator();
+ assertTrue(iterator.hasNext());
+ for (int i = 100; iterator.hasNext(); i++) {
+ assertEquals(i, ((Entry) iterator.next()).getValue());
+ }
+
+ try {
+ iterator.next();
+ fail("should throw java.util.NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ }
+
+ public void test_BoundedKeyIterator_next() {
+ Iterator iterator = subMap_default.keySet().iterator();
+ assertTrue(iterator.hasNext());
+ for (int i = 100; iterator.hasNext(); i++) {
+ assertEquals(new Integer(i).toString(), iterator.next());
+ }
+
+ try {
+ iterator.next();
+ fail("should throw java.util.NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ public void test_BoundedValueIterator_next() {
+ String startKey = new Integer(101).toString();
+ String endKey = new Integer(108).toString();
+
+ Collection values = tm.subMap(startKey, endKey).values();
+ Iterator iter = values.iterator();
+ for (int i = 101; i < 108; i++) {
+ assertEquals(i, iter.next());
+ }
+ try {
+ iter.next();
+ fail("should throw java.util.NoSuchElementException");
+ } catch (Exception e) {
+ // Expected
+ }
+ }
+
+ /*
+ * SubMapEntrySet
+ */
+ public void test_SubMapEntrySet_Constructor() {
+ }
+
+ public void test_SubMapEntrySet_contains() {
+ // covered in test_SubMapEntrySet_remove
+ }
+
+ public void test_SubMapEntrySet_iterator() {
+ Set entrySet = subMap_default.entrySet();
+ Iterator iterator;
+ Entry entry;
+ Integer value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startExcluded_endExcluded.entrySet();
+ value = new Integer(101);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startExcluded_endIncluded.entrySet();
+ value = new Integer(101);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(110, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startIncluded_endExcluded.entrySet();
+ value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startIncluded_endIncluded.entrySet();
+ value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(110, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ String startKey = new Integer(-1).toString();
+ String endKey = new Integer(0).toString();
+ SortedMap subMap = tm.subMap(startKey, endKey);
+ entrySet = subMap.entrySet();
+ iterator = entrySet.iterator();
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ endKey = new Integer(1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ entrySet = subMap.entrySet();
+ iterator = entrySet.iterator();
+ assertEquals(0, ((Entry) iterator.next()).getValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ endKey = new Integer(2000).toString();
+ subMap = tm.subMap(startKey, endKey);
+ entrySet = subMap.entrySet();
+ iterator = entrySet.iterator();
+ for (int i = 0; i < subMap.size(); i++) {
+ iterator.next();
+ }
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ startKey = new Integer(9).toString();
+ endKey = new Integer(100).toString();
+ try {
+ tm.subMap(startKey, endKey);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // With Comparator
+ entrySet = subMap_default_comparator.entrySet();
+ value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ value = new Integer(101);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ value = new Integer(101);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(110, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(109, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ entrySet = subMap_startIncluded_endIncluded_comparator.entrySet();
+ value = new Integer(100);
+ for (iterator = entrySet.iterator(); iterator.hasNext(); value++) {
+ entry = (Entry) iterator.next();
+ assertEquals(value.toString(), entry.getKey());
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(110, value.intValue());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ public void test_SubMapEntrySet_remove() {
+ Set entrySet = subMap_default.entrySet();
+ assertFalse(entrySet.remove(null));
+ int size = entrySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = entrySet.iterator();
+ assertTrue(entrySet.remove(iterator.next()));
+ }
+
+ entrySet = subMap_startExcluded_endExcluded.entrySet();
+ assertFalse(entrySet.remove(null));
+ size = entrySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = entrySet.iterator();
+ assertTrue(entrySet.remove(iterator.next()));
+ }
+
+ entrySet = subMap_startExcluded_endIncluded.entrySet();
+ assertFalse(entrySet.remove(null));
+ size = entrySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = entrySet.iterator();
+ assertTrue(entrySet.remove(iterator.next()));
+ }
+
+ entrySet = subMap_startIncluded_endExcluded.entrySet();
+ assertFalse(entrySet.remove(null));
+ size = entrySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = entrySet.iterator();
+ assertTrue(entrySet.remove(iterator.next()));
+ }
+
+ entrySet = subMap_startIncluded_endIncluded.entrySet();
+ assertFalse(entrySet.remove(null));
+ size = entrySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = entrySet.iterator();
+ assertTrue(entrySet.remove(iterator.next()));
+ }
+ }
+
+ public void test_SubMapEntrySet_isEmpty() {
+ assertFalse(subMap_default.entrySet().isEmpty());
+ assertFalse(subMap_startExcluded_endExcluded.entrySet().isEmpty());
+ assertFalse(subMap_startExcluded_endIncluded.entrySet().isEmpty());
+ assertFalse(subMap_startIncluded_endExcluded.entrySet().isEmpty());
+ assertFalse(subMap_startIncluded_endIncluded.entrySet().isEmpty());
+
+ String startKey = new Integer(0).toString();
+ String endKey = startKey;
+ SortedMap subMap = tm.subMap(startKey, endKey);
+ assertTrue(subMap.entrySet().isEmpty());
+
+ startKey = new Integer(-1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertTrue(subMap.entrySet().isEmpty());
+
+ endKey = new Integer(1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertFalse(subMap.entrySet().isEmpty());
+ }
+
+ public void test_SubMapEntrySet_size() {
+ assertEquals(9, subMap_default.entrySet().size());
+ assertEquals(8, subMap_startExcluded_endExcluded.entrySet().size());
+ assertEquals(9, subMap_startExcluded_endIncluded.entrySet().size());
+ assertEquals(9, subMap_startIncluded_endExcluded.entrySet().size());
+ assertEquals(10, subMap_startIncluded_endIncluded.entrySet().size());
+
+ String startKey = new Integer(0).toString();
+ String endKey = new Integer(2).toString();
+ SortedMap subMap = tm.subMap(startKey, endKey);
+ assertEquals(112, subMap.entrySet().size());
+
+ startKey = new Integer(0).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.entrySet().size());
+
+ startKey = new Integer(-1).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.entrySet().size());
+
+ endKey = new Integer(1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(1, subMap.entrySet().size());
+
+ startKey = new Integer(999).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.entrySet().size());
+ }
+
+ /*
+ * SubMapKeySet
+ */
+ public void test_SubMapKeySet_Constructor() {
+ // covered in other test
+ }
+
+ public void test_SubMapKeySet_iterator() {
+ Set keySet = subMap_default.keySet();
+ Iterator iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startExcluded_endExcluded.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(101 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startExcluded_endIncluded.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(101 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startIncluded_endExcluded.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startIncluded_endIncluded.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ // With Comparator
+ keySet = subMap_default_comparator.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startExcluded_endExcluded_comparator.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(101 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startExcluded_endIncluded_comparator.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(101 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startIncluded_endExcluded_comparator.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ keySet = subMap_startIncluded_endIncluded_comparator.keySet();
+ iterator = keySet.iterator();
+ for (int i = 0; i < keySet.size(); i++) {
+ assertEquals(new Integer(100 + i).toString(), iterator.next());
+ }
+ assertFalse(iterator.hasNext());
+ try {
+ iterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+
+ public void test_SubMapKeySet_isEmpty() {
+ assertFalse(subMap_default.keySet().isEmpty());
+ assertFalse(subMap_startExcluded_endExcluded.keySet().isEmpty());
+ assertFalse(subMap_startExcluded_endIncluded.keySet().isEmpty());
+ assertFalse(subMap_startIncluded_endExcluded.keySet().isEmpty());
+ assertFalse(subMap_startIncluded_endIncluded.keySet().isEmpty());
+
+ String startKey = new Integer(0).toString();
+ String endKey = startKey;
+ SortedMap subMap = tm.subMap(startKey, endKey);
+ assertTrue(subMap.keySet().isEmpty());
+
+ startKey = new Integer(999).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertTrue(subMap.keySet().isEmpty());
+
+ startKey = new Integer(-1).toString();
+ endKey = new Integer(1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertFalse(subMap.keySet().isEmpty());
+
+ endKey = new Integer(0).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertTrue(subMap.keySet().isEmpty());
+ }
+
+ public void test_SubMapKeySet_contains() {
+ Set keySet = subMap_default.keySet();
+ try {
+ keySet.contains(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ String key = new Integer(-1).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(99).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(100).toString();
+ assertTrue(keySet.contains(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(keySet.contains(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(110).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(1001).toString();
+ assertFalse(keySet.contains(key));
+
+ keySet = subMap_startExcluded_endExcluded.keySet();
+ try {
+ keySet.contains(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ key = new Integer(-1).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(99).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(100).toString();
+ assertFalse(keySet.contains(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(keySet.contains(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(110).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(1001).toString();
+ assertFalse(keySet.contains(key));
+
+ keySet = subMap_startExcluded_endIncluded.keySet();
+ try {
+ keySet.contains(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ key = new Integer(-1).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(99).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(100).toString();
+ assertFalse(keySet.contains(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(keySet.contains(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(keySet.contains(key));
+ key = new Integer(110).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(1001).toString();
+ assertFalse(keySet.contains(key));
+
+ keySet = subMap_startIncluded_endExcluded.keySet();
+ try {
+ keySet.contains(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ key = new Integer(-1).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(99).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(100).toString();
+ assertTrue(keySet.contains(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(keySet.contains(key));
+ }
+ key = new Integer(109).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(110).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(1001).toString();
+ assertFalse(keySet.contains(key));
+
+ keySet = subMap_startIncluded_endIncluded.keySet();
+ try {
+ keySet.contains(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ key = new Integer(-1).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(99).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(100).toString();
+ assertTrue(keySet.contains(key));
+ for (int i = 101; i < 109; i++) {
+ key = new Integer(i).toString();
+ assertTrue(keySet.contains(key));
+ }
+ key = new Integer(109).toString();
+ assertTrue(keySet.contains(key));
+ key = new Integer(110).toString();
+ assertFalse(keySet.contains(key));
+ key = new Integer(1001).toString();
+ assertFalse(keySet.contains(key));
+ }
+
+ public void test_SubMapKeySet_size() {
+ assertEquals(9, subMap_default.keySet().size());
+ assertEquals(8, subMap_startExcluded_endExcluded.keySet().size());
+ assertEquals(9, subMap_startExcluded_endIncluded.keySet().size());
+ assertEquals(9, subMap_startIncluded_endExcluded.keySet().size());
+ assertEquals(10, subMap_startIncluded_endIncluded.keySet().size());
+
+ String startKey = new Integer(0).toString();
+ String endKey = new Integer(2).toString();
+ SortedMap subMap = tm.subMap(startKey, endKey);
+ assertEquals(112, subMap.keySet().size());
+
+ startKey = new Integer(0).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.keySet().size());
+
+ startKey = new Integer(-1).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.keySet().size());
+
+ endKey = new Integer(1).toString();
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(1, subMap.keySet().size());
+
+ startKey = new Integer(999).toString();
+ endKey = startKey;
+ subMap = tm.subMap(startKey, endKey);
+ assertEquals(0, subMap.keySet().size());
+ }
+
+ public void test_SubMapKeySet_remove() {
+ Set keySet = subMap_default.keySet();
+ try {
+ keySet.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ int size = keySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = keySet.iterator();
+ assertTrue(keySet.remove(iterator.next()));
+ }
+
+ keySet = subMap_startExcluded_endExcluded.keySet();
+ try {
+ keySet.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ size = keySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = keySet.iterator();
+ assertTrue(keySet.remove(iterator.next()));
+ }
+
+ keySet = subMap_startExcluded_endIncluded.keySet();
+ try {
+ keySet.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ size = keySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = keySet.iterator();
+ assertTrue(keySet.remove(iterator.next()));
+ }
+
+ keySet = subMap_startIncluded_endExcluded.keySet();
+ try {
+ keySet.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ size = keySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = keySet.iterator();
+ assertTrue(keySet.remove(iterator.next()));
+ }
+
+ keySet = subMap_startIncluded_endIncluded.keySet();
+ try {
+ keySet.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ size = keySet.size();
+ for (int i = 0; i < size; i++) {
+ Iterator iterator = keySet.iterator();
+ assertTrue(keySet.remove(iterator.next()));
+ }
+ }
+
+ /*
+ * AscendingSubMapEntrySet
+ */
+
+ public void test_AscendingSubMapEntrySet_comparator() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ assertNull(ascendingSubMapEntrySet.comparator());
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ assertNull(ascendingSubMapEntrySet.comparator());
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ assertNull(ascendingSubMapEntrySet.comparator());
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ assertNull(ascendingSubMapEntrySet.comparator());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_descendingSet() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet, descendingSet;
+ Entry entry;
+ int value;
+ Iterator iterator;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ iterator = descendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 108; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(100, value);
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ iterator = descendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 109; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(100, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ iterator = descendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 108; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(99, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ descendingSet = ascendingSubMapEntrySet.descendingSet();
+ iterator = descendingSet.iterator();
+ assertTrue(iterator.hasNext());
+ for (value = 109; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(99, value);
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_descendingIterator() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.descendingIterator();
+ assertTrue(iterator.hasNext());
+ for (value = 108; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(100, value);
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.descendingIterator();
+ assertTrue(iterator.hasNext());
+ for (value = 109; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(100, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.descendingIterator();
+ assertTrue(iterator.hasNext());
+ for (value = 108; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(99, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.descendingIterator();
+ assertTrue(iterator.hasNext());
+ for (value = 109; iterator.hasNext(); value--) {
+ entry = (Entry) iterator.next();
+ assertEquals(value, entry.getValue());
+ }
+ assertEquals(99, value);
+ }
+
+ String startKey = new Integer(2).toString();
+ entrySet = tm.headMap(startKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.descendingIterator();
+ assertTrue(iterator.hasNext());
+ assertEquals(2, ((Entry) iterator.next()).getValue());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollFirst_startExcluded_endExcluded() {
+ Set entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 101; value < 109; value++) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollFirst();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty.
+ assertNull(ascendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollFirst_startExcluded_endIncluded() {
+ Set entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 101; value < 110; value++) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollFirst();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty.
+ assertNull(ascendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollFirst_startIncluded_endExcluded() {
+ Set entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 100; value < 109; value++) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollFirst();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty.
+ assertNull(ascendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollFirst_startIncluded_endIncluded() {
+ Set entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 100; value < 110; value++) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollFirst();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty.
+ assertNull(ascendingSubMapEntrySet.pollFirst());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollLast_startExcluded_endExcluded() {
+ Set entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 108; value > 100; value--) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollLast();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty
+ assertNull(ascendingSubMapEntrySet.pollLast());
+ }
+
+ // NavigableMap ascendingSubMap = tm.headMap("2", true);
+ // Set entrySet = ascendingSubMap.entrySet();
+ // Object last;
+ // if (entrySet instanceof NavigableSet) {
+ // last = ((NavigableSet) entrySet).pollLast();
+ // assertEquals("2=2", last.toString());
+ // }
+ //
+ // ascendingSubMap = tm.tailMap("2", true);
+ // entrySet = ascendingSubMap.entrySet();
+ // if (entrySet instanceof NavigableSet) {
+ // last = ((NavigableSet) entrySet).pollLast();
+ // assertEquals("999=999", last.toString());
+ // }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollLast_startExcluded_endIncluded() {
+ Set entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 109; value > 100; value--) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollLast();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty
+ assertNull(ascendingSubMapEntrySet.pollLast());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollLast_startIncluded_endExcluded() {
+ Set entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 108; value > 99; value--) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollLast();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty
+ assertNull(ascendingSubMapEntrySet.pollLast());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_pollLast_startIncluded_endIncluded() {
+ Set entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ NavigableSet ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ for (int value = 109; value > 99; value--) {
+ Entry entry = (Entry) ascendingSubMapEntrySet.pollLast();
+ assertEquals(value, entry.getValue());
+ }
+ assertTrue(ascendingSubMapEntrySet.isEmpty());
+ // should return null if the set is empty
+ assertNull(ascendingSubMapEntrySet.pollLast());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_headSet() {
+ Set entrySet, headSet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator, headSetIterator;
+ Entry entry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = ascendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value - 1);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = ascendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 101; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value - 1);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = ascendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value - 1);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ headSet = ascendingSubMapEntrySet.headSet(entry);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, false);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ headSet = ascendingSubMapEntrySet.headSet(entry, true);
+ headSetIterator = headSet.iterator();
+ for (value = 100; headSetIterator.hasNext(); value++) {
+ assertEquals(value, ((Entry) headSetIterator.next())
+ .getValue());
+ }
+ assertEquals(entry.getValue(), value - 1);
+ try {
+ headSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ // NavigableMap ascendingSubMap = tm.headMap("1", true);
+ // entrySet = ascendingSubMap.entrySet();
+ // if (entrySet instanceof SortedSet) {
+ // Iterator it = entrySet.iterator();
+ // it.next();
+ // Object end = it.next();// 1=1
+ // Set headSet = ((NavigableSet) entrySet).headSet(end);// inclusive
+ // // false
+ // assertEquals(1, headSet.size());
+ // }
+ }
+
+ public void test_AscendingSubMapEntrySet_tailSet() {
+ Set entrySet, tailSet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator, tailSetIterator;
+ Entry entry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = ascendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = ascendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = ascendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(109, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ tailSet = ascendingSubMapEntrySet.tailSet(entry);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, false);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue() + 1; tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+
+ tailSet = ascendingSubMapEntrySet.tailSet(entry, true);
+ tailSetIterator = tailSet.iterator();
+ for (value = (Integer) entry.getValue(); tailSetIterator
+ .hasNext(); value++) {
+ assertEquals(value, ((Entry) tailSetIterator.next())
+ .getValue());
+ }
+ assertEquals(110, value);
+ try {
+ tailSetIterator.next();
+ fail("should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Expected
+ }
+ }
+ }
+
+ // NavigableMap ascendingSubMap = tm.headMap("1", true);
+ // Set entrySet = ascendingSubMap.entrySet();
+ // if (entrySet instanceof NavigableSet) {
+ // Iterator it = entrySet.iterator();
+ // Object start = it.next();// 0=0
+ // Set tailSet = ((NavigableSet) entrySet).tailSet(start);// default
+ // // inclusive
+ // // false
+ // assertEquals(1, tailSet.size());
+ // }
+ }
+
+ public void test_AscendingSubMapEntrySet_subSet() {
+ Set entrySet, subSet;
+ NavigableSet ascendingSubMapEntrySet;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ Iterator iteratorStart = ascendingSubMapEntrySet.iterator();
+ while (iteratorStart.hasNext()) {
+ Entry startEntry = (Entry) iteratorStart.next();
+ Iterator iteratorEnd = ascendingSubMapEntrySet.iterator();
+ while (iteratorEnd.hasNext()) {
+ Entry endEntry = (Entry) iteratorEnd.next();
+ int startIndex = (Integer) startEntry.getValue();
+ int endIndex = (Integer) endEntry.getValue();
+ if (startIndex > endIndex) {
+ try {
+ ascendingSubMapEntrySet
+ .subSet(startEntry, endEntry);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ ascendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ ascendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ ascendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ ascendingSubMapEntrySet.subSet(startEntry, true,
+ endEntry, true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } else {
+ subSet = ascendingSubMapEntrySet.subSet(startEntry,
+ endEntry);
+ Iterator subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator
+ .hasNext(); index++) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator
+ .hasNext(); index++) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry,
+ false, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex + 1; subSetIterator
+ .hasNext(); index++) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, false);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry,
+ true, endEntry, true);
+ subSetIterator = subSet.iterator();
+ for (int index = startIndex; subSetIterator.hasNext(); index++) {
+ assertEquals(index, ((Entry) subSetIterator.next())
+ .getValue());
+ }
+ }
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ Iterator iterator = entrySet.iterator();
+ Object startEntry = iterator.next();
+ iterator.next();
+ Object endEntry = iterator.next();
+ subSet = ascendingSubMapEntrySet.subSet(startEntry, endEntry);
+ assertEquals(1, subSet.size());
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, false);
+ assertEquals(1, subSet.size());
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry, false,
+ endEntry, true);
+ assertEquals(2, subSet.size());
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry, true, endEntry,
+ false);
+ assertEquals(2, subSet.size());
+
+ subSet = ascendingSubMapEntrySet.subSet(startEntry, true, endEntry,
+ true);
+ assertEquals(3, subSet.size());
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_lower() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry, lowerEntry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ Entry expectedEntry = (Entry) iterator.next();
+ entry = (Entry) iterator.next();
+ assertEquals(expectedEntry, ascendingSubMapEntrySet.lower(entry));
+ }
+
+ // With Comparator
+
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 101) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startIncluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.lower(entry);
+ value = (Integer) entry.getValue();
+ if (value > 100) {
+ assertEquals(value - 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_higher() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry, lowerEntry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ String endKey = new Integer(2).toString();
+ entrySet = tm.headMap(endKey, true).entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = entrySet.iterator();
+ entry = (Entry) iterator.next();
+ Entry expectedEntry = (Entry) iterator.next();
+ assertEquals(expectedEntry, ascendingSubMapEntrySet.higher(entry));
+ }
+
+ // With Comparator
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 108) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+
+ entrySet = subMap_startIncluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.higher(entry);
+ value = (Integer) entry.getValue();
+ if (value < 109) {
+ assertEquals(value + 1, lowerEntry.getValue());
+ } else {
+ assertNull(lowerEntry);
+ }
+ }
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_ceiling() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator;
+
+ Set entrySet_beyondBound;
+ Iterator iterator_beyondBound;
+ Entry beyondBoundEntry;
+
+ Entry entry, lowerEntry;
+ int value = 0;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(108, value);
+
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(109, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(108, value);
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(109, value);
+ }
+
+ // With Comparator
+ entrySet = subMap_startIncluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(109, value);
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(108, value);
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(109, value);
+ }
+
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.ceiling(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ while (iterator.hasNext()) {
+ entry = (Entry) iterator.next();
+ lowerEntry = (Entry) ascendingSubMapEntrySet.ceiling(entry);
+ value = (Integer) entry.getValue();
+ assertEquals(value, lowerEntry.getValue());
+ }
+ assertEquals(108, value);
+ }
+ }
+
+ public void test_AscendingSubMapEntrySet_floor() {
+ Set entrySet;
+ NavigableSet ascendingSubMapEntrySet;
+ Iterator iterator;
+ Entry entry, floorEntry;
+ int value;
+
+ entrySet = navigableMap_startExcluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 101; i < 109; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = navigableMap_startExcluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 101; i < 110; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = navigableMap_startIncluded_endExcluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 100; i < 109; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = navigableMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 100; i < 110; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ // With Comparator
+ entrySet = subMap_startExcluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 101; i < 109; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = subMap_startExcluded_endIncluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 101; i < 110; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = subMap_startIncluded_endExcluded_comparator.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 100; i < 109; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ entrySet = subMap_startIncluded_endIncluded.entrySet();
+ if (entrySet instanceof NavigableSet) {
+ ascendingSubMapEntrySet = (NavigableSet) entrySet;
+ try {
+ ascendingSubMapEntrySet.floor(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ iterator = ascendingSubMapEntrySet.iterator();
+ for (int i = 100; i < 110; i++) {
+ entry = (Entry) iterator.next();
+ floorEntry = (Entry) ascendingSubMapEntrySet.floor(entry);
+ assertEquals(entry.getValue(), floorEntry.getValue());
+ }
+ assertFalse(iterator.hasNext());
+ }
+ }
+
+ @Override
+ protected void setUp() {
+ tm = new TreeMap();
+ tm_comparator = new TreeMap(new MockComparator());
+ for (int i = 0; i < objArray.length; i++) {
+ Object x = objArray[i] = new Integer(i);
+ tm.put(x.toString(), x);
+ tm_comparator.put(x.toString(), x);
+ }
+
+ subMap_default = tm.subMap(objArray[100].toString(), objArray[109]
+ .toString());
+ subMap_startExcluded_endExcluded = tm.subMap(objArray[100].toString(),
+ false, objArray[109].toString(), false);
+ subMap_startExcluded_endIncluded = tm.subMap(objArray[100].toString(),
+ false, objArray[109].toString(), true);
+ subMap_startIncluded_endExcluded = tm.subMap(objArray[100].toString(),
+ true, objArray[109].toString(), false);
+ subMap_startIncluded_endIncluded = tm.subMap(objArray[100].toString(),
+ true, objArray[109].toString(), true);
+
+ subMap_default_beforeStart_100 = tm.subMap(objArray[0].toString(),
+ objArray[1].toString());
+
+ subMap_default_afterEnd_109 = tm.subMap(objArray[110].toString(),
+ objArray[119].toString());
+
+ assertTrue(subMap_startExcluded_endExcluded instanceof NavigableMap);
+ assertTrue(subMap_startExcluded_endIncluded instanceof NavigableMap);
+ assertTrue(subMap_startIncluded_endExcluded instanceof NavigableMap);
+ assertTrue(subMap_startIncluded_endIncluded instanceof NavigableMap);
+
+ navigableMap_startExcluded_endExcluded = (NavigableMap) subMap_startExcluded_endExcluded;
+ navigableMap_startExcluded_endIncluded = (NavigableMap) subMap_startExcluded_endIncluded;
+ navigableMap_startIncluded_endExcluded = (NavigableMap) subMap_startIncluded_endExcluded;
+ navigableMap_startIncluded_endIncluded = (NavigableMap) subMap_startIncluded_endIncluded;
+
+ subMap_default_comparator = tm_comparator.subMap(objArray[100]
+ .toString(), objArray[109].toString());
+ subMap_startExcluded_endExcluded_comparator = tm_comparator.subMap(
+ objArray[100].toString(), false, objArray[109].toString(),
+ false);
+
+ subMap_startExcluded_endIncluded_comparator = tm_comparator
+ .subMap(objArray[100].toString(), false, objArray[109]
+ .toString(), true);
+ subMap_startIncluded_endExcluded_comparator = tm_comparator
+ .subMap(objArray[100].toString(), true, objArray[109]
+ .toString(), false);
+ subMap_startIncluded_endIncluded_comparator = tm_comparator.subMap(
+ objArray[100].toString(), true, objArray[109].toString(), true);
+ }
+
+ @Override
+ protected void tearDown() {
+ tm = null;
+ tm_comparator = null;
+
+ subMap_default = null;
+ subMap_startExcluded_endExcluded = null;
+ subMap_startExcluded_endIncluded = null;
+ subMap_startIncluded_endExcluded = null;
+ subMap_startIncluded_endIncluded = null;
+
+ subMap_default_beforeStart_100 = null;
+ subMap_default_afterEnd_109 = null;
+
+ subMap_default_comparator = null;
+ subMap_startExcluded_endExcluded_comparator = null;
+ subMap_startExcluded_endIncluded_comparator = null;
+ subMap_startIncluded_endExcluded_comparator = null;
+ subMap_startIncluded_endIncluded_comparator = null;
+ }
+
+ public void test_lower_null() throws Exception {
+ NavigableMap map = tm.subMap(objArray[100].toString(), true,
+ objArray[100].toString(), false);
+ assertNull(map.ceilingKey(objArray[100].toString()));
+ assertNull(map.floorKey(objArray[100].toString()));
+ assertNull(map.lowerKey(objArray[100].toString()));
+ assertNull(map.higherKey(objArray[100].toString()));
+ assertNull(map.ceilingKey(objArray[111].toString()));
+ assertNull(map.floorKey(objArray[111].toString()));
+ assertNull(map.lowerKey(objArray[111].toString()));
+ assertNull(map.higherKey(objArray[111].toString()));
+ assertNull(map.ceilingKey(objArray[1].toString()));
+ assertNull(map.floorKey(objArray[1].toString()));
+ assertNull(map.lowerKey(objArray[1].toString()));
+ assertNull(map.higherKey(objArray[1].toString()));
+ map = map.descendingMap();
+ assertNull(map.ceilingKey(objArray[100].toString()));
+ assertNull(map.floorKey(objArray[100].toString()));
+ assertNull(map.lowerKey(objArray[100].toString()));
+ assertNull(map.higherKey(objArray[100].toString()));
+ assertNull(map.ceilingKey(objArray[111].toString()));
+ assertNull(map.floorKey(objArray[111].toString()));
+ assertNull(map.lowerKey(objArray[111].toString()));
+ assertNull(map.higherKey(objArray[111].toString()));
+ assertNull(map.ceilingKey(objArray[1].toString()));
+ assertNull(map.floorKey(objArray[1].toString()));
+ assertNull(map.lowerKey(objArray[1].toString()));
+ assertNull(map.higherKey(objArray[1].toString()));
+ }
+
+ public void test_lower_tail() throws Exception {
+ NavigableMap map = tm.subMap(objArray[102].toString(), true,
+ objArray[103].toString(), false);
+ assertTrue(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[103].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ map = map.descendingMap();
+ assertTrue(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[103].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ map = tm.subMap(objArray[102].toString(), true, objArray[102]
+ .toString(), false);
+ assertFalse(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[103].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ map = map.descendingMap();
+ assertFalse(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[103].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ }
+
+ public void test_contains_null() throws Exception {
+ NavigableMap map = tm.subMap(objArray[100].toString(), true,
+ objArray[100].toString(), false);
+ assertFalse(map.containsKey(objArray[100].toString()));
+ assertFalse(map.containsKey(objArray[10].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[1].toString()));
+ map = map.descendingMap();
+ assertFalse(map.containsKey(objArray[100].toString()));
+ assertFalse(map.containsKey(objArray[10].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertFalse(map.containsKey(objArray[102].toString()));
+ assertFalse(map.containsKey(objArray[1].toString()));
+ }
+
+ public void test_contains() throws Exception {
+ NavigableMap map = tm.subMap(objArray[102].toString(), true,
+ objArray[103].toString(), false);
+ assertFalse(map.containsKey(objArray[100].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertTrue(map.containsKey(objArray[102].toString()));
+ map = map.descendingMap();
+ assertFalse(map.containsKey(objArray[100].toString()));
+ assertFalse(map.containsKey(objArray[104].toString()));
+ assertFalse(map.containsKey(objArray[101].toString()));
+ assertTrue(map.containsKey(objArray[102].toString()));
+ }
+
+ public void test_size() throws Exception {
+ NavigableMap map = tm.subMap(objArray[102].toString(), true,
+ objArray[103].toString(), false);
+ assertEquals(0, map.headMap(objArray[102].toString(), false).size());
+ assertEquals(1, map.headMap(objArray[102].toString(), true).size());
+ try {
+ assertEquals(1, map.headMap(objArray[103].toString(), true).size());
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ assertEquals(1, map.headMap(objArray[103].toString(), false).size());
+ assertEquals(1, map.tailMap(objArray[102].toString(), true).size());
+ assertEquals(0, map.tailMap(objArray[102].toString(), false).size());
+ assertTrue(map.headMap(objArray[103].toString(), false).containsKey(
+ objArray[102].toString()));
+ try {
+ assertTrue(map.headMap(objArray[103].toString(), true).containsKey(
+ objArray[102].toString()));
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ assertFalse(map.headMap(objArray[102].toString(), false).containsKey(
+ objArray[102].toString()));
+ assertTrue(map.headMap(objArray[102].toString(), true).containsKey(
+ objArray[102].toString()));
+ assertTrue(map.tailMap(objArray[102].toString(), true).containsKey(
+ objArray[102].toString()));
+ assertFalse(map.tailMap(objArray[102].toString(), true).containsKey(
+ objArray[103].toString()));
+ try {
+ assertEquals(0, map.tailMap(objArray[101].toString()).size());
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ map = map.descendingMap();
+ try {
+ map = map.subMap(objArray[103].toString(), true, objArray[102]
+ .toString(), true);
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ map = map.subMap(objArray[102].toString(), true, objArray[102]
+ .toString(), true);
+ assertEquals(1, map.headMap(objArray[102].toString(), true).size());
+ assertEquals(0, map.headMap(objArray[102].toString(), false).size());
+ try {
+ assertEquals(0, map.headMap(objArray[103].toString(), true).size());
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+
+ assertEquals(1, map.tailMap(objArray[102].toString(), true).size());
+ try {
+ assertFalse(map.headMap(objArray[103].toString(), true)
+ .containsKey(objArray[102].toString()));
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ assertTrue(map.headMap(objArray[102].toString(), true).containsKey(
+ objArray[102].toString()));
+ assertFalse(map.headMap(objArray[102].toString(), false).containsKey(
+ objArray[102].toString()));
+ assertTrue(map.tailMap(objArray[102].toString(), true).containsKey(
+ objArray[102].toString()));
+ assertFalse(map.tailMap(objArray[102].toString(), true).containsKey(
+ objArray[103].toString()));
+ try {
+ assertEquals(0, map.tailMap(objArray[101].toString()).size());
+ fail("should throw IAE");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ public void test_lower() throws Exception {
+ NavigableMap map = tm.subMap(objArray[102].toString(), true,
+ objArray[103].toString(), false);
+ assertEquals(objArray[102].toString(), map.higherKey(objArray[101]
+ .toString()));
+ assertEquals(null, map.higherKey(objArray[102].toString()));
+ assertEquals(null, map.higherKey(objArray[103].toString()));
+ assertEquals(null, map.higherKey(objArray[104].toString()));
+ assertEquals(objArray[102].toString(), map.ceilingKey(objArray[101]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.ceilingKey(objArray[102]
+ .toString()));
+ assertEquals(null, map.ceilingKey(objArray[103].toString()));
+ assertEquals(null, map.ceilingKey(objArray[104].toString()));
+ assertEquals(null, map.lowerKey(objArray[101].toString()));
+ assertEquals(null, map.lowerKey(objArray[102].toString()));
+ assertEquals(objArray[102].toString(), map.lowerKey(objArray[103]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.lowerKey(objArray[104]
+ .toString()));
+ assertEquals(null, map.floorKey(objArray[101].toString()));
+ assertEquals(objArray[102].toString(), map.floorKey(objArray[102]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.floorKey(objArray[103]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.floorKey(objArray[104]
+ .toString()));
+ map = map.descendingMap();
+ assertEquals(null, map.higherKey(objArray[101].toString()));
+ assertEquals(null, map.higherKey(objArray[102].toString()));
+ assertEquals(objArray[102].toString(), map.higherKey(objArray[103]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.higherKey(objArray[104]
+ .toString()));
+ assertEquals(null, map.ceilingKey(objArray[101].toString()));
+ assertEquals(objArray[102].toString(), map.ceilingKey(objArray[102]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.ceilingKey(objArray[103]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.ceilingKey(objArray[104]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.lowerKey(objArray[101]
+ .toString()));
+ assertEquals(null, map.lowerKey(objArray[102].toString()));
+ assertEquals(null, map.lowerKey(objArray[103].toString()));
+ assertEquals(null, map.lowerKey(objArray[104].toString()));
+ assertEquals(objArray[102].toString(), map.floorKey(objArray[101]
+ .toString()));
+ assertEquals(objArray[102].toString(), map.floorKey(objArray[102]
+ .toString()));
+ assertEquals(null, map.floorKey(objArray[103].toString()));
+ assertEquals(null, map.floorKey(objArray[104].toString()));
+ }
+
+ public void test_lowerkey() throws Exception {
+ try {
+ tm.subMap(objArray[100].toString(), true, objArray[100].toString(),
+ false).descendingMap().firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (Exception e) {
+ // expected
+ }
+ try {
+ tm.subMap(objArray[100].toString(), true, objArray[100].toString(),
+ false).descendingMap().lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (Exception e) {
+ // expected
+ }
+ try {
+ tm.subMap(objArray[100].toString(), true, objArray[100].toString(),
+ false).firstKey();
+ fail("should throw NoSuchElementException");
+ } catch (Exception e) {
+ // expected
+ }
+ try {
+ tm.subMap(objArray[100].toString(), true, objArray[100].toString(),
+ false).lastKey();
+ fail("should throw NoSuchElementException");
+ } catch (Exception e) {
+ // expected
+ }
+
+ }
+
+ public void test_headMap() throws Exception {
+ TreeMap tree = new TreeMap();
+ tree.put(new Integer(0), null);
+ tree.put(new Integer(1), null);
+ Map submap = tree.subMap(tree.firstKey(), tree.lastKey());
+ tree.remove(tree.lastKey());
+ assertEquals(submap, tree);
+ }
+
+ public void testname() throws Exception {
+ TreeMap nullTree = new TreeMap(new Comparator() {
+ public int compare(Object o1, Object o2) {
+ if (o1 == null) {
+ return o2 == null ? 0 : -1;
+ }
+ return ((String) o1).compareTo((String) o2);
+ }
+ });
+ nullTree.put(new String("One"), 1);
+ nullTree.put(new String("Two"), 2);
+ nullTree.put(new String("Three"), 3);
+ nullTree.put(new String("Four"), 4);
+ nullTree.put(null, 0);
+ nullTree.subMap(null, "two").size();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapRndTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapRndTest.java
new file mode 100644
index 0000000..bec75a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapRndTest.java
@@ -0,0 +1,28 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.TreeMap;
+
+public class TreeMapRndTest extends SortedMapTestBase {
+ protected void setUp() throws Exception {
+ ref = new RefSortedMap<Integer, Integer>();
+ super.setUp();
+ map = new TreeMap<Integer, Integer>(ref);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapTest.java
new file mode 100644
index 0000000..58ffaf6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeMapTest.java
@@ -0,0 +1,1968 @@
+/*
+ * 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.tests.java.util;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.support.Support_MapTest2;
+import tests.support.Support_UnmodifiableCollectionTest;
+import java.io.Serializable;
+import java.text.CollationKey;
+import java.text.Collator;
+import java.util.AbstractMap;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.NavigableMap;
+import java.util.NavigableSet;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+public class TreeMapTest extends junit.framework.TestCase {
+
+ public static class ReversedComparator implements Comparator {
+ public int compare(Object o1, Object o2) {
+ return -(((Comparable) o1).compareTo(o2));
+ }
+
+ public boolean equals(Object o1, Object o2) {
+ return (((Comparable) o1).compareTo(o2)) == 0;
+ }
+ }
+
+ // Regression for Harmony-1026
+ public static class MockComparator<T extends Comparable<T>> implements
+ Comparator<T>, Serializable {
+
+ public int compare(T o1, T o2) {
+ if (o1 == o2) {
+ return 0;
+ }
+ if (null == o1 || null == o2) {
+ return -1;
+ }
+ T c1 = o1;
+ T c2 = o2;
+ return c1.compareTo(c2);
+ }
+ }
+
+ // Regression for Harmony-1161
+ class MockComparatorNullTolerable implements Comparator<String> {
+
+ public int compare(String o1, String o2) {
+ if (o1 == o2) {
+ return 0;
+ }
+ if (null == o1) {
+ return -1;
+ }
+ if (null == o2) { // comparator should be symmetric
+ return 1;
+ }
+ return o1.compareTo(o2);
+ }
+ }
+
+ TreeMap tm;
+
+ Object objArray[] = new Object[1000];
+
+ /**
+ * java.util.TreeMap#TreeMap()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.TreeMap()
+ new Support_MapTest2(new TreeMap()).runTest();
+
+ assertTrue("New treeMap non-empty", new TreeMap().isEmpty());
+ }
+
+ /**
+ * java.util.TreeMap#TreeMap(java.util.Comparator)
+ */
+ public void test_ConstructorLjava_util_Comparator() {
+ // Test for method java.util.TreeMap(java.util.Comparator)
+ Comparator comp = new ReversedComparator();
+ TreeMap reversedTreeMap = new TreeMap(comp);
+ assertTrue("TreeMap answered incorrect comparator", reversedTreeMap
+ .comparator() == comp);
+ reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
+ reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
+ assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
+ reversedTreeMap.firstKey().equals(new Integer(2).toString()));
+ assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
+ reversedTreeMap.lastKey().equals(new Integer(1).toString()));
+
+ }
+
+ /**
+ * java.util.TreeMap#TreeMap(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ // Test for method java.util.TreeMap(java.util.Map)
+ TreeMap myTreeMap = new TreeMap(new HashMap(tm));
+ assertTrue("Map is incorrect size", myTreeMap.size() == objArray.length);
+ for (Object element : objArray) {
+ assertTrue("Map has incorrect mappings", myTreeMap.get(
+ element.toString()).equals(element));
+ }
+ }
+
+ /**
+ * java.util.TreeMap#TreeMap(java.util.SortedMap)
+ */
+ public void test_ConstructorLjava_util_SortedMap() {
+ // Test for method java.util.TreeMap(java.util.SortedMap)
+ Comparator comp = new ReversedComparator();
+ TreeMap reversedTreeMap = new TreeMap(comp);
+ reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
+ reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
+ TreeMap anotherTreeMap = new TreeMap(reversedTreeMap);
+ assertTrue("New tree map does not answer correct comparator",
+ anotherTreeMap.comparator() == comp);
+ assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
+ anotherTreeMap.firstKey().equals(new Integer(2).toString()));
+ assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
+ anotherTreeMap.lastKey().equals(new Integer(1).toString()));
+
+ }
+
+ /**
+ * java.util.TreeMap#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.TreeMap.clear()
+ tm.clear();
+ assertEquals("Cleared map returned non-zero size", 0, tm.size());
+ }
+
+ /**
+ * java.util.TreeMap#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.TreeMap.clone()
+ TreeMap clonedMap = (TreeMap) tm.clone();
+ assertTrue("Cloned map does not equal the original map", clonedMap
+ .equals(tm));
+ assertTrue("Cloned map is the same reference as the original map",
+ clonedMap != tm);
+ for (Object element : objArray) {
+ assertTrue("Cloned map contains incorrect elements", clonedMap
+ .get(element.toString()) == tm.get(element.toString()));
+ }
+
+ TreeMap map = new TreeMap();
+ 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());
+ }
+
+ /**
+ * java.util.TreeMap#comparator()
+ */
+ public void test_comparator() {
+ // Test for method java.util.Comparator java.util.TreeMap.comparator()\
+ Comparator comp = new ReversedComparator();
+ TreeMap reversedTreeMap = new TreeMap(comp);
+ assertTrue("TreeMap answered incorrect comparator", reversedTreeMap
+ .comparator() == comp);
+ reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
+ reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
+ assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
+ reversedTreeMap.firstKey().equals(new Integer(2).toString()));
+ assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
+ reversedTreeMap.lastKey().equals(new Integer(1).toString()));
+ }
+
+ /**
+ * java.util.TreeMap#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.TreeMap.containsKey(java.lang.Object)
+ assertTrue("Returned false for valid key", tm.containsKey("95"));
+ assertTrue("Returned true for invalid key", !tm.containsKey("XXXXX"));
+ }
+
+ /**
+ * java.util.TreeMap#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ // Test for method boolean
+ // java.util.TreeMap.containsValue(java.lang.Object)
+ assertTrue("Returned false for valid value", tm
+ .containsValue(objArray[986]));
+ assertTrue("Returned true for invalid value", !tm
+ .containsValue(new Object()));
+ }
+
+ /**
+ * java.util.TreeMap#entrySet()
+ */
+ public void test_entrySet() {
+ // Test for method java.util.Set java.util.TreeMap.entrySet()
+ Set anEntrySet = tm.entrySet();
+ Iterator entrySetIterator = anEntrySet.iterator();
+ assertTrue("EntrySet is incorrect size",
+ anEntrySet.size() == objArray.length);
+ Map.Entry entry;
+ while (entrySetIterator.hasNext()) {
+ entry = (Map.Entry) entrySetIterator.next();
+ assertTrue("EntrySet does not contain correct mappings", tm
+ .get(entry.getKey()) == entry.getValue());
+ }
+ }
+
+ /**
+ * java.util.TreeMap#firstKey()
+ */
+ public void test_firstKey() {
+ // Test for method java.lang.Object java.util.TreeMap.firstKey()
+ assertEquals("Returned incorrect first key", "0", tm.firstKey());
+ }
+
+ /**
+ * java.util.TreeMap#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.TreeMap.get(java.lang.Object)
+ Object o = new Object();
+ tm.put("Hello", o);
+ assertTrue("Failed to get mapping", tm.get("Hello") == o);
+
+ // Test for the same key & same value
+ tm = new TreeMap();
+ Object o2 = new Object();
+ Integer key1 = 1;
+ Integer key2 = 2;
+ assertNull(tm.put(key1, o));
+ assertNull(tm.put(key2, o));
+ assertEquals(2, tm.values().size());
+ assertEquals(2, tm.keySet().size());
+ assertSame(tm.get(key1), tm.get(key2));
+ assertSame(o, tm.put(key1, o2));
+ assertSame(o2, tm.get(key1));
+ }
+
+ /**
+ * java.util.TreeMap#headMap(java.lang.Object)
+ */
+ public void test_headMapLjava_lang_Object() {
+ // Test for method java.util.SortedMap
+ // java.util.TreeMap.headMap(java.lang.Object)
+ Map head = tm.headMap("100");
+ assertEquals("Returned map of incorrect size", 3, head.size());
+ assertTrue("Returned incorrect elements", head.containsKey("0")
+ && head.containsValue(new Integer("1"))
+ && head.containsKey("10"));
+
+ // Regression for Harmony-1026
+ TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(
+ new MockComparator());
+ map.put(1, 2.1);
+ map.put(2, 3.1);
+ map.put(3, 4.5);
+ map.put(7, 21.3);
+ map.put(null, null);
+
+ SortedMap<Integer, Double> smap = map.headMap(null);
+ assertEquals(0, smap.size());
+
+ Set<Integer> keySet = smap.keySet();
+ assertEquals(0, keySet.size());
+
+ Set<Map.Entry<Integer, Double>> entrySet = smap.entrySet();
+ assertEquals(0, entrySet.size());
+
+ Collection<Double> valueCollection = smap.values();
+ assertEquals(0, valueCollection.size());
+
+ // Regression for Harmony-1066
+ assertTrue(head instanceof Serializable);
+
+ // Regression for ill-behaved collator
+ Collator c = new Collator() {
+ @Override
+ public int compare(String o1, String o2) {
+ if (o1 == null) {
+ return 0;
+ }
+ return o1.compareTo(o2);
+ }
+
+ @Override
+ public CollationKey getCollationKey(String string) {
+ return null;
+ }
+
+ @Override
+ public int hashCode() {
+ return 0;
+ }
+ };
+
+ TreeMap<String, String> treemap = new TreeMap<String, String>(c);
+ assertEquals(0, treemap.headMap(null).size());
+
+ treemap = new TreeMap();
+ SortedMap<String, String> headMap = treemap.headMap("100");
+ headMap.headMap("100");
+
+ SortedMap<Integer, Integer> intMap, sub;
+ int size = 16;
+ intMap = new TreeMap<Integer, Integer>();
+ for (int i = 0; i < size; i++) {
+ intMap.put(i, i);
+ }
+ sub = intMap.headMap(-1);
+ assertEquals("size should be zero", sub.size(), 0);
+ assertTrue("submap should be empty", sub.isEmpty());
+ try {
+ sub.firstKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ TreeMap t = new TreeMap();
+ try {
+ SortedMap th = t.headMap(null);
+ fail("Should throw a NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ sub.lastKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ size = 256;
+ intMap = new TreeMap<Integer, Integer>();
+ for (int i = 0; i < size; i++) {
+ intMap.put(i, i);
+ }
+ sub = intMap.headMap(-1);
+ assertEquals("size should be zero", sub.size(), 0);
+ assertTrue("submap should be empty", sub.isEmpty());
+ try {
+ sub.firstKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ try {
+ sub.lastKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ }
+
+ /**
+ * java.util.TreeMap#keySet()
+ */
+ public void test_keySet() {
+ // Test for method java.util.Set java.util.TreeMap.keySet()
+ Set ks = tm.keySet();
+ assertTrue("Returned set of incorrect size",
+ ks.size() == objArray.length);
+ for (int i = 0; i < tm.size(); i++) {
+ assertTrue("Returned set is missing keys", ks.contains(new Integer(
+ i).toString()));
+ }
+ }
+
+ /**
+ * java.util.TreeMap#lastKey()
+ */
+ public void test_lastKey() {
+ // Test for method java.lang.Object java.util.TreeMap.lastKey()
+ assertTrue("Returned incorrect last key", tm.lastKey().equals(
+ objArray[objArray.length - 1].toString()));
+ assertNotSame(objArray[objArray.length - 1].toString(), tm.lastKey());
+ assertEquals(objArray[objArray.length - 2].toString(), tm
+ .headMap("999").lastKey());
+ assertEquals(objArray[objArray.length - 1].toString(), tm
+ .tailMap("123").lastKey());
+ assertEquals(objArray[objArray.length - 2].toString(), tm.subMap("99",
+ "999").lastKey());
+ }
+
+ public void test_lastKey_after_subMap() {
+ TreeMap<String, String> tm = new TreeMap<String, String>();
+ tm.put("001", "VAL001");
+ tm.put("003", "VAL003");
+ tm.put("002", "VAL002");
+ SortedMap<String, String> sm = tm;
+ String firstKey = (String) sm.firstKey();
+ String lastKey = "";
+ for (int i = 1; i <= tm.size(); i++) {
+ try {
+ lastKey = (String) sm.lastKey();
+ } catch (NoSuchElementException excep) {
+ fail("NoSuchElementException thrown when there are elements in the map");
+ }
+ sm = sm.subMap(firstKey, lastKey);
+ }
+ }
+
+ /**
+ * java.util.TreeMap#put(java.lang.Object, java.lang.Object)
+ */
+ public void test_remove_throwsWhenNotComparable() {
+ // Test for method java.lang.Object
+ // java.util.TreeMap.put(java.lang.Object, java.lang.Object)
+ Object o = new Object();
+ tm = new TreeMap();
+ try {
+ tm.remove(o);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.TreeMap#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ // Test for method void java.util.TreeMap.putAll(java.util.Map)
+ TreeMap x = new TreeMap();
+ x.putAll(tm);
+ assertTrue("Map incorrect size after put", x.size() == tm.size());
+ for (Object element : objArray) {
+ assertTrue("Failed to put all elements", x.get(element.toString())
+ .equals(element));
+ }
+ }
+
+ /**
+ * java.util.TreeMap#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.TreeMap.remove(java.lang.Object)
+ tm.remove("990");
+ assertTrue("Failed to remove mapping", !tm.containsKey("990"));
+
+ }
+
+ /**
+ * java.util.TreeMap#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.TreeMap.size()
+ assertEquals("Returned incorrect size", 1000, tm.size());
+ assertEquals("Returned incorrect size", 447, tm.headMap("500").size());
+ assertEquals("Returned incorrect size", 1000, tm.headMap("null").size());
+ assertEquals("Returned incorrect size", 0, tm.headMap("").size());
+ assertEquals("Returned incorrect size", 448, tm.headMap("500a").size());
+ assertEquals("Returned incorrect size", 553, tm.tailMap("500").size());
+ assertEquals("Returned incorrect size", 0, tm.tailMap("null").size());
+ assertEquals("Returned incorrect size", 1000, tm.tailMap("").size());
+ assertEquals("Returned incorrect size", 552, tm.tailMap("500a").size());
+ assertEquals("Returned incorrect size", 111, tm.subMap("500", "600")
+ .size());
+ try {
+ tm.subMap("null", "600");
+ fail("Should throw an IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals("Returned incorrect size", 1000, tm.subMap("", "null")
+ .size());
+ }
+
+ /**
+ * java.util.TreeMap#subMap(java.lang.Object, java.lang.Object)
+ */
+ public void test_subMapLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.util.SortedMap
+ // java.util.TreeMap.subMap(java.lang.Object, java.lang.Object)
+ SortedMap subMap = tm.subMap(objArray[100].toString(), objArray[109]
+ .toString());
+ assertEquals("subMap is of incorrect size", 9, subMap.size());
+ for (int counter = 100; counter < 109; counter++) {
+ assertTrue("SubMap contains incorrect elements", subMap.get(
+ objArray[counter].toString()).equals(objArray[counter]));
+ }
+
+ try {
+ tm.subMap(objArray[9].toString(), objArray[1].toString());
+ fail("end key less than start key should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ // Regression for Harmony-1161
+ TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
+ new MockComparatorNullTolerable());
+ treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
+ treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
+ SortedMap<String, String> subMapWithNull = treeMapWithNull.subMap(null,
+ "key1"); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$
+
+ // Regression test for typo in lastKey method
+ SortedMap<String, String> map = new TreeMap<String, String>();
+ map.put("1", "one"); //$NON-NLS-1$ //$NON-NLS-2$
+ map.put("2", "two"); //$NON-NLS-1$ //$NON-NLS-2$
+ map.put("3", "three"); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("3", map.lastKey());
+ SortedMap<String, String> sub = map.subMap("1", "3"); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("2", sub.lastKey()); //$NON-NLS-1$
+
+ // NOTE: The contract of this method allows us to throw either
+ // an NPE or a class cast exception.
+ TreeMap t = new TreeMap();
+ try {
+ t.subMap(null, new Object());
+ fail("Should throw a ClassCastException");
+ } catch (ClassCastException npe) {
+ // expected
+ }
+ }
+
+
+ /**
+ * java.util.TreeMap#subMap(java.lang.Object, java.lang.Object)
+ */
+ public void test_subMap_Iterator() {
+ TreeMap<String, String> map = new TreeMap<String, String>();
+
+ String[] keys = { "1", "2", "3" };
+ String[] values = { "one", "two", "three" };
+ for (int i = 0; i < keys.length; i++) {
+ map.put(keys[i], values[i]);
+ }
+
+ assertEquals(3, map.size());
+
+ Map subMap = map.subMap("", "test");
+ assertEquals(3, subMap.size());
+
+ Set entrySet = subMap.entrySet();
+ Iterator iter = entrySet.iterator();
+ int size = 0;
+ while (iter.hasNext()) {
+ Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
+ .next();
+ assertTrue(map.containsKey(entry.getKey()));
+ assertTrue(map.containsValue(entry.getValue()));
+ size++;
+ }
+ assertEquals(map.size(), size);
+
+ Set<String> keySet = subMap.keySet();
+ iter = keySet.iterator();
+ size = 0;
+ while (iter.hasNext()) {
+ String key = (String) iter.next();
+ assertTrue(map.containsKey(key));
+ size++;
+ }
+ assertEquals(map.size(), size);
+ }
+
+
+ /**
+ * java.util.TreeMap#tailMap(java.lang.Object)
+ */
+ public void test_tailMapLjava_lang_Object() {
+ // Test for method java.util.SortedMap
+ // java.util.TreeMap.tailMap(java.lang.Object)
+ Map tail = tm.tailMap(objArray[900].toString());
+ assertTrue("Returned map of incorrect size : " + tail.size(), tail
+ .size() == (objArray.length - 900) + 9);
+ for (int i = 900; i < objArray.length; i++) {
+ assertTrue("Map contains incorrect entries", tail
+ .containsValue(objArray[i]));
+ }
+
+ // Regression for Harmony-1066
+ assertTrue(tail instanceof Serializable);
+
+ SortedMap<Integer, Integer> intMap, sub;
+ int size = 16;
+ intMap = new TreeMap<Integer, Integer>();
+ for (int i = 0; i < size; i++) {
+ intMap.put(i, i);
+ }
+ sub = intMap.tailMap(size);
+ assertEquals("size should be zero", sub.size(), 0);
+ assertTrue("submap should be empty", sub.isEmpty());
+ try {
+ sub.firstKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ TreeMap t = new TreeMap();
+ try {
+ SortedMap th = t.tailMap(null);
+ fail("Should throw a NullPointerException");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ sub.lastKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ size = 256;
+ intMap = new TreeMap<Integer, Integer>();
+ for (int i = 0; i < size; i++) {
+ intMap.put(i, i);
+ }
+ sub = intMap.tailMap(size);
+ assertEquals("size should be zero", sub.size(), 0);
+ assertTrue("submap should be empty", sub.isEmpty());
+ try {
+ sub.firstKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ try {
+ sub.lastKey();
+ fail("java.util.NoSuchElementException should be thrown");
+ } catch (java.util.NoSuchElementException e) {
+ }
+
+ }
+
+ /**
+ * java.util.TreeMap#values()
+ */
+ public void test_values() {
+ // Test for method java.util.Collection java.util.TreeMap.values()
+ Collection vals = tm.values();
+ vals.iterator();
+ assertTrue("Returned collection of incorrect size",
+ vals.size() == objArray.length);
+ for (Object element : objArray) {
+ assertTrue("Collection contains incorrect elements", vals
+ .contains(element));
+ }
+ assertEquals(1000, vals.size());
+ int j = 0;
+ for (Iterator iter = vals.iterator(); iter.hasNext(); ) {
+ Object element = (Object) iter.next();
+ j++;
+ }
+ assertEquals(1000, j);
+
+ vals = tm.descendingMap().values();
+ vals.iterator();
+ assertTrue("Returned collection of incorrect size",
+ vals.size() == objArray.length);
+ for (Object element : objArray) {
+ assertTrue("Collection contains incorrect elements", vals
+ .contains(element));
+ }
+ assertEquals(1000, vals.size());
+ j = 0;
+ for (Iterator iter = vals.iterator(); iter.hasNext(); ) {
+ Object element = (Object) iter.next();
+ j++;
+ }
+ assertEquals(1000, j);
+
+ TreeMap myTreeMap = new TreeMap();
+ for (int i = 0; i < 100; i++) {
+ myTreeMap.put(objArray[i], objArray[i]);
+ }
+ Collection values = myTreeMap.values();
+ new Support_UnmodifiableCollectionTest(
+ "Test Returned Collection From TreeMap.values()", values)
+ .runTest();
+ values.remove(new Integer(0));
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(new Integer(0)));
+ assertEquals(99, values.size());
+ j = 0;
+ for (Iterator iter = values.iterator(); iter.hasNext(); ) {
+ Object element = (Object) iter.next();
+ j++;
+ }
+ assertEquals(99, j);
+
+ }
+
+ /**
+ * java.util.TreeMap the values() method in sub maps
+ */
+ public void test_subMap_values_size() {
+ TreeMap myTreeMap = new TreeMap();
+ for (int i = 0; i < 1000; i++) {
+ myTreeMap.put(i, objArray[i]);
+ }
+ // Test for method values() in subMaps
+ Collection vals = myTreeMap.subMap(200, 400).values();
+ assertTrue("Returned collection of incorrect size", vals.size() == 200);
+ for (int i = 200; i < 400; i++) {
+ assertTrue("Collection contains incorrect elements" + i, vals
+ .contains(objArray[i]));
+ }
+ assertEquals(200, vals.toArray().length);
+ vals.remove(objArray[300]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(objArray[300]));
+ assertTrue("Returned collection of incorrect size", vals.size() == 199);
+ assertEquals(199, vals.toArray().length);
+
+ myTreeMap.put(300, objArray[300]);
+ // Test for method values() in subMaps
+ vals = myTreeMap.headMap(400).values();
+ assertEquals("Returned collection of incorrect size", vals.size(), 400);
+ for (int i = 0; i < 400; i++) {
+ assertTrue("Collection contains incorrect elements " + i, vals
+ .contains(objArray[i]));
+ }
+ assertEquals(400, vals.toArray().length);
+ vals.remove(objArray[300]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(objArray[300]));
+ assertTrue("Returned collection of incorrect size", vals.size() == 399);
+ assertEquals(399, vals.toArray().length);
+
+ myTreeMap.put(300, objArray[300]);
+ // Test for method values() in subMaps
+ vals = myTreeMap.tailMap(400).values();
+ assertEquals("Returned collection of incorrect size", vals.size(), 600);
+ for (int i = 400; i < 1000; i++) {
+ assertTrue("Collection contains incorrect elements " + i, vals
+ .contains(objArray[i]));
+ }
+ assertEquals(600, vals.toArray().length);
+ vals.remove(objArray[600]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(objArray[600]));
+ assertTrue("Returned collection of incorrect size", vals.size() == 599);
+ assertEquals(599, vals.toArray().length);
+
+
+ myTreeMap.put(600, objArray[600]);
+ // Test for method values() in subMaps
+ vals = myTreeMap.descendingMap().headMap(400).values();
+ assertEquals("Returned collection of incorrect size", vals.size(), 599);
+ for (int i = 401; i < 1000; i++) {
+ assertTrue("Collection contains incorrect elements " + i, vals
+ .contains(objArray[i]));
+ }
+ assertEquals(599, vals.toArray().length);
+ vals.remove(objArray[600]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(objArray[600]));
+ assertTrue("Returned collection of incorrect size", vals.size() == 598);
+ assertEquals(598, vals.toArray().length);
+
+ myTreeMap.put(600, objArray[600]);
+ // Test for method values() in subMaps
+ vals = myTreeMap.descendingMap().tailMap(400).values();
+ assertEquals("Returned collection of incorrect size", vals.size(), 401);
+ for (int i = 0; i <= 400; i++) {
+ assertTrue("Collection contains incorrect elements " + i, vals
+ .contains(objArray[i]));
+ }
+ assertEquals(401, vals.toArray().length);
+ vals.remove(objArray[300]);
+ assertTrue(
+ "Removing from the values collection should remove from the original map",
+ !myTreeMap.containsValue(objArray[300]));
+ assertTrue("Returned collection of incorrect size", vals.size() == 400);
+ assertEquals(400, vals.toArray().length);
+
+ }
+
+ /**
+ * java.util.TreeMap#subMap()
+ */
+ public void test_subMap_Iterator2() {
+ TreeMap<String, String> map = new TreeMap<String, String>();
+
+ String[] keys = { "1", "2", "3" };
+ String[] values = { "one", "two", "three" };
+ for (int i = 0; i < keys.length; i++) {
+ map.put(keys[i], values[i]);
+ }
+
+ assertEquals(3, map.size());
+
+ Map subMap = map.subMap("", "test");
+ assertEquals(3, subMap.size());
+
+ Set entrySet = subMap.entrySet();
+ Iterator iter = entrySet.iterator();
+ int size = 0;
+ while (iter.hasNext()) {
+ Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
+ .next();
+ assertTrue(map.containsKey(entry.getKey()));
+ assertTrue(map.containsValue(entry.getValue()));
+ size++;
+ }
+ assertEquals(map.size(), size);
+
+ Set<String> keySet = subMap.keySet();
+ iter = keySet.iterator();
+ size = 0;
+ while (iter.hasNext()) {
+ String key = (String) iter.next();
+ assertTrue(map.containsKey(key));
+ size++;
+ }
+ assertEquals(map.size(), size);
+ }
+
+ /**
+ * java.util.TreeMap#SerializationTest()
+ */
+ // Regression for Harmony-1066
+ public void test_SubMap_Serializable() throws Exception {
+ TreeMap<Integer, Double> map = new TreeMap<Integer, Double>();
+ map.put(1, 2.1);
+ map.put(2, 3.1);
+ map.put(3, 4.5);
+ map.put(7, 21.3);
+ SortedMap<Integer, Double> headMap = map.headMap(3);
+ assertTrue(headMap instanceof Serializable);
+ assertFalse(headMap instanceof TreeMap);
+ assertTrue(headMap instanceof SortedMap);
+
+ assertFalse(headMap.entrySet() instanceof Serializable);
+ assertFalse(headMap.keySet() instanceof Serializable);
+ assertFalse(headMap.values() instanceof Serializable);
+
+ // This assertion will fail on RI. This is a bug of RI.
+ SerializationTest.verifySelf(headMap);
+ }
+
+ /**
+ * {@link java.util.TreeMap#firstEntry()}
+ */
+ public void test_firstEntry() throws Exception {
+ Integer testint = new Integer(-1);
+ Integer testint10000 = new Integer(-10000);
+ Integer testint9999 = new Integer(-9999);
+ assertEquals(objArray[0].toString(), tm.firstEntry().getKey());
+ assertEquals(objArray[0], tm.firstEntry().getValue());
+ tm.put(testint.toString(), testint);
+ assertEquals(testint.toString(), tm.firstEntry().getKey());
+ assertEquals(testint, tm.firstEntry().getValue());
+ tm.put(testint10000.toString(), testint10000);
+ assertEquals(testint.toString(), tm.firstEntry().getKey());
+ assertEquals(testint, tm.firstEntry().getValue());
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint.toString(), tm.firstEntry().getKey());
+ Entry entry = tm.firstEntry();
+ assertEquals(testint, entry.getValue());
+ assertEntry(entry);
+ tm.clear();
+ assertNull(tm.firstEntry());
+ }
+
+ /**
+ * {@link java.util.TreeMap#lastEntry()
+ */
+ public void test_lastEntry() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999].toString(), tm.lastEntry().getKey());
+ assertEquals(objArray[999], tm.lastEntry().getValue());
+ tm.put(testint10000.toString(), testint10000);
+ assertEquals(objArray[999].toString(), tm.lastEntry().getKey());
+ assertEquals(objArray[999], tm.lastEntry().getValue());
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint9999.toString(), tm.lastEntry().getKey());
+ Entry entry = tm.lastEntry();
+ assertEquals(testint9999, entry.getValue());
+ assertEntry(entry);
+ tm.clear();
+ assertNull(tm.lastEntry());
+ }
+
+ /**
+ * {@link java.util.TreeMap#pollFirstEntry()
+ */
+ public void test_pollFirstEntry() throws Exception {
+ Integer testint = new Integer(-1);
+ Integer testint10000 = new Integer(-10000);
+ Integer testint9999 = new Integer(-9999);
+ assertEquals(objArray[0].toString(), tm.pollFirstEntry().getKey());
+ assertEquals(objArray[1], tm.pollFirstEntry().getValue());
+ assertEquals(objArray[10], tm.pollFirstEntry().getValue());
+ tm.put(testint.toString(), testint);
+ tm.put(testint10000.toString(), testint10000);
+ assertEquals(testint.toString(), tm.pollFirstEntry().getKey());
+ assertEquals(testint10000, tm.pollFirstEntry().getValue());
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint9999.toString(), tm.pollFirstEntry().getKey());
+ Entry entry = tm.pollFirstEntry();
+ assertEntry(entry);
+ assertEquals(objArray[100], entry.getValue());
+ tm.clear();
+ assertNull(tm.pollFirstEntry());
+ }
+
+ /**
+ * {@link java.util.TreeMap#pollLastEntry()
+ */
+ public void test_pollLastEntry() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999].toString(), tm.pollLastEntry().getKey());
+ assertEquals(objArray[998], tm.pollLastEntry().getValue());
+ assertEquals(objArray[997], tm.pollLastEntry().getValue());
+ tm.put(testint10000.toString(), testint10000);
+ assertEquals(objArray[996], tm.pollLastEntry().getValue());
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint9999.toString(), tm.pollLastEntry().getKey());
+ Entry entry = tm.pollLastEntry();
+ assertEquals(objArray[995], entry.getValue());
+ assertEntry(entry);
+ tm.clear();
+ assertNull(tm.pollLastEntry());
+ }
+
+ /**
+ * {@link java.util.TreeMap#lowerEntry(Object)
+ */
+ public void test_lowerEntry() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999], tm.lowerEntry(testint9999.toString())
+ .getValue());
+ assertEquals(objArray[100], tm.lowerEntry(testint10000.toString())
+ .getValue());
+ tm.put(testint10000.toString(), testint10000);
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(objArray[999], tm.lowerEntry(testint9999.toString())
+ .getValue());
+ Entry entry = tm.lowerEntry(testint10000.toString());
+ assertEquals(objArray[100], entry.getValue());
+ assertEntry(entry);
+ try {
+ tm.lowerEntry(testint10000);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.lowerEntry(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.lowerEntry(testint9999.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#lowerKey(Object)
+ */
+ public void test_lowerKey() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999].toString(), tm.lowerKey(testint9999
+ .toString()));
+ assertEquals(objArray[100].toString(), tm.lowerKey(testint10000
+ .toString()));
+ tm.put(testint10000.toString(), testint10000);
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(objArray[999].toString(), tm.lowerKey(testint9999
+ .toString()));
+ assertEquals(objArray[100].toString(), tm.lowerKey(testint10000
+ .toString()));
+ try {
+ tm.lowerKey(testint10000);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.lowerKey(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.lowerKey(testint9999.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#floorEntry(Object)
+ */
+ public void test_floorEntry() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999], tm.floorEntry(testint9999.toString())
+ .getValue());
+ assertEquals(objArray[100], tm.floorEntry(testint10000.toString())
+ .getValue());
+ tm.put(testint10000.toString(), testint10000);
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint9999, tm.floorEntry(testint9999.toString())
+ .getValue());
+ Entry entry = tm.floorEntry(testint10000.toString());
+ assertEquals(testint10000, entry.getValue());
+ assertEntry(entry);
+ try {
+ tm.floorEntry(testint10000);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.floorEntry(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.floorEntry(testint9999.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#floorKey(Object)
+ */
+ public void test_floorKey() throws Exception {
+ Integer testint10000 = new Integer(10000);
+ Integer testint9999 = new Integer(9999);
+ assertEquals(objArray[999].toString(), tm.floorKey(testint9999
+ .toString()));
+ assertEquals(objArray[100].toString(), tm.floorKey(testint10000
+ .toString()));
+ tm.put(testint10000.toString(), testint10000);
+ tm.put(testint9999.toString(), testint9999);
+ assertEquals(testint9999.toString(), tm
+ .floorKey(testint9999.toString()));
+ assertEquals(testint10000.toString(), tm.floorKey(testint10000
+ .toString()));
+ try {
+ tm.floorKey(testint10000);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.floorKey(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.floorKey(testint9999.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#ceilingEntry(Object)
+ */
+ public void test_ceilingEntry() throws Exception {
+ Integer testint100 = new Integer(100);
+ Integer testint = new Integer(-1);
+ assertEquals(objArray[0], tm.ceilingEntry(testint.toString())
+ .getValue());
+ assertEquals(objArray[100], tm.ceilingEntry(testint100.toString())
+ .getValue());
+ tm.put(testint.toString(), testint);
+ tm.put(testint100.toString(), testint);
+ assertEquals(testint, tm.ceilingEntry(testint.toString()).getValue());
+ Entry entry = tm.ceilingEntry(testint100.toString());
+ assertEquals(testint, entry.getValue());
+ assertEntry(entry);
+ try {
+ tm.ceilingEntry(testint100);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.ceilingEntry(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.ceilingEntry(testint.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#ceilingKey(Object)
+ */
+ public void test_ceilingKey() throws Exception {
+ Integer testint100 = new Integer(100);
+ Integer testint = new Integer(-1);
+ assertEquals(objArray[0].toString(), tm.ceilingKey(testint.toString()));
+ assertEquals(objArray[100].toString(), tm.ceilingKey(testint100
+ .toString()));
+ tm.put(testint.toString(), testint);
+ tm.put(testint100.toString(), testint);
+ assertEquals(testint.toString(), tm.ceilingKey(testint.toString()));
+ assertEquals(testint100.toString(), tm
+ .ceilingKey(testint100.toString()));
+ try {
+ tm.ceilingKey(testint100);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.ceilingKey(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.ceilingKey(testint.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#higherEntry(Object)
+ */
+ public void test_higherEntry() throws Exception {
+ Integer testint9999 = new Integer(9999);
+ Integer testint10000 = new Integer(10000);
+ Integer testint100 = new Integer(100);
+ Integer testint = new Integer(-1);
+ assertEquals(objArray[0], tm.higherEntry(testint.toString()).getValue());
+ assertEquals(objArray[101], tm.higherEntry(testint100.toString())
+ .getValue());
+ assertEquals(objArray[101], tm.higherEntry(testint10000.toString())
+ .getValue());
+ tm.put(testint9999.toString(), testint);
+ tm.put(testint100.toString(), testint);
+ tm.put(testint10000.toString(), testint);
+ assertEquals(objArray[0], tm.higherEntry(testint.toString()).getValue());
+ assertEquals(testint, tm.higherEntry(testint100.toString()).getValue());
+ Entry entry = tm.higherEntry(testint10000.toString());
+ assertEquals(objArray[101], entry.getValue());
+ assertEntry(entry);
+ assertNull(tm.higherEntry(testint9999.toString()));
+ try {
+ tm.higherEntry(testint100);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.higherEntry(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.higherEntry(testint.toString()));
+ }
+
+ /**
+ * {@link java.util.TreeMap#higherKey(Object)
+ */
+ public void test_higherKey() throws Exception {
+ Integer testint9999 = new Integer(9999);
+ Integer testint10000 = new Integer(10000);
+ Integer testint100 = new Integer(100);
+ Integer testint = new Integer(-1);
+ assertEquals(objArray[0].toString(), tm.higherKey(testint.toString()));
+ assertEquals(objArray[101].toString(), tm.higherKey(testint100
+ .toString()));
+ assertEquals(objArray[101].toString(), tm.higherKey(testint10000
+ .toString()));
+ tm.put(testint9999.toString(), testint);
+ tm.put(testint100.toString(), testint);
+ tm.put(testint10000.toString(), testint);
+ assertEquals(objArray[0].toString(), tm.higherKey(testint.toString()));
+ assertEquals(testint10000.toString(), tm.higherKey(testint100
+ .toString()));
+ assertEquals(objArray[101].toString(), tm.higherKey(testint10000
+ .toString()));
+ assertNull(tm.higherKey(testint9999.toString()));
+ try {
+ tm.higherKey(testint100);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.higherKey(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ tm.clear();
+ assertNull(tm.higherKey(testint.toString()));
+ }
+
+ public void test_navigableKeySet() throws Exception {
+ Integer testint9999 = new Integer(9999);
+ Integer testint10000 = new Integer(10000);
+ Integer testint100 = new Integer(100);
+ Integer testint0 = new Integer(0);
+ NavigableSet set = tm.navigableKeySet();
+ assertFalse(set.contains(testint9999.toString()));
+ tm.put(testint9999.toString(), testint9999);
+ assertTrue(set.contains(testint9999.toString()));
+ tm.remove(testint9999.toString());
+ assertFalse(set.contains(testint9999.toString()));
+ try {
+ set.add(new Object());
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ set.add(null);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ set.addAll(null);
+ fail("should throw UnsupportedOperationException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ Collection collection = new LinkedList();
+ set.addAll(collection);
+ try {
+ collection.add(new Object());
+ set.addAll(collection);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ set.remove(testint100.toString());
+ assertFalse(tm.containsKey(testint100.toString()));
+ assertTrue(tm.containsKey(testint0.toString()));
+ Iterator iter = set.iterator();
+ iter.next();
+ iter.remove();
+ assertFalse(tm.containsKey(testint0.toString()));
+ collection.add(new Integer(200).toString());
+ set.retainAll(collection);
+ assertEquals(1, tm.size());
+ set.removeAll(collection);
+ assertEquals(0, tm.size());
+ tm.put(testint10000.toString(), testint10000);
+ assertEquals(1, tm.size());
+ set.clear();
+ assertEquals(0, tm.size());
+ }
+
+ private void assertEntry(Entry entry) {
+ try {
+ entry.setValue(new Object());
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ assertEquals((entry.getKey() == null ? 0 : entry.getKey().hashCode())
+ ^ (entry.getValue() == null ? 0 : entry.getValue().hashCode()),
+ entry.hashCode());
+ assertEquals(entry.toString(), entry.getKey() + "=" + entry.getValue());
+ }
+
+ /**
+ * java.util.TreeMap#subMap(java.lang.Object, boolean,
+ *java.lang.Object, boolean)
+ */
+ public void test_subMapLjava_lang_ObjectZLjava_lang_ObjectZ() {
+ // normal case
+ SortedMap subMap = tm.subMap(objArray[100].toString(), true,
+ objArray[109].toString(), true);
+ assertEquals("subMap is of incorrect size", 10, subMap.size());
+ subMap = tm.subMap(objArray[100].toString(), true, objArray[109]
+ .toString(), false);
+ assertEquals("subMap is of incorrect size", 9, subMap.size());
+ for (int counter = 100; counter < 109; counter++) {
+ assertTrue("SubMap contains incorrect elements", subMap.get(
+ objArray[counter].toString()).equals(objArray[counter]));
+ }
+ subMap = tm.subMap(objArray[100].toString(), false, objArray[109]
+ .toString(), true);
+ assertEquals("subMap is of incorrect size", 9, subMap.size());
+ assertNull(subMap.get(objArray[100].toString()));
+
+ // Exceptions
+ try {
+ tm.subMap(objArray[9].toString(), true, objArray[1].toString(),
+ true);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ tm.subMap(objArray[9].toString(), false, objArray[1].toString(),
+ false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ tm.subMap(null, true, null, true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.subMap(null, false, objArray[100], true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.subMap(new LinkedList(), false, objArray[100], true);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ // use integer elements to test
+ TreeMap<Integer, String> treeMapInt = new TreeMap<Integer, String>();
+ assertEquals(0, treeMapInt.subMap(new Integer(-1), true,
+ new Integer(100), true).size());
+ for (int i = 0; i < 100; i++) {
+ treeMapInt.put(new Integer(i), new Integer(i).toString());
+ }
+ SortedMap<Integer, String> result = treeMapInt.subMap(new Integer(-1),
+ true, new Integer(100), true);
+ assertEquals(100, result.size());
+ result.put(new Integer(-1), new Integer(-1).toString());
+ assertEquals(101, result.size());
+ assertEquals(101, treeMapInt.size());
+ result = treeMapInt
+ .subMap(new Integer(50), true, new Integer(60), true);
+ assertEquals(11, result.size());
+ try {
+ result.put(new Integer(-2), new Integer(-2).toString());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(11, result.size());
+ treeMapInt.remove(new Integer(50));
+ assertEquals(100, treeMapInt.size());
+ assertEquals(10, result.size());
+ result.remove(new Integer(60));
+ assertEquals(99, treeMapInt.size());
+ assertEquals(9, result.size());
+ SortedMap<Integer, String> result2 = null;
+ try {
+ result2 = result.subMap(new Integer(-2), new Integer(100));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ result2 = result.subMap(new Integer(50), new Integer(60));
+ assertEquals(9, result2.size());
+
+ // sub map of sub map
+ NavigableMap<Integer, Object> mapIntObj = new TreeMap<Integer, Object>();
+ for (int i = 0; i < 10; ++i) {
+ mapIntObj.put(i, new Object());
+ }
+ mapIntObj = mapIntObj.subMap(5, false, 9, true);
+ assertEquals(4, mapIntObj.size());
+ mapIntObj = mapIntObj.subMap(5, false, 9, true);
+ assertEquals(4, mapIntObj.size());
+ mapIntObj = mapIntObj.subMap(5, false, 6, false);
+ assertEquals(0, mapIntObj.size());
+
+ // a special comparator dealing with null key
+ tm = new TreeMap(new Comparator() {
+ public int compare(Object o1, Object o2) {
+ if (o1 == null) {
+ return -1;
+ }
+ if (o2 == null) {
+ return 1;
+ }
+ return ((String) o1).compareTo((String) o2);
+ }
+ });
+ tm.put(null, -1);
+ tm.put(new String("1st"), 1);
+ tm.put(new String("2nd"), 2);
+ tm.put(new String("3rd"), 3);
+ SortedMap s = tm.subMap(null, "3rd");
+ assertEquals(3, s.size());
+ assertTrue(s.containsValue(-1));
+ assertTrue(s.containsValue(1));
+ assertTrue(s.containsValue(2));
+ assertFalse(s.containsKey(null));
+
+ s = tm.descendingMap();
+ s = s.subMap("3rd", null);
+ assertFalse(s.containsKey(null));
+ assertTrue(s.containsKey("1st"));
+ assertTrue(s.containsKey("2nd"));
+ assertTrue(s.containsKey("3rd"));
+ }
+
+ public void test_subMap_NullTolerableComparator() {
+ // Null Tolerable Comparator
+ TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
+ new MockComparatorNullTolerable());
+ treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
+ treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
+ SortedMap<String, String> subMapWithNull = treeMapWithNull.subMap(null,
+ true, "key1", true); //$NON-NLS-1$
+
+ // RI fails here
+ assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
+ assertEquals("value1", subMapWithNull.get("key1"));
+ assertEquals("value2", subMapWithNull.get(null));
+ treeMapWithNull.put("key0", "value2");
+ treeMapWithNull.put("key3", "value3");
+ treeMapWithNull.put("key4", "value4");
+ treeMapWithNull.put("key5", "value5");
+ treeMapWithNull.put("key6", "value6");
+ assertEquals("Size of subMap should be 3:", 3, subMapWithNull.size()); //$NON-NLS-1$
+ subMapWithNull = treeMapWithNull.subMap(null, false, "key1", true); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
+ }
+
+
+ /**
+ * java.util.TreeMap#headMap(java.lang.Object, boolea)
+ */
+ public void test_headMapLjava_lang_ObjectZL() {
+ // normal case
+ SortedMap subMap = tm.headMap(objArray[100].toString(), true);
+ assertEquals("subMap is of incorrect size", 4, subMap.size());
+ subMap = tm.headMap(objArray[109].toString(), true);
+ assertEquals("subMap is of incorrect size", 13, subMap.size());
+ for (int counter = 100; counter < 109; counter++) {
+ assertTrue("SubMap contains incorrect elements", subMap.get(
+ objArray[counter].toString()).equals(objArray[counter]));
+ }
+ subMap = tm.headMap(objArray[100].toString(), false);
+ assertEquals("subMap is of incorrect size", 3, subMap.size());
+ assertNull(subMap.get(objArray[100].toString()));
+
+ // Exceptions
+ assertEquals(0, tm.headMap("", true).size());
+ assertEquals(0, tm.headMap("", false).size());
+
+ try {
+ tm.headMap(null, true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.headMap(null, false);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.headMap(new Object(), true);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.headMap(new Object(), false);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ // use integer elements to test
+ TreeMap<Integer, String> treeMapInt = new TreeMap<Integer, String>();
+ assertEquals(0, treeMapInt.headMap(new Integer(-1), true).size());
+ for (int i = 0; i < 100; i++) {
+ treeMapInt.put(new Integer(i), new Integer(i).toString());
+ }
+ SortedMap<Integer, String> result = treeMapInt
+ .headMap(new Integer(101));
+ assertEquals(100, result.size());
+ try {
+ result.put(new Integer(101), new Integer(101).toString());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(100, result.size());
+ assertEquals(100, treeMapInt.size());
+ result = treeMapInt.headMap(new Integer(50), true);
+ assertEquals(51, result.size());
+ result.put(new Integer(-1), new Integer(-1).toString());
+ assertEquals(52, result.size());
+
+ treeMapInt.remove(new Integer(40));
+ assertEquals(100, treeMapInt.size());
+ assertEquals(51, result.size());
+ result.remove(new Integer(30));
+ assertEquals(99, treeMapInt.size());
+ assertEquals(50, result.size());
+ SortedMap<Integer, String> result2 = null;
+ try {
+ result.subMap(new Integer(-2), new Integer(100));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ result.subMap(new Integer(1), new Integer(100));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ result2 = result.subMap(new Integer(-2), new Integer(48));
+ assertEquals(47, result2.size());
+
+ result2 = result.subMap(new Integer(40), new Integer(50));
+ assertEquals(9, result2.size());
+
+ // Null Tolerable Comparator
+ TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
+ new MockComparatorNullTolerable());
+ treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
+ treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
+ SortedMap<String, String> subMapWithNull = treeMapWithNull.headMap(
+ null, true); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$
+ assertEquals(null, subMapWithNull.get("key1"));
+ assertEquals("value2", subMapWithNull.get(null));
+ treeMapWithNull.put("key0", "value2");
+ treeMapWithNull.put("key3", "value3");
+ treeMapWithNull.put("key4", "value4");
+ treeMapWithNull.put("key5", "value5");
+ treeMapWithNull.put("key6", "value6");
+ assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$
+ subMapWithNull = treeMapWithNull.subMap(null, false, "key1", true); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
+
+ // head map of head map
+ NavigableMap<Integer, Object> original = new TreeMap<Integer, Object>();
+ for (int i = 0; i < 10; ++i) {
+ original.put(i, new Object());
+ }
+ NavigableMap<Integer, Object> mapIntObj = original.headMap(5, false);
+ assertEquals(5, mapIntObj.size());
+ mapIntObj = mapIntObj.headMap(5, false);
+ assertEquals(5, mapIntObj.size());
+ try {
+ mapIntObj = mapIntObj.tailMap(5, false);
+ fail("IllegalArgumentException expected: key falls outside restricted range");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(0, original.headMap(0, false).size());
+ }
+
+ /**
+ * java.util.TreeMap#tailMap(java.lang.Object, boolea)
+ */
+ public void test_tailMapLjava_lang_ObjectZL() {
+ // normal case
+ SortedMap subMap = tm.tailMap(objArray[100].toString(), true);
+ assertEquals("subMap is of incorrect size", 997, subMap.size());
+ subMap = tm.tailMap(objArray[109].toString(), true);
+ assertEquals("subMap is of incorrect size", 988, subMap.size());
+ for (int counter = 119; counter > 110; counter--) {
+ assertTrue("SubMap contains incorrect elements", subMap.get(
+ objArray[counter].toString()).equals(objArray[counter]));
+ }
+ subMap = tm.tailMap(objArray[100].toString(), false);
+ assertEquals("subMap is of incorrect size", 996, subMap.size());
+ assertNull(subMap.get(objArray[100].toString()));
+
+ // Exceptions
+ assertEquals(1000, tm.tailMap("", true).size());
+ assertEquals(1000, tm.tailMap("", false).size());
+
+ try {
+ tm.tailMap(null, true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.tailMap(null, false);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ tm.tailMap(new Object(), true);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ try {
+ tm.tailMap(new Object(), false);
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+
+ // use integer elements to test
+ TreeMap<Integer, String> treeMapInt = new TreeMap<Integer, String>();
+ assertEquals(0, treeMapInt.tailMap(new Integer(-1), true).size());
+ for (int i = 0; i < 100; i++) {
+ treeMapInt.put(new Integer(i), new Integer(i).toString());
+ }
+ SortedMap<Integer, String> result = treeMapInt.tailMap(new Integer(1));
+ assertEquals(99, result.size());
+ try {
+ result.put(new Integer(-1), new Integer(-1).toString());
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ assertEquals(99, result.size());
+ assertEquals(100, treeMapInt.size());
+ result = treeMapInt.tailMap(new Integer(50), true);
+ assertEquals(50, result.size());
+ result.put(new Integer(101), new Integer(101).toString());
+ assertEquals(51, result.size());
+
+ treeMapInt.remove(new Integer(60));
+ assertEquals(100, treeMapInt.size());
+ assertEquals(50, result.size());
+ result.remove(new Integer(70));
+ assertEquals(99, treeMapInt.size());
+ assertEquals(49, result.size());
+ SortedMap<Integer, String> result2 = null;
+ try {
+ result2 = result.subMap(new Integer(-2), new Integer(100));
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ result2 = result.subMap(new Integer(60), new Integer(70));
+ assertEquals(9, result2.size());
+
+ // Null Tolerable Comparator
+ TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
+ new MockComparatorNullTolerable());
+ treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
+ treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
+ SortedMap<String, String> subMapWithNull = treeMapWithNull.tailMap(
+ "key1", true); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$
+ assertEquals("value1", subMapWithNull.get("key1"));
+ assertEquals(null, subMapWithNull.get(null));
+ treeMapWithNull.put("key0", "value2");
+ treeMapWithNull.put("key3", "value3");
+ treeMapWithNull.put("key4", "value4");
+ treeMapWithNull.put("key5", "value5");
+ treeMapWithNull.put("key6", "value6");
+ assertEquals("Size of subMap should be 5:", 5, subMapWithNull.size()); //$NON-NLS-1$
+ subMapWithNull = treeMapWithNull.subMap(null, false, "key1", true); //$NON-NLS-1$
+ assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
+
+ // tail map of tail map
+ NavigableMap<Integer, Object> original = new TreeMap<Integer, Object>();
+ for (int i = 0; i < 10; ++i) {
+ original.put(i, new Object());
+ }
+ NavigableMap<Integer, Object> mapIntObj = original.tailMap(5, false);
+ assertEquals(4, mapIntObj.size());
+ mapIntObj = mapIntObj.tailMap(5, false);
+ assertEquals(4, mapIntObj.size());
+ try {
+ mapIntObj = mapIntObj.headMap(5, false);
+ fail("IllegalArgumentException expected: key falls outside restricted range");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(0, original.headMap(0, false).size());
+ }
+
+ public void test_descendingMap_subMap() throws Exception {
+ TreeMap<Integer, Object> tm = new TreeMap<Integer, Object>();
+ for (int i = 0; i < 10; ++i) {
+ tm.put(i, new Object());
+ }
+ NavigableMap<Integer, Object> descMap = tm.descendingMap();
+ assertEquals(7, descMap.subMap(8, true, 1, false).size());
+ assertEquals(4, descMap.headMap(6, true).size());
+ assertEquals(2, descMap.tailMap(2, false).size());
+
+ // sub map of sub map of descendingMap
+ NavigableMap<Integer, Object> mapIntObj = new TreeMap<Integer, Object>();
+ for (int i = 0; i < 10; ++i) {
+ mapIntObj.put(i, new Object());
+ }
+ mapIntObj = mapIntObj.descendingMap();
+ NavigableMap<Integer, Object> subMapIntObj = mapIntObj.subMap(9, true,
+ 5, false);
+ assertEquals(4, subMapIntObj.size());
+ subMapIntObj = subMapIntObj.subMap(9, true, 5, false);
+ assertEquals(4, subMapIntObj.size());
+ subMapIntObj = subMapIntObj.subMap(6, false, 5, false);
+ assertEquals(0, subMapIntObj.size());
+
+ subMapIntObj = mapIntObj.headMap(5, false);
+ assertEquals(4, subMapIntObj.size());
+ subMapIntObj = subMapIntObj.headMap(5, false);
+ assertEquals(4, subMapIntObj.size());
+ try {
+ subMapIntObj = subMapIntObj.tailMap(5, false);
+ fail("IllegalArgumentException expected: key falls outside restricted range");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ subMapIntObj = mapIntObj.tailMap(5, false);
+ assertEquals(5, subMapIntObj.size());
+ subMapIntObj = subMapIntObj.tailMap(5, false);
+ assertEquals(5, subMapIntObj.size());
+ try {
+ subMapIntObj = subMapIntObj.headMap(5, false);
+ fail("IllegalArgumentException expected: key falls outside restricted range");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ private void illegalFirstNullKeyMapTester(NavigableMap<String, String> map) {
+ try {
+ map.get(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ map.put("NormalKey", "value");
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ Set<String> keySet = map.keySet();
+ assertTrue(!keySet.isEmpty());
+ assertEquals(1, keySet.size());
+ for (String key : keySet) {
+ assertEquals(key, null);
+ try {
+ map.get(key);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ }
+ Set<Entry<String, String>> entrySet = map.entrySet();
+ assertTrue(!entrySet.isEmpty());
+ assertEquals(1, entrySet.size());
+ for (Entry<String, String> entry : entrySet) {
+ assertEquals(null, entry.getKey());
+ assertEquals("NullValue", entry.getValue());
+ }
+ Collection<String> values = map.values();
+ assertTrue(!values.isEmpty());
+ assertEquals(1, values.size());
+ for (String value : values) {
+ assertEquals("NullValue", value);
+ }
+
+ try {
+ map.headMap(null, true);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ try {
+ map.headMap(null, false);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+
+ try {
+ map.subMap(null, false, null, false);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ try {
+ map.subMap(null, true, null, true);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ try {
+ map.tailMap(null, true);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ try {
+ map.tailMap(null, false);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // ignore
+ }
+ }
+
+ /**
+ * Tests equals() method.
+ * Tests that no ClassCastException will be thrown in all cases.
+ * Regression test for HARMONY-1639.
+ */
+ public void test_equals() throws Exception {
+ // comparing TreeMaps with different object types
+ Map m1 = new TreeMap();
+ Map m2 = new TreeMap();
+ m1.put("key1", "val1");
+ m1.put("key2", "val2");
+ m2.put(new Integer(1), "val1");
+ m2.put(new Integer(2), "val2");
+ assertFalse("Maps should not be equal 1", m1.equals(m2));
+ assertFalse("Maps should not be equal 2", m2.equals(m1));
+
+ // comparing TreeMap with HashMap
+ m1 = new TreeMap();
+ m2 = new HashMap();
+ m1.put("key", "val");
+ m2.put(new Object(), "val");
+ assertFalse("Maps should not be equal 3", m1.equals(m2));
+ assertFalse("Maps should not be equal 4", m2.equals(m1));
+ }
+
+ public void test_invalidKeys() throws Exception {
+ // comparing TreeMaps with not-comparable objects inside
+ TreeMap m1 = new TreeMap();
+ try {
+ m1.put(new Object(), "val1");
+ fail("ClassCastException expected");
+ } catch (ClassCastException expected) {
+
+ }
+ }
+
+ public void test_remove_from_iterator() throws Exception {
+ Set set = tm.keySet();
+ Iterator iter = set.iterator();
+ iter.next();
+ iter.remove();
+ try {
+ iter.remove();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Tests entrySet().contains() method behaviour with respect to entries
+ * with null values.
+ * Regression test for HARMONY-5788.
+ */
+ public void test_entrySet_contains() throws Exception {
+ TreeMap master = new TreeMap<String, String>();
+ TreeMap test_map = new TreeMap<String, String>();
+
+ master.put("null", null);
+ Object[] entry = master.entrySet().toArray();
+ assertFalse("Empty map should not contain the null-valued entry",
+ test_map.entrySet().contains(entry[0]));
+
+ Map<String, String> submap = test_map.subMap("a", "z");
+ entry = master.entrySet().toArray();
+ assertFalse("Empty submap should not contain the null-valued entry",
+ submap.entrySet().contains(entry[0]));
+
+ test_map.put("null", null);
+ assertTrue("entrySet().containsAll(...) should work with null values",
+ test_map.entrySet().containsAll(master.entrySet()));
+
+ master.clear();
+ master.put("null", '0');
+ entry = master.entrySet().toArray();
+ assertFalse("Null-valued entry should not equal non-null-valued entry",
+ test_map.entrySet().contains(entry[0]));
+ }
+
+ public void test_iterator_next_() {
+ Map m = tm.subMap("0", "1");
+ Iterator it = m.entrySet().iterator();
+ assertEquals("0=0", it.next().toString());
+ while (it.hasNext()) {
+ }
+ try {
+ it.next();
+ fail("should throw java.util.NoSuchElementException");
+ } catch (Exception e) {
+ assertTrue(e instanceof java.util.NoSuchElementException);
+ }
+ }
+
+ public void test_empty_subMap() throws Exception {
+ TreeMap<Float, List<Integer>> tm = new TreeMap<Float, List<Integer>>();
+ SortedMap<Float, List<Integer>> sm = tm.tailMap(1.1f);
+ assertTrue(sm.values().size() == 0);
+ }
+
+ public static TreeMap treeMap = new TreeMap();
+
+ public void test_values_1() {
+ treeMap.put("firstKey", "firstValue");
+ treeMap.put("secondKey", "secondValue");
+ treeMap.put("thirdKey", "thirdValue");
+ Object firstKey = treeMap.firstKey();
+ SortedMap subMap = ((SortedMap) treeMap).subMap(firstKey, firstKey);
+ Iterator iter = subMap.values().iterator();
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ @Override
+ protected void setUp() {
+ tm = new TreeMap();
+ for (int i = 0; i < objArray.length; i++) {
+ Object x = objArray[i] = new Integer(i);
+ tm.put(x.toString(), x);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeSetTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeSetTest.java
new file mode 100644
index 0000000..43efa2d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/TreeSetTest.java
@@ -0,0 +1,342 @@
+/*
+ * 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.tests.java.util;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+public class TreeSetTest extends junit.framework.TestCase {
+
+ 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;
+ }
+ }
+
+ TreeSet ts;
+
+ Object objArray[] = new Object[1000];
+
+ /**
+ * java.util.TreeSet#TreeSet()
+ */
+ public void test_Constructor() {
+ // Test for method java.util.TreeSet()
+ assertTrue("Did not construct correct TreeSet", new TreeSet().isEmpty());
+ }
+
+ /**
+ * java.util.TreeSet#TreeSet(java.util.Collection)
+ */
+ public void test_ConstructorLjava_util_Collection() {
+ // Test for method java.util.TreeSet(java.util.Collection)
+ TreeSet myTreeSet = new TreeSet(Arrays.asList(objArray));
+ assertTrue("TreeSet incorrect size",
+ myTreeSet.size() == objArray.length);
+ for (int counter = 0; counter < objArray.length; counter++)
+ assertTrue("TreeSet does not contain correct elements", myTreeSet
+ .contains(objArray[counter]));
+ }
+
+ /**
+ * java.util.TreeSet#TreeSet(java.util.Comparator)
+ */
+ public void test_ConstructorLjava_util_Comparator() {
+ // Test for method java.util.TreeSet(java.util.Comparator)
+ TreeSet myTreeSet = new TreeSet(new ReversedIntegerComparator());
+ assertTrue("Did not construct correct TreeSet", myTreeSet.isEmpty());
+ myTreeSet.add(new Integer(1));
+ myTreeSet.add(new Integer(2));
+ assertTrue(
+ "Answered incorrect first element--did not use custom comparator ",
+ myTreeSet.first().equals(new Integer(2)));
+ assertTrue(
+ "Answered incorrect last element--did not use custom comparator ",
+ myTreeSet.last().equals(new Integer(1)));
+ }
+
+ /**
+ * java.util.TreeSet#TreeSet(java.util.SortedSet)
+ */
+ public void test_ConstructorLjava_util_SortedSet() {
+ // Test for method java.util.TreeSet(java.util.SortedSet)
+ ReversedIntegerComparator comp = new ReversedIntegerComparator();
+ TreeSet myTreeSet = new TreeSet(comp);
+ for (int i = 0; i < objArray.length; i++)
+ myTreeSet.add(objArray[i]);
+ TreeSet anotherTreeSet = new TreeSet(myTreeSet);
+ assertTrue("TreeSet is not correct size",
+ anotherTreeSet.size() == objArray.length);
+ for (int counter = 0; counter < objArray.length; counter++)
+ assertTrue("TreeSet does not contain correct elements",
+ anotherTreeSet.contains(objArray[counter]));
+ assertTrue("TreeSet does not answer correct comparator", anotherTreeSet
+ .comparator() == comp);
+ assertTrue("TreeSet does not use comparator",
+ anotherTreeSet.first() == objArray[objArray.length - 1]);
+ }
+
+ /**
+ * java.util.TreeSet#add(java.lang.Object)
+ */
+ public void test_addLjava_lang_Object() {
+ // Test for method boolean java.util.TreeSet.add(java.lang.Object)
+ ts.add(new Integer(-8));
+ assertTrue("Failed to add Object", ts.contains(new Integer(-8)));
+ ts.add(objArray[0]);
+ assertTrue("Added existing element", ts.size() == objArray.length + 1);
+
+ }
+
+ /**
+ * java.util.TreeSet#addAll(java.util.Collection)
+ */
+ public void test_addAllLjava_util_Collection() {
+ // Test for method boolean
+ // java.util.TreeSet.addAll(java.util.Collection)
+ TreeSet s = new TreeSet();
+ s.addAll(ts);
+ assertTrue("Incorrect size after add", s.size() == ts.size());
+ Iterator i = ts.iterator();
+ while (i.hasNext())
+ assertTrue("Returned incorrect set", s.contains(i.next()));
+
+ }
+
+ /**
+ * java.util.TreeSet#clear()
+ */
+ public void test_clear() {
+ // Test for method void java.util.TreeSet.clear()
+ ts.clear();
+ assertEquals("Returned non-zero size after clear", 0, ts.size());
+ assertTrue("Found element in cleared set", !ts.contains(objArray[0]));
+ }
+
+ /**
+ * java.util.TreeSet#clone()
+ */
+ public void test_clone() {
+ // Test for method java.lang.Object java.util.TreeSet.clone()
+ TreeSet s = (TreeSet) ts.clone();
+ Iterator i = ts.iterator();
+ while (i.hasNext())
+ assertTrue("Clone failed to copy all elements", s
+ .contains(i.next()));
+ }
+
+ /**
+ * java.util.TreeSet#comparator()
+ */
+ public void test_comparator() {
+ // Test for method java.util.Comparator java.util.TreeSet.comparator()
+ ReversedIntegerComparator comp = new ReversedIntegerComparator();
+ TreeSet myTreeSet = new TreeSet(comp);
+ assertTrue("Answered incorrect comparator",
+ myTreeSet.comparator() == comp);
+ }
+
+ /**
+ * java.util.TreeSet#contains(java.lang.Object)
+ */
+ public void test_containsLjava_lang_Object() {
+ // Test for method boolean java.util.TreeSet.contains(java.lang.Object)
+ assertTrue("Returned false for valid Object", ts
+ .contains(objArray[objArray.length / 2]));
+ assertTrue("Returned true for invalid Object", !ts
+ .contains(new Integer(-9)));
+ try {
+ ts.contains(new Object());
+ } catch (ClassCastException e) {
+ // Correct
+ return;
+ }
+ fail("Failed to throw exception when passed invalid element");
+
+ }
+
+ /**
+ * java.util.TreeSet#first()
+ */
+ public void test_first() {
+ // Test for method java.lang.Object java.util.TreeSet.first()
+ assertTrue("Returned incorrect first element",
+ ts.first() == objArray[0]);
+ }
+
+ /**
+ * java.util.TreeSet#headSet(java.lang.Object)
+ */
+ public void test_headSetLjava_lang_Object() {
+ // Test for method java.util.SortedSet
+ // java.util.TreeSet.headSet(java.lang.Object)
+ Set s = ts.headSet(new Integer(100));
+ assertEquals("Returned set of incorrect size", 100, s.size());
+ for (int i = 0; i < 100; i++)
+ assertTrue("Returned incorrect set", s.contains(objArray[i]));
+ }
+
+ /**
+ * java.util.TreeSet#isEmpty()
+ */
+ public void test_isEmpty() {
+ // Test for method boolean java.util.TreeSet.isEmpty()
+ assertTrue("Empty set returned false", new TreeSet().isEmpty());
+ assertTrue("Non-Empty returned true", !ts.isEmpty());
+ }
+
+ /**
+ * java.util.TreeSet#iterator()
+ */
+ public void test_iterator() {
+ // Test for method java.util.Iterator java.util.TreeSet.iterator()
+ TreeSet s = new TreeSet();
+ s.addAll(ts);
+ Iterator i = ts.iterator();
+ Set as = new HashSet(Arrays.asList(objArray));
+ while (i.hasNext())
+ as.remove(i.next());
+ assertEquals("Returned incorrect iterator", 0, as.size());
+
+ }
+
+ /**
+ * java.util.TreeSet#last()
+ */
+ public void test_last() {
+ // Test for method java.lang.Object java.util.TreeSet.last()
+ assertTrue("Returned incorrect last element",
+ ts.last() == objArray[objArray.length - 1]);
+ }
+
+ /**
+ * java.util.TreeSet#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ // Test for method boolean java.util.TreeSet.remove(java.lang.Object)
+ ts.remove(objArray[0]);
+ assertTrue("Failed to remove object", !ts.contains(objArray[0]));
+ assertTrue("Failed to change size after remove",
+ ts.size() == objArray.length - 1);
+ try {
+ ts.remove(new Object());
+ } catch (ClassCastException e) {
+ // Correct
+ return;
+ }
+ fail("Failed to throw exception when past uncomparable value");
+ }
+
+ /**
+ * java.util.TreeSet#size()
+ */
+ public void test_size() {
+ // Test for method int java.util.TreeSet.size()
+ assertTrue("Returned incorrect size", ts.size() == objArray.length);
+ }
+
+ /**
+ * java.util.TreeSet#subSet(java.lang.Object, java.lang.Object)
+ */
+ public void test_subSetLjava_lang_ObjectLjava_lang_Object() {
+ // Test for method java.util.SortedSet
+ // java.util.TreeSet.subSet(java.lang.Object, java.lang.Object)
+ final int startPos = objArray.length / 4;
+ final int endPos = 3 * objArray.length / 4;
+ SortedSet aSubSet = ts.subSet(objArray[startPos], objArray[endPos]);
+ assertTrue("Subset has wrong number of elements",
+ aSubSet.size() == (endPos - startPos));
+ for (int counter = startPos; counter < endPos; counter++)
+ assertTrue("Subset does not contain all the elements it should",
+ aSubSet.contains(objArray[counter]));
+
+ int result;
+ try {
+ ts.subSet(objArray[3], objArray[0]);
+ result = 0;
+ } catch (IllegalArgumentException e) {
+ result = 1;
+ }
+ assertEquals("end less than start should throw", 1, result);
+ }
+
+ /**
+ * java.util.TreeSet#tailSet(java.lang.Object)
+ */
+ public void test_tailSetLjava_lang_Object() {
+ // Test for method java.util.SortedSet
+ // java.util.TreeSet.tailSet(java.lang.Object)
+ Set s = ts.tailSet(new Integer(900));
+ assertEquals("Returned set of incorrect size", 100, s.size());
+ for (int i = 900; i < objArray.length; i++)
+ assertTrue("Returned incorrect set", s.contains(objArray[i]));
+ }
+
+ /**
+ * Tests equals() method.
+ * Tests that no ClassCastException will be thrown in all cases.
+ * Regression test for HARMONY-1639.
+ */
+ public void test_equals() throws Exception {
+ // comparing TreeSets with different object types
+ Set s1 = new TreeSet();
+ Set s2 = new TreeSet();
+ s1.add("key1");
+ s1.add("key2");
+ s2.add(new Integer(1));
+ s2.add(new Integer(2));
+ assertFalse("Sets should not be equal 1", s1.equals(s2));
+ assertFalse("Sets should not be equal 2", s2.equals(s1));
+
+ // comparing TreeSet with HashSet
+ s1 = new TreeSet();
+ s2 = new HashSet();
+ s1.add("key");
+ s2.add(new Object());
+ assertFalse("Sets should not be equal 3", s1.equals(s2));
+ assertFalse("Sets should not be equal 4", s2.equals(s1));
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ ts = new TreeSet();
+ for (int i = 0; i < objArray.length; i++) {
+ Object x = objArray[i] = new Integer(i);
+ ts.add(x);
+ }
+ }
+
+ /**
+ * 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/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UUIDTest.java
index d8f4cc4..a56a2d4 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UUIDTest.java
@@ -15,7 +15,7 @@
* the License.
*/
-package org.apache.harmony.luni.tests.java.util;
+package org.apache.harmony.tests.java.util;
import java.util.UUID;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatConversionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatConversionExceptionTest.java
new file mode 100644
index 0000000..a265887
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatConversionExceptionTest.java
@@ -0,0 +1,96 @@
+/* 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.tests.java.util;
+
+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;
+
+public class UnknownFormatConversionExceptionTest extends TestCase {
+
+ /**
+ * java.util.UnknownFormatConversionException#UnknownFormatConversionException(String)
+ */
+ public void test_unknownFormatConversionException() {
+
+ // RI 5.0 will not throw NullPointerException, it is the bug according
+ // to spec.
+ try {
+ new UnknownFormatConversionException(null);
+ fail("should throw NullPointerExcepiton");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * java.util.UnknownFormatConversionException#getConversion()
+ */
+ public void test_getConversion() {
+ String s = "MYTESTSTRING";
+ UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
+ s);
+ assertEquals(s, UnknownFormatConversionException.getConversion());
+ }
+
+ /**
+ * java.util.UnknownFormatConversionException#getMessage()
+ */
+ public void test_getMessage() {
+ String s = "MYTESTSTRING";
+ UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
+ s);
+ assertTrue(null != UnknownFormatConversionException.getMessage());
+ }
+
+ // comparator for comparing UnknownFormatConversionException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ UnknownFormatConversionException initEx = (UnknownFormatConversionException) initial;
+ UnknownFormatConversionException desrEx = (UnknownFormatConversionException) deserialized;
+
+ assertEquals("Conversion", initEx.getConversion(), desrEx
+ .getConversion());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new UnknownFormatConversionException(
+ "MYTESTSTRING"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new UnknownFormatConversionException("MYTESTSTRING"),
+ exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatFlagsExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatFlagsExceptionTest.java
new file mode 100644
index 0000000..667ff98
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UnknownFormatFlagsExceptionTest.java
@@ -0,0 +1,94 @@
+/* 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.tests.java.util;
+
+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;
+
+public class UnknownFormatFlagsExceptionTest extends TestCase {
+
+ /**
+ * java.util.UnknownFormatFlagsException#UnknownFormatFlagsException(String)
+ */
+ public void test_unknownFormatFlagsException() {
+
+ try {
+ new UnknownFormatFlagsException(null);
+ fail("should throw NullPointerExcepiton");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.UnknownFormatFlagsException#getFlags()
+ */
+ public void test_getFlags() {
+ String s = "MYTESTSTRING";
+ UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException(
+ s);
+ assertEquals(s, UnknownFormatFlagsException.getFlags());
+ }
+
+ /**
+ * java.util.UnknownFormatFlagsException#getMessage()
+ */
+ public void test_getMessage() {
+ String s = "MYTESTSTRING";
+ UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException(
+ s);
+ assertNotNull(UnknownFormatFlagsException.getMessage());
+ }
+
+ // comparator for comparing UnknownFormatFlagsException objects
+ private static final SerializableAssert exComparator = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ UnknownFormatFlagsException initEx = (UnknownFormatFlagsException) initial;
+ UnknownFormatFlagsException desrEx = (UnknownFormatFlagsException) deserialized;
+
+ assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
+ }
+ };
+
+ /**
+ * serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new UnknownFormatFlagsException(
+ "MYTESTSTRING"), exComparator);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new UnknownFormatFlagsException(
+ "MYTESTSTRING"), exComparator);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/VectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/VectorTest.java
new file mode 100644
index 0000000..e32ca94
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/VectorTest.java
@@ -0,0 +1,1406 @@
+/*
+ * 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.tests.java.util;
+
+import tests.support.Support_ListTest;
+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;
+
+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]";
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+
+ try {
+ new Vector(-1);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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)));
+
+ try {
+ new Vector(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+
+ try {
+ tVector.add(-5, null);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ tVector.add(tVector.size() + 1, null);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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 {
+ tVector.addAll(-5, Arrays.asList(new String[] { "two", "three" }));
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ tVector.addAll(tVector.size() + 1, Arrays.asList(new String[] { "two", "three" }));
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ tVector.addAll(tVector.size() / 2, null);
+ fail("NullPointerException expected");
+ } catch(NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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 {
+ tVector.addAll(tVector.size() / 2, null);
+ fail("NullPointerException expected");
+ } catch(NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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()));
+ }
+
+ /**
+ * 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());
+
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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));
+
+ try {
+ tVector.containsAll(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+
+ try {
+ tVector.copyInto(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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));
+
+ try {
+ tVector.elementAt(-5);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ tVector.elementAt(tVector.size() + 1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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) {
+ }
+ }
+ }
+
+ /**
+ * 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(
+ "ensureCapacity failed to set to be twice the old capacity",
+ 20, v.capacity());
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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(10);
+ try {
+ v.firstElement();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * 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));
+
+ try {
+ tVector.get(-5);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ tVector.get(tVector.size() + 1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch(ArrayIndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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) {
+
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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) {
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+
+ try {
+ v.removeAll(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * {@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
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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()
+ );
+
+ }
+
+ /**
+ * 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()));
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ }
+
+ }
+
+ /**
+ * java.util.Vector#toString()
+ */
+ public void test_toString() {
+ // Ensure toString works with self-referencing elements.
+ Vector<Object> vec = new Vector<Object>(3);
+ vec.add(null);
+ 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ public void test_removeRangeII() {
+ MockVector mv = new MockVector();
+ mv.add("First");
+ mv.add("Second");
+ mv.add("One more");
+ mv.add("Last");
+ mv.removeRange(1, 3);
+ assertTrue(mv.contains("First"));
+ assertFalse(mv.contains("Second"));
+ assertFalse(mv.contains("One more"));
+ assertTrue(mv.contains("Last"));
+ }
+
+ 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/WeakHashMapTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/WeakHashMapTest.java
new file mode 100644
index 0000000..1d5294f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/WeakHashMapTest.java
@@ -0,0 +1,423 @@
+/*
+ * 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.tests.java.util;
+
+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;
+import libcore.java.lang.ref.FinalizationTester;
+
+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;
+
+ /**
+ * 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]);
+
+ }
+
+ /**
+ * 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");
+
+ try {
+ new WeakHashMap(-50);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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");
+
+ try {
+ new WeakHashMap(50, -0.5f);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+
+ try {
+ new WeakHashMap(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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]));
+
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * java.util.WeakHashMap#entrySet()
+ */
+ public void test_entrySet() {
+ // 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;
+
+ FinalizationTester.induceFinalization();
+ long startTime = System.currentTimeMillis();
+ // We use a busy wait loop here since we can not know when the ReferenceQueue
+ // daemon will enqueue the cleared references on their internal reference
+ // queues. The current timeout is 5 seconds.
+ do {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ }
+ } while (entrySet.size() != 99 &&
+ System.currentTimeMillis() - startTime < 5000);
+
+ assertTrue(
+ "Incorrect number of entries returned after gc--wanted 99, got: "
+ + entrySet.size(), entrySet.size() == 99);
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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.gc();
+ FinalizationTester.induceFinalization();
+ map.remove("nothing"); // Cause objects in queue to be removed
+ assertEquals("null key was removed", 1, map.size());
+ }
+
+ /**
+ * 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());
+
+ try {
+ map.putAll(null);
+ fail("NullPointerException exected");
+ } catch (NullPointerException e) {
+ //expected
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.WeakHashMap#size()
+ */
+ public void test_size() {
+ whm = new WeakHashMap();
+ assertEquals(0, whm.size());
+ }
+
+ /**
+ * 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();
+ FinalizationTester.induceFinalization();
+ count++;
+ } while (count <= 5 && keySet.size() == 100);
+
+ assertEquals("Incorrect number of keys returned after gc,", 99, keySet
+ .size());
+ }
+
+ /**
+ * Regression test for HARMONY-3883
+ *
+ * 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();
+ int count = 0;
+ do {
+ System.gc();
+ System.gc();
+ FinalizationTester.induceFinalization();
+ count++;
+ } while (count <= 5);
+ 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 + "]";
+ }
+ }
+
+
+ /**
+ * 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();
+ FinalizationTester.induceFinalization();
+ 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/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesNameTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesNameTest.java
new file mode 100644
index 0000000..8eb7fe0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesNameTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.util.jar.Attributes;
+
+import junit.framework.TestCase;
+
+public class AttributesNameTest extends TestCase {
+
+ /**
+ * java.util.jar.Attributes.Name#Name(java.lang.String)
+ */
+ public void testAttributesNameConstructor() {
+ // Regression for HARMONY-85
+ try {
+ new Attributes.Name(
+ "01234567890123456789012345678901234567890123456789012345678901234567890");
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesTest.java
new file mode 100644
index 0000000..15f6851
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/AttributesTest.java
@@ -0,0 +1,286 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.Attributes;
+import junit.framework.TestCase;
+
+public class AttributesTest extends TestCase {
+ private Attributes a;
+
+ @Override
+ protected void setUp() {
+ a = new Attributes();
+ a.putValue("1", "one");
+ a.putValue("2", "two");
+ a.putValue("3", "three");
+ a.putValue("4", "four");
+ }
+
+ /**
+ * java.util.jar.Attributes#Attributes(java.util.jar.Attributes)
+ */
+ public void test_ConstructorLjava_util_jar_Attributes() {
+ Attributes a2 = new Attributes(a);
+ assertEquals(a, a2);
+ a.putValue("1", "one(1)");
+ assertTrue("equal", !a.equals(a2));
+ }
+
+ /**
+ * java.util.jar.Attributes#clear()
+ */
+ public void test_clear() {
+ a.clear();
+ assertNull("a) All entries should be null after clear", a.get("1"));
+ assertNull("b) All entries should be null after clear", a.get("2"));
+ assertNull("c) All entries should be null after clear", a.get("3"));
+ assertNull("d) All entries should be null after clear", a.get("4"));
+ assertTrue("Should not contain any keys", !a.containsKey("1"));
+ }
+
+ /**
+ * java.util.jar.Attributes#containsKey(java.lang.Object)
+ */
+ public void test_containsKeyLjava_lang_Object() {
+ assertTrue("a) Should have returned false", !a.containsKey(new Integer(1)));
+ assertTrue("b) Should have returned false", !a.containsKey("0"));
+ assertTrue("Should have returned true", a.containsKey(new Attributes.Name("1")));
+ }
+
+ /**
+ * java.util.jar.Attributes#containsValue(java.lang.Object)
+ */
+ public void test_containsValueLjava_lang_Object() {
+ assertTrue("Should have returned false", !a.containsValue("One"));
+ assertTrue("Should have returned true", a.containsValue("one"));
+ }
+
+ /**
+ * java.util.jar.Attributes#entrySet()
+ */
+ public void test_entrySet() {
+ Set<Map.Entry<Object, Object>> entrySet = a.entrySet();
+ Set<Object> keySet = new HashSet<Object>();
+ Set<Object> valueSet = new HashSet<Object>();
+ Iterator<?> i;
+ assertEquals(4, entrySet.size());
+ i = entrySet.iterator();
+ while (i.hasNext()) {
+ java.util.Map.Entry<?, ?> e;
+ e = (Map.Entry<?, ?>) i.next();
+ keySet.add(e.getKey());
+ valueSet.add(e.getValue());
+ }
+ assertTrue("a) Should contain entry", valueSet.contains("one"));
+ assertTrue("b) Should contain entry", valueSet.contains("two"));
+ assertTrue("c) Should contain entry", valueSet.contains("three"));
+ assertTrue("d) Should contain entry", valueSet.contains("four"));
+ assertTrue("a) Should contain key", keySet.contains(new Attributes.Name("1")));
+ assertTrue("b) Should contain key", keySet.contains(new Attributes.Name("2")));
+ assertTrue("c) Should contain key", keySet.contains(new Attributes.Name("3")));
+ assertTrue("d) Should contain key", keySet.contains(new Attributes.Name("4")));
+ }
+
+ /**
+ * java.util.jar.Attributes#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ assertEquals("a) Incorrect value returned", "one", a.getValue("1"));
+ assertNull("b) Incorrect value returned", a.getValue("0"));
+ }
+
+ /**
+ * java.util.jar.Attributes#isEmpty()
+ */
+ public void test_isEmpty() {
+ assertTrue("Should not be empty", !a.isEmpty());
+ a.clear();
+ assertTrue("a) Should be empty", a.isEmpty());
+ a = new Attributes();
+ assertTrue("b) Should be empty", a.isEmpty());
+ }
+
+ /**
+ * java.util.jar.Attributes#keySet()
+ */
+ public void test_keySet() {
+ Set<?> s = a.keySet();
+ assertEquals(4, s.size());
+ assertTrue("a) Should contain entry", s.contains(new Attributes.Name("1")));
+ assertTrue("b) Should contain entry", s.contains(new Attributes.Name("2")));
+ assertTrue("c) Should contain entry", s.contains(new Attributes.Name("3")));
+ assertTrue("d) Should contain entry", s.contains(new Attributes.Name("4")));
+ }
+
+ /**
+ * java.util.jar.Attributes#putAll(java.util.Map)
+ */
+ public void test_putAllLjava_util_Map() {
+ Attributes b = new Attributes();
+ b.putValue("3", "san");
+ b.putValue("4", "shi");
+ b.putValue("5", "go");
+ b.putValue("6", "roku");
+ a.putAll(b);
+ assertEquals("Should not have been replaced", "one", a.getValue("1"));
+ assertEquals("Should have been replaced", "san", a.getValue("3"));
+ assertEquals("Should have been added", "go", a.getValue("5"));
+ Attributes atts = new Attributes();
+ assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH, "tools.jar"));
+ assertNull("Assert 1: ", atts.put(Attributes.Name.MANIFEST_VERSION, "1"));
+ Attributes atts2 = new Attributes();
+ atts2.putAll(atts);
+ assertEquals("Assert 2:", "tools.jar", atts2.get(Attributes.Name.CLASS_PATH));
+ assertEquals("Assert 3: ", "1", atts2.get(Attributes.Name.MANIFEST_VERSION));
+ try {
+ atts.putAll(Collections.EMPTY_MAP);
+ fail("Assert 4: no class cast from attrib parameter");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.jar.Attributes#remove(java.lang.Object)
+ */
+ public void test_removeLjava_lang_Object() {
+ a.remove(new Attributes.Name("1"));
+ a.remove(new Attributes.Name("3"));
+ assertNull("Should have been removed", a.getValue("1"));
+ assertEquals("Should not have been removed", "four", a.getValue("4"));
+ }
+
+ /**
+ * java.util.jar.Attributes#size()
+ */
+ public void test_size() {
+ assertEquals("Incorrect size returned", 4, a.size());
+ a.clear();
+ assertEquals(0, a.size());
+ }
+
+ /**
+ * java.util.jar.Attributes#values()
+ */
+ public void test_values() {
+ Collection<?> valueCollection = a.values();
+ assertTrue("a) Should contain entry", valueCollection.contains("one"));
+ assertTrue("b) Should contain entry", valueCollection.contains("two"));
+ assertTrue("c) Should contain entry", valueCollection.contains("three"));
+ assertTrue("d) Should contain entry", valueCollection.contains("four"));
+ }
+
+ /**
+ * java.util.jar.Attributes#clone()
+ */
+ public void test_clone() {
+ Attributes a2 = (Attributes) a.clone();
+ assertEquals(a, a2);
+ a.putValue("1", "one(1)");
+ assertTrue("equal", !a.equals(a2));
+ }
+
+ /**
+ * java.util.jar.Attributes#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ Attributes.Name n1 = new Attributes.Name("name"), n2 = new Attributes.Name("Name");
+ assertEquals(n1, n2);
+ Attributes a1 = new Attributes();
+ a1.putValue("one", "1");
+ a1.putValue("two", "2");
+ Attributes a2 = new Attributes();
+ a2.putValue("One", "1");
+ a2.putValue("TWO", "2");
+ assertEquals(a1, a2);
+ assertEquals(a1, a1);
+ a2 = null;
+ assertFalse(a1.equals(a2));
+ }
+
+ /**
+ * java.util.jar.Attributes.put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ Attributes atts = new Attributes();
+ assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH, "tools.jar"));
+ assertEquals("Assert 1: ", "tools.jar", atts.getValue(Attributes.Name.CLASS_PATH));
+ // Regression for HARMONY-79
+ try {
+ atts.put("not a name", "value");
+ fail("Assert 2: no class cast from key parameter");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ try {
+ atts.put(Attributes.Name.CLASS_PATH, Boolean.TRUE);
+ fail("Assert 3: no class cast from value parameter");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.jar.Attributes.put(java.lang.Object, java.lang.Object)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object_Null() {
+
+ Attributes attribute = new Attributes();
+
+ assertFalse(attribute.containsKey(null));
+ assertFalse(attribute.containsValue(null));
+ attribute.put(null, null);
+ attribute.put(null, null);
+ assertEquals(1, attribute.size());
+ assertTrue(attribute.containsKey(null));
+ assertTrue(attribute.containsValue(null));
+ assertNull(attribute.get(null));
+
+ String value = "It's null";
+ attribute.put(null, value);
+ assertEquals(1, attribute.size());
+ assertEquals(value, attribute.get(null));
+
+ Attributes.Name name = new Attributes.Name("null");
+ attribute.put(name, null);
+ assertEquals(2, attribute.size());
+ assertNull(attribute.get(name));
+ }
+
+ /**
+ * java.util.jar.Attributes.hashCode()
+ */
+ public void test_hashCode() {
+ MockAttributes mockAttr = new MockAttributes();
+ mockAttr.putValue("1", "one");
+ assertEquals(mockAttr.getMap().hashCode(), mockAttr.hashCode());
+ }
+
+ private static class MockAttributes extends Attributes {
+ public Map<Object, Object> getMap() {
+ return map;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarEntryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarEntryTest.java
new file mode 100644
index 0000000..a48bd60
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarEntryTest.java
@@ -0,0 +1,182 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.CodeSigner;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.zip.ZipEntry;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class JarEntryTest extends TestCase {
+ private ZipEntry zipEntry;
+
+ private JarEntry jarEntry;
+
+ private JarFile jarFile;
+
+ private final String jarName = "hyts_patch.jar";
+
+ private final String entryName = "foo/bar/A.class";
+
+ private final String entryName2 = "Blah.txt";
+
+ private final String attJarName = "hyts_att.jar";
+
+ private final String attEntryName = "HasAttributes.txt";
+
+ private final String attEntryName2 = "NoAttributes.txt";
+
+ private File resources;
+
+ @Override
+ protected void setUp() throws Exception {
+ resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, jarName);
+ jarFile = new JarFile(new File(resources, jarName));
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (jarFile != null) {
+ jarFile.close();
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.jar.JarEntry#JarEntry(java.util.jar.JarEntry)
+ */
+ public void test_ConstructorLjava_util_jar_JarEntry() throws IOException {
+ JarEntry newJarEntry = new JarEntry(jarFile.getJarEntry(entryName));
+ assertNotNull(newJarEntry);
+
+ jarEntry = null;
+ try {
+ newJarEntry = new JarEntry(jarEntry);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.jar.JarEntry#JarEntry(java.util.zip.ZipEntry)
+ */
+ public void test_ConstructorLjava_util_zip_ZipEntry() {
+ assertNotNull("Jar file is null", jarFile);
+ zipEntry = jarFile.getEntry(entryName);
+ assertNotNull("Zip entry is null", zipEntry);
+ jarEntry = new JarEntry(zipEntry);
+ assertNotNull("Jar entry is null", jarEntry);
+ assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
+ .getName());
+ assertEquals("Wrong entry constructed--wrong size", 311, jarEntry
+ .getSize());
+ }
+
+ /**
+ * java.util.jar.JarEntry#getAttributes()
+ */
+ public void test_getAttributes() throws Exception {
+ JarFile attrJar = null;
+ File file = null;
+
+ Support_Resources.copyFile(resources, null, attJarName);
+ file = new File(resources, attJarName);
+ attrJar = new JarFile(file);
+
+ jarEntry = attrJar.getJarEntry(attEntryName);
+ assertNotNull("Should have Manifest attributes", jarEntry
+ .getAttributes());
+
+ jarEntry = attrJar.getJarEntry(attEntryName2);
+ assertNull("Shouldn't have any Manifest attributes", jarEntry
+ .getAttributes());
+ attrJar.close();
+ }
+
+ /**
+ * java.util.jar.JarEntry#getCertificates()
+ */
+ public void test_getCertificates() throws Exception {
+ zipEntry = jarFile.getEntry(entryName2);
+ jarEntry = new JarEntry(zipEntry);
+ assertNull(jarEntry.getCertificates());
+
+ // Regression Test for HARMONY-3424
+ String jarFileName = "TestCodeSigners.jar";
+ Support_Resources.copyFile(resources, null, jarFileName);
+ File file = new File(resources, jarFileName);
+ JarFile jarFile = new JarFile(file);
+ JarEntry jarEntry1 = jarFile.getJarEntry("Test.class");
+ JarEntry jarEntry2 = jarFile.getJarEntry("Test.class");
+ InputStream in = jarFile.getInputStream(jarEntry1);
+ byte[] buffer = new byte[1024];
+ while (in.available() > 0) {
+ assertNull("getCertificates() should be null until the entry is read",
+ jarEntry1.getCertificates());
+ assertNull(jarEntry2.getCertificates());
+ in.read(buffer);
+ }
+ assertEquals("the file is fully read", -1, in.read());
+ assertNotNull(jarEntry1.getCertificates());
+ assertNotNull(jarEntry2.getCertificates());
+ in.close();
+ }
+
+ /**
+ * java.util.jar.JarEntry#getCodeSigners()
+ */
+ public void test_getCodeSigners() throws IOException {
+ String jarFileName = "TestCodeSigners.jar";
+ Support_Resources.copyFile(resources, null, jarFileName);
+ File file = new File(resources, jarFileName);
+ JarFile jarFile = new JarFile(file);
+ JarEntry jarEntry = jarFile.getJarEntry("Test.class");
+ InputStream in = jarFile.getInputStream(jarEntry);
+ byte[] buffer = new byte[1024];
+ while (in.available() > 0) {
+ assertNull("getCodeSigners() should be null until the entry is read",
+ jarEntry.getCodeSigners());
+ in.read(buffer);
+ }
+ assertEquals("the file is fully read", -1, in.read());
+ CodeSigner[] codeSigners = jarEntry.getCodeSigners();
+ assertEquals(2, codeSigners.length);
+ List<?> certs_bob = codeSigners[0].getSignerCertPath()
+ .getCertificates();
+ List<?> certs_alice = codeSigners[1].getSignerCertPath()
+ .getCertificates();
+ if (1 == certs_bob.size()) {
+ List<?> temp = certs_bob;
+ certs_bob = certs_alice;
+ certs_alice = temp;
+ }
+ assertEquals(2, certs_bob.size());
+ assertEquals(1, certs_alice.size());
+ assertNull(
+ "getCodeSigners() should be null for a primitive JarEntry",
+ new JarEntry("aaa").getCodeSigners());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarExceptionTest.java
new file mode 100644
index 0000000..66ff400
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarExceptionTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.jar.JarException;
+import java.util.jar.Manifest;
+import junit.framework.TestCase;
+
+public class JarExceptionTest extends TestCase {
+ /**
+ * java.util.jar.JarException#JarException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws Exception {
+ try {
+ new Manifest(new ByteArrayInputStream(
+ "jlkasj dl: dsklf jlks dslka : fdsfsd\n\n\n\ndsfas".getBytes()));
+ fail("Should have thrown exception");
+ } catch (IOException e) {
+ // correct
+ }
+ }
+
+ /**
+ * java.util.jar.JarException#JarException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String1() throws Exception {
+ assertEquals("Jar Exception", new JarException("Jar Exception").getMessage());
+ }
+
+ /**
+ * java.util.jar.JarException#JarException()
+ */
+ public void test_Constructor_void() throws Exception {
+ new JarException();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarFileTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarFileTest.java
new file mode 100644
index 0000000..d5d8191
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarFileTest.java
@@ -0,0 +1,1017 @@
+/*
+ * 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.tests.java.util.jar;
+
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.CodeSigner;
+import java.security.Permission;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.Vector;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+
+public class JarFileTest extends TestCase {
+
+ // BEGIN android-added
+ public byte[] getAllBytesFromStream(InputStream is) throws IOException {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ byte[] buf = new byte[666];
+ int iRead;
+ int off;
+ while (is.available() > 0) {
+ iRead = is.read(buf, 0, buf.length);
+ if (iRead > 0) bs.write(buf, 0, iRead);
+ }
+ return bs.toByteArray();
+ }
+
+ // END android-added
+
+ private final String jarName = "hyts_patch.jar"; // a 'normal' jar file
+
+ private final String jarName2 = "hyts_patch2.jar";
+
+ private final String jarName3 = "hyts_manifest1.jar";
+
+ private final String jarName4 = "hyts_signed.jar";
+
+ private final String jarName5 = "hyts_signed_inc.jar";
+
+ private final String jarName6 = "hyts_signed_sha256withrsa.jar";
+
+ private final String jarName7 = "hyts_signed_sha256digest_sha256withrsa.jar";
+
+ private final String jarName8 = "hyts_signed_sha512digest_sha512withecdsa.jar";
+
+ private final String jarName9 = "hyts_signed_sha256digest_sha256withecdsa.jar";
+
+ private final String authAttrsJar = "hyts_signed_authAttrs.jar";
+
+ private final String entryName = "foo/bar/A.class";
+
+ private final String entryName3 = "coucou/FileAccess.class";
+
+ private final String integrateJar = "Integrate.jar";
+
+ private final String integrateJarEntry = "Test.class";
+
+ private final String emptyEntryJar = "EmptyEntries_signed.jar";
+
+ private final String emptyEntry1 = "subfolder/internalSubset01.js";
+
+ private final String emptyEntry2 = "svgtest.js";
+
+ private final String emptyEntry3 = "svgunit.js";
+
+ private static final String VALID_CHAIN_JAR = "hyts_signed_validChain.jar";
+
+ private static final String INVALID_CHAIN_JAR = "hyts_signed_invalidChain.jar";
+
+ private static final String AMBIGUOUS_SIGNERS_JAR = "hyts_signed_ambiguousSignerArray.jar";
+
+ private File resources;
+
+ // custom security manager
+ SecurityManager sm = new SecurityManager() {
+ final String forbidenPermissionName = "user.dir";
+
+ public void checkPermission(Permission perm) {
+ if (perm.getName().equals(forbidenPermissionName)) {
+ throw new SecurityException();
+ }
+ }
+ };
+
+ @Override
+ protected void setUp() {
+ resources = Support_Resources.createTempFolder();
+ }
+
+ /**
+ * java.util.jar.JarFile#JarFile(java.io.File)
+ */
+ public void test_ConstructorLjava_io_File() {
+ try {
+ JarFile jarFile = new JarFile(new File("Wrong.file"));
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#JarFile(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ try {
+ JarFile jarFile = new JarFile("Wrong.file");
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ String fileName = (new File(resources, jarName)).getCanonicalPath();
+ JarFile jarFile = new JarFile(fileName);
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#JarFile(java.lang.String, boolean)
+ */
+ public void test_ConstructorLjava_lang_StringZ() {
+ try {
+ JarFile jarFile = new JarFile("Wrong.file", false);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ String fileName = (new File(resources, jarName)).getCanonicalPath();
+ JarFile jarFile = new JarFile(fileName, true);
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#JarFile(java.io.File, boolean)
+ */
+ public void test_ConstructorLjava_io_FileZ() {
+ try {
+ JarFile jarFile = new JarFile(new File("Wrong.file"), true);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName), false);
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#JarFile(java.io.File, boolean, int)
+ */
+ public void test_ConstructorLjava_io_FileZI() {
+ try {
+ JarFile jarFile = new JarFile(new File("Wrong.file"), true,
+ ZipFile.OPEN_READ);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName), false,
+ ZipFile.OPEN_READ);
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName), false,
+ ZipFile.OPEN_READ | ZipFile.OPEN_DELETE + 33);
+ fail("Should throw IllegalArgumentException");
+ } catch (IOException e) {
+ fail("Should not throw IOException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * Constructs JarFile object.
+ *
+ * java.util.jar.JarFile#JarFile(java.io.File)
+ * java.util.jar.JarFile#JarFile(java.lang.String)
+ */
+ public void testConstructor_file() throws IOException {
+ File f = new File(resources, jarName);
+ Support_Resources.copyFile(resources, null, jarName);
+ assertTrue(new JarFile(f).getEntry(entryName).getName().equals(
+ entryName));
+ assertTrue(new JarFile(f.getPath()).getEntry(entryName).getName()
+ .equals(entryName));
+ }
+
+ /**
+ * java.util.jar.JarFile#entries()
+ */
+ public void test_entries() throws Exception {
+ /*
+ * Note only (and all of) the following should be contained in the file
+ * META-INF/ META-INF/MANIFEST.MF foo/ foo/bar/ foo/bar/A.class Blah.txt
+ */
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ Enumeration<JarEntry> e = jarFile.entries();
+ int i;
+ for (i = 0; e.hasMoreElements(); i++) {
+ e.nextElement();
+ }
+ assertEquals(jarFile.size(), i);
+ jarFile.close();
+ assertEquals(6, i);
+ }
+
+ public void test_entries2() throws Exception {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ Enumeration<JarEntry> enumeration = jarFile.entries();
+ jarFile.close();
+ try {
+ enumeration.hasMoreElements();
+ fail("hasMoreElements() did not detect a closed jar file");
+ } catch (IllegalStateException e) {
+ }
+ Support_Resources.copyFile(resources, null, jarName);
+ jarFile = new JarFile(new File(resources, jarName));
+ enumeration = jarFile.entries();
+ jarFile.close();
+ try {
+ enumeration.nextElement();
+ fail("nextElement() did not detect closed jar file");
+ } catch (IllegalStateException e) {
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.jar.JarFile#getJarEntry(java.lang.String)
+ */
+ public void test_getEntryLjava_lang_String() throws IOException {
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ assertEquals("Error in returned entry", 311, jarFile.getEntry(
+ entryName).getSize());
+ jarFile.close();
+ } catch (Exception e) {
+ fail("Exception during test: " + e.toString());
+ }
+
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ Enumeration<JarEntry> enumeration = jarFile.entries();
+ assertTrue(enumeration.hasMoreElements());
+ while (enumeration.hasMoreElements()) {
+ JarEntry je = enumeration.nextElement();
+ jarFile.getEntry(je.getName());
+ }
+
+ enumeration = jarFile.entries();
+ assertTrue(enumeration.hasMoreElements());
+ JarEntry je = enumeration.nextElement();
+ try {
+ jarFile.close();
+ jarFile.getEntry(je.getName());
+ // fail("IllegalStateException expected.");
+ } catch (IllegalStateException ee) { // Per documentation exception
+ // may be thrown.
+ // expected
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.jar.JarFile#getJarEntry(java.lang.String)
+ */
+ public void test_getJarEntryLjava_lang_String() throws IOException {
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ assertEquals("Error in returned entry", 311, jarFile.getJarEntry(
+ entryName).getSize());
+ jarFile.close();
+ } catch (Exception e) {
+ fail("Exception during test: " + e.toString());
+ }
+
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ Enumeration<JarEntry> enumeration = jarFile.entries();
+ assertTrue(enumeration.hasMoreElements());
+ while (enumeration.hasMoreElements()) {
+ JarEntry je = enumeration.nextElement();
+ jarFile.getJarEntry(je.getName());
+ }
+
+ enumeration = jarFile.entries();
+ assertTrue(enumeration.hasMoreElements());
+ JarEntry je = enumeration.nextElement();
+ try {
+ jarFile.close();
+ jarFile.getJarEntry(je.getName());
+ // fail("IllegalStateException expected.");
+ } catch (IllegalStateException ee) { // Per documentation exception
+ // may be thrown.
+ // expected
+ }
+ }
+
+
+ /**
+ * java.util.jar.JarFile#getJarEntry(java.lang.String)
+ */
+ public void testGetJarEntry() throws Exception {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ assertEquals("Error in returned entry", 311, jarFile.getEntry(
+ entryName).getSize());
+ jarFile.close();
+
+ // tests for signed jars
+ // test all signed jars in the /Testres/Internal/SignedJars directory
+ String jarDirUrl = Support_Resources
+ .getResourceURL("/../internalres/signedjars");
+ Vector<String> signedJars = new Vector<String>();
+ try {
+ InputStream is = new URL(jarDirUrl + "/jarlist.txt").openStream();
+ while (is.available() > 0) {
+ StringBuilder linebuff = new StringBuilder(80); // Typical line
+ // length
+ done: while (true) {
+ int nextByte = is.read();
+ switch (nextByte) {
+ case -1:
+ break done;
+ case (byte) '\r':
+ if (linebuff.length() == 0) {
+ // ignore
+ }
+ break done;
+ case (byte) '\n':
+ if (linebuff.length() == 0) {
+ // ignore
+ }
+ break done;
+ default:
+ linebuff.append((char) nextByte);
+ }
+ }
+ if (linebuff.length() == 0) {
+ break;
+ }
+ String line = linebuff.toString();
+ signedJars.add(line);
+ }
+ is.close();
+ } catch (IOException e) {
+ // no list of jars found
+ }
+
+ for (int i = 0; i < signedJars.size(); i++) {
+ String jarName = signedJars.get(i);
+ try {
+ File file = Support_Resources.getExternalLocalFile(jarDirUrl
+ + "/" + jarName);
+ jarFile = new JarFile(file, true);
+ boolean foundCerts = false;
+ Enumeration<JarEntry> e = jarFile.entries();
+ while (e.hasMoreElements()) {
+ JarEntry entry = e.nextElement();
+ InputStream is = jarFile.getInputStream(entry);
+ is.skip(100000);
+ is.close();
+ Certificate[] certs = entry.getCertificates();
+ if (certs != null && certs.length > 0) {
+ foundCerts = true;
+ break;
+ }
+ }
+ assertTrue(
+ "No certificates found during signed jar test for jar \""
+ + jarName + "\"", foundCerts);
+ } catch (IOException e) {
+ fail("Exception during signed jar test for jar \"" + jarName
+ + "\": " + e.toString());
+ }
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#getManifest()
+ */
+ public void test_getManifest() {
+ // Test for method java.util.jar.Manifest
+ // java.util.jar.JarFile.getManifest()
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ JarFile jarFile = new JarFile(new File(resources, jarName));
+ assertNotNull("Error--Manifest not returned", jarFile.getManifest());
+ jarFile.close();
+ } catch (Exception e) {
+ fail("Exception during 1st test: " + e.toString());
+ }
+ try {
+ Support_Resources.copyFile(resources, null, jarName2);
+ JarFile jarFile = new JarFile(new File(resources, jarName2));
+ assertNull("Error--should have returned null", jarFile
+ .getManifest());
+ jarFile.close();
+ } catch (Exception e) {
+ fail("Exception during 2nd test: " + e.toString());
+ }
+
+ try {
+ // jarName3 was created using the following test
+ Support_Resources.copyFile(resources, null, jarName3);
+ JarFile jarFile = new JarFile(new File(resources, jarName3));
+ assertNotNull("Should find manifest without verifying", jarFile
+ .getManifest());
+ jarFile.close();
+ } catch (Exception e) {
+ fail("Exception during 3rd test: " + e.toString());
+ }
+
+ try {
+ // this is used to create jarName3 used in the previous test
+ Manifest manifest = new Manifest();
+ Attributes attributes = manifest.getMainAttributes();
+ attributes.put(new Attributes.Name("Manifest-Version"), "1.0");
+ ByteArrayOutputStream manOut = new ByteArrayOutputStream();
+ manifest.write(manOut);
+ byte[] manBytes = manOut.toByteArray();
+ File file = File.createTempFile("hyts_manifest1", ".jar");
+ JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(
+ file.getAbsolutePath()));
+ ZipEntry entry = new ZipEntry("META-INF/");
+ entry.setSize(0);
+ jarOut.putNextEntry(entry);
+ entry = new ZipEntry(JarFile.MANIFEST_NAME);
+ entry.setSize(manBytes.length);
+ jarOut.putNextEntry(entry);
+ jarOut.write(manBytes);
+ entry = new ZipEntry("myfile");
+ entry.setSize(1);
+ jarOut.putNextEntry(entry);
+ jarOut.write(65);
+ jarOut.close();
+ JarFile jar = new JarFile(file.getAbsolutePath(), false);
+ assertNotNull("Should find manifest without verifying", jar
+ .getManifest());
+ jar.close();
+ file.delete();
+ } catch (IOException e) {
+ fail("IOException 3");
+ }
+ try {
+ Support_Resources.copyFile(resources, null, jarName2);
+ JarFile jF = new JarFile(new File(resources, jarName2));
+ jF.close();
+ jF.getManifest();
+ fail("FAILED: expected IllegalStateException");
+ } catch (IllegalStateException ise) {
+ // expected;
+ } catch (Exception e) {
+ fail("Exception during 4th test: " + e.toString());
+ }
+
+ Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+ JarFile jf;
+ try {
+ jf = new JarFile(new File(resources, "Broken_manifest.jar"));
+ jf.getManifest();
+ fail("IOException expected.");
+ } catch (IOException e) {
+ // expected.
+ }
+ }
+
+ /**
+ * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
+ */
+ // This test doesn't pass on RI. If entry size is set up incorrectly,
+ // SecurityException is thrown. But SecurityException is thrown on RI only
+ // if jar file is signed incorrectly.
+ public void test_getInputStreamLjava_util_jar_JarEntry_subtest0() throws Exception {
+ File signedFile = null;
+ try {
+ Support_Resources.copyFile(resources, null, jarName4);
+ signedFile = new File(resources, jarName4);
+ } catch (Exception e) {
+ fail("Failed to create local file 2: " + e);
+ }
+
+ try {
+ JarFile jar = new JarFile(signedFile);
+ JarEntry entry = new JarEntry(entryName3);
+ InputStream in = jar.getInputStream(entry);
+ in.read();
+ } catch (Exception e) {
+ fail("Exception during test 3: " + e);
+ }
+
+ try {
+ JarFile jar = new JarFile(signedFile);
+ JarEntry entry = new JarEntry(entryName3);
+ InputStream in = jar.getInputStream(entry);
+ // BEGIN android-added
+ byte[] dummy = getAllBytesFromStream(in);
+ // END android-added
+ assertNull("found certificates", entry.getCertificates());
+ } catch (Exception e) {
+ fail("Exception during test 4: " + e);
+ }
+
+ try {
+ JarFile jar = new JarFile(signedFile);
+ JarEntry entry = new JarEntry(entryName3);
+ entry.setSize(1076);
+ InputStream in = jar.getInputStream(entry);
+ // BEGIN android-added
+ byte[] dummy = getAllBytesFromStream(in);
+ // END android-added
+ fail("SecurityException should be thrown.");
+ } catch (SecurityException e) {
+ // expected
+ } catch (Exception e) {
+ fail("Exception during test 5: " + e);
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName5);
+ signedFile = new File(resources, jarName5);
+ } catch (Exception e) {
+ fail("Failed to create local file 5: " + e);
+ }
+
+ try {
+ JarFile jar = new JarFile(signedFile);
+ JarEntry entry = new JarEntry(entryName3);
+ InputStream in = jar.getInputStream(entry);
+ fail("SecurityException should be thrown.");
+ } catch (SecurityException e) {
+ // expected
+ } catch (Exception e) {
+ fail("Exception during test 5: " + e);
+ }
+
+ // SHA1 digest, SHA256withRSA signed JAR
+ checkSignedJar(jarName6);
+
+ // SHA-256 digest, SHA256withRSA signed JAR
+ checkSignedJar(jarName7);
+
+ // SHA-512 digest, SHA512withECDSA signed JAR
+ checkSignedJar(jarName8);
+
+ // JAR with a signature that has PKCS#7 Authenticated Attributes
+ checkSignedJar(authAttrsJar);
+ }
+
+ /**
+ * This test uses a jar file signed with an algorithm that has its own OID
+ * that is valid as a signature type. SHA256withECDSA is an algorithm that
+ * isn't combined as DigestAlgorithm + "with" + DigestEncryptionAlgorithm
+ * like RSAEncryption needs to be.
+ */
+ public void testJarFile_Signed_Valid_DigestEncryptionAlgorithm() throws Exception {
+ checkSignedJar(jarName9);
+ }
+
+ private void checkSignedJar(String jarName) throws Exception {
+ Support_Resources.copyFile(resources, null, jarName);
+
+ File file = new File(resources, jarName);
+ boolean foundCerts = false;
+
+ JarFile jarFile = new JarFile(file, true);
+ try {
+
+ Enumeration<JarEntry> e = jarFile.entries();
+ while (e.hasMoreElements()) {
+ JarEntry entry = e.nextElement();
+ InputStream is = jarFile.getInputStream(entry);
+ is.skip(100000);
+ is.close();
+ Certificate[] certs = entry.getCertificates();
+ if (certs != null && certs.length > 0) {
+ foundCerts = true;
+ break;
+ }
+ }
+ } finally {
+ jarFile.close();
+ }
+
+ assertTrue(
+ "No certificates found during signed jar test for jar \""
+ + jarName + "\"", foundCerts);
+ }
+
+ private static class Results {
+ public Certificate[] certificates;
+ public CodeSigner[] signers;
+ }
+
+ private Results getSignedJarCerts(String jarName) throws Exception {
+ Support_Resources.copyFile(resources, null, jarName);
+
+ File file = new File(resources, jarName);
+ Results results = new Results();
+
+ JarFile jarFile = new JarFile(file, true, ZipFile.OPEN_READ);
+ try {
+
+ Enumeration<JarEntry> e = jarFile.entries();
+ while (e.hasMoreElements()) {
+ JarEntry entry = e.nextElement();
+ InputStream is = jarFile.getInputStream(entry);
+ // Skip bytes because we have to read the entire file for it to read signatures.
+ is.skip(entry.getSize());
+ is.close();
+ Certificate[] certs = entry.getCertificates();
+ CodeSigner[] signers = entry.getCodeSigners();
+ if (certs != null && certs.length > 0) {
+ results.certificates = certs;
+ results.signers = signers;
+ break;
+ }
+ }
+ } finally {
+ jarFile.close();
+ }
+
+ return results;
+ }
+
+ public void testJarFile_Signed_ValidChain() throws Exception {
+ Results result = getSignedJarCerts(VALID_CHAIN_JAR);
+ assertNotNull(result);
+ assertEquals(Arrays.deepToString(result.certificates), 3, result.certificates.length);
+ assertEquals(Arrays.deepToString(result.signers), 1, result.signers.length);
+ assertEquals(3, result.signers[0].getSignerCertPath().getCertificates().size());
+ assertEquals("CN=fake-chain", ((X509Certificate) result.certificates[0]).getSubjectDN().toString());
+ assertEquals("CN=intermediate1", ((X509Certificate) result.certificates[1]).getSubjectDN().toString());
+ assertEquals("CN=root1", ((X509Certificate) result.certificates[2]).getSubjectDN().toString());
+ }
+
+ public void testJarFile_Signed_InvalidChain() throws Exception {
+ Results result = getSignedJarCerts(INVALID_CHAIN_JAR);
+ assertNotNull(result);
+ assertEquals(Arrays.deepToString(result.certificates), 3, result.certificates.length);
+ assertEquals(Arrays.deepToString(result.signers), 1, result.signers.length);
+ assertEquals(3, result.signers[0].getSignerCertPath().getCertificates().size());
+ assertEquals("CN=fake-chain", ((X509Certificate) result.certificates[0]).getSubjectDN().toString());
+ assertEquals("CN=intermediate1", ((X509Certificate) result.certificates[1]).getSubjectDN().toString());
+ assertEquals("CN=root1", ((X509Certificate) result.certificates[2]).getSubjectDN().toString());
+ }
+
+ public void testJarFile_Signed_AmbiguousSigners() throws Exception {
+ Results result = getSignedJarCerts(AMBIGUOUS_SIGNERS_JAR);
+ assertNotNull(result);
+ assertEquals(Arrays.deepToString(result.certificates), 2, result.certificates.length);
+ assertEquals(Arrays.deepToString(result.signers), 2, result.signers.length);
+ assertEquals(1, result.signers[0].getSignerCertPath().getCertificates().size());
+ assertEquals(1, result.signers[1].getSignerCertPath().getCertificates().size());
+ }
+
+ /*
+ * The jar created by 1.4 which does not provide a
+ * algorithm-Digest-Manifest-Main-Attributes entry in .SF file.
+ */
+ public void test_Jar_created_before_java_5() throws IOException {
+ String modifiedJarName = "Created_by_1_4.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ jarFile.getInputStream(zipEntry);
+ }
+ }
+
+ /* The jar is intact, then everything is all right. */
+ public void test_JarFile_Integrate_Jar() throws IOException {
+ String modifiedJarName = "Integrate.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
+ }
+ }
+
+ /**
+ * The jar is intact, but the entry object is modified.
+ */
+ public void testJarVerificationModifiedEntry() throws IOException {
+ Support_Resources.copyFile(resources, null, integrateJar);
+ File f = new File(resources, integrateJar);
+
+ JarFile jarFile = new JarFile(f);
+ ZipEntry zipEntry = jarFile.getJarEntry(integrateJarEntry);
+ zipEntry.setSize(zipEntry.getSize() + 1);
+ jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
+
+ jarFile = new JarFile(f);
+ zipEntry = jarFile.getJarEntry(integrateJarEntry);
+ zipEntry.setSize(zipEntry.getSize() - 1);
+ try {
+ //jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
+ jarFile.getInputStream(zipEntry).read(new byte[5000], 0, 5000);
+ fail("SecurityException expected");
+ } catch (SecurityException e) {
+ // desired
+ }
+ }
+
+ /*
+ * If another entry is inserted into Manifest, no security exception will be
+ * thrown out.
+ */
+ public void test_JarFile_InsertEntry_in_Manifest_Jar() throws IOException {
+ String modifiedJarName = "Inserted_Entry_Manifest.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ int count = 0;
+ while (entries.hasMoreElements()) {
+
+ ZipEntry zipEntry = entries.nextElement();
+ jarFile.getInputStream(zipEntry);
+ count++;
+ }
+ assertEquals(5, count);
+ }
+
+ /*
+ * If another entry is inserted into Manifest, no security exception will be
+ * thrown out.
+ */
+ public void test_Inserted_Entry_Manifest_with_DigestCode()
+ throws IOException {
+ String modifiedJarName = "Inserted_Entry_Manifest_with_DigestCode.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ int count = 0;
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ jarFile.getInputStream(zipEntry);
+ count++;
+ }
+ assertEquals(5, count);
+ }
+
+ /*
+ * The content of Test.class is modified, jarFile.getInputStream will not
+ * throw security Exception, but it will anytime before the inputStream got
+ * from getInputStream method has been read to end.
+ */
+ public void test_JarFile_Modified_Class() throws IOException {
+ String modifiedJarName = "Modified_Class.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ jarFile.getInputStream(zipEntry);
+ }
+ /* The content of Test.class has been tampered. */
+ ZipEntry zipEntry = jarFile.getEntry("Test.class");
+ InputStream in = jarFile.getInputStream(zipEntry);
+ byte[] buffer = new byte[1024];
+ try {
+ while (in.available() > 0) {
+ in.read(buffer);
+ }
+ fail("SecurityException expected");
+ } catch (SecurityException e) {
+ // desired
+ }
+ }
+
+ /*
+ * In the Modified.jar, the main attributes of META-INF/MANIFEST.MF is
+ * tampered manually. Hence the RI 5.0 JarFile.getInputStream of any
+ * JarEntry will throw security exception.
+ */
+ public void test_JarFile_Modified_Manifest_MainAttributes()
+ throws IOException {
+ String modifiedJarName = "Modified_Manifest_MainAttributes.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ try {
+ jarFile.getInputStream(zipEntry);
+ fail("SecurityException expected");
+ } catch (SecurityException e) {
+ // desired
+ }
+ }
+ }
+
+ /*
+ * It is all right in our original JarFile. If the Entry Attributes, for
+ * example Test.class in our jar, the jarFile.getInputStream will throw
+ * Security Exception.
+ */
+ public void test_JarFile_Modified_Manifest_EntryAttributes()
+ throws IOException {
+ String modifiedJarName = "Modified_Manifest_EntryAttributes.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ try {
+ jarFile.getInputStream(zipEntry);
+ fail("should throw Security Exception");
+ } catch (SecurityException e) {
+ // desired
+ }
+ }
+ }
+
+ /*
+ * If the content of the .SA file is modified, no matter what it resides,
+ * JarFile.getInputStream of any JarEntry will throw Security Exception.
+ */
+ public void test_JarFile_Modified_SF_EntryAttributes() throws IOException {
+ String modifiedJarName = "Modified_SF_EntryAttributes.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry zipEntry = entries.nextElement();
+ try {
+ jarFile.getInputStream(zipEntry);
+ fail("should throw Security Exception");
+ } catch (SecurityException e) {
+ // desired
+ }
+ }
+ }
+
+ public void test_close() throws IOException {
+ String modifiedJarName = "Modified_SF_EntryAttributes.jar";
+ Support_Resources.copyFile(resources, null, modifiedJarName);
+ JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
+ true);
+ Enumeration<JarEntry> entries = jarFile.entries();
+
+ jarFile.close();
+ jarFile.close();
+
+ // Can not check IOException
+ }
+
+ /**
+ * @throws IOException
+ * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
+ */
+ public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException {
+ File localFile = null;
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ localFile = new File(resources, jarName);
+ } catch (Exception e) {
+ fail("Failed to create local file: " + e);
+ }
+
+ byte[] b = new byte[1024];
+ try {
+ JarFile jf = new JarFile(localFile);
+ java.io.InputStream is = jf.getInputStream(jf.getEntry(entryName));
+ // BEGIN android-removed
+ // jf.close();
+ // END android-removed
+ assertTrue("Returned invalid stream", is.available() > 0);
+ int r = is.read(b, 0, 1024);
+ is.close();
+ StringBuffer sb = new StringBuffer(r);
+ for (int i = 0; i < r; i++) {
+ sb.append((char) (b[i] & 0xff));
+ }
+ String contents = sb.toString();
+ assertTrue("Incorrect stream read", contents.indexOf("bar") > 0);
+ // BEGIN android-added
+ jf.close();
+ // END android-added
+ } catch (Exception e) {
+ fail("Exception during test: " + e.toString());
+ }
+
+ try {
+ JarFile jf = new JarFile(localFile);
+ InputStream in = jf.getInputStream(new JarEntry("invalid"));
+ assertNull("Got stream for non-existent entry", in);
+ } catch (Exception e) {
+ fail("Exception during test 2: " + e);
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ File signedFile = new File(resources, jarName);
+ JarFile jf = new JarFile(signedFile);
+ JarEntry jre = new JarEntry("foo/bar/A.class");
+ jf.getInputStream(jre);
+ // InputStream returned in any way, exception can be thrown in case
+ // of reading from this stream only.
+ // fail("Should throw ZipException");
+ } catch (ZipException ee) {
+ // expected
+ }
+
+ try {
+ Support_Resources.copyFile(resources, null, jarName);
+ File signedFile = new File(resources, jarName);
+ JarFile jf = new JarFile(signedFile);
+ JarEntry jre = new JarEntry("foo/bar/A.class");
+ jf.close();
+ jf.getInputStream(jre);
+ // InputStream returned in any way, exception can be thrown in case
+ // of reading from this stream only.
+ // The same for IOException
+ fail("Should throw IllegalStateException");
+ } catch (IllegalStateException ee) {
+ // expected
+ }
+ }
+
+ /**
+ * The jar is intact, but the entry object is modified.
+ */
+ // Regression test for issue introduced by HARMONY-4569: signed archives containing files with size 0 could not get verified.
+ public void testJarVerificationEmptyEntry() throws IOException {
+ Support_Resources.copyFile(resources, null, emptyEntryJar);
+ File f = new File(resources, emptyEntryJar);
+
+ JarFile jarFile = new JarFile(f);
+
+ ZipEntry zipEntry = jarFile.getJarEntry(emptyEntry1);
+ int res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
+ assertEquals("Wrong length of empty jar entry", -1, res);
+
+ zipEntry = jarFile.getJarEntry(emptyEntry2);
+ res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
+ assertEquals("Wrong length of empty jar entry", -1, res);
+
+ zipEntry = jarFile.getJarEntry(emptyEntry3);
+ res = jarFile.getInputStream(zipEntry).read();
+ assertEquals("Wrong length of empty jar entry", -1, res);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarInputStreamTest.java
new file mode 100644
index 0000000..9d4224a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarInputStreamTest.java
@@ -0,0 +1,406 @@
+/*
+ * 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.tests.java.util.jar;
+
+import tests.support.resource.Support_Resources;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+
+public class JarInputStreamTest extends junit.framework.TestCase {
+
+ private static final int DSA_INDEX = 2;
+
+ private static final int TEST_CLASS_INDEX = 4;
+
+ private static final int TOTAL_ENTRIES = 4;
+
+ private static final String A_CLASS = "foo/bar/A.class";
+
+ // a 'normal' jar file
+ private String jarName;
+
+ // same as patch.jar but without a manifest file
+ private String jarName2;
+
+ @Override
+ protected void setUp() {
+ jarName = Support_Resources.getURL("morestuff/hyts_patch.jar");
+ jarName2 = Support_Resources.getURL("morestuff/hyts_patch2.jar");
+ }
+
+ public void test_ConstructorLjava_io_InputStream() throws Exception {
+ // Test for method java.util.jar.JarInputStream(java.io.InputStream)
+ InputStream is = new URL(jarName).openConnection().getInputStream();
+ boolean hasCorrectEntry = false;
+ JarInputStream jis = new JarInputStream(is);
+ assertNotNull("The jar input stream should have a manifest", jis.getManifest());
+
+ JarEntry je = jis.getNextJarEntry();
+ while (je != null) {
+ if (je.getName().equals(A_CLASS)) {
+ hasCorrectEntry = true;
+ }
+ je = jis.getNextJarEntry();
+ }
+ assertTrue("The jar input stream does not contain the correct entries", hasCorrectEntry);
+ }
+
+ public void test_closeAfterException() throws Exception {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_entry.jar");
+ InputStream is = Support_Resources.getStream("Broken_entry.jar");
+ JarInputStream jis = new JarInputStream(is, false);
+ jis.getNextEntry();
+ try {
+ jis.getNextEntry();
+ fail("ZipException expected");
+ } catch (ZipException ee) {
+ // expected
+ }
+ jis.close();
+ try {
+ jis.getNextEntry();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+
+ public void test_getNextJarEntry_Ex() throws Exception {
+ final Set<String> desired = new HashSet<String>(Arrays
+ .asList("foo/", "foo/bar/", "foo/bar/A.class", "Blah.txt"));
+ Set<String> actual = new HashSet<String>();
+ InputStream is = new URL(jarName).openConnection().getInputStream();
+ JarInputStream jis = new JarInputStream(is);
+ JarEntry je = jis.getNextJarEntry();
+ while (je != null) {
+ actual.add(je.toString());
+ je = jis.getNextJarEntry();
+ }
+ assertEquals(actual, desired);
+ jis.close();
+
+ try {
+ jis.getNextJarEntry();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_entry.jar");
+ is = Support_Resources.getStream("Broken_entry.jar");
+ jis = new JarInputStream(is, false);
+ jis.getNextJarEntry();
+ try {
+ jis.getNextJarEntry();
+ fail("ZipException expected");
+ } catch (ZipException ee) {
+ // expected
+ }
+ }
+
+ public void test_getManifest() throws Exception {
+ // Test for method java.util.jar.Manifest
+ // java.util.jar.JarInputStream.getManifest()
+ Manifest m;
+ InputStream is = new URL(jarName2).openConnection().getInputStream();
+ JarInputStream jis = new JarInputStream(is);
+ m = jis.getManifest();
+ assertNull("The jar input stream should not have a manifest", m);
+
+ is = new URL(jarName).openConnection().getInputStream();
+ jis = new JarInputStream(is);
+ m = jis.getManifest();
+ assertNotNull("The jar input stream should have a manifest", m);
+ }
+
+ public void test_getNextJarEntry() throws Exception {
+ final Set<String> desired = new HashSet<String>(Arrays.asList(new String[] { "foo/",
+ "foo/bar/", A_CLASS, "Blah.txt" }));
+ Set<String> actual = new HashSet<String>();
+ InputStream is = new URL(jarName).openConnection().getInputStream();
+ JarInputStream jis = new JarInputStream(is);
+ JarEntry je = jis.getNextJarEntry();
+ while (je != null) {
+ actual.add(je.toString());
+ je = jis.getNextJarEntry();
+ }
+ assertEquals(actual, desired);
+ }
+
+ public void test_JarInputStream_Integrate_Jar_getNextEntry()
+ throws IOException {
+ String intJarName = Support_Resources.getURL("Integrate.jar");
+ InputStream is = new URL(intJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ ZipEntry entry = null;
+ int count = 0;
+ while (count == 0 || entry != null) {
+ count++;
+ entry = jin.getNextEntry();
+ }
+ assertEquals(TOTAL_ENTRIES + 1, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_Class_getNextEntry()
+ throws IOException {
+ String modJarName = Support_Resources.getURL("Modified_Class.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ ZipEntry zipEntry = null;
+
+ int count = 0;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ try {
+ zipEntry = jin.getNextEntry();
+ if (count == TEST_CLASS_INDEX + 1) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count != TEST_CLASS_INDEX + 1) {
+ throw e;
+ }
+
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 2, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_Manifest_MainAttributes_getNextEntry()
+ throws IOException {
+ String modJarName = Support_Resources.getURL("Modified_Manifest_MainAttributes.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+
+ assertEquals("META-INF/TESTROOT.SF", jin.getNextEntry().getName());
+ assertEquals("META-INF/TESTROOT.DSA", jin.getNextEntry().getName());
+ try {
+ jin.getNextEntry();
+ fail();
+ } catch (SecurityException expected) {
+ }
+ assertEquals("META-INF/", jin.getNextEntry().getName());
+ assertEquals("Test.class", jin.getNextEntry().getName());
+ assertNull(jin.getNextEntry());
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_Manifest_EntryAttributes_getNextEntry()
+ throws IOException {
+ String modJarName = Support_Resources
+ .getURL("Modified_Manifest_EntryAttributes.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ ZipEntry zipEntry = null;
+
+ int count = 0;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ try {
+ zipEntry = jin.getNextEntry();
+ if (count == DSA_INDEX + 1) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count != DSA_INDEX + 1) {
+ throw e;
+ }
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 2, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_SF_EntryAttributes_getNextEntry()
+ throws IOException {
+ String modJarName = Support_Resources
+ .getURL("Modified_SF_EntryAttributes.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ ZipEntry zipEntry = null;
+
+ int count = 0;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ try {
+ zipEntry = jin.getNextEntry();
+ if (count == DSA_INDEX + 1) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count != DSA_INDEX + 1) {
+ throw e;
+ }
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 2, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_Class_read() throws IOException {
+ String modJarName = Support_Resources.getURL("Modified_Class.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ int count = 0;
+ ZipEntry zipEntry = null;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ zipEntry = jin.getNextEntry();
+ byte[] buffer = new byte[1024];
+ try {
+ int length = 0;
+ while (length >= 0) {
+ length = jin.read(buffer);
+ }
+ if (count == TEST_CLASS_INDEX) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count < TEST_CLASS_INDEX) {
+ throw e;
+ }
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 1, count);
+ jin.close();
+ }
+
+ public void test_Integrate_Jar_read() throws IOException {
+ String intJarName = Support_Resources.getURL("Integrate.jar");
+ InputStream is = new URL(intJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ int count = 0;
+ ZipEntry zipEntry = null;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ zipEntry = jin.getNextEntry();
+ byte[] buffer = new byte[1024];
+ int length = 0;
+ while (length >= 0) {
+ length = jin.read(buffer);
+ }
+
+ }
+ assertEquals(TOTAL_ENTRIES + 1, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_Manifest_MainAttributes_read()
+ throws IOException {
+ String modJarName = Support_Resources
+ .getURL("Modified_Manifest_MainAttributes.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ int count = 0;
+ ZipEntry zipEntry = null;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ zipEntry = jin.getNextEntry();
+ byte[] buffer = new byte[1024];
+ try {
+ int length = 0;
+ while (length >= 0) {
+ length = jin.read(buffer);
+ }
+ if (count == DSA_INDEX) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count != DSA_INDEX) {
+ throw e;
+ }
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 1, count);
+ jin.close();
+ }
+
+ public void test_JarInputStream_Modified_SF_EntryAttributes_read()
+ throws IOException {
+ String modJarName = Support_Resources
+ .getURL("Modified_SF_EntryAttributes.jar");
+ InputStream is = new URL(modJarName).openConnection()
+ .getInputStream();
+ JarInputStream jin = new JarInputStream(is, true);
+ int count = 0;
+ ZipEntry zipEntry = null;
+ while (count == 0 || zipEntry != null) {
+ count++;
+ zipEntry = jin.getNextEntry();
+ byte[] buffer = new byte[1024];
+ try {
+ int length = 0;
+ while (length >= 0) {
+ length = jin.read(buffer);
+ }
+ if (count == DSA_INDEX) {
+ fail("Should throw Security Exception");
+ }
+ } catch (SecurityException e) {
+ if (count != DSA_INDEX) {
+ throw e;
+ }
+ }
+ }
+ assertEquals(TOTAL_ENTRIES + 1, count);
+ jin.close();
+ }
+
+ public void test_getNextEntry() throws Exception {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_entry.jar");
+ InputStream is = Support_Resources.getStream("Broken_entry.jar");
+ JarInputStream jis = new JarInputStream(is, false);
+ jis.getNextEntry();
+ try {
+ jis.getNextEntry();
+ fail("ZipException expected");
+ } catch (ZipException ee) {
+ // expected
+ }
+
+ try {
+ jis.close(); // Android throws exception here, already!
+ jis.getNextEntry(); // But RI here, only!
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarOutputStreamTest.java
new file mode 100644
index 0000000..37750db
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/JarOutputStreamTest.java
@@ -0,0 +1,91 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.jar.Attributes;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+
+public class JarOutputStreamTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.jar.JarOutputStream#putNextEntry(java.util.zip.ZipEntry)
+ */
+ public void test_putNextEntryLjava_util_zip_ZipEntry() throws Exception {
+
+ }
+
+ public void test_JarOutputStreamLjava_io_OutputStreamLjava_util_jar_Manifest()
+ throws IOException {
+ File fooJar = File.createTempFile("hyts_", ".jar");
+ fooJar.deleteOnExit();
+ File barZip = File.createTempFile("hyts_", ".zip");
+ barZip.deleteOnExit();
+
+ FileOutputStream fos = new FileOutputStream(fooJar);
+
+ Manifest man = new Manifest();
+ Attributes att = man.getMainAttributes();
+ att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+ att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
+ att.put(Attributes.Name.CLASS_PATH, barZip.getName());
+
+ fos.close();
+ try {
+ new JarOutputStream(fos, man);
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+
+ try {
+ new JarOutputStream(fos, null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException ee) {
+ // expected
+ }
+ }
+
+ public void test_JarOutputStreamLjava_io_OutputStream() throws IOException {
+ File fooJar = File.createTempFile("hyts_", ".jar");
+
+ FileOutputStream fos = new FileOutputStream(fooJar);
+ ZipEntry ze = new ZipEntry("Test");
+
+ try {
+ JarOutputStream joutFoo = new JarOutputStream(fos);
+ joutFoo.putNextEntry(ze);
+ joutFoo.write(33);
+ } catch (IOException ee) {
+ fail("IOException is not expected");
+ }
+
+ fos.close();
+ fooJar.delete();
+ try {
+ JarOutputStream joutFoo = new JarOutputStream(fos);
+ joutFoo.putNextEntry(ze);
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/ManifestTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/ManifestTest.java
new file mode 100644
index 0000000..c4d7735
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/jar/ManifestTest.java
@@ -0,0 +1,456 @@
+/*
+ * 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.tests.java.util.jar;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+import junit.framework.TestCase;
+
+import tests.support.resource.Support_Resources;
+
+public class ManifestTest extends TestCase {
+
+ private final String JAR_NAME = "hyts_patch.jar";
+
+ private final String ATT_JAR_NAME = "hyts_att.jar";
+
+ private final String ATT_ENTRY_NAME = "HasAttributes.txt";
+
+ private final String ATT_ATT_NAME = "MyAttribute";
+
+ private final String MANIFEST_NAME = "manifest/hyts_MANIFEST.MF";
+
+ private static final String MANIFEST_CONTENTS = "Manifest-Version: 1.0\nBundle-Name: ClientSupport\nBundle-Description: Provides SessionService, AuthenticationService. Extends RegistryService.\nBundle-Activator: com.ibm.ive.eccomm.client.support.ClientSupportActivator\nImport-Package: com.ibm.ive.eccomm.client.services.log,\n com.ibm.ive.eccomm.client.services.registry,\n com.ibm.ive.eccomm.service.registry; specification-version=1.0.0,\n com.ibm.ive.eccomm.service.session; specification-version=1.0.0,\n com.ibm.ive.eccomm.service.framework; specification-version=1.2.0,\n org.osgi.framework; specification-version=1.0.0,\n org.osgi.service.log; specification-version=1.0.0,\n com.ibm.ive.eccomm.flash; specification-version=1.2.0,\n com.ibm.ive.eccomm.client.xml,\n com.ibm.ive.eccomm.client.http.common,\n com.ibm.ive.eccomm.client.http.client\nImport-Service: org.osgi.service.log.LogReaderService\n org.osgi.service.log.LogService,\n com.ibm.ive.eccomm.service.registry.RegistryService\nExport-Package: com.ibm.ive.eccomm.client.services.authentication; specification-version=1.0.0,\n com.ibm.ive.eccomm.service.authentication; specification-version=1.0.0,\n com.ibm.ive.eccomm.common; specification-version=1.0.0,\n com.ibm.ive.eccomm.client.services.registry.store; specification-version=1.0.0\nExport-Service: com.ibm.ive.eccomm.service.authentication.AuthenticationService,\n com.ibm.ive.eccomm.service.session.SessionService\nBundle-Vendor: IBM\nBundle-Version: 1.2.0\n";
+
+ private static final String MANIFEST_CONTENTS_1 = "Manifest-Version: 2.0\nBundle-Name: ClientSupport\nBundle-Description: Provides SessionService, AuthenticationService. Extends RegistryService.\nBundle-Activator: com.ibm.ive.eccomm.client.support.ClientSupportActivator\nImport-Package: com.ibm.ive.eccomm.client.services.log,\n com.ibm.ive.eccomm.client.services.registry,\n com.ibm.ive.eccomm.service.registry; specification-version=2.0.0,\n com.ibm.ive.eccomm.service.session; specification-version=2.0.0,\n com.ibm.ive.eccomm.service.framework; specification-version=2.1.0,\n org.osgi.framework; specification-version=2.0.0,\n org.osgi.service.log; specification-version=2.0.0,\n com.ibm.ive.eccomm.flash; specification-version=2.2.0,\n com.ibm.ive.eccomm.client.xml,\n com.ibm.ive.eccomm.client.http.common,\n com.ibm.ive.eccomm.client.http.client\nImport-Service: org.osgi.service.log.LogReaderService\n org.osgi.service.log.LogService,\n com.ibm.ive.eccomm.service.registry.RegistryService\nExport-Package: com.ibm.ive.eccomm.client.services.authentication; specification-version=1.0.0,\n com.ibm.ive.eccomm.service.authentication; specification-version=1.0.0,\n com.ibm.ive.eccomm.common; specification-version=1.0.0,\n com.ibm.ive.eccomm.client.services.registry.store; specification-version=1.0.0\nExport-Service: com.ibm.ive.eccomm.service.authentication.AuthenticationService,\n com.ibm.ive.eccomm.service.session.SessionService\nBundle-Vendor: IBM\nBundle-Version: 1.2.0\n";
+
+ private static final String MANIFEST_CONTENTS_2 = "Manifest-Version: 1.0\nName: value\n \n"; // Note penultimate line is single space
+
+ private File resources;
+
+ @Override
+ protected void setUp() {
+ resources = Support_Resources.createTempFolder();
+ }
+
+ private Manifest getManifest(String fileName) {
+ try {
+ Support_Resources.copyFile(resources, null, fileName);
+ JarFile jarFile = new JarFile(new File(resources, fileName));
+ Manifest m = jarFile.getManifest();
+ jarFile.close();
+ return m;
+ } catch (Exception e) {
+ fail("Exception during setup: " + e.toString());
+ return null;
+ }
+ }
+
+ /**
+ * java.util.jar.Manifest#Manifest()
+ */
+ public void testConstructor() {
+ // Test for method java.util.jar.Manifest()
+ Manifest emptyManifest = new Manifest();
+ assertTrue("Should have no entries", emptyManifest.getEntries()
+ .isEmpty());
+ assertTrue("Should have no main attributes", emptyManifest
+ .getMainAttributes().isEmpty());
+ }
+
+ /**
+ * java.util.jar.Manifest#Manifest(java.util.jar.Manifest)
+ */
+ public void testCopyingConstructor() throws IOException {
+ Manifest firstManifest = new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS.getBytes("ISO-8859-1")));
+ Manifest secondManifest = new Manifest(firstManifest);
+ assertEquals(firstManifest, secondManifest);
+ }
+
+ private void assertAttribute(Attributes attr, String name, String value) {
+ assertEquals("Incorrect " + name, value, attr.getValue(name));
+ }
+
+ private void checkManifest(Manifest manifest) {
+ Attributes main = manifest.getMainAttributes();
+ assertAttribute(main, "Bundle-Name", "ClientSupport");
+ assertAttribute(main, "Bundle-Description",
+ "Provides SessionService, AuthenticationService. Extends RegistryService.");
+ assertAttribute(main, "Bundle-Activator",
+ "com.ibm.ive.eccomm.client.support.ClientSupportActivator");
+ assertAttribute(
+ main,
+ "Import-Package",
+ "com.ibm.ive.eccomm.client.services.log,com.ibm.ive.eccomm.client.services.registry,com.ibm.ive.eccomm.service.registry; specification-version=1.0.0,com.ibm.ive.eccomm.service.session; specification-version=1.0.0,com.ibm.ive.eccomm.service.framework; specification-version=1.2.0,org.osgi.framework; specification-version=1.0.0,org.osgi.service.log; specification-version=1.0.0,com.ibm.ive.eccomm.flash; specification-version=1.2.0,com.ibm.ive.eccomm.client.xml,com.ibm.ive.eccomm.client.http.common,com.ibm.ive.eccomm.client.http.client");
+ assertAttribute(
+ main,
+ "Import-Service",
+ "org.osgi.service.log.LogReaderServiceorg.osgi.service.log.LogService,com.ibm.ive.eccomm.service.registry.RegistryService");
+ assertAttribute(
+ main,
+ "Export-Package",
+ "com.ibm.ive.eccomm.client.services.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.service.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.common; specification-version=1.0.0,com.ibm.ive.eccomm.client.services.registry.store; specification-version=1.0.0");
+ assertAttribute(
+ main,
+ "Export-Service",
+ "com.ibm.ive.eccomm.service.authentication.AuthenticationService,com.ibm.ive.eccomm.service.session.SessionService");
+ assertAttribute(main, "Bundle-Vendor", "IBM");
+ assertAttribute(main, "Bundle-Version", "1.2.0");
+ }
+
+ /**
+ * java.util.jar.Manifest#Manifest(java.io.InputStream)
+ */
+ public void testStreamConstructor() throws IOException {
+ Manifest m = getManifest(ATT_JAR_NAME);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ m.write(baos);
+ InputStream is = new ByteArrayInputStream(baos.toByteArray());
+ Manifest mCopy = new Manifest(is);
+ assertEquals(m, mCopy);
+
+ Manifest manifest = new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS.getBytes("ISO-8859-1")));
+ checkManifest(manifest);
+
+ // regression test for HARMONY-5424
+ String manifestContent = "Manifest-Version: 1.0\nCreated-By: Apache\nPackage: \nBuild-Jdk: 1.4.1_01\n\n"
+ + "Name: \nSpecification-Title: foo\nSpecification-Version: 1.0\nSpecification-Vendor: \n"
+ + "Implementation-Title: \nImplementation-Version: 1.0\nImplementation-Vendor: \n\n";
+ ByteArrayInputStream bis = new ByteArrayInputStream(manifestContent
+ .getBytes("ISO-8859-1"));
+
+
+ Manifest mf = new Manifest(bis);
+ assertEquals("Should be 4 main attributes", 4, mf.getMainAttributes()
+ .size());
+
+ Map<String, Attributes> entries = mf.getEntries();
+ assertEquals("Should be one named entry", 1, entries.size());
+
+ Attributes namedEntryAttributes = (Attributes) (entries.get(""));
+ assertEquals("Should be 6 named entry attributes", 6,
+ namedEntryAttributes.size());
+
+ // Regression test for HARMONY-6669
+ new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS_2.getBytes("ISO-8859-1")));
+ }
+
+ /**
+ * java.util.jar.Manifest#clear()
+ */
+ public void testClear() {
+ Manifest m = getManifest(ATT_JAR_NAME);
+ m.clear();
+ assertTrue("Should have no entries", m.getEntries().isEmpty());
+ assertTrue("Should have no main attributes", m.getMainAttributes()
+ .isEmpty());
+ }
+
+ /**
+ * java.util.jar.Manifest#clone()
+ */
+ public void testClone() {
+ Manifest m = getManifest(JAR_NAME);
+ assertEquals(m, m.clone());
+ }
+
+ /**
+ * java.util.jar.Manifest#equals(java.lang.Object)
+ */
+ public void testEquals() throws IOException {
+ Manifest firstManifest = new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS.getBytes("ISO-8859-1")));
+ Manifest secondManifest = new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS.getBytes("ISO-8859-1")));
+
+ assertEquals(firstManifest, secondManifest);
+
+ Manifest thirdManifest = new Manifest(new ByteArrayInputStream(
+ MANIFEST_CONTENTS_1.getBytes("ISO-8859-1")));
+ assertNotSame(firstManifest, thirdManifest);
+
+ firstManifest = null;
+ assertFalse(secondManifest.equals(firstManifest));
+ assertFalse(secondManifest.equals(new String("abc"))); //non Manifest Object
+ }
+
+ /**
+ * java.util.jar.Manifest#hashCode()
+ */
+ public void testHashCode() {
+ Manifest m = getManifest(JAR_NAME);
+ assertEquals(m.hashCode(), m.clone().hashCode());
+ }
+
+ /**
+ * java.util.jar.Manifest#getAttributes(java.lang.String)
+ */
+ public void testGetAttributes() {
+ Manifest m = getManifest(ATT_JAR_NAME);
+ assertNull("Should not exist", m.getAttributes("Doesn't Exist"));
+ assertEquals("Should exist", "OK", m.getAttributes(ATT_ENTRY_NAME).get(
+ new Attributes.Name(ATT_ATT_NAME)));
+ }
+
+ /**
+ * java.util.jar.Manifest#getEntries()
+ */
+ public void testGetEntries() {
+ Manifest m = getManifest(ATT_JAR_NAME);
+ Map<String, Attributes> myMap = m.getEntries();
+ assertNull("Shouldn't exist", myMap.get("Doesn't exist"));
+ assertEquals("Should exist", "OK", myMap.get(ATT_ENTRY_NAME).get(
+ new Attributes.Name(ATT_ATT_NAME)));
+ }
+
+ /**
+ * java.util.jar.Manifest#getMainAttributes()
+ */
+ public void testGetMainAttributes() {
+ Manifest m = getManifest(JAR_NAME);
+ Attributes a = m.getMainAttributes();
+ assertEquals("Manifest_Version should return 1.0", "1.0", a
+ .get(Attributes.Name.MANIFEST_VERSION));
+ }
+
+ /**
+ * {@link java.util.jar.Manifest#write(java.io.OutputStream)
+ */
+ public void testWrite() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Manifest m = getManifest(JAR_NAME);
+ // maximum allowed length is 72 for a header, colon and a following
+ // space
+ StringBuffer headerName = new StringBuffer(71);
+ headerName.append("Manifest-");
+ while (headerName.length() < 70) {
+ headerName.append("0");
+ }
+ m.getMainAttributes().put(new Attributes.Name(headerName.toString()),
+ "Value");
+ m.write(baos); // ok
+ }
+
+ /**
+ * Ensures compatibility with manifests produced by gcc.
+ *
+ * @see <a
+ * href="http://issues.apache.org/jira/browse/HARMONY-5662">HARMONY-5662</a>
+ */
+ public void testNul() throws IOException {
+ String manifestContent =
+ "Manifest-Version: 1.0\nCreated-By: nasty gcc tool\n\n\0";
+
+ byte[] bytes = manifestContent.getBytes("ISO-8859-1");
+ new Manifest(new ByteArrayInputStream(bytes)); // the last NUL is ok
+
+ bytes[bytes.length - 1] = 26;
+ new Manifest(new ByteArrayInputStream(bytes)); // the last EOF is ok
+
+ bytes[bytes.length - 1] = 'A'; // the last line ignored
+ new Manifest(new ByteArrayInputStream(bytes));
+
+ bytes[2] = 0; // NUL char in Manifest
+ try {
+ new Manifest(new ByteArrayInputStream(bytes));
+ fail("IOException expected");
+ } catch (IOException e) {
+ // desired
+ }
+ }
+
+ public void testDecoding() throws IOException {
+ Manifest m = getManifest(ATT_JAR_NAME);
+ final byte[] bVendor = new byte[] { (byte) 0xd0, (byte) 0x9C,
+ (byte) 0xd0, (byte) 0xb8, (byte) 0xd0, (byte) 0xbb,
+ (byte) 0xd0, (byte) 0xb0, (byte) 0xd1, (byte) 0x8f, ' ',
+ (byte) 0xd0, (byte) 0xb4, (byte) 0xd0, (byte) 0xbe,
+ (byte) 0xd1, (byte) 0x87, (byte) 0xd1, (byte) 0x83,
+ (byte) 0xd0, (byte) 0xbd, (byte) 0xd1, (byte) 0x8C,
+ (byte) 0xd0, (byte) 0xba, (byte) 0xd0, (byte) 0xb0, ' ',
+ (byte) 0xd0, (byte) 0x9C, (byte) 0xd0, (byte) 0xb0,
+ (byte) 0xd1, (byte) 0x88, (byte) 0xd0, (byte) 0xb0 };
+
+ final byte[] bSpec = new byte[] { (byte) 0xe1, (byte) 0x88,
+ (byte) 0xb0, (byte) 0xe1, (byte) 0x88, (byte) 0x8b,
+ (byte) 0xe1, (byte) 0x88, (byte) 0x9d, ' ', (byte) 0xe1,
+ (byte) 0x9a, (byte) 0xa0, (byte) 0xe1, (byte) 0x9a,
+ (byte) 0xb1, (byte) 0xe1, (byte) 0x9b, (byte) 0x81,
+ (byte) 0xe1, (byte) 0x9a, (byte) 0xa6, ' ', (byte) 0xd8,
+ (byte) 0xb3, (byte) 0xd9, (byte) 0x84, (byte) 0xd8,
+ (byte) 0xa7, (byte) 0xd9, (byte) 0x85, ' ', (byte) 0xd8,
+ (byte) 0xb9, (byte) 0xd8, (byte) 0xb3, (byte) 0xd9,
+ (byte) 0x84, (byte) 0xd8, (byte) 0xa7, (byte) 0xd9,
+ (byte) 0x85, (byte) 0xd8, (byte) 0xa9, ' ', (byte) 0xdc,
+ (byte) 0xab, (byte) 0xdc, (byte) 0xa0, (byte) 0xdc,
+ (byte) 0xa1, (byte) 0xdc, (byte) 0x90, ' ', (byte) 0xe0,
+ (byte) 0xa6, (byte) 0xb6, (byte) 0xe0, (byte) 0xa6,
+ (byte) 0xbe, (byte) 0xe0, (byte) 0xa6, (byte) 0xa8,
+ (byte) 0xe0, (byte) 0xa7, (byte) 0x8d, (byte) 0xe0,
+ (byte) 0xa6, (byte) 0xa4, (byte) 0xe0, (byte) 0xa6,
+ (byte) 0xbf, ' ', (byte) 0xd0, (byte) 0xa0, (byte) 0xd0,
+ (byte) 0xb5, (byte) 0xd0, (byte) 0xba, (byte) 0xd1,
+ (byte) 0x8a, (byte) 0xd0, (byte) 0xb5, (byte) 0xd0,
+ (byte) 0xbb, ' ', (byte) 0xd0, (byte) 0x9c, (byte) 0xd0,
+ (byte) 0xb8, (byte) 0xd1, (byte) 0x80, ' ', (byte) 0xe0,
+ (byte) 0xa6, (byte) 0xb6, (byte) 0xe0, (byte) 0xa6,
+ (byte) 0xbe, (byte) 0xe0, (byte) 0xa6, (byte) 0xa8,
+ (byte) 0xe0, (byte) 0xa7, (byte) 0x8d, (byte) 0xe0,
+ (byte) 0xa6, (byte) 0xa4, (byte) 0xe0, (byte) 0xa6,
+ (byte) 0xbf, ' ', (byte) 0xe0, (byte) 0xbd, (byte) 0x9e,
+ (byte) 0xe0, (byte) 0xbd, (byte) 0xb2, (byte) 0xe0,
+ (byte) 0xbc, (byte) 0x8b, (byte) 0xe0, (byte) 0xbd,
+ (byte) 0x96, (byte) 0xe0, (byte) 0xbd, (byte) 0x91,
+ (byte) 0xe0, (byte) 0xbd, (byte) 0xba, ' ', (byte) 0xd0,
+ (byte) 0x9c, (byte) 0xd0, (byte) 0xb0, (byte) 0xd1,
+ (byte) 0x88, (byte) 0xd0, (byte) 0xb0, (byte) 0xd1,
+ (byte) 0x80, ' ', (byte) 0xe1, (byte) 0x8f, (byte) 0x99,
+ (byte) 0xe1, (byte) 0x8e, (byte) 0xaf, (byte) 0xe1,
+ (byte) 0x8f, (byte) 0xb1, ' ', (byte) 0xcf, (byte) 0xa8,
+ (byte) 0xce, (byte) 0xb9, (byte) 0xcf, (byte) 0x81,
+ (byte) 0xce, (byte) 0xb7, (byte) 0xce, (byte) 0xbd,
+ (byte) 0xce, (byte) 0xb7, ' ', (byte) 0xde, (byte) 0x90,
+ (byte) 0xde, (byte) 0xaa, (byte) 0xde, (byte) 0x85,
+ (byte) 0xde, (byte) 0xa6, ' ', (byte) 0xe0, (byte) 0xbd,
+ (byte) 0x82, (byte) 0xe0, (byte) 0xbd, (byte) 0x9e,
+ (byte) 0xe0, (byte) 0xbd, (byte) 0xb2, (byte) 0xe0,
+ (byte) 0xbc, (byte) 0x8b, (byte) 0xe0, (byte) 0xbd,
+ (byte) 0x96, (byte) 0xe0, (byte) 0xbd, (byte) 0x91,
+ (byte) 0xe0, (byte) 0xbd, (byte) 0xba, ' ', (byte) 0xce,
+ (byte) 0x95, (byte) 0xce, (byte) 0xb9, (byte) 0xcf,
+ (byte) 0x81, (byte) 0xce, (byte) 0xae, (byte) 0xce,
+ (byte) 0xbd, (byte) 0xce, (byte) 0xb7, ' ', (byte) 0xd8,
+ (byte) 0xb5, (byte) 0xd9, (byte) 0x84, (byte) 0xd8,
+ (byte) 0xad, ' ', (byte) 0xe0, (byte) 0xaa, (byte) 0xb6,
+ (byte) 0xe0, (byte) 0xaa, (byte) 0xbe, (byte) 0xe0,
+ (byte) 0xaa, (byte) 0x82, (byte) 0xe0, (byte) 0xaa,
+ (byte) 0xa4, (byte) 0xe0, (byte) 0xaa, (byte) 0xbf, ' ',
+ (byte) 0xe5, (byte) 0xb9, (byte) 0xb3, (byte) 0xe5,
+ (byte) 0x92, (byte) 0x8c, ' ', (byte) 0xd7, (byte) 0xa9,
+ (byte) 0xd7, (byte) 0x9c, (byte) 0xd7, (byte) 0x95,
+ (byte) 0xd7, (byte) 0x9d, ' ', (byte) 0xd7, (byte) 0xa4,
+ (byte) 0xd7, (byte) 0xa8, (byte) 0xd7, (byte) 0x99,
+ (byte) 0xd7, (byte) 0x93, (byte) 0xd7, (byte) 0x9f, ' ',
+ (byte) 0xe5, (byte) 0x92, (byte) 0x8c, (byte) 0xe5,
+ (byte) 0xb9, (byte) 0xb3, ' ', (byte) 0xe5, (byte) 0x92,
+ (byte) 0x8c, (byte) 0xe5, (byte) 0xb9, (byte) 0xb3, ' ',
+ (byte) 0xd8, (byte) 0xaa, (byte) 0xd9, (byte) 0x89,
+ (byte) 0xd9, (byte) 0x86, (byte) 0xda, (byte) 0x86,
+ (byte) 0xd9, (byte) 0x84, (byte) 0xd9, (byte) 0x89,
+ (byte) 0xd9, (byte) 0x82, ' ', (byte) 0xe0, (byte) 0xae,
+ (byte) 0x85, (byte) 0xe0, (byte) 0xae, (byte) 0xae,
+ (byte) 0xe0, (byte) 0xaf, (byte) 0x88, (byte) 0xe0,
+ (byte) 0xae, (byte) 0xa4, (byte) 0xe0, (byte) 0xae,
+ (byte) 0xbf, ' ', (byte) 0xe0, (byte) 0xb0, (byte) 0xb6,
+ (byte) 0xe0, (byte) 0xb0, (byte) 0xbe, (byte) 0xe0,
+ (byte) 0xb0, (byte) 0x82, (byte) 0xe0, (byte) 0xb0,
+ (byte) 0xa4, (byte) 0xe0, (byte) 0xb0, (byte) 0xbf, ' ',
+ (byte) 0xe0, (byte) 0xb8, (byte) 0xaa, (byte) 0xe0,
+ (byte) 0xb8, (byte) 0xb1, (byte) 0xe0, (byte) 0xb8,
+ (byte) 0x99, (byte) 0xe0, (byte) 0xb8, (byte) 0x95,
+ (byte) 0xe0, (byte) 0xb8, (byte) 0xb4, (byte) 0xe0,
+ (byte) 0xb8, (byte) 0xa0, (byte) 0xe0, (byte) 0xb8,
+ (byte) 0xb2, (byte) 0xe0, (byte) 0xb8, (byte) 0x9e, ' ',
+ (byte) 0xe1, (byte) 0x88, (byte) 0xb0, (byte) 0xe1,
+ (byte) 0x88, (byte) 0x8b, (byte) 0xe1, (byte) 0x88,
+ (byte) 0x9d, ' ', (byte) 0xe0, (byte) 0xb7, (byte) 0x83,
+ (byte) 0xe0, (byte) 0xb7, (byte) 0x8f, (byte) 0xe0,
+ (byte) 0xb6, (byte) 0xb8, (byte) 0xe0, (byte) 0xb6,
+ (byte) 0xba, ' ', (byte) 0xe0, (byte) 0xa4, (byte) 0xb6,
+ (byte) 0xe0, (byte) 0xa4, (byte) 0xbe, (byte) 0xe0,
+ (byte) 0xa4, (byte) 0xa8, (byte) 0xe0, (byte) 0xa5,
+ (byte) 0x8d, (byte) 0xe0, (byte) 0xa4, (byte) 0xa4,
+ (byte) 0xe0, (byte) 0xa4, (byte) 0xbf, (byte) 0xe0,
+ (byte) 0xa4, (byte) 0x83, ' ', (byte) 0xe1, (byte) 0x83,
+ (byte) 0x9b, (byte) 0xe1, (byte) 0x83, (byte) 0xa8,
+ (byte) 0xe1, (byte) 0x83, (byte) 0x95, (byte) 0xe1,
+ (byte) 0x83, (byte) 0x98, (byte) 0xe1, (byte) 0x83,
+ (byte) 0x93, (byte) 0xe1, (byte) 0x83, (byte) 0x9d,
+ (byte) 0xe1, (byte) 0x83, (byte) 0x91, (byte) 0xe1,
+ (byte) 0x83, (byte) 0x90 };
+ // TODO Cannot make the following word work, encoder changes needed
+ // (byte) 0xed, (byte) 0xa0, (byte) 0x80,
+ // (byte) 0xed, (byte) 0xbc, (byte) 0xb2, (byte) 0xed,
+ // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
+ // (byte) 0xb0, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
+ // (byte) 0xed, (byte) 0xbd, (byte) 0x85, (byte) 0xed,
+ // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
+ // (byte) 0xb0, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
+ // (byte) 0xed, (byte) 0xbc, (byte) 0xb9, (byte) 0xed,
+ // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
+ // (byte) 0xb8, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
+ // (byte) 0xed, (byte) 0xbc, (byte) 0xb9, ' '
+
+ final String vendor = new String(bVendor, "UTF-8");
+ final String spec = new String(bSpec, "UTF-8");
+ m.getMainAttributes()
+ .put(Attributes.Name.IMPLEMENTATION_VENDOR, vendor);
+ m.getAttributes(ATT_ENTRY_NAME).put(
+ Attributes.Name.IMPLEMENTATION_VENDOR, vendor);
+ m.getEntries().get(ATT_ENTRY_NAME).put(
+ Attributes.Name.SPECIFICATION_TITLE, spec);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ m.write(baos);
+ m = new Manifest(new ByteArrayInputStream(baos.toByteArray()));
+
+ assertEquals(vendor, m.getMainAttributes().get(
+ Attributes.Name.IMPLEMENTATION_VENDOR));
+ assertEquals(vendor, m.getEntries().get(ATT_ENTRY_NAME).get(
+ Attributes.Name.IMPLEMENTATION_VENDOR));
+ assertEquals(spec, m.getAttributes(ATT_ENTRY_NAME).get(
+ Attributes.Name.SPECIFICATION_TITLE));
+ }
+
+ /**
+ * {@link java.util.jar.Manifest#read(java.io.InputStream)
+ */
+ public void testRead() {
+ // Regression for HARMONY-89
+ InputStream is = new InputStreamImpl();
+ try {
+ new Manifest().read(is);
+ fail("IOException expected");
+ } catch (IOException e) {
+ // desired
+ }
+ }
+
+ // helper class
+ private class InputStreamImpl extends InputStream {
+ public InputStreamImpl() {
+ super();
+ }
+
+ @Override
+ public int read() {
+ return 0;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/AbstractPreferencesTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/AbstractPreferencesTest.java
new file mode 100644
index 0000000..98476f5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/AbstractPreferencesTest.java
@@ -0,0 +1,1699 @@
+/*
+ * 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.tests.java.util.prefs;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.prefs.AbstractPreferences;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.FilePreferencesImpl;
+import java.util.prefs.NodeChangeEvent;
+import java.util.prefs.NodeChangeListener;
+import java.util.prefs.PreferenceChangeEvent;
+import java.util.prefs.PreferenceChangeListener;
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import junit.framework.TestCase;
+import libcore.io.IoUtils;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+
+public class AbstractPreferencesTest extends TestCase {
+
+ public static final class TestPreferencesFactory implements PreferencesFactory {
+ private final Preferences userPrefs;
+ private final Preferences systemPrefs;
+
+ public TestPreferencesFactory(String root) {
+ userPrefs = new FilePreferencesImpl(root + "/user", true);
+ systemPrefs = new FilePreferencesImpl(root + "/system", false);
+ }
+
+ public Preferences userRoot() {
+ return userPrefs;
+ }
+
+ public Preferences systemRoot() {
+ return systemPrefs;
+ }
+ }
+
+ private AbstractPreferences pref;
+ private AbstractPreferences root;
+ private AbstractPreferences parent;
+ private PreferencesFactory defaultFactory;
+
+ private final static String LONG_KEY;
+ private final static String LONG_VALUE;
+ private final static String LONG_NAME;
+
+ static {
+ final byte[] chars = new byte[Preferences.MAX_VALUE_LENGTH];
+
+ LONG_VALUE = new String(chars, StandardCharsets.US_ASCII);
+ LONG_KEY = LONG_VALUE.substring(0, Preferences.MAX_KEY_LENGTH);
+ LONG_NAME = LONG_VALUE.substring(0, Preferences.MAX_NAME_LENGTH);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ File tmpDir = IoUtils.createTemporaryDirectory("OldAbstractPreferencesTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new TestPreferencesFactory(tmpDir.getAbsolutePath()));
+ root = (AbstractPreferences) Preferences.userRoot();
+ parent = (AbstractPreferences) Preferences.userNodeForPackage(Preferences.class);
+
+ pref = (AbstractPreferences) parent.node("mock");
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ }
+
+ public void testConstructor() throws BackingStoreException {
+ try {
+ pref = new MockAbstractPreferences(
+ (AbstractPreferences) Preferences.userRoot(), "mo/ck");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ pref = new MockAbstractPreferences(null, "mock");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ new MockAbstractPreferences(null, " ");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ new MockAbstractPreferences(pref, "");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ new MockAbstractPreferences(pref, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ new MockAbstractPreferences(pref, " ");
+
+ Preferences p2 = new MockAbstractPreferences(null, "");
+ assertNotSame(p2, Preferences.systemRoot());
+ assertNotSame(p2, Preferences.userRoot());
+ assertFalse(p2.isUserNode());
+
+ p2 = new MockAbstractPreferences((AbstractPreferences) Preferences
+ .userRoot(), "mock");
+ assertNotSame(p2, pref);
+ p2.removeNode();
+ }
+
+ public void testProtectedFields() throws BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = new MockAbstractPreferences(pref, "newNode");
+ assertFalse(p.getNewNode());
+ assertSame(p.getLock().getClass(), Object.class);
+
+ p = (MockAbstractPreferences) pref.node("child");
+ assertTrue(p.getNewNode());
+
+ p = (MockAbstractPreferences) ((MockAbstractPreferences) pref)
+ .publicChildSpi("child2");
+ assertTrue(p.getNewNode());
+ }
+
+ public void testToString() {
+ assertEquals("User Preference Node: " + pref.absolutePath(), pref
+ .toString());
+
+ pref = new MockAbstractPreferences((AbstractPreferences) Preferences
+ .systemRoot(), "mock");
+ assertEquals("System Preference Node: " + pref.absolutePath(), pref
+ .toString());
+ }
+
+ public void testAbsolutePath() {
+ assertEquals("/java/util/prefs/mock", pref.absolutePath());
+
+ pref = new MockAbstractPreferences(pref, " ");
+ assertEquals("/java/util/prefs/mock/ ", pref.absolutePath());
+ }
+
+ public void testChildrenNames() throws BackingStoreException {
+ assertEquals(0, pref.childrenNames().length);
+
+ // MockAbstractPreferences child1 = new MockAbstractPreferences(pref,
+ // "child1");
+ // MockAbstractPreferences child2 = new MockAbstractPreferences(pref,
+ // "child2");
+ // MockAbstractPreferences child3 = new MockAbstractPreferences(pref,
+ // "child3");
+ // MockAbstractPreferences subchild1 = new
+ // MockAbstractPreferences(child1,
+ // "subchild1");
+ Preferences child1 = pref.node("child1");
+
+ pref.node("child2");
+ pref.node("child3");
+ child1.node("subchild1");
+
+ assertSame(pref, child1.parent());
+ assertEquals(3, pref.childrenNames().length);
+ }
+
+ public void testClear() throws BackingStoreException {
+ pref.put("testClearKey", "testClearValue");
+ pref.put("testClearKey1", "testClearValue1");
+ assertEquals("testClearValue", pref.get("testClearKey", null));
+ assertEquals("testClearValue1", pref.get("testClearKey1", null));
+ pref.clear();
+ assertNull(pref.get("testClearKey", null));
+ assertNull(pref.get("testClearKey1", null));
+ }
+
+ public void testGet() throws BackingStoreException {
+ assertNull(pref.get("", null));
+ assertEquals("default", pref.get("key", "default"));
+ assertNull(pref.get("key", null));
+ pref.put("testGetkey", "value");
+ assertNull(pref.get("testGetKey", null));
+ assertEquals("value", pref.get("testGetkey", null));
+
+ try {
+ pref.get(null, "abc");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.get("", "abc");
+ pref.get("key", null);
+ pref.get("key", "");
+ pref.putFloat("floatKey", 1.0f);
+ assertEquals("1.0", pref.get("floatKey", null));
+
+ pref.removeNode();
+ try {
+ pref.get("key", "abc");
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.get(null, "abc");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testGetBoolean() {
+ try {
+ pref.getBoolean(null, false);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.put("testGetBooleanKey", "false");
+ pref.put("testGetBooleanKey2", "value");
+ assertFalse(pref.getBoolean("testGetBooleanKey", true));
+ assertTrue(pref.getBoolean("testGetBooleanKey2", true));
+ }
+
+ public void testPutByteArray() {
+ try {
+ pref.putByteArray(null, new byte[0]);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ pref.putByteArray("testPutByteArrayKey4", null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putByteArray(LONG_KEY, new byte[0]);
+ try {
+ pref.putByteArray(LONG_KEY + "a", new byte[0]);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ byte[] longArray = new byte[(int) (Preferences.MAX_VALUE_LENGTH * 0.74)];
+ byte[] longerArray = new byte[(int) (Preferences.MAX_VALUE_LENGTH * 0.75) + 1];
+ pref.putByteArray(LONG_KEY, longArray);
+ try {
+ pref.putByteArray(LONG_KEY, longerArray);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putByteArray("testPutByteArrayKey", new byte[0]);
+ assertEquals("", pref.get("testPutByteArrayKey", null));
+ assertTrue(Arrays.equals(new byte[0], pref.getByteArray(
+ "testPutByteArrayKey", null)));
+
+ pref.putByteArray("testPutByteArrayKey3", new byte[] { 'a', 'b', 'c' });
+ assertEquals("YWJj", pref.get("testPutByteArrayKey3", null));
+ assertTrue(Arrays.equals(new byte[] { 'a', 'b', 'c' }, pref
+ .getByteArray("testPutByteArrayKey3", null)));
+ }
+
+ public void testGetByteArray() throws UnsupportedEncodingException {
+ try {
+ pref.getByteArray(null, new byte[0]);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ byte[] b64Array = new byte[] { 0x59, 0x57, 0x4a, 0x6a };// BASE64
+ // encoding for
+ // "abc"
+
+ pref.put("testGetByteArrayKey", "abc=");
+ pref.put("testGetByteArrayKey2", new String(b64Array, "UTF-8"));
+ pref.put("invalidKey", "<>?");
+ // assertTrue(Arrays.equals(new byte[0], p.getByteArray(
+ // "testGetByteArrayKey", new byte[0])));
+ assertTrue(Arrays.equals(new byte[] { 105, -73 }, pref.getByteArray(
+ "testGetByteArrayKey", new byte[0])));
+ assertTrue(Arrays.equals(new byte[] { 'a', 'b', 'c' }, pref
+ .getByteArray("testGetByteArrayKey2", new byte[0])));
+ assertTrue(Arrays.equals(new byte[0], pref.getByteArray("invalidKey",
+ new byte[0])));
+
+ pref.putByteArray("testGetByteArrayKey3", b64Array);
+ pref.putByteArray("testGetByteArrayKey4", "abc".getBytes());
+ assertTrue(Arrays.equals(b64Array, pref.getByteArray(
+ "testGetByteArrayKey3", new byte[0])));
+ assertTrue(Arrays.equals("abc".getBytes(), pref.getByteArray(
+ "testGetByteArrayKey4", new byte[0])));
+ }
+
+ public void testGetDouble() {
+ try {
+ pref.getDouble(null, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.put("testGetDoubleKey", "1");
+ pref.put("testGetDoubleKey2", "value");
+ pref.putDouble("testGetDoubleKey3", 1);
+ pref.putInt("testGetDoubleKey4", 1);
+ assertEquals(1.0, pref.getDouble("testGetDoubleKey", 0.0), 0);
+ assertEquals(0.0, pref.getDouble("testGetDoubleKey2", 0.0), 0);
+ assertEquals(1.0, pref.getDouble("testGetDoubleKey3", 0.0), 0);
+ assertEquals(1.0, pref.getDouble("testGetDoubleKey4", 0.0), 0);
+ }
+
+ public void testGetFloat() {
+ try {
+ pref.getFloat(null, 0f);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ pref.put("testGetFloatKey", "1");
+ pref.put("testGetFloatKey2", "value");
+ assertEquals(1f, pref.getFloat("testGetFloatKey", 0f), 0); //$NON-NLS-1$
+ assertEquals(0f, pref.getFloat("testGetFloatKey2", 0f), 0);
+ }
+
+ public void testGetInt() {
+ try {
+ pref.getInt(null, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.put("testGetIntKey", "1");
+ pref.put("testGetIntKey2", "value");
+ assertEquals(1, pref.getInt("testGetIntKey", 0));
+ assertEquals(0, pref.getInt("testGetIntKey2", 0));
+ }
+
+ public void testGetLong() {
+ try {
+ pref.getLong(null, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.put("testGetLongKey", "1");
+ pref.put("testGetLongKey2", "value");
+ assertEquals(1, pref.getInt("testGetLongKey", 0));
+ assertEquals(0, pref.getInt("testGetLongKey2", 0));
+ }
+
+ public void testIsUserNode() {
+ assertTrue(pref.isUserNode());
+
+ pref = new MockAbstractPreferences((AbstractPreferences) Preferences
+ .systemRoot(), "mock");
+ assertFalse(pref.isUserNode());
+ }
+
+ // TODO, how to test the "stored defaults"
+ // TODO, how to test the multi-thread
+ public void testKeys() throws BackingStoreException {
+ assertEquals(0, pref.keys().length);
+
+ pref.put("key0", "value");
+ pref.put("key1", "value1");
+ pref.put("key2", "value2");
+ pref.put("key3", "value3");
+
+ String[] keys = pref.keys();
+ assertEquals(4, keys.length);
+ for (int i = 0; i < keys.length; i++) {
+ assertEquals(0, keys[i].indexOf("key"));
+ assertEquals(4, keys[i].length());
+ }
+ }
+
+ public void testName() {
+ assertEquals("mock", pref.name());
+
+ pref = new MockAbstractPreferences(pref, " ");
+ assertEquals(" ", pref.name());
+ }
+
+ public void testCharCase() throws BackingStoreException {
+ assertSame(pref.node("samechild"), pref.node("samechild"));
+ assertNotSame(pref.node("sameChild"), pref.node("samechild"));
+ assertNotSame(pref.node("child"), pref.node("Child"));
+ assertNotSame(pref.node("child"), pref.node("Child"));
+ assertNotSame(pref.node("child"), pref.node(" child"));
+ String[] names = pref.childrenNames();
+ assertEquals(5, names.length);
+ for (int i = 0; i < names.length; i++) {
+ String name = names[i];
+ assertTrue("samechild".equals(name) || "sameChild".equals(name)
+ || "child".equals(name) || "Child".equals(name)
+ || " child".equals(name));
+ }
+
+ Preferences mock1 = pref.node("mock1");
+ mock1.put("key", "1value");
+ mock1.put("KEY", "2value");
+ mock1.put("/K/E/Y", "7value");
+ mock1.put("/K/E\\Y\\abc~@!#$%^&*(\\", "8value");
+
+ assertEquals("8value", mock1.get("/K/E\\Y\\abc~@!#$%^&*(\\", null));
+ assertNull(mock1.get("/k/e/y", null));
+ assertEquals("7value", mock1.get("/K/E/Y", null));
+ assertEquals("1value", mock1.get("key", null));
+
+ String[] keys = mock1.keys();
+ assertEquals(4, keys.length);
+ for (int i = 0; i < keys.length; i++) {
+ String key = keys[i];
+ assertTrue("key".equals(key) || "KEY".equals(key)
+ || "/K/E/Y".equals(key)
+ || "/K/E\\Y\\abc~@!#$%^&*(\\".equals(key));
+ }
+ }
+
+ public void testNode() throws BackingStoreException {
+ try {
+ pref.node(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ pref.node("/java/util/prefs/");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ pref.node("/java//util/prefs");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ pref.node(LONG_NAME + "a");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ assertNotNull(pref.node(LONG_NAME));
+
+ assertSame(root, pref.node("/"));
+
+ Preferences prefs = pref.node("/java/util/prefs");
+ assertSame(prefs, parent);
+
+ assertSame(pref, pref.node(""));
+
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences child = (MockAbstractPreferences) ((MockAbstractPreferences) pref)
+ .publicChildSpi("child");
+ assertSame(child, pref.node("child"));
+
+ Preferences child2 = pref.node("child2");
+ assertSame(child2, ((MockAbstractPreferences) pref)
+ .publicChildSpi("child2"));
+
+ Preferences grandchild = pref.node("child/grandchild");
+ assertSame(grandchild, child.childSpi("grandchild"));
+ assertSame(grandchild, child.cachedChildrenImpl()[0]);
+ grandchild.removeNode();
+ assertNotSame(grandchild, pref.node("child/grandchild"));
+
+ grandchild = pref.node("child3/grandchild");
+ AbstractPreferences[] childs = ((MockAbstractPreferences) pref)
+ .cachedChildrenImpl();
+ Preferences child3 = child;
+ for (int i = 0; i < childs.length; i++) {
+ if (childs[i].name().equals("child3")) {
+ child3 = childs[i];
+ break;
+ }
+ }
+ assertSame(child3, grandchild.parent());
+ }
+
+ public void testNodeExists() throws BackingStoreException {
+ try {
+ pref.nodeExists(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ pref.nodeExists("/java/util/prefs/");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ pref.nodeExists("/java//util/prefs");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertTrue(pref.nodeExists("/"));
+
+ assertTrue(pref.nodeExists("/java/util/prefs"));
+
+ assertTrue(pref.nodeExists(""));
+
+ assertFalse(pref.nodeExists("child"));
+ Preferences grandchild = pref.node("child/grandchild");
+ assertTrue(pref.nodeExists("child"));
+ assertTrue(pref.nodeExists("child/grandchild"));
+ grandchild.removeNode();
+ assertTrue(pref.nodeExists("child"));
+ assertFalse(pref.nodeExists("child/grandchild"));
+ assertFalse(grandchild.nodeExists(""));
+
+ assertFalse(pref.nodeExists("child2/grandchild"));
+ pref.node("child2/grandchild");
+ assertTrue(pref.nodeExists("child2/grandchild"));
+ }
+
+ public void test_nodeExists() throws BackingStoreException {
+ AbstractPreferences test = (AbstractPreferences) Preferences.userRoot()
+ .node("test");
+ try {
+ test.nodeExists(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ test.removeNode();
+ try {
+ test.nodeExists(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testParent() {
+ assertSame(parent, pref.parent());
+ AbstractPreferences child1 = new MockAbstractPreferences(pref, "child1");
+ assertSame(pref, child1.parent());
+ assertNull(root.parent());
+ }
+
+ public void testPut() throws BackingStoreException {
+ pref.put("", "emptyvalue");
+ assertEquals("emptyvalue", pref.get("", null));
+ pref.put("testPutkey", "value1");
+ assertEquals("value1", pref.get("testPutkey", null));
+ pref.put("testPutkey", "value2");
+ assertEquals("value2", pref.get("testPutkey", null));
+
+ pref.put("", "emptyvalue");
+ assertEquals("emptyvalue", pref.get("", null));
+
+ try {
+ pref.put(null, "value");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ pref.put("key", null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.put(LONG_KEY, LONG_VALUE);
+ try {
+ pref.put(LONG_KEY + 1, LONG_VALUE);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ pref.put(LONG_KEY, LONG_VALUE + 1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.removeNode();
+ try {
+ pref.put(LONG_KEY, LONG_VALUE + 1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ pref.put(LONG_KEY, LONG_VALUE);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ public void testPutBoolean() {
+ try {
+ pref.putBoolean(null, false);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putBoolean(LONG_KEY, false);
+ try {
+ pref.putBoolean(LONG_KEY + "a", false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putBoolean("testPutBooleanKey", false);
+ assertEquals("false", pref.get("testPutBooleanKey", null));
+ assertFalse(pref.getBoolean("testPutBooleanKey", true));
+ }
+
+ public void testPutDouble() {
+ try {
+ pref.putDouble(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putDouble(LONG_KEY, 3);
+ try {
+ pref.putDouble(LONG_KEY + "a", 3);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putDouble("testPutDoubleKey", 3);
+ assertEquals("3.0", pref.get("testPutDoubleKey", null));
+ assertEquals(3, pref.getDouble("testPutDoubleKey", 0), 0);
+ }
+
+ public void testPutFloat() {
+ try {
+ pref.putFloat(null, 3f);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putFloat(LONG_KEY, 3f);
+ try {
+ pref.putFloat(LONG_KEY + "a", 3f);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putFloat("testPutFloatKey", 3f);
+ assertEquals("3.0", pref.get("testPutFloatKey", null));
+ assertEquals(3f, pref.getFloat("testPutFloatKey", 0), 0);
+ }
+
+ public void testPutInt() {
+ try {
+ pref.putInt(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putInt(LONG_KEY, 3);
+ try {
+ pref.putInt(LONG_KEY + "a", 3);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putInt("testPutIntKey", 3);
+ assertEquals("3", pref.get("testPutIntKey", null));
+ assertEquals(3, pref.getInt("testPutIntKey", 0));
+ }
+
+ public void testPutLong() {
+ try {
+ pref.putLong(null, 3L);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putLong(LONG_KEY, 3L);
+ try {
+ pref.putLong(LONG_KEY + "a", 3L);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ pref.putLong("testPutLongKey", 3L);
+ assertEquals("3", pref.get("testPutLongKey", null));
+ assertEquals(3L, pref.getLong("testPutLongKey", 0));
+ }
+
+ public void testRemove() throws BackingStoreException {
+ pref.remove("key");
+
+ pref.put("key", "value");
+ assertEquals("value", pref.get("key", null));
+ pref.remove("key");
+ assertNull(pref.get("key", null));
+
+ pref.remove("key");
+
+ try {
+ pref.remove(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.removeNode();
+ try {
+ pref.remove("key");
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ public void testRemoveNode() throws BackingStoreException {
+ Preferences child = pref.node("child");
+ Preferences child1 = pref.node("child1");
+ Preferences grandchild = child.node("grandchild");
+
+ pref.removeNode();
+
+ assertFalse(child.nodeExists(""));
+ assertFalse(child1.nodeExists(""));
+ assertFalse(grandchild.nodeExists(""));
+ assertFalse(pref.nodeExists(""));
+ }
+
+ public void testRemoveNodeChangeListener() {
+ try {
+ pref.removeNodeChangeListener(null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ MockNodeChangeListener l1 = new MockNodeChangeListener();
+ MockNodeChangeListener l2 = new MockNodeChangeListener();
+ pref.addNodeChangeListener(l1);
+ pref.addNodeChangeListener(l1);
+
+ pref.removeNodeChangeListener(l1);
+ pref.removeNodeChangeListener(l1);
+ try {
+ pref.removeNodeChangeListener(l1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ pref.removeNodeChangeListener(l2);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testRemovePreferenceChangeListener() {
+ try {
+ pref.removePreferenceChangeListener(null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ MockPreferenceChangeListener l1 = new MockPreferenceChangeListener();
+ MockPreferenceChangeListener l2 = new MockPreferenceChangeListener();
+ pref.addPreferenceChangeListener(l1);
+ pref.addPreferenceChangeListener(l1);
+ try {
+ pref.removePreferenceChangeListener(l2);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ pref.removePreferenceChangeListener(l1);
+ pref.removePreferenceChangeListener(l1);
+ try {
+ pref.removePreferenceChangeListener(l1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testSync() throws BackingStoreException {
+ pref.sync();
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.resetSyncTimes();
+ p.sync();
+ assertEquals(1, p.getSyncTimes());
+
+ p.resetSyncTimes();
+ MockAbstractPreferences child = (MockAbstractPreferences) p
+ .node("child");
+ MockAbstractPreferences child2 = new MockAbstractPreferences(p,
+ "child2");
+ p.childs.put("child2", child2);
+ assertEquals(1, p.cachedChildrenImpl().length);
+ assertSame(child, p.cachedChildrenImpl()[0]);
+ p.sync();
+ assertEquals(1, p.getSyncTimes());
+ assertEquals(1, child.getSyncTimes());
+ assertEquals(0, child2.getSyncTimes());
+
+ p.resetSyncTimes();
+ child.resetSyncTimes();
+ child.sync();
+ assertEquals(0, p.getSyncTimes());
+ assertEquals(1, child.getSyncTimes());
+
+ p.resetSyncTimes();
+ child.resetSyncTimes();
+ MockAbstractPreferences grandson = (MockAbstractPreferences) child
+ .node("grandson");
+ child.sync();
+ assertEquals(0, p.getSyncTimes());
+ assertEquals(1, child.getSyncTimes());
+ assertEquals(1, grandson.getSyncTimes());
+ }
+
+ public void testFlush() throws BackingStoreException {
+ pref.flush();
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.resetFlushedTimes();
+ p.flush();
+ assertEquals(1, p.getFlushedTimes());
+
+ p.resetFlushedTimes();
+ MockAbstractPreferences child = (MockAbstractPreferences) p
+ .node("child");
+ MockAbstractPreferences child2 = new MockAbstractPreferences(p,
+ "child2");
+ p.childs.put("child2", child2);
+ assertEquals(1, p.cachedChildrenImpl().length);
+ assertSame(child, p.cachedChildrenImpl()[0]);
+ p.flush();
+ assertEquals(1, p.getFlushedTimes());
+ assertEquals(1, child.getFlushedTimes());
+ assertEquals(0, child2.getFlushedTimes());
+
+ p.resetFlushedTimes();
+ child.resetFlushedTimes();
+ child.flush();
+ assertEquals(0, p.getFlushedTimes());
+ assertEquals(1, child.getFlushedTimes());
+
+ p.resetFlushedTimes();
+ child.resetFlushedTimes();
+ MockAbstractPreferences grandson = (MockAbstractPreferences) child
+ .node("grandson");
+ child.flush();
+ assertEquals(0, p.getFlushedTimes());
+ assertEquals(1, child.getFlushedTimes());
+ assertEquals(1, grandson.getFlushedTimes());
+
+ p.resetFlushedTimes();
+ child.resetFlushedTimes();
+ grandson.resetFlushedTimes();
+ child.removeNode();
+ child.flush();
+ assertEquals(0, p.getFlushedTimes());
+ assertEquals(1, child.getFlushedTimes());
+ assertEquals(0, grandson.getFlushedTimes());
+ }
+
+ public void testGetChild() throws BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ assertNull(p.getChildImpl("child"));
+ MockAbstractPreferences child = new MockAbstractPreferences(p, "child");
+ p.childs.put("child", child);
+ assertSame(child, p.getChildImpl("child"));
+ assertNull(p.getChildImpl("child "));
+
+ assertNull(p.getChildImpl("child/grandson"));
+ child.childs.put("grandson", new MockAbstractPreferences(child,
+ "grandson"));
+ assertNull(p.getChildImpl("child/grandson"));
+
+ assertNull(p.getChildImpl(null));
+ assertNull(p.getChildImpl(""));
+ assertNull(p.getChildImpl(" "));
+ assertNull(p.getChildImpl("abc//abc"));
+ assertNull(p.getChildImpl("child/"));
+ assertNull(p.getChildImpl(LONG_NAME + "a"));
+
+ child.removeNode();
+ assertNull(p.getChildImpl("child"));
+ }
+
+ public void testIsRemoved() throws BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ assertFalse(p.isRemovedImpl());
+ p.removeNode();
+ assertTrue(p.isRemovedImpl());
+ }
+
+ public void testExportNode() throws Exception {
+ try {
+ pref.exportNode(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ pref.putBoolean("key", false);
+ Preferences child = pref.node("child<");
+ child.put("key2", "value2<");
+ Preferences grandson = child.node("grandson");
+ grandson.put("key3", "value3");
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ child.exportNode(out);
+
+ byte[] result = out.toByteArray();
+ ByteArrayInputStream in = new ByteArrayInputStream(result);
+
+ parseXmlStream(in, false);
+ }
+
+ private static Document parseXmlStream(InputStream input, boolean validating)
+ throws SAXException, IOException, ParserConfigurationException {
+ // Create a builder factory
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setValidating(validating);
+ // Create the builder and parse the file
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ return builder.parse(input);
+ }
+
+ public void testExportSubtree() throws Exception {
+ try {
+ pref.exportSubtree(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ pref.putBoolean("key", false);
+ Preferences child = pref.node("child");
+ child.put("key2", "value2");
+ Preferences grandson = child.node("grandson");
+ grandson.put("key3", "value3");
+ child.node("grandson2");
+ Preferences grandgrandson = grandson.node("grandgrandson");
+ grandgrandson.put("key4", "value4");
+ child.exportSubtree(out);
+
+ byte[] result = out.toByteArray();
+ ByteArrayInputStream in = new ByteArrayInputStream(result);
+
+ // We don't have an xpath API so all we can do is test that the
+ // generated XML parses correctly.
+ parseXmlStream(in, false);
+ }
+
+ public void testCachedChildren() throws Exception {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ assertEquals(0, p.cachedChildrenImpl().length);
+
+ MockAbstractPreferences child = (MockAbstractPreferences) p
+ .getChildImpl("child");
+ assertNull(child);
+
+ child = new MockAbstractPreferences(p, "child");
+ assertSame(child, p.getChildImpl("child"));
+
+ assertEquals(0, p.cachedChildrenImpl().length);
+
+ p.node("child");
+ assertSame(child, p.cachedChildrenImpl()[0]);
+
+ MockAbstractPreferences grandchild = new MockAbstractPreferences(child,
+ "grandchild");
+ assertSame(grandchild, child.getChildImpl("grandchild"));
+ assertNull(p.getChildImpl("grandchild"));
+
+ assertEquals(1, p.cachedChildrenImpl().length);
+ assertEquals(0, child.cachedChildrenImpl().length);
+
+ p.node("child/grandchild");
+ assertSame(child, p.cachedChildrenImpl()[0]);
+ assertSame(grandchild, child.cachedChildrenImpl()[0]);
+ assertEquals(1, p.cachedChildrenImpl().length);
+ assertEquals(1, child.cachedChildrenImpl().length);
+
+ p.childs.put("child2", new MockAbstractPreferences(p, "child2"));
+ p.nodeExists("child2/grandchild");
+ assertSame(child, p.cachedChildrenImpl()[0]);
+ assertSame(grandchild, child.cachedChildrenImpl()[0]);
+ assertEquals(1, p.cachedChildrenImpl().length);
+ assertEquals(1, child.cachedChildrenImpl().length);
+ }
+
+ public void testAbstractMethod() {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ ((MockAbstractPreferences) pref).protectedAbstractMethod();
+ }
+
+ public void testBackingStoreException() throws IOException,
+ BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.setResult(MockAbstractPreferences.backingException);
+ try {
+ p.childrenNames();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException e) {
+ }
+ p.put("exceptionkey", "value");
+ p.absolutePath();
+ p.toString();
+ assertEquals("exception default", p.get("key", "exception default"));
+ p.remove("key");
+ try {
+ p.clear();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+
+ p.putInt("key", 3);
+ p.getInt("key", 3);
+ p.putLong("key", 3l);
+ p.getLong("key", 3l);
+ p.putDouble("key", 3);
+ p.getDouble("key", 3);
+ p.putBoolean("key", true);
+ p.getBoolean("key", true);
+ p.putFloat("key", 3f);
+ p.getFloat("key", 3f);
+ p.putByteArray("key", new byte[0]);
+ p.getByteArray("key", new byte[0]);
+ try {
+ p.keys();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+
+ try {
+ p.keys();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ try {
+ p.childrenNames();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ p.parent();
+ p.node("");
+ p.nodeExists("");
+ try {
+ p.removeNode();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ p.name();
+ p.absolutePath();
+ p.isUserNode();
+ MockPreferenceChangeListener mockPreferenceChangeListener = new MockPreferenceChangeListener();
+ p.addPreferenceChangeListener(mockPreferenceChangeListener);
+ p.removePreferenceChangeListener(mockPreferenceChangeListener);
+ MockNodeChangeListener mockNodeChangeListener = new MockNodeChangeListener();
+ p.addNodeChangeListener(mockNodeChangeListener);
+ p.removeNodeChangeListener(mockNodeChangeListener);
+ p.toString();
+ try {
+ p.sync();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ try {
+ p.flush();
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ try {
+ p.exportNode(new ByteArrayOutputStream());
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ try {
+ p.exportSubtree(new ByteArrayOutputStream());
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ p.isRemovedImpl();
+ try {
+ p.getChildImpl(null);
+ fail("should throw BackingStoreException");
+ } catch (BackingStoreException expected) {
+ }
+ p.cachedChildrenImpl();
+ }
+
+ public void testRuntimeException() throws IOException,
+ BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.setResult(MockAbstractPreferences.runtimeException);
+ try {
+ p.childrenNames();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.put("exceptionkey", "value");
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.absolutePath();
+ p.toString();
+ assertEquals("exception default", p.get("key", "exception default"));
+ try {
+ p.remove("key");
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.clear();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.putInt("key", 3);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getInt("key", 3);
+ try {
+ p.putLong("key", 3l);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getLong("key", 3l);
+ try {
+ p.putDouble("key", 3);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getDouble("key", 3);
+ try {
+ p.putBoolean("key", true);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getBoolean("key", true);
+ try {
+ p.putFloat("key", 3f);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getFloat("key", 3f);
+ try {
+ p.putByteArray("key", new byte[0]);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.getByteArray("key", new byte[0]);
+ try {
+ p.keys();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.keys();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.childrenNames();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.parent();
+ p.node("");
+ p.nodeExists("");
+ try {
+ p.removeNode();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.name();
+ p.absolutePath();
+ p.isUserNode();
+ MockPreferenceChangeListener pcl = new MockPreferenceChangeListener();
+ p.addPreferenceChangeListener(pcl);
+ p.removePreferenceChangeListener(pcl);
+ MockNodeChangeListener ncl = new MockNodeChangeListener();
+ p.addNodeChangeListener(ncl);
+ p.removeNodeChangeListener(ncl);
+ p.toString();
+ try {
+ p.sync();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.flush();
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.exportNode(new ByteArrayOutputStream());
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ try {
+ p.exportSubtree(new ByteArrayOutputStream());
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.isRemovedImpl();
+ try {
+ p.getChildImpl(null);
+ fail("should throw MockRuntimeException");
+ } catch (MockRuntimeException expected) {
+ }
+ p.cachedChildrenImpl();
+ }
+
+ public void testSPIReturnNull() throws IOException, BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.setResult(MockAbstractPreferences.returnNull);
+ try {
+ p.childrenNames();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.absolutePath();
+ p.toString();
+ p.put("nullkey", "value");
+ assertEquals("null default", p.get("key", "null default"));
+ p.remove("key");
+ try {
+ p.clear();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.putInt("key", 3);
+ p.getInt("key", 3);
+ p.putLong("key", 3l);
+ p.getLong("key", 3l);
+ p.putDouble("key", 3);
+ p.getDouble("key", 3);
+ p.putBoolean("key", true);
+ p.getBoolean("key", true);
+ p.putFloat("key", 3f);
+ p.getFloat("key", 3f);
+ p.putByteArray("key", new byte[0]);
+ p.getByteArray("key", new byte[0]);
+ p.keys();
+ try {
+ p.childrenNames();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.parent();
+ p.node("");
+ p.nodeExists("");
+ try {
+ p.removeNode();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.name();
+ p.absolutePath();
+ p.isUserNode();
+ MockPreferenceChangeListener mockPreferenceChangeListener = new MockPreferenceChangeListener();
+ p.addPreferenceChangeListener(mockPreferenceChangeListener);
+ p.removePreferenceChangeListener(mockPreferenceChangeListener);
+ MockNodeChangeListener mockNodeChangeListener = new MockNodeChangeListener();
+ p.addNodeChangeListener(mockNodeChangeListener);
+ p.removeNodeChangeListener(mockNodeChangeListener);
+ p.toString();
+ p.sync();
+ p.flush();
+ try {
+ p.exportNode(System.out);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.exportSubtree(System.out);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.isRemovedImpl();
+ try {
+ p.getChildImpl("");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ p.cachedChildrenImpl();
+ }
+
+ public void testIllegalStateException() throws IOException,
+ BackingStoreException {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ pref.removeNode();
+ // after remove node, every methods, except name(), absolutePath(),
+ // isUserNode(), flush() or nodeExists(""),
+ // will throw illegal state exception
+ pref.nodeExists("");
+ pref.name();
+ pref.absolutePath();
+ pref.isUserNode();
+ pref.toString();
+ pref.flush();
+ try {
+ pref.nodeExists("child");
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.childrenNames();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.remove(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.clear();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.get("key", "null default");
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.put("nullkey", "value");
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putInt("key", 3);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getInt("key", 3);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putLong("key", 3l);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getLong("key", 3l);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putDouble("key", 3);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getDouble("key", 3);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putBoolean("key", true);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getBoolean("key", true);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putFloat("key", 3f);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getFloat("key", 3f);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.putByteArray("key", new byte[0]);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.getByteArray("key", new byte[0]);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.keys();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.keys();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.childrenNames();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.parent();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.node(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.removeNode();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref
+ .addPreferenceChangeListener(new MockPreferenceChangeListener());
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref
+ .removePreferenceChangeListener(new MockPreferenceChangeListener());
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.addNodeChangeListener(new MockNodeChangeListener());
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.removeNodeChangeListener(new MockNodeChangeListener());
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.sync();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.exportNode(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ pref.exportSubtree(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.isRemovedImpl();
+ p.cachedChildrenImpl();
+ try {
+ p.getChildImpl(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ public void testNullAndIllegalStateException() throws Exception {
+ if (!(pref instanceof MockAbstractPreferences)) {
+ return;
+ }
+ MockAbstractPreferences p = (MockAbstractPreferences) pref;
+ p.removeNode();
+ try {
+ p.get(null, "null default");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.put(null, "value");
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putInt(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getInt(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putLong(null, 3l);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getLong(null, 3l);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putDouble(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getDouble(null, 3);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putBoolean(null, true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getBoolean(null, true);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putFloat(null, 3f);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getFloat(null, 3f);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.putByteArray(null, new byte[0]);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.getByteArray(null, new byte[0]);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.addPreferenceChangeListener(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.removePreferenceChangeListener(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ p.addNodeChangeListener(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ try {
+ p.removeNodeChangeListener(null);
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * Regression for HARMONY-828
+ */
+ public void testLongPath() throws Exception {
+ assertFalse(pref.nodeExists("ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"));
+ }
+
+ public static class MockPreferenceChangeListener implements
+ PreferenceChangeListener {
+ private int changed = 0;
+
+ public void preferenceChange(PreferenceChangeEvent pce) {
+ changed++;
+ }
+
+ public int getChanged() {
+ int result = changed;
+ changed = 0;
+ return result;
+ }
+ }
+
+ public static class MockNodeChangeListener implements NodeChangeListener {
+ private boolean addDispatched = false;
+
+ private boolean removeDispatched = false;
+
+ private Object addLock = new Object();
+
+ private Object removeLock = new Object();
+
+ private int added = 0;
+
+ private int removed = 0;
+
+ public void childAdded(NodeChangeEvent e) {
+ synchronized (addLock) {
+ ++added;
+ addDispatched = true;
+ addLock.notifyAll();
+ }
+ }
+
+ public void childRemoved(NodeChangeEvent e) {
+ synchronized (removeLock) {
+ removed++;
+ removeDispatched = true;
+ removeLock.notifyAll();
+ }
+ }
+
+ public int getAdded() {
+ synchronized (addLock) {
+ if (!addDispatched) {
+ try {
+ // TODO: don't know why must add limitation
+ addLock.wait(100);
+ } catch (InterruptedException e) {
+ }
+ }
+ addDispatched = false;
+ }
+ return added;
+ }
+
+ public int getRemoved() {
+ synchronized (removeLock) {
+ if (!removeDispatched) {
+ try {
+ removeLock.wait(100);
+ } catch (InterruptedException e) {
+ }
+ }
+ removeDispatched = false;
+ }
+ return removed;
+
+ }
+
+ public void reset() {
+ added = 0;
+ removed = 0;
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/BackingStoreExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/BackingStoreExceptionTest.java
new file mode 100644
index 0000000..4d264e1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/BackingStoreExceptionTest.java
@@ -0,0 +1,62 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.prefs.BackingStoreException;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ *
+ *
+ */
+public class BackingStoreExceptionTest extends TestCase {
+
+ /*
+ * Class under test for void BackingStoreException(String)
+ */
+ public void testBackingStoreExceptionString() {
+ BackingStoreException e = new BackingStoreException("msg");
+ assertNull(e.getCause());
+ assertEquals("msg", e.getMessage());
+ }
+
+ /*
+ * Class under test for void BackingStoreException(Throwable)
+ */
+ public void testBackingStoreExceptionThrowable() {
+ Throwable t = new Throwable("msg");
+ BackingStoreException e = new BackingStoreException(t);
+ assertTrue(e.getMessage().indexOf(t.getClass().getName()) >= 0);
+ assertTrue(e.getMessage().indexOf("msg") >= 0);
+ assertEquals(t, e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new BackingStoreException("msg"));
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SerializationTest.verifyGolden(this, new BackingStoreException("msg"));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/FilePreferencesImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/FilePreferencesImplTest.java
new file mode 100644
index 0000000..352603c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/FilePreferencesImplTest.java
@@ -0,0 +1,120 @@
+/* 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.tests.java.util.prefs;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+import junit.framework.TestCase;
+import libcore.io.IoUtils;
+
+public class FilePreferencesImplTest extends TestCase {
+
+ private Preferences uroot;
+ private Preferences sroot;
+
+ @Override
+ protected void setUp() throws Exception {
+ File tmpDir = IoUtils.createTemporaryDirectory("FilePreferencesImplTest");
+ AbstractPreferencesTest.TestPreferencesFactory factory
+ = new AbstractPreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath());
+
+ uroot = factory.userRoot().node("harmony_test");
+ sroot = factory.systemRoot().node("harmony_test");
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ uroot.removeNode();
+ sroot.removeNode();
+ uroot = null;
+ sroot = null;
+ }
+
+ public void testPutGet() throws IOException, BackingStoreException {
+ uroot.put("ukey1", "value1");
+ assertEquals("value1", uroot.get("ukey1", null));
+ String[] names = uroot.keys();
+ assertEquals(1, names.length);
+
+ uroot.put("ukey2", "value3");
+ assertEquals("value3", uroot.get("ukey2", null));
+ uroot.put("\u4e2d key1", "\u4e2d value1");
+ assertEquals("\u4e2d value1", uroot.get("\u4e2d key1", null));
+ names = uroot.keys();
+ assertEquals(3, names.length);
+
+ uroot.flush();
+ uroot.clear();
+ names = uroot.keys();
+ assertEquals(0, names.length);
+
+ sroot.put("skey1", "value1");
+ assertEquals("value1", sroot.get("skey1", null));
+ sroot.put("\u4e2d key1", "\u4e2d value1");
+ assertEquals("\u4e2d value1", sroot.get("\u4e2d key1", null));
+ }
+
+ public void testChildNodes() throws Exception {
+ Preferences child1 = uroot.node("child1");
+ Preferences child2 = uroot.node("\u4e2d child2");
+ Preferences grandchild = child1.node("grand");
+ assertNotNull(grandchild);
+
+ String[] childNames = uroot.childrenNames();
+ assertEquals(2, childNames.length);
+
+ childNames = child1.childrenNames();
+ assertEquals(1, childNames.length);
+
+ childNames = child2.childrenNames();
+ assertEquals(0, childNames.length);
+
+ child1.removeNode();
+ childNames = uroot.childrenNames();
+ assertEquals(1, childNames.length);
+
+ child2.removeNode();
+ childNames = uroot.childrenNames();
+ assertEquals(0, childNames.length);
+
+ child1 = sroot.node("child1");
+ child2 = sroot.node("child2");
+ childNames = sroot.childrenNames();
+
+ Preferences grandchild2 = child1.node("grand");
+ assertEquals(2, childNames.length);
+
+ childNames = child1.childrenNames();
+ assertEquals(1, childNames.length);
+
+ childNames = child2.childrenNames();
+ assertEquals(0, childNames.length);
+
+ child1.removeNode();
+ assertNotSame(child1, sroot.node("child1"));
+ assertSame(sroot.node("child1"), sroot.node("child1"));
+ sroot.node("child1").removeNode();
+ childNames = sroot.childrenNames();
+ assertEquals(1, childNames.length);
+ child2.removeNode();
+ childNames = sroot.childrenNames();
+ assertEquals(0, childNames.length);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/InvalidPreferencesFormatExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/InvalidPreferencesFormatExceptionTest.java
new file mode 100644
index 0000000..7c4891f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/InvalidPreferencesFormatExceptionTest.java
@@ -0,0 +1,81 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.prefs.InvalidPreferencesFormatException;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ *
+ */
+public class InvalidPreferencesFormatExceptionTest extends TestCase {
+
+ /*
+ * Class under test for void InvalidPreferencesFormatException(String)
+ */
+ public void testInvalidPreferencesFormatExceptionString() {
+ InvalidPreferencesFormatException e = new InvalidPreferencesFormatException(
+ "msg");
+ assertNull(e.getCause());
+ assertEquals("msg", e.getMessage());
+ }
+
+ /*
+ * Class under test for void InvalidPreferencesFormatException(String,
+ * Throwable)
+ */
+ public void testInvalidPreferencesFormatExceptionStringThrowable() {
+ Throwable t = new Throwable("root");
+ InvalidPreferencesFormatException e = new InvalidPreferencesFormatException(
+ "msg", t);
+ assertSame(t, e.getCause());
+ assertTrue(e.getMessage().indexOf("root") < 0);
+ assertTrue(e.getMessage().indexOf(t.getClass().getName()) < 0);
+ assertTrue(e.getMessage().indexOf("msg") >= 0);
+ }
+
+ /*
+ * Class under test for void InvalidPreferencesFormatException(Throwable)
+ */
+ public void testInvalidPreferencesFormatExceptionThrowable() {
+ Throwable t = new Throwable("root");
+ InvalidPreferencesFormatException e = new InvalidPreferencesFormatException(
+ t);
+ assertSame(t, e.getCause());
+ assertTrue(e.getMessage().indexOf("root") >= 0);
+ assertTrue(e.getMessage().indexOf(t.getClass().getName()) >= 0);
+ }
+
+ /**
+ * @tests serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new InvalidPreferencesFormatException(
+ "msg"));
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new InvalidPreferencesFormatException("msg"));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockAbstractPreferences.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockAbstractPreferences.java
new file mode 100644
index 0000000..88f184b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockAbstractPreferences.java
@@ -0,0 +1,263 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.prefs.AbstractPreferences;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
+
+public class MockAbstractPreferences extends AbstractPreferences {
+ static final int NORMAL = 0;
+
+ static final int backingException = 1;
+
+ static final int runtimeException = 2;
+
+ static final int returnNull = 3;
+
+ int result = NORMAL;
+
+ Properties attr = new Properties();
+
+ Map<String, MockAbstractPreferences> childs = new HashMap<String, MockAbstractPreferences>();
+
+ private int flushedTimes;
+
+ private int syncTimes;
+
+ protected MockAbstractPreferences(AbstractPreferences parent, String name) {
+ this(parent, name, false);
+
+ }
+
+ protected MockAbstractPreferences(AbstractPreferences parent, String name,
+ boolean newNode) {
+ super(parent, name);
+ super.newNode = newNode;
+ if (parent instanceof MockAbstractPreferences) {
+ ((MockAbstractPreferences) parent).addChild(this);
+ }
+ }
+
+ public int getFlushedTimes() {
+ return flushedTimes;
+ }
+
+ public void resetFlushedTimes() {
+ flushedTimes = 0;
+ }
+
+ public int getSyncTimes() {
+ return syncTimes;
+ }
+
+ public void resetSyncTimes() {
+ syncTimes = 0;
+ }
+
+ private void addChild(MockAbstractPreferences c) {
+ childs.put(c.name(), c);
+ }
+
+ public void setResult(int r) {
+ result = r;
+ }
+
+ public Object lock() {
+ return lock;
+ }
+
+ @Override
+ protected String[] childrenNamesSpi() throws BackingStoreException {
+ checkException();
+ if (result == returnNull)
+ return null;
+ String[] r = new String[childs.size()];
+ childs.keySet().toArray(r);
+ return r;
+ }
+
+ private void checkException() throws BackingStoreException {
+ switch (result) {
+ case NORMAL:
+ return;
+ case backingException:
+ throw new BackingStoreException("test");
+ case runtimeException:
+ throw new MockRuntimeException("test");
+ }
+ }
+
+ public AbstractPreferences publicChildSpi(String name) {
+ return childSpi(name);
+ }
+
+ @Override
+ protected AbstractPreferences childSpi(String name) {
+ try {
+ checkException();
+ } catch (BackingStoreException e) {
+ }
+ if (result == returnNull)
+ return null;
+ AbstractPreferences r = childs.get(name);
+ if (r == null) {
+ r = new MockAbstractPreferences(this, name, true);
+
+ }
+ return r;
+ }
+
+ @Override
+ protected void flushSpi() throws BackingStoreException {
+ checkException();
+ flushedTimes++;
+ }
+
+ @Override
+ protected String getSpi(String key) {
+ try {
+ checkException();
+ } catch (BackingStoreException e) {
+ }
+ if (null == key) {
+ return null;
+ }
+ return result == returnNull ? null : attr.getProperty(key);
+ }
+
+ @Override
+ protected String[] keysSpi() throws BackingStoreException {
+ checkException();
+ Set<Object> keys = attr.keySet();
+ String[] results = new String[keys.size()];
+ keys.toArray(results);
+ return result == returnNull ? null : results;
+ }
+
+ @Override
+ protected void putSpi(String name, String value) {
+ try {
+ checkException();
+ } catch (BackingStoreException e) {
+ }
+ if (name == null || value == null) {
+ return;
+ }
+ attr.put(name, value);
+ }
+
+ @Override
+ protected void removeNodeSpi() throws BackingStoreException {
+ checkException();
+ Preferences p = parent();
+ if (p instanceof MockAbstractPreferences) {
+ ((MockAbstractPreferences) p).childs.remove(name());
+ } else {
+ String[] children = p.childrenNames();
+ for (String child : children) {
+ p.node(child).removeNode();
+ }
+ }
+ }
+
+ @Override
+ protected void removeSpi(String key) {
+ try {
+ checkException();
+ } catch (BackingStoreException e) {
+ }
+ if (null == key) {
+ return;
+ }
+ attr.remove(key);
+ }
+
+ @Override
+ protected void syncSpi() throws BackingStoreException {
+ checkException();
+ syncTimes++;
+ }
+
+ public boolean getNewNode() {
+ return newNode;
+ }
+
+ public Object getLock() {
+ return lock;
+ }
+
+ public void protectedAbstractMethod() {
+ try {
+ childrenNamesSpi();
+ } catch (BackingStoreException e) {
+ }
+ childSpi("mock");
+ try {
+ flushSpi();
+ } catch (BackingStoreException e1) {
+ }
+ getSpi(null);
+ isRemoved();
+ try {
+ keysSpi();
+ } catch (BackingStoreException e2) {
+ }
+ putSpi(null, null);
+ try {
+ removeNodeSpi();
+ } catch (BackingStoreException e3) {
+ }
+ removeSpi(null);
+ try {
+ syncSpi();
+ } catch (BackingStoreException e4) {
+ }
+ }
+
+ public boolean isRemovedImpl() {
+ return super.isRemoved();
+ }
+
+ public AbstractPreferences getChildImpl(String name)
+ throws BackingStoreException {
+ return super.getChild(name);
+ }
+
+ public AbstractPreferences[] cachedChildrenImpl() {
+ return super.cachedChildren();
+ }
+
+}
+
+class MockRuntimeException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ public MockRuntimeException(String s) {
+ super(s);
+ }
+
+ public MockRuntimeException() {
+ super();
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockPreferencesFactory.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockPreferencesFactory.java
new file mode 100644
index 0000000..8bbbed2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/MockPreferencesFactory.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.tests.java.util.prefs;
+
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
+/**
+ *
+ */
+public class MockPreferencesFactory implements PreferencesFactory {
+ static MockAbstractPreferences userRoot = new MockAbstractPreferences(null,
+ "");
+
+ static MockAbstractPreferences systemRoot = new MockAbstractPreferences(
+ null, "");
+
+ public MockPreferencesFactory() {
+ }
+
+ public Preferences userRoot() {
+ return userRoot;
+ }
+
+ public Preferences systemRoot() {
+ return systemRoot;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeEventTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeEventTest.java
new file mode 100644
index 0000000..07fd887
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeEventTest.java
@@ -0,0 +1,63 @@
+/* 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.tests.java.util.prefs;
+
+import java.io.NotSerializableException;
+import java.util.prefs.NodeChangeEvent;
+import java.util.prefs.Preferences;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ *
+ */
+public class NodeChangeEventTest extends TestCase {
+
+ NodeChangeEvent event;
+
+ public void testConstructor() {
+ event = new NodeChangeEvent(Preferences.systemRoot(), Preferences
+ .userRoot());
+ assertSame(Preferences.systemRoot(), event.getParent());
+ assertSame(Preferences.userRoot(), event.getChild());
+ assertSame(Preferences.systemRoot(), event.getSource());
+ }
+
+ public void testConstructorNullParam() {
+ try {
+ event = new NodeChangeEvent(null, Preferences.userRoot());
+ fail();
+ } catch (IllegalArgumentException e) {
+ }
+
+ event = new NodeChangeEvent(Preferences.systemRoot(), null);
+ assertSame(Preferences.systemRoot(), event.getParent());
+ assertNull(event.getChild());
+ assertSame(Preferences.systemRoot(), event.getSource());
+ }
+
+ public void testSerialization() throws Exception {
+
+ event = new NodeChangeEvent(Preferences.systemRoot(), null);
+
+ try {
+ SerializationTest.copySerializable(event);
+ fail("No expected NotSerializableException");
+ } catch (NotSerializableException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeListenerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeListenerTest.java
new file mode 100644
index 0000000..cda52ec
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/NodeChangeListenerTest.java
@@ -0,0 +1,68 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.prefs.NodeChangeEvent;
+import java.util.prefs.NodeChangeListener;
+import java.util.prefs.Preferences;
+import junit.framework.TestCase;
+
+/**
+ *
+ */
+public class NodeChangeListenerTest extends TestCase {
+
+ NodeChangeListener l;
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ l = new NodeChangeListenerImpl();
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testChildAdded() {
+ l.childAdded(new NodeChangeEvent(Preferences.userRoot(), Preferences
+ .userRoot()));
+ }
+
+ public void testChildRemoved() {
+ l.childRemoved(new NodeChangeEvent(Preferences.userRoot(), Preferences
+ .userRoot()));
+ }
+
+ public static class NodeChangeListenerImpl implements NodeChangeListener {
+
+ public void childAdded(NodeChangeEvent e) {
+ }
+
+ public void childRemoved(NodeChangeEvent e) {
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeEventTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeEventTest.java
new file mode 100644
index 0000000..7d403c7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeEventTest.java
@@ -0,0 +1,84 @@
+/* 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.tests.java.util.prefs;
+
+import java.io.NotSerializableException;
+import java.util.prefs.PreferenceChangeEvent;
+import java.util.prefs.Preferences;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ *
+ */
+public class PreferenceChangeEventTest extends TestCase {
+
+ PreferenceChangeEvent event;
+
+ public void testPreferenceChangeEventException() {
+ try {
+ event = new PreferenceChangeEvent(null, "key", "value");
+ fail();
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ public void testConstructorNullValue() {
+ event = new PreferenceChangeEvent(Preferences.userRoot(), "key", null);
+ assertEquals("key", event.getKey());
+ assertNull(event.getNewValue());
+ assertSame(Preferences.userRoot(), event.getNode());
+ assertSame(Preferences.userRoot(), event.getSource());
+
+ event = new PreferenceChangeEvent(Preferences.userRoot(), "", null);
+ assertEquals("", event.getKey());
+ assertNull(event.getNewValue());
+ assertSame(Preferences.userRoot(), event.getNode());
+ assertSame(Preferences.userRoot(), event.getSource());
+
+ event = new PreferenceChangeEvent(Preferences.userRoot(), null, "value");
+ assertNull(event.getKey());
+ assertEquals("value", event.getNewValue());
+ assertSame(Preferences.userRoot(), event.getNode());
+ assertSame(Preferences.userRoot(), event.getSource());
+
+ event = new PreferenceChangeEvent(Preferences.userRoot(), null, "");
+ assertNull(event.getKey());
+ assertEquals("", event.getNewValue());
+ assertSame(Preferences.userRoot(), event.getNode());
+ assertSame(Preferences.userRoot(), event.getSource());
+ }
+
+ public void testConstructor() {
+ event = new PreferenceChangeEvent(Preferences.userRoot(), "key",
+ "value");
+ assertEquals("key", event.getKey());
+ assertEquals("value", event.getNewValue());
+ assertSame(Preferences.userRoot(), event.getNode());
+ assertSame(Preferences.userRoot(), event.getSource());
+ }
+
+ public void testSerialization() throws Exception {
+ event = new PreferenceChangeEvent(Preferences.userRoot(), "key",
+ "value");
+ try {
+ SerializationTest.copySerializable(event);
+ fail("No expected NotSerializableException");
+ } catch (NotSerializableException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeListenerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeListenerTest.java
new file mode 100644
index 0000000..63170e7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferenceChangeListenerTest.java
@@ -0,0 +1,52 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.prefs.PreferenceChangeEvent;
+import java.util.prefs.PreferenceChangeListener;
+import java.util.prefs.Preferences;
+import junit.framework.TestCase;
+
+/**
+ *
+ */
+public class PreferenceChangeListenerTest extends TestCase {
+
+ PreferenceChangeListener l;
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ l = new PreferenceChangeListenerImpl();
+ }
+
+ public void testPreferenceChange() {
+ l.preferenceChange(new PreferenceChangeEvent(Preferences.userRoot(),
+ "", ""));
+ }
+
+ public static class PreferenceChangeListenerImpl implements
+ PreferenceChangeListener {
+ public void preferenceChange(PreferenceChangeEvent pce) {
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesFactoryTest.java
new file mode 100644
index 0000000..e70fc5a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesFactoryTest.java
@@ -0,0 +1,59 @@
+/* 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.tests.java.util.prefs;
+
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+import junit.framework.TestCase;
+
+/**
+ *
+ */
+public class PreferencesFactoryTest extends TestCase {
+
+ PreferencesFactory f;
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ f = new PreferencesFactoryImpl();
+ }
+
+ public void testUserRoot() {
+ assertNull(f.userRoot());
+ }
+
+ public void testSystemRoot() {
+ assertNull(f.systemRoot());
+ }
+
+ public static class PreferencesFactoryImpl implements PreferencesFactory {
+
+ public Preferences userRoot() {
+ return null;
+ }
+
+ public Preferences systemRoot() {
+ return null;
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesTest.java
new file mode 100644
index 0000000..3d194da
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/prefs/PreferencesTest.java
@@ -0,0 +1,420 @@
+/* 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.tests.java.util.prefs;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+import java.nio.charset.StandardCharsets;
+import java.util.prefs.AbstractPreferences;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.InvalidPreferencesFormatException;
+import java.util.prefs.NodeChangeListener;
+import java.util.prefs.PreferenceChangeListener;
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+import junit.framework.TestCase;
+import libcore.io.IoUtils;
+
+/**
+ *
+ */
+public class PreferencesTest extends TestCase {
+
+ private static final String PREFS =
+ "<!DOCTYPE preferences SYSTEM \"http://java.sun.com/dtd/preferences.dtd\">" +
+ "<preferences>" +
+ "<root type=\"user\">" +
+ "<map></map>" +
+ "</root>" +
+ "</preferences>";
+
+
+ private MockInputStream stream ;
+ private InputStream in;
+ private PreferencesFactory defaultFactory;
+
+ @Override
+ protected void setUp() throws Exception {
+ File tmpDir = IoUtils.createTemporaryDirectory("OldAbstractPreferencesTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new AbstractPreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
+
+ in = new ByteArrayInputStream(PREFS.getBytes(StandardCharsets.US_ASCII));
+ stream = new MockInputStream(in);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ stream.close();
+ }
+
+ public void testSystemNodeForPackage() throws Exception {
+ Preferences p = Preferences.systemNodeForPackage(Object.class);
+
+ assertEquals("/java/lang", p.absolutePath());
+ assertTrue(p instanceof AbstractPreferences);
+ Preferences root = Preferences.systemRoot();
+ Preferences parent = root.node("java");
+ assertSame(parent, p.parent());
+ assertFalse(p.isUserNode());
+ assertEquals("lang", p.name());
+ assertEquals("System Preference Node: " + p.absolutePath(), p
+ .toString());
+
+ assertEquals(0, p.childrenNames().length);
+ assertEquals(0, p.keys().length);
+ parent.removeNode();
+ try {
+ Preferences.userNodeForPackage(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testSystemRoot() throws BackingStoreException {
+ Preferences p = Preferences.systemRoot();
+ assertTrue(p instanceof AbstractPreferences);
+ assertEquals("/", p.absolutePath());
+ assertSame(null, p.parent());
+ assertFalse(p.isUserNode());
+ assertEquals("", p.name());
+ assertEquals("System Preference Node: " + p.absolutePath(), p
+ .toString());
+ }
+
+ public void testConsts() {
+ assertEquals(80, Preferences.MAX_KEY_LENGTH);
+ assertEquals(80, Preferences.MAX_NAME_LENGTH);
+ assertEquals(8192, Preferences.MAX_VALUE_LENGTH);
+ }
+
+ public void testUserNodeForPackage() throws BackingStoreException {
+ Preferences p = Preferences.userNodeForPackage(Object.class);
+ assertEquals("/java/lang", p.absolutePath());
+ assertTrue(p instanceof AbstractPreferences);
+ Preferences root = Preferences.userRoot();
+ Preferences parent = root.node("java");
+ assertSame(parent, p.parent());
+ assertTrue(p.isUserNode());
+ assertEquals("lang", p.name());
+ assertEquals("User Preference Node: " + p.absolutePath(), p.toString());
+ assertEquals(0, p.childrenNames().length);
+ assertEquals(0, p.keys().length);
+
+ try {
+ Preferences.userNodeForPackage(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testUserRoot() throws BackingStoreException {
+ Preferences p = Preferences.userRoot();
+ assertTrue(p instanceof AbstractPreferences);
+ assertEquals("/", p.absolutePath());
+ assertSame(null, p.parent());
+ assertTrue(p.isUserNode());
+ assertEquals("", p.name());
+ assertEquals("User Preference Node: " + p.absolutePath(), p.toString());
+ }
+
+ public void testImportPreferences() throws Exception {
+ Preferences prefs = null;
+ try {
+ prefs = Preferences.userNodeForPackage(PreferencesTest.class);
+
+ prefs.put("prefskey", "oldvalue");
+ prefs.put("prefskey2", "oldvalue2");
+ in = PreferencesTest.class
+ .getResourceAsStream("/resources/prefs/java/util/prefs/userprefs.xml");
+ Preferences.importPreferences(in);
+
+ prefs = Preferences.userNodeForPackage(PreferencesTest.class);
+ assertEquals(1, prefs.childrenNames().length);
+ assertTrue(prefs.nodeExists("mock/child/grandson"));
+ assertEquals("newvalue", prefs.get("prefskey", null));
+ assertEquals("oldvalue2", prefs.get("prefskey2", null));
+ assertEquals("newvalue3", prefs.get("prefskey3", null));
+
+ in = PreferencesTest.class.getResourceAsStream(
+ "/prefs/java/util/prefs/userprefs-badform.xml");
+ try {
+ Preferences.importPreferences(in);
+ fail("should throw InvalidPreferencesFormatException");
+ } catch (InvalidPreferencesFormatException expected) {
+ }
+ } finally {
+ try {
+ prefs = Preferences.userNodeForPackage(PreferencesTest.class);
+ prefs.removeNode();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ public void testImportPreferencesException() throws Exception {
+ try {
+ Preferences.importPreferences(null);
+ fail("should throw MalformedURLException");
+ } catch (MalformedURLException expected) {
+ }
+
+ byte[] source = new byte[0];
+ InputStream in = new ByteArrayInputStream(source);
+ try {
+ Preferences.importPreferences(in);
+ fail("should throw InvalidPreferencesFormatException");
+ } catch (InvalidPreferencesFormatException expected) {
+ }
+
+ stream.setResult(MockInputStream.exception);
+ try {
+ Preferences.importPreferences(stream);
+ fail("should throw IOException");
+ } catch (IOException expected) {
+ }
+
+ stream.setResult(MockInputStream.runtimeException);
+ try {
+ Preferences.importPreferences(stream);
+ fail("should throw RuntimeException");
+ } catch (RuntimeException expected) {
+ }
+ }
+
+ static class MockInputStream extends InputStream {
+
+ static final int normal = 0;
+
+ static final int exception = 1;
+
+ static final int runtimeException = 2;
+
+ int result = normal;
+
+ InputStream wrapper;
+
+ public void setResult(int i) {
+ result = i;
+ }
+
+ private void checkException() throws IOException {
+ switch (result) {
+ case normal:
+ return;
+ case exception:
+ throw new IOException("test");
+ case runtimeException:
+ throw new RuntimeException("test");
+ }
+ }
+
+ public MockInputStream(InputStream in) {
+ wrapper = in;
+ }
+
+ @Override
+ public int read() throws IOException {
+ checkException();
+ return wrapper.read();
+ }
+ }
+
+ static class MockPreferences extends Preferences {
+
+ public MockPreferences() {
+ super();
+ }
+
+ @Override
+ public String absolutePath() {
+ return null;
+ }
+
+ @Override
+ public String[] childrenNames() throws BackingStoreException {
+ return null;
+ }
+
+ @Override
+ public void clear() throws BackingStoreException {
+ }
+
+ @Override
+ public void exportNode(OutputStream ostream) throws IOException,
+ BackingStoreException {
+ }
+
+ @Override
+ public void exportSubtree(OutputStream ostream) throws IOException,
+ BackingStoreException {
+ }
+
+ @Override
+ public void flush() throws BackingStoreException {
+ }
+
+ @Override
+ public String get(String key, String deflt) {
+ return null;
+ }
+
+ @Override
+ public boolean getBoolean(String key, boolean deflt) {
+ return false;
+ }
+
+ @Override
+ public byte[] getByteArray(String key, byte[] deflt) {
+ return null;
+ }
+
+ @Override
+ public double getDouble(String key, double deflt) {
+ return 0;
+ }
+
+ @Override
+ public float getFloat(String key, float deflt) {
+ return 0;
+ }
+
+ @Override
+ public int getInt(String key, int deflt) {
+ return 0;
+ }
+
+ @Override
+ public long getLong(String key, long deflt) {
+ return 0;
+ }
+
+ @Override
+ public boolean isUserNode() {
+ return false;
+ }
+
+ @Override
+ public String[] keys() throws BackingStoreException {
+ return null;
+ }
+
+ @Override
+ public String name() {
+ return null;
+ }
+
+ @Override
+ public Preferences node(String name) {
+ return null;
+ }
+
+ @Override
+ public boolean nodeExists(String name) throws BackingStoreException {
+ return false;
+ }
+
+ @Override
+ public Preferences parent() {
+ return null;
+ }
+
+ @Override
+ public void put(String key, String value) {
+
+ }
+
+ @Override
+ public void putBoolean(String key, boolean value) {
+
+ }
+
+ @Override
+ public void putByteArray(String key, byte[] value) {
+
+ }
+
+ @Override
+ public void putDouble(String key, double value) {
+
+ }
+
+ @Override
+ public void putFloat(String key, float value) {
+
+ }
+
+ @Override
+ public void putInt(String key, int value) {
+
+ }
+
+ @Override
+ public void putLong(String key, long value) {
+
+ }
+
+ @Override
+ public void remove(String key) {
+
+ }
+
+ @Override
+ public void removeNode() throws BackingStoreException {
+
+ }
+
+ @Override
+ public void addNodeChangeListener(NodeChangeListener ncl) {
+
+ }
+
+ @Override
+ public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
+
+ }
+
+ @Override
+ public void removeNodeChangeListener(NodeChangeListener ncl) {
+
+ }
+
+ @Override
+ public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
+
+ }
+
+ @Override
+ public void sync() throws BackingStoreException {
+
+ }
+
+ @Override
+ public String toString() {
+ return null;
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/regex/MatcherTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/regex/MatcherTest.java
index 98450a4..9f749c6 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/regex/MatcherTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/regex/MatcherTest.java
@@ -22,7 +22,6 @@ import java.util.regex.Pattern;
import junit.framework.TestCase;
-@SuppressWarnings("nls")
public class MatcherTest extends TestCase {
String[] testPatterns = {
"(a|b)*abb",
@@ -40,42 +39,42 @@ public class MatcherTest extends TestCase {
public MatcherTest(String name) {
super(name);
}
-
+
public void testRegionsIntInt() {
Pattern p = Pattern.compile("x*");
Matcher m = p.matcher("axxxxxa");
assertFalse(m.matches());
-
+
m.region(1, 6);
assertEquals(1, m.regionStart());
assertEquals(6, m.regionEnd());
assertTrue(m.matches());
-
+
try {
m.region(1, 0);
fail("expected an IOOBE");
} catch(IndexOutOfBoundsException e) {
}
-
+
try {
m.region(-1, 2);
fail("expected an IOOBE");
} catch(IndexOutOfBoundsException e) {
}
-
+
try {
m.region(10, 11);
fail("expected an IOOBE");
} catch(IndexOutOfBoundsException e) {
}
-
+
try {
m.region(1, 10);
fail("expected an IOOBE");
} catch(IndexOutOfBoundsException e) {
}
}
-
+
public void testAppendReplacement() {
Pattern pat = Pattern.compile("XX");
Matcher m = pat.matcher("Today is XX-XX-XX ...");
@@ -109,16 +108,13 @@ public class MatcherTest extends TestCase {
assertEquals("-foo-foo-foo-", mat.replaceAll("-"));
}
- /*
- * Class under test for Matcher reset(CharSequence)
- */
public void testResetCharSequence() {
Pattern p = Pattern.compile("abcd");
Matcher m = p.matcher("abcd");
assertTrue(m.matches());
m.reset("efgh");
assertFalse(m.matches());
-
+
try {
m.reset(null);
fail("expected a NPE");
@@ -159,15 +155,9 @@ public class MatcherTest extends TestCase {
}
}
- /*
- * Class under test for Matcher reset()
- */
public void testReset() {
}
- /*
- * Class under test for String group(int)
- */
public void testGroupint() {
String positiveTestString = "ababababbaaabb";
@@ -245,24 +235,6 @@ public class MatcherTest extends TestCase {
assertEquals("a", mat.group(1));
}
- /*
- * Class under test for boolean find(int)
- */
- public void testFindint() {
- }
-
- /*
- * Class under test for int start(int)
- */
- public void testStartint() {
- }
-
- /*
- * Class under test for int end(int)
- */
- public void testEndint() {
- }
-
public void testMatchesMisc() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
@@ -350,9 +322,6 @@ public class MatcherTest extends TestCase {
public void testLookingAt() {
}
- /*
- * Class under test for boolean find()
- */
public void testFind() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -389,12 +358,6 @@ public class MatcherTest extends TestCase {
assertTrue(mat.matches());
}
- /*
- * Class under test for int start()
- */
- public void testStart() {
- }
-
public void testGroupCount() {
for (int i = 0; i < groupPatterns.length; i++) {
Pattern test = Pattern.compile(groupPatterns[i]);
@@ -595,11 +558,9 @@ public class MatcherTest extends TestCase {
assertEquals("a", mat.group());
}
- /*
- * Verify if the Matcher can match the input when region is changed
- */
public void testMatchesRegionChanged() {
// Regression for HARMONY-610
+ // Verify if the Matcher can match the input when region is changed
String input = " word ";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(input);
@@ -645,11 +606,9 @@ public class MatcherTest extends TestCase {
assertEquals(0x110000 / step, cnt);
}
- /*
- * Verify if the Matcher behaves correct when region is changed
- */
public void testFindRegionChanged() {
// Regression for HARMONY-625
+ // Verify if the Matcher behaves correct when region is changed.
Pattern pattern = Pattern.compile("(?s).*");
Matcher matcher = pattern.matcher("abcde");
matcher.find();
@@ -662,12 +621,9 @@ public class MatcherTest extends TestCase {
}
- /*
- * Verify if the Matcher behaves correct with pattern "c" when region is
- * changed
- */
public void testFindRegionChanged2() {
// Regression for HARMONY-713
+ // Verify if the Matcher behaves correct with pattern "c" when region is changed.
Pattern pattern = Pattern.compile("c");
String inputStr = "aabb.c";
@@ -677,18 +633,14 @@ public class MatcherTest extends TestCase {
assertFalse(matcher.find());
}
- /*
- * Regression test for HARMONY-674
- */
public void testPatternMatcher() throws Exception {
+ // Regression test for HARMONY-674
Pattern pattern = Pattern.compile("(?:\\d+)(?:pt)");
assertTrue(pattern.matcher("14pt").matches());
}
- /**
- * Inspired by HARMONY-3360
- */
public void test3360() {
+ // Inspired by HARMONY-3360
String str = "!\"#%&'(),-./";
Pattern p = Pattern.compile("\\s");
Matcher m = p.matcher(str);
@@ -696,12 +648,9 @@ public class MatcherTest extends TestCase {
assertFalse(m.find());
}
- /**
- * Regression test for HARMONY-3360
- */
public void testGeneralPunctuationCategory() {
- String[] s = { ",", "!", "\"", "#", "%", "&", "'", "(", ")", "-", ".",
- "/" };
+ // Regression test for HARMONY-3360
+ String[] s = { ",", "!", "\"", "#", "%", "&", "'", "(", ")", "-", ".", "/" };
String regexp = "\\p{P}";
for (int i = 0; i < s.length; i++) {
@@ -711,10 +660,8 @@ public class MatcherTest extends TestCase {
}
}
- /**
- * Regression test for HARMONY-4396
- */
public void testHitEndAfterFind() {
+ // Regression test for HARMONY-4396
hitEndTest(true, "#01.0", "r((ege)|(geg))x", "regexx", false);
hitEndTest(true, "#01.1", "r((ege)|(geg))x", "regex", false);
hitEndTest(true, "#01.2", "r((ege)|(geg))x", "rege", true);
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/A.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/A.java
new file mode 100644
index 0000000..a03935a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/A.java
@@ -0,0 +1,13 @@
+package org.apache.harmony.tests.java.util.support;
+
+public class A implements I {
+ private static P pp = new P();
+
+ public A() {
+ pp.setClazz(getClass());
+ }
+
+ public String find(String key) {
+ return pp.findProp(key);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/B.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/B.java
new file mode 100644
index 0000000..03ebb15
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/B.java
@@ -0,0 +1,4 @@
+package org.apache.harmony.tests.java.util.support;
+
+public class B extends A {
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/I.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/I.java
new file mode 100644
index 0000000..4538945
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/I.java
@@ -0,0 +1,5 @@
+package org.apache.harmony.tests.java.util.support;
+
+public interface I {
+ String find(String key);
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/P.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/P.java
new file mode 100644
index 0000000..bba2537
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/support/P.java
@@ -0,0 +1,28 @@
+package org.apache.harmony.tests.java.util.support;
+
+import java.util.ResourceBundle;
+
+public class P {
+ private Class c;
+
+ public void setClazz(Class c) {
+ this.c = c;
+ }
+
+ public String findProp(String key) {
+ return findProp(this.c, key);
+ }
+
+ private String findProp(Class cls, String key) {
+ String ret = null;
+ try {
+ ResourceBundle b = ResourceBundle.getBundle(cls.getName());
+ ret = (String)b.getObject(key);
+ } catch (Exception e) {
+ }
+ if (ret == null && !cls.equals(Object.class) && !cls.isPrimitive()) {
+ ret = findProp(cls.getSuperclass(), key);
+ }
+ return ret;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/Adler32Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/Adler32Test.java
new file mode 100644
index 0000000..7555896
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/Adler32Test.java
@@ -0,0 +1,169 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.util.zip.Adler32;
+
+public class Adler32Test extends junit.framework.TestCase {
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+
+ }
+
+ /**
+ * 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());
+
+ }
+
+ /**
+ * java.util.zip.Adler32#update(byte[], int, int)
+ */
+ public void test_update$BII() {
+ // test methods of java.util.zip.update(byte[],int,int)
+ byte[] byteArray = { 1, 2, 3 };
+ Adler32 adl = new Adler32();
+ int off = 2;// accessing the 2nd element of byteArray
+ int len = 1;
+ int lenError = 3;
+ int offError = 4;
+ adl.update(byteArray, off, len);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 262148
+ assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
+ 262148, adl.getValue());
+ int r = 0;
+
+ try {
+ adl.update(byteArray, off, lenError);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
+ 1, r);
+
+ try {
+ adl.update(byteArray, offError, len);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 2;
+ }
+ assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
+ 2, r);
+
+ }
+
+ @Override
+ protected void setUp() {
+ }
+
+ @Override
+ protected void tearDown() {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CRC32Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CRC32Test.java
new file mode 100644
index 0000000..30bdf9f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CRC32Test.java
@@ -0,0 +1,186 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.util.zip.CRC32;
+
+public class CRC32Test extends junit.framework.TestCase {
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.zip.CRC32#update(byte[], int, int)
+ */
+ public void test_update$BII() {
+ // test methods of java.util.zip.update(byte[],int,int)
+ byte[] byteArray = { 1, 2, 3 };
+ CRC32 crc = new CRC32();
+ int off = 2;// accessing the 2nd element of byteArray
+ int len = 1;
+ int lenError = 3;
+ int offError = 4;
+ crc.update(byteArray, off, len);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 1259060791
+ assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
+ 1259060791L, crc.getValue());
+ int r = 0;
+ try {
+ crc.update(byteArray, off, lenError);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
+ 1, r);
+
+ try {
+ crc.update(byteArray, offError, len);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 2;
+ }
+ assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
+ 2, r);
+ }
+
+ @Override
+ protected void setUp() {
+
+ }
+
+ @Override
+ protected void tearDown() {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedInputStreamTest.java
new file mode 100644
index 0000000..903f60b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedInputStreamTest.java
@@ -0,0 +1,130 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.zip.CRC32;
+import java.util.zip.CheckedInputStream;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class CheckedInputStreamTest extends TestCase {
+
+ /**
+ * 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();
+ }
+
+ /**
+ * java.util.zip.CheckedInputStream#getChecksum()
+ */
+ public void test_getChecksum() throws Exception {
+ byte outBuf[] = new byte[100];
+ File f = File.createTempFile("CheckedInputStreamTest", ".txt");
+ InputStream inEmp = new FileInputStream(f);
+ CheckedInputStream checkEmpty = new CheckedInputStream(inEmp, new CRC32());
+ while (checkEmpty.read() >= 0) {
+ }
+ assertEquals("the checkSum value of an empty file is not zero", 0, checkEmpty
+ .getChecksum().getValue());
+ inEmp.close();
+
+ // testing getChecksum for the file checkInput
+ InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
+ while (checkIn.read() >= 0) {
+ }
+ // ran JDK and found that the checkSum value of this is 2036203193
+ // System.out.print(" " + checkIn.getChecksum().getValue());
+ assertEquals("the checksum value is incorrect", 2036203193, checkIn.getChecksum()
+ .getValue());
+ checkInput.close();
+ // testing getChecksum for file checkInput
+ checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn2 = new CheckedInputStream(checkInput, new CRC32());
+ checkIn2.read(outBuf, 0, 10);
+ // ran JDK and found that the checkSum value of this is 2235765342
+ // System.out.print(" " + checkIn2.getChecksum().getValue());
+ assertEquals("the checksum value is incorrect", 2235765342L, checkIn2.getChecksum()
+ .getValue());
+ checkInput.close();
+ }
+
+ /**
+ * java.util.zip.CheckedInputStream#skip(long)
+ */
+ public void test_skipJ() throws Exception {
+ // testing that the return by skip is valid
+ InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
+ long skipValue = 5;
+ assertEquals("the value returned by skip(n) is not the same as its parameter",
+ skipValue, checkIn.skip(skipValue));
+ checkIn.skip(skipValue);
+ // ran JDK and found the checkSum value is 2235765342
+ // System.out.print(checkIn.getChecksum().getValue());
+ assertEquals("checkSum value is not correct", 2235765342L, checkIn.getChecksum()
+ .getValue());
+ assertEquals(0, checkIn.skip(0));
+ checkInput.close();
+ }
+
+ public void test_read() throws Exception {
+ // testing that the return by skip is valid
+ InputStream checkInput = Support_Resources
+ .getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput,
+ new CRC32());
+ checkIn.read();
+ checkIn.close();
+ try {
+ checkIn.read();
+ fail("IOException expected.");
+ } catch (IOException ee) {
+ // expected
+ }
+ checkInput.close();
+ }
+
+ public void test_read$byteII() throws Exception {
+ // testing that the return by skip is valid
+ InputStream checkInput = Support_Resources
+ .getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput,
+ new CRC32());
+ byte buff[] = new byte[50];
+ checkIn.read(buff, 10, 5);
+ checkIn.close();
+ try {
+ checkIn.read(buff, 10, 5);
+ fail("IOException expected.");
+ } catch (IOException ee) {
+ // expected
+ }
+ checkInput.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedOutputStreamTest.java
new file mode 100644
index 0000000..09d5756
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/CheckedOutputStreamTest.java
@@ -0,0 +1,140 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.Adler32;
+import java.util.zip.CRC32;
+import java.util.zip.CheckedOutputStream;
+
+public class CheckedOutputStreamTest extends junit.framework.TestCase {
+
+ /**
+ * java.util.zip.CheckedOutputStream#CheckedOutputStream(java.io.OutputStream,
+ *java.util.zip.Checksum)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Checksum() {
+ // test method java.util.zip.checkedOutputStream.constructor
+ try {
+ FileOutputStream outFile = new FileOutputStream(
+ File.createTempFile("CheckedOutputStreamTest", ".txt"));
+ CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
+ new CRC32());
+ assertEquals("the checkSum value of the constructor is not 0", 0, chkOut
+ .getChecksum().getValue());
+ outFile.close();
+ } catch (IOException e) {
+ fail("Unable to find file");
+ } catch (SecurityException e) {
+ fail(
+ "file cannot be opened for writing due to security reasons");
+ }
+ }
+
+ /**
+ * java.util.zip.CheckedOutputStream#getChecksum()
+ */
+ public void test_getChecksum() {
+ // test method java.util.zip.checkedOutputStream.getChecksum()
+ byte byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
+ try {
+ FileOutputStream outFile = new FileOutputStream(
+ File.createTempFile("CheckedOutputStreamTest", ".txt"));
+ CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
+ new Adler32());
+ chkOut.write(byteArray[4]);
+ // ran JDK and found that checkSum value is 7536755
+ // System.out.print(chkOut.getChecksum().getValue());
+
+ assertEquals("the checkSum value for writeI is incorrect", 7536755, chkOut
+ .getChecksum().getValue());
+ chkOut.getChecksum().reset();
+ chkOut.write(byteArray, 5, 4);
+ // ran JDK and found that checkSum value is 51708133
+ // System.out.print(" " +chkOut.getChecksum().getValue());
+
+ assertEquals("the checkSum value for writeBII is incorrect ", 51708133, chkOut
+ .getChecksum().getValue());
+ outFile.close();
+ } catch (IOException e) {
+ fail("Unable to find file");
+ } catch (SecurityException e) {
+ fail(
+ "file cannot be opened for writing due to security reasons");
+ }
+ }
+
+ /**
+ * java.util.zip.CheckedOutputStream#write(int)
+ */
+ public void test_writeI() {
+ // test method java.util.zip.checkedOutputStream.writeI()
+ byte byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
+ try {
+ FileOutputStream outFile = new FileOutputStream(
+ File.createTempFile("CheckedOutputStreamTest", ".txt"));
+ CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
+ new CRC32());
+ for (byte element : byteArray) {
+ chkOut.write(element);
+ }
+ assertTrue(
+ "the checkSum value is zero, no bytes are written to the output file",
+ chkOut.getChecksum().getValue() != 0);
+ outFile.close();
+ } catch (IOException e) {
+ fail("Unable to find file");
+ } catch (SecurityException e) {
+ fail("File cannot be opened for writing due to security reasons");
+ }
+ }
+
+ /**
+ * java.util.zip.CheckedOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() {
+ // test method java.util.zip.checkOutputStream.writeBII()
+ byte byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
+ try {
+ FileOutputStream outFile = new FileOutputStream(
+ File.createTempFile("CheckedOutputStreamTest", ".txt"));
+ CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
+ new CRC32());
+ chkOut.write(byteArray, 4, 5);
+ assertTrue(
+ "the checkSum value is zero, no bytes are written to the output file",
+ chkOut.getChecksum().getValue() != 0);
+ int r = 0;
+ try {
+ chkOut.write(byteArray, 4, 6);
+ } catch (IndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("boundary check is not performed", 1, r);
+ outFile.close();
+ } catch (IOException e) {
+ fail("Unable to find file");
+ } catch (SecurityException e) {
+ fail(
+ "file cannot be opened for writing due to security reasons");
+ } catch (IndexOutOfBoundsException e) {
+ fail("Index for write is out of bounds");
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterInputStreamTest.java
new file mode 100644
index 0000000..7ed5916
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterInputStreamTest.java
@@ -0,0 +1,426 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.zip.DataFormatException;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterInputStream;
+
+import junit.framework.TestCase;
+import libcore.io.Streams;
+
+public class DeflaterInputStreamTest extends TestCase {
+
+ private static final String TEST_STR = "Hi,this is a test";
+
+ private static final byte[] TEST_STRING_DEFLATED_BYTES = {
+ 120, -100, -13, -56, -44, 41, -55, -56, 44, 86,
+ 0, -94, 68, -123, -110, -44, -30, 18, 0, 52,
+ 34, 5, -13 };
+
+ private InputStream is;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ is = new ByteArrayInputStream(TEST_STR.getBytes("UTF-8"));
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ is.close();
+ super.tearDown();
+ }
+
+ /**
+ * DeflaterInputStream#available()
+ */
+ public void testAvailable() throws IOException {
+ byte[] buf = new byte[1024];
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ assertEquals(120, dis.read());
+ assertEquals(1, dis.available());
+ assertEquals(22, dis.read(buf, 0, 1024));
+ assertEquals(0, dis.available());
+ assertEquals(-1, dis.read());
+ assertEquals(0, dis.available());
+ dis.close();
+ try {
+ dis.available();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * DeflaterInputStream#close()
+ */
+ public void testClose() throws IOException {
+ byte[] buf = new byte[1024];
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ dis.close();
+ try {
+ dis.available();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(buf, 0, 1024);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ // can close after close
+ dis.close();
+ }
+
+ /**
+ * DeflaterInputStream#mark()
+ */
+ public void testMark() throws IOException {
+ // mark do nothing
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ dis.mark(-1);
+ dis.mark(0);
+ dis.mark(1);
+ dis.close();
+ dis.mark(1);
+ }
+
+ /**
+ * DeflaterInputStream#markSupported()
+ */
+ public void testMarkSupported() throws IOException {
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertFalse(dis.markSupported());
+ dis.close();
+ assertFalse(dis.markSupported());
+ }
+
+ /**
+ * DeflaterInputStream#read()
+ */
+ public void testRead() throws IOException {
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ assertEquals(120, dis.read());
+ assertEquals(1, dis.available());
+ assertEquals(156, dis.read());
+ assertEquals(1, dis.available());
+ assertEquals(243, dis.read());
+ assertEquals(1, dis.available());
+ dis.close();
+ try {
+ dis.read();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ public void testRead_golden() throws Exception {
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ byte[] contents = Streams.readFully(dis);
+ assertTrue(Arrays.equals(TEST_STRING_DEFLATED_BYTES, contents));
+
+ byte[] result = new byte[32];
+ dis = new DeflaterInputStream(new ByteArrayInputStream(TEST_STR.getBytes("UTF-8")));
+ int count = 0;
+ int bytesRead = 0;
+ while ((bytesRead = dis.read(result, count, 4)) != -1) {
+ count += bytesRead;
+ }
+ assertEquals(23, count);
+ byte[] splicedResult = new byte[23];
+ System.arraycopy(result, 0, splicedResult, 0, 23);
+ assertTrue(Arrays.equals(TEST_STRING_DEFLATED_BYTES, splicedResult));
+ }
+
+ public void testRead_leavesBufUnmodified() throws Exception {
+ DeflaterInputStreamWithPublicBuffer dis = new DeflaterInputStreamWithPublicBuffer(is);
+ byte[] contents = Streams.readFully(dis);
+ assertTrue(Arrays.equals(TEST_STRING_DEFLATED_BYTES, contents));
+
+ // protected field buf is a part of the public API of this class.
+ // we guarantee that it's only used as an input buffer, and not for
+ // anything else.
+ byte[] buf = dis.getBuffer();
+ byte[] expected = TEST_STR.getBytes("UTF-8");
+
+ byte[] splicedBuf = new byte[expected.length];
+ System.arraycopy(buf, 0, splicedBuf, 0, splicedBuf.length);
+ assertTrue(Arrays.equals(expected, splicedBuf));
+ }
+
+ /**
+ * DeflaterInputStream#read(byte[], int, int)
+ */
+ public void testReadByteArrayIntInt() throws IOException {
+ byte[] buf1 = new byte[256];
+ byte[] buf2 = new byte[256];
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertEquals(23, dis.read(buf1, 0, 256));
+ dis = new DeflaterInputStream(is);
+ assertEquals(8, dis.read(buf2, 0, 256));
+ is = new ByteArrayInputStream(TEST_STR.getBytes("UTF-8"));
+ dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ assertEquals(120, dis.read());
+ assertEquals(1, dis.available());
+ assertEquals(22, dis.read(buf2, 0, 256));
+ assertEquals(0, dis.available());
+ assertEquals(-1, dis.read());
+ assertEquals(0, dis.available());
+ try {
+ dis.read(buf1, 0, 512);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ dis.read(null, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ dis.read(null, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ dis.read(null, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ dis.read(buf1, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ dis.read(buf1, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ dis.close();
+ try {
+ dis.read(buf1, 0, 512);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(buf1, 0, 1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(null, 0, 0);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(null, -1, 0);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(null, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(buf1, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ dis.read(buf1, 0, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * DeflaterInputStream#reset()
+ */
+ public void testReset() throws IOException {
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ try {
+ dis.reset();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ dis.close();
+ try {
+ dis.reset();
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * DeflaterInputStream#skip()
+ */
+ public void testSkip() throws IOException {
+ byte[] buf = new byte[1024];
+ DeflaterInputStream dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ dis.skip(1);
+ assertEquals(1, dis.available());
+ assertEquals(22, dis.read(buf, 0, 1024));
+ assertEquals(0, dis.available());
+ assertEquals(0, dis.available());
+ is = new ByteArrayInputStream(TEST_STR.getBytes("UTF-8"));
+ dis = new DeflaterInputStream(is);
+ assertEquals(1, dis.available());
+ dis.skip(56);
+ assertEquals(0, dis.available());
+ assertEquals(-1, dis.read(buf, 0, 1024));
+
+ assertEquals(0, dis.available());
+ // can still skip
+ dis.skip(1);
+ dis.close();
+ try {
+ dis.skip(1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ is = new ByteArrayInputStream(TEST_STR.getBytes("UTF-8"));
+ dis = new DeflaterInputStream(is);
+ assertEquals(23, dis.skip(Long.MAX_VALUE));
+ assertEquals(0, dis.available());
+ }
+
+ /**
+ * DeflaterInputStream#DeflaterInputStream(InputStream)
+ */
+ public void testDeflaterInputStreamInputStream() {
+ // ok
+ new DeflaterInputStream(is);
+ // fail
+ try {
+ new DeflaterInputStream(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * DataFormatException#DataFormatException()
+ */
+ public void testDataFormatException() {
+ new DataFormatException();
+ }
+
+ /**
+ * DeflaterInputStream#DeflaterInputStream(InputStream, Deflater)
+ */
+ public void testDeflaterInputStreamInputStreamDeflater() {
+ // ok
+ new DeflaterInputStream(is, new Deflater());
+ // fail
+ try {
+ new DeflaterInputStream(is, null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new DeflaterInputStream(null, new Deflater());
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * DeflaterInputStream#DeflaterInputStream(InputStream, Deflater, int)
+ */
+ public void testDeflaterInputStreamInputStreamDeflaterInt() {
+ // ok
+ new DeflaterInputStream(is, new Deflater(), 1024);
+ // fail
+ try {
+ new DeflaterInputStream(is, null, 1024);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new DeflaterInputStream(null, new Deflater(), 1024);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new DeflaterInputStream(is, new Deflater(), -1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ new DeflaterInputStream(null, new Deflater(), -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ new DeflaterInputStream(is, null, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public static final class DeflaterInputStreamWithPublicBuffer extends DeflaterInputStream {
+
+ public DeflaterInputStreamWithPublicBuffer(InputStream in) {
+ super(in);
+ }
+
+ public byte[] getBuffer() {
+ return buf;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterOutputStreamTest.java
new file mode 100644
index 0000000..e4be198
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterOutputStreamTest.java
@@ -0,0 +1,402 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.InflaterInputStream;
+
+import junit.framework.TestCase;
+
+public class DeflaterOutputStreamTest extends TestCase {
+
+ private class MyDeflaterOutputStream extends DeflaterOutputStream {
+ boolean deflateFlag = false;
+
+ MyDeflaterOutputStream(OutputStream out) {
+ super(out);
+ }
+
+ MyDeflaterOutputStream(OutputStream out, Deflater defl) {
+ super(out, defl);
+ }
+
+ MyDeflaterOutputStream(OutputStream out, Deflater defl, int size) {
+ super(out, defl, size);
+ }
+
+ byte[] getProtectedBuf() {
+ return buf;
+ }
+
+ protected void deflate() throws IOException {
+ deflateFlag = true;
+ super.deflate();
+ }
+
+ boolean getDaflateFlag() {
+ return deflateFlag;
+ }
+ }
+
+ private final byte outputBuf[] = new byte[500];
+
+ @Override
+ protected void setUp() {
+ // setting up a deflater to be used
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ int x = 0;
+ Deflater deflate = new Deflater(1);
+ deflate.setInput(byteArray);
+ while (!(deflate.needsInput())) {
+ x += deflate.deflate(outputBuf, x, outputBuf.length - x);
+ }
+ deflate.finish();
+ while (!(deflate.finished())) {
+ x = x + deflate.deflate(outputBuf, x, outputBuf.length - x);
+ }
+ deflate.end();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
+ *java.util.zip.Deflater)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater() throws Exception {
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ File f1 = File.createTempFile("hyts_ConstruOD", ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ Deflater defl = null;
+ MyDeflaterOutputStream dos;
+ // Test for a null Deflater.
+ try {
+ dos = new MyDeflaterOutputStream(fos, defl);
+ fail("NullPointerException Not Thrown");
+ } catch (NullPointerException e) {
+ }
+ defl = new Deflater();
+ dos = new MyDeflaterOutputStream(fos, defl);
+
+ // Test to see if DeflaterOutputStream was created with the correct
+ // buffer.
+ assertEquals("Incorrect Buffer Size", 512, dos.getProtectedBuf().length);
+
+ dos.write(byteArray);
+ dos.close();
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws Exception {
+ File f1 = File.createTempFile("hyts_ConstruO", ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos);
+
+ // Test to see if DeflaterOutputStream was created with the correct
+ // buffer.
+ assertEquals("Incorrect Buffer Size", 512, dos.getProtectedBuf().length);
+
+ dos.write(outputBuf);
+ dos.close();
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
+ *java.util.zip.Deflater, int)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_DeflaterI()
+ throws Exception {
+ int buf = 5;
+ int negBuf = -5;
+ int zeroBuf = 0;
+ byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
+ File f1 = File.createTempFile("hyts_ConstruODI", ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ Deflater defl = null;
+ MyDeflaterOutputStream dos;
+
+ // Test for a null Deflater.
+ try {
+ dos = new MyDeflaterOutputStream(fos, defl, buf);
+ fail("NullPointerException Not Thrown");
+ } catch (NullPointerException e) {
+ }
+ defl = new Deflater();
+
+ // Test for a negative buf.
+ try {
+ dos = new MyDeflaterOutputStream(fos, defl, negBuf);
+ fail("IllegalArgumentException Not Thrown");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // Test for a zero buf.
+ try {
+ dos = new MyDeflaterOutputStream(fos, defl, zeroBuf);
+ fail("IllegalArgumentException Not Thrown");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // Test to see if DeflaterOutputStream was created with the correct
+ // buffer.
+ dos = new MyDeflaterOutputStream(fos, defl, buf);
+ assertEquals("Incorrect Buffer Size", 5, dos.getProtectedBuf().length);
+
+ dos.write(byteArray);
+ dos.close();
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#close()
+ */
+ public void test_close() throws Exception {
+ File f1 = File.createTempFile("close", ".tst");
+
+ InflaterInputStream iis = new InflaterInputStream(new FileInputStream(f1));
+ try {
+ iis.read();
+ fail("EOFException Not Thrown");
+ } catch (EOFException e) {
+ }
+
+ FileOutputStream fos = new FileOutputStream(f1);
+ DeflaterOutputStream dos = new DeflaterOutputStream(fos);
+ byte byteArray[] = { 1, 3, 4, 6 };
+ dos.write(byteArray);
+ dos.close();
+
+ iis = new InflaterInputStream(new FileInputStream(f1));
+
+ // Test to see if the finish method wrote the bytes to the file.
+ assertEquals("Incorrect Byte Returned.", 1, iis.read());
+ assertEquals("Incorrect Byte Returned.", 3, iis.read());
+ assertEquals("Incorrect Byte Returned.", 4, iis.read());
+ assertEquals("Incorrect Byte Returned.", 6, iis.read());
+ assertEquals("Incorrect Byte Returned.", -1, iis.read());
+ assertEquals("Incorrect Byte Returned.", -1, iis.read());
+ iis.close();
+
+ // Not sure if this test will stay.
+ FileOutputStream fos2 = new FileOutputStream(f1);
+ DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
+ fos2.close();
+ try {
+ dos2.close();
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ }
+
+ // Test to write to a closed DeflaterOutputStream
+ try {
+ dos.write(5);
+ fail("DeflaterOutputStream Able To Write After Being Closed.");
+ } catch (IOException e) {
+ }
+
+ // Test to write to a FileOutputStream that should have been closed
+ // by
+ // the DeflaterOutputStream.
+ try {
+ fos.write(("testing").getBytes());
+ fail("FileOutputStream Able To Write After Being Closed.");
+ } catch (IOException e) {
+ }
+
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#finish()
+ */
+ public void test_finish() throws Exception {
+ // Need test to see if method finish() actually finishes
+ // Only testing possible errors, not if it actually works
+
+ File f1 = File.createTempFile("finish", ".tst");
+ FileOutputStream fos1 = new FileOutputStream(f1);
+ DeflaterOutputStream dos = new DeflaterOutputStream(fos1);
+ byte byteArray[] = { 1, 3, 4, 6 };
+ dos.write(byteArray);
+ dos.finish();
+
+ // Test to see if the same FileOutputStream can be used with the
+ // DeflaterOutputStream after finish is called.
+ try {
+ dos.write(1);
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ }
+
+ // Test for writing with a new FileOutputStream using the same
+ // DeflaterOutputStream.
+ FileOutputStream fos2 = new FileOutputStream(f1);
+ dos = new DeflaterOutputStream(fos2);
+ dos.write(1);
+
+ // Test for writing to FileOutputStream fos1, which should be open.
+ fos1.write(("testing").getBytes());
+
+ // Test for writing to FileOutputStream fos2, which should be open.
+ fos2.write(("testing").getBytes());
+
+ // Not sure if this test will stay.
+ FileOutputStream fos3 = new FileOutputStream(f1);
+ DeflaterOutputStream dos3 = new DeflaterOutputStream(fos3);
+ fos3.close();
+ try {
+ dos3.finish();
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ }
+
+ // dos.close() won't close fos1 because it has been re-assigned to
+ // fos2
+ fos1.close();
+ dos.close();
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#write(int)
+ */
+ public void test_writeI() throws Exception {
+ File f1 = File.createTempFile("writeIL", ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ DeflaterOutputStream dos = new DeflaterOutputStream(fos);
+ for (int i = 0; i < 3; i++) {
+ dos.write(i);
+ }
+ dos.close();
+ FileInputStream fis = new FileInputStream(f1);
+ InflaterInputStream iis = new InflaterInputStream(fis);
+ for (int i = 0; i < 3; i++) {
+ assertEquals("Incorrect Byte Returned.", i, iis.read());
+ }
+ assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
+ assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
+ iis.close();
+
+ // Not sure if this test is that important.
+ // Checks to see if you can write using the DeflaterOutputStream
+ // after
+ // the FileOutputStream has been closed.
+ FileOutputStream fos2 = new FileOutputStream(f1);
+ DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
+ fos2.close();
+ try {
+ dos2.write(2);
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ }
+
+ f1.delete();
+ }
+
+ /**
+ * java.util.zip.DeflaterOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws Exception {
+ byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
+
+ // Test to see if the correct bytes are saved.
+ File f1 = File.createTempFile("writeBII", ".tst");
+ FileOutputStream fos1 = new FileOutputStream(f1);
+ DeflaterOutputStream dos1 = new DeflaterOutputStream(fos1);
+ dos1.write(byteArray, 2, 3);
+ dos1.close();
+ FileInputStream fis = new FileInputStream(f1);
+ InflaterInputStream iis = new InflaterInputStream(fis);
+ assertEquals("Incorrect Byte Returned.", 4, iis.read());
+ assertEquals("Incorrect Byte Returned.", 7, iis.read());
+ assertEquals("Incorrect Byte Returned.", 8, iis.read());
+ assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
+ assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
+ iis.close();
+ f1.delete();
+
+ // Test for trying to write more bytes than available from the array
+ File f2 = File.createTempFile("writeBII2", ".tst");
+ FileOutputStream fos2 = new FileOutputStream(f2);
+ DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
+ try {
+ dos2.write(byteArray, 2, 10);
+ fail("IndexOutOfBoundsException not thrown");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ // Test for trying to write a negative number of bytes.
+ try {
+ dos2.write(byteArray, 2, Integer.MIN_VALUE);
+ fail("IndexOutOfBoundsException not thrown");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ // Test for trying to start writing from a byte < 0 from the array.
+ try {
+ dos2.write(byteArray, Integer.MIN_VALUE, 2);
+ fail("IndexOutOfBoundsException not thrown");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ // Test for trying to start writing from a byte > than the array
+ // size.
+ try {
+ dos2.write(byteArray, 10, 2);
+ fail("IndexOutOfBoundsException not thrown");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ dos2.close();
+
+ // Not sure if this test is that important.
+ // Checks to see if you can write using the DeflaterOutputStream
+ // after
+ // the FileOutputStream has been closed.
+ FileOutputStream fos3 = new FileOutputStream(f2);
+ DeflaterOutputStream dos3 = new DeflaterOutputStream(fos3);
+ fos3.close();
+ try {
+ dos3.write(byteArray, 2, 3);
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ }
+
+ f2.delete();
+ }
+
+ public void test_deflate() throws Exception {
+ File f1 = File.createTempFile("writeI1", ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos);
+ assertFalse(dos.getDaflateFlag());
+ for (int i = 0; i < 3; i++) {
+ dos.write(i);
+ }
+ assertTrue(dos.getDaflateFlag());
+ dos.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
new file mode 100644
index 0000000..75e4a64
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
@@ -0,0 +1,1129 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.zip.Adler32;
+import java.util.zip.DataFormatException;
+import java.util.zip.Deflater;
+import java.util.zip.Inflater;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class DeflaterTest extends TestCase {
+
+ class MyDeflater extends Deflater {
+ MyDeflater() {
+ super();
+ }
+
+ MyDeflater(int lvl) {
+ super(lvl);
+ }
+
+ void myFinalize() {
+ finalize();
+ }
+
+ int getDefCompression() {
+ return DEFAULT_COMPRESSION;
+ }
+
+ int getDefStrategy() {
+ return DEFAULT_STRATEGY;
+ }
+
+ int getHuffman() {
+ return HUFFMAN_ONLY;
+ }
+
+ int getFiltered() {
+ return FILTERED;
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#deflate(byte[])
+ */
+ public void test_deflate$B() {
+ byte outPutBuf[] = new byte[50];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ byte outPutInf[] = new byte[50];
+ int x = 0;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf);
+ }
+ assertEquals("Deflater at end of stream, should return 0", 0, defl
+ .deflate(outPutBuf));
+ int totalOut = defl.getTotalOut();
+ int totalIn = defl.getTotalIn();
+ assertEquals(x, totalOut);
+ assertEquals(byteArray.length, totalIn);
+ defl.end();
+
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ assertEquals(totalIn, infl.getTotalOut());
+ assertEquals(totalOut, infl.getTotalIn());
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals(byteArray[i], outPutInf[i]);
+ }
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#deflate(byte[], int, int)
+ */
+ public void test_deflate$BII() {
+ byte outPutBuf[] = new byte[50];
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutInf[] = new byte[50];
+ int offSet = 1;
+ int length = outPutBuf.length - 1;
+ int x = 0;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf, offSet, length);
+ }
+ assertEquals("Deflater at end of stream, should return 0", 0, defl.deflate(
+ outPutBuf, offSet, length));
+ int totalOut = defl.getTotalOut();
+ int totalIn = defl.getTotalIn();
+ assertEquals(x, totalOut);
+ assertEquals(byteArray.length, totalIn);
+ defl.end();
+
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf, offSet, length);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ assertEquals(totalIn, infl.getTotalOut());
+ assertEquals(totalOut, infl.getTotalIn());
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals(byteArray[i], outPutInf[i]);
+ }
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+
+ // Set of tests testing the boundaries of the offSet/length
+ defl = new Deflater();
+ outPutBuf = new byte[100];
+ defl.setInput(byteArray);
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = outPutBuf.length + 1;
+ length = outPutBuf.length;
+ } else {
+ offSet = 0;
+ length = outPutBuf.length + 1;
+ }
+ try {
+ defl.deflate(outPutBuf, offSet, length);
+ fail("Test " + i
+ + ": ArrayIndexOutOfBoundsException not thrown");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ defl.end();
+ }
+
+ /**
+ * 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");
+ }
+
+ /**
+ * java.util.zip.Deflater#finalize()
+ */
+ public void test_finalize() {
+ MyDeflater mdefl = new MyDeflater();
+ mdefl.myFinalize();
+ System.gc();
+ helper_end_test(mdefl, "finalize");
+ }
+
+ /**
+ * java.util.zip.Deflater#finish()
+ */
+ public void test_finish() throws Exception {
+ // This test already here, its the same as test_deflate()
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutBuf[] = new byte[100];
+ byte outPutInf[] = new byte[100];
+ int x = 0;
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+
+ // needsInput should never return true after finish() is called
+ if (System.getProperty("java.vendor").startsWith("IBM")) {
+ assertFalse("needsInput() should return false after finish() is called", defl
+ .needsInput());
+ }
+
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf);
+ }
+ int totalOut = defl.getTotalOut();
+ int totalIn = defl.getTotalIn();
+ assertEquals(x, totalOut);
+ assertEquals(byteArray.length, totalIn);
+ defl.end();
+
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ assertEquals(totalIn, infl.getTotalOut());
+ assertEquals(totalOut, infl.getTotalIn());
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals(byteArray[i], outPutInf[i]);
+ }
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.zip.Deflater#getAdler()
+ */
+ public void test_getAdler() {
+ byte byteArray[] = { 'a', 'b', 'c', 1, 2, 3 };
+ byte outPutBuf[] = new byte[100];
+ Deflater defl = new Deflater();
+
+ // getting the checkSum value using the Adler
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ long checkSumD = defl.getAdler();
+ defl.end();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(byteArray);
+ long checkSumR = adl.getValue();
+ assertEquals(
+ "The checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
+ checkSumD, checkSumR);
+ }
+
+ /**
+ * java.util.zip.Deflater#getTotalIn()
+ */
+ public void test_getTotalIn() {
+ byte outPutBuf[] = new byte[5];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertEquals(byteArray.length, defl.getTotalIn());
+ defl.end();
+
+ defl = new Deflater();
+ int offSet = 2;
+ int length = 3;
+ outPutBuf = new byte[5];
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertEquals(length, defl.getTotalIn());
+ defl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#getTotalOut()
+ */
+ public void test_getTotalOut() {
+ // the getTotalOut should equal the sum of value returned by deflate()
+ byte outPutBuf[] = new byte[5];
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ int x = 0;
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf);
+ }
+ assertEquals(x, defl.getTotalOut());
+ defl.end();
+
+ x = 0;
+ int offSet = 2;
+ int length = 3;
+ defl = new Deflater();
+ outPutBuf = new byte[5];
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf);
+ }
+ assertEquals(x, defl.getTotalOut());
+ }
+
+ /**
+ * java.util.zip.Deflater#needsInput()
+ */
+ public void test_needsInput() {
+ Deflater defl = new Deflater();
+ assertTrue(
+ "needsInput give the wrong boolean value as a result of no input buffer",
+ defl.needsInput());
+ byte byteArray[] = { 1, 2, 3 };
+ defl.setInput(byteArray);
+ assertFalse(
+ "needsInput give wrong boolean value as a result of a full input buffer",
+ defl.needsInput());
+ byte[] outPutBuf = new byte[50];
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ byte emptyByteArray[] = new byte[0];
+ defl.setInput(emptyByteArray);
+ assertTrue(
+ "needsInput give wrong boolean value as a result of an empty input buffer",
+ defl.needsInput());
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ // needsInput should NOT return true after finish() has been
+ // called.
+ if (System.getProperty("java.vendor").startsWith("IBM")) {
+ assertFalse(
+ "needsInput gave wrong boolean value as a result of finish() being called",
+ defl.needsInput());
+ }
+ defl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#reset()
+ */
+ public void test_reset() {
+ byte outPutBuf[] = new byte[100];
+ byte outPutInf[] = new byte[100];
+ byte curArray[] = new byte[5];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ byte byteArray2[] = { 8, 7, 4, 3, 1 };
+ int x = 0;
+ int orgValue = 0;
+ Deflater defl = new Deflater();
+
+ for (int i = 0; i < 3; i++) {
+ if (i == 0) {
+ curArray = byteArray;
+ } else if (i == 1) {
+ curArray = byteArray2;
+ } else {
+ defl.reset();
+ }
+
+ defl.setInput(curArray);
+ defl.finish();
+ while (!defl.finished()) {
+ x += defl.deflate(outPutBuf);
+ }
+
+ if (i == 0) {
+ assertEquals(x, defl.getTotalOut());
+ } else if (i == 1) {
+ assertEquals(x, orgValue);
+ } else {
+ assertEquals(x, orgValue * 2);
+ }
+
+ if (i == 0) {
+ orgValue = x;
+ }
+
+ try {
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ infl.end();
+ } catch (DataFormatException e) {
+ fail("Test " + i + ": Invalid input to be decompressed");
+ }
+
+ if (i == 1) {
+ curArray = byteArray;
+ }
+
+ for (int j = 0; j < curArray.length; j++) {
+ assertEquals(curArray[j], outPutInf[j]);
+ }
+ assertEquals(0, outPutInf[curArray.length]);
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#setDictionary(byte[])
+ */
+ public void test_setDictionary$B() {
+ // This test is very close to getAdler()
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r' };
+ byte outPutBuf[] = new byte[100];
+
+ Deflater defl = new Deflater();
+ long deflAdler = defl.getAdler();
+ assertEquals("No dictionary set, no data deflated, getAdler should return 1",
+ 1, deflAdler);
+ defl.setDictionary(dictionaryArray);
+ deflAdler = defl.getAdler();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(dictionaryArray);
+ long realAdler = adl.getValue();
+ assertEquals(deflAdler, realAdler);
+
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ deflAdler = defl.getAdler();
+ adl = new Adler32();
+ adl.update(byteArray);
+ realAdler = adl.getValue();
+ // Deflate is finished and there were bytes deflated that did not occur
+ // in the dictionaryArray, therefore a new dictionary was automatically
+ // set.
+ assertEquals(realAdler, deflAdler);
+ defl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#setDictionary(byte[], int, int)
+ */
+ public void test_setDictionary$BII() {
+ // This test is very close to getAdler()
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't' };
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r', 't', 'u', 'i', 'o', 4, 5, 6, 7 };
+ byte outPutBuf[] = new byte[500];
+
+ int offSet = 4;
+ int length = 5;
+
+ Deflater defl = new Deflater();
+ long deflAdler = defl.getAdler();
+ assertEquals("No dictionary set, no data deflated, getAdler should return 1",
+ 1, deflAdler);
+ defl.setDictionary(dictionaryArray, offSet, length);
+ deflAdler = defl.getAdler();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(dictionaryArray, offSet, length);
+ long realAdler = adl.getValue();
+ assertEquals(deflAdler, realAdler);
+
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ deflAdler = defl.getAdler();
+ adl = new Adler32();
+ adl.update(byteArray);
+ realAdler = adl.getValue();
+ // Deflate is finished and there were bytes deflated that did not occur
+ // in the dictionaryArray, therefore a new dictionary was automatically
+ // set.
+ assertEquals(realAdler, deflAdler);
+ defl.end();
+
+ // boundary check
+ defl = new Deflater();
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = 0;
+ length = dictionaryArray.length + 1;
+ } else {
+ offSet = dictionaryArray.length + 1;
+ length = 1;
+ }
+ try {
+ defl.setDictionary(dictionaryArray, offSet, length);
+ fail(
+ "Test "
+ + i
+ + ": boundary check for setDictionary failed for offset "
+ + offSet + " and length " + length);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#setInput(byte[])
+ */
+ public void test_setInput$B() {
+ byte[] byteArray = { 1, 2, 3 };
+ byte[] outPutBuf = new byte[50];
+ byte[] outPutInf = new byte[50];
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ assertTrue("the array buffer in setInput() is empty", !defl
+ .needsInput());
+ // The second setInput() should be ignored since needsInput() return
+ // false
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.end();
+
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals(byteArray[i], outPutInf[i]);
+ }
+ assertEquals(byteArray.length, infl.getTotalOut());
+ infl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#setInput(byte[], int, int)
+ */
+ public void test_setInput$BII() throws Exception {
+ byte[] byteArray = { 1, 2, 3, 4, 5 };
+ byte[] outPutBuf = new byte[50];
+ byte[] outPutInf = new byte[50];
+ int offSet = 1;
+ int length = 3;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray, offSet, length);
+ assertFalse("the array buffer in setInput() is empty", defl.needsInput());
+ // The second setInput() should be ignored since needsInput() return
+ // false
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.end();
+
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ for (int i = 0; i < length; i++) {
+ assertEquals(byteArray[i + offSet], outPutInf[i]);
+ }
+ assertEquals(length, infl.getTotalOut());
+ infl.end();
+
+ // boundary check
+ defl = new Deflater();
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = 0;
+ length = byteArray.length + 1;
+ } else {
+ offSet = byteArray.length + 1;
+ length = 1;
+ }
+ try {
+ defl.setInput(byteArray, offSet, length);
+ fail("Test " + i
+ + ": boundary check for setInput failed for offset "
+ + offSet + " and length " + length);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#setLevel(int)
+ */
+ public void test_setLevelI() throws Exception {
+ // Very similar to test_Constructor(int)
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ byte[] outPutBuf;
+ int totalOut;
+ for (int i = 0; i < 10; i++) {
+ Deflater defl = new Deflater();
+ defl.setLevel(i);
+ outPutBuf = new byte[500];
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ totalOut = defl.getTotalOut();
+ defl.end();
+
+ outPutBuf = new byte[500];
+ defl = new Deflater(i);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
+ }
+
+ // testing boundaries
+ try {
+ Deflater boundDefl = new Deflater();
+ // Level must be between 0-9
+ boundDefl.setLevel(-2);
+ fail(
+ "IllegalArgumentException not thrown when setting level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ Deflater boundDefl = new Deflater();
+ boundDefl.setLevel(10);
+ fail(
+ "IllegalArgumentException not thrown when setting level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#setStrategy(int)
+ */
+ public void test_setStrategyI() throws Exception {
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ for (int i = 0; i < 3; i++) {
+ byte outPutBuf[] = new byte[500];
+ MyDeflater mdefl = new MyDeflater();
+
+ if (i == 0) {
+ mdefl.setStrategy(mdefl.getDefStrategy());
+ } else if (i == 1) {
+ mdefl.setStrategy(mdefl.getHuffman());
+ } else {
+ mdefl.setStrategy(mdefl.getFiltered());
+ }
+
+ mdefl.setInput(byteArray);
+ while (!mdefl.needsInput()) {
+ mdefl.deflate(outPutBuf);
+ }
+ mdefl.finish();
+ while (!mdefl.finished()) {
+ mdefl.deflate(outPutBuf);
+ }
+
+ if (i == 0) {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that getTotalOut() = 86 for this particular
+ // file
+ assertEquals("getTotalOut() for the default strategy did not correspond with JDK",
+ 86, mdefl.getTotalOut());
+ } else if (i == 1) {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that getTotalOut() = 100 for this
+ // particular file
+ assertEquals("getTotalOut() for the Huffman strategy did not correspond with JDK",
+ 100, mdefl.getTotalOut());
+ } else {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that totalOut = 93 for this particular file
+ assertEquals("Total Out for the Filtered strategy did not correspond with JDK",
+ 93, mdefl.getTotalOut());
+ }
+ mdefl.end();
+ }
+
+ // Attempting to setStrategy to an invalid value
+ try {
+ Deflater defl = new Deflater();
+ defl.setStrategy(-412);
+ fail(
+ "IllegalArgumentException not thrown when setting strategy to an invalid value.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#Deflater()
+ */
+ public void test_Constructor() throws Exception {
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ Deflater defl = new Deflater();
+ byte[] outPutBuf = new byte[500];
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ int totalOut = defl.getTotalOut();
+ defl.end();
+
+ // creating a Deflater using the DEFAULT_COMPRESSION as the int
+ MyDeflater mdefl = new MyDeflater();
+ mdefl = new MyDeflater(mdefl.getDefCompression());
+ outPutBuf = new byte[500];
+ mdefl.setInput(byteArray);
+ while (!mdefl.needsInput()) {
+ mdefl.deflate(outPutBuf);
+ }
+ mdefl.finish();
+ while (!mdefl.finished()) {
+ mdefl.deflate(outPutBuf);
+ }
+ assertEquals(totalOut, mdefl.getTotalOut());
+ mdefl.end();
+ }
+
+ /**
+ * java.util.zip.Deflater#Deflater(int, boolean)
+ */
+ public void test_ConstructorIZ() throws Exception {
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r' };
+
+ Deflater defl = new Deflater();
+ byte outPutBuf[] = new byte[500];
+ defl.setLevel(2);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ int totalOut = defl.getTotalOut();
+ defl.end();
+
+ outPutBuf = new byte[500];
+ defl = new Deflater(2, false);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
+
+ outPutBuf = new byte[500];
+ defl = new Deflater(2, true);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertTrue(
+ "getTotalOut() should not be equal comparing two Deflaters with different header options.",
+ defl.getTotalOut() != totalOut);
+ defl.end();
+
+ byte outPutInf[] = new byte[500];
+ Inflater infl = new Inflater(true);
+ while (!infl.finished()) {
+ if (infl.needsInput()) {
+ infl.setInput(outPutBuf);
+ }
+ infl.inflate(outPutInf);
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals(byteArray[i], outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - constructorIZ",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+
+ infl = new Inflater(false);
+ outPutInf = new byte[500];
+ int r = 0;
+ try {
+ while (!infl.finished()) {
+ if (infl.needsInput()) {
+ infl.setInput(outPutBuf);
+ }
+ infl.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ r = 1;
+ }
+ assertEquals("header option did not correspond", 1, r);
+
+ // testing boundaries
+ try {
+ Deflater boundDefl = new Deflater();
+ // Level must be between 0-9
+ boundDefl.setLevel(-2);
+ fail("IllegalArgumentException not thrown when setting level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ Deflater boundDefl = new Deflater();
+ boundDefl.setLevel(10);
+ fail("IllegalArgumentException not thrown when setting level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ Deflater boundDefl = new Deflater(-2, true);
+ fail("IllegalArgumentException not thrown when passing level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+
+ try {
+ Deflater boundDefl = new Deflater(10, true);
+ fail("IllegalArgumentException not thrown when passing level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater#Deflater(int)
+ */
+ public void test_ConstructorI() throws Exception {
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ byte outPutBuf[] = new byte[500];
+ Deflater defl = new Deflater(3);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ int totalOut = defl.getTotalOut();
+ defl.end();
+
+ // test to see if the compression ratio is the same as setting the level
+ // on a deflater
+ outPutBuf = new byte[500];
+ defl = new Deflater();
+ defl.setLevel(3);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
+ defl.deflate(outPutBuf);
+ }
+ defl.finish();
+ while (!defl.finished()) {
+ defl.deflate(outPutBuf);
+ }
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
+
+ // testing boundaries
+ try {
+ Deflater boundDefl = new Deflater();
+ // Level must be between 0-9
+ boundDefl.setLevel(-2);
+ fail("IllegalArgumentException not thrown when setting level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ Deflater boundDefl = new Deflater();
+ boundDefl.setLevel(10);
+ fail("IllegalArgumentException not thrown when setting level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ private void helper_end_test(Deflater defl, String desc) {
+ // Help tests for test_end() and test_reset().
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+
+ // Methods where we expect IllegalStateException or NullPointerException
+ // to be thrown
+ try {
+ defl.getTotalOut();
+ fail("defl.getTotalOut() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getAdler();
+ fail("defl.getAdler() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ byte[] dict = { 'a', 'b', 'c' };
+ defl.setDictionary(dict);
+ fail("defl.setDictionary() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.deflate(byteArray);
+ fail("defl.deflate() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+
+ // Methods where we expect NullPointerException to be thrown
+ try {
+ defl.reset();
+ fail("defl.reset() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (NullPointerException expected) {
+ } catch (IllegalStateException expected) {
+ }
+
+ // Methods where we expect NullPointerException to be thrown
+ try {
+ defl.getBytesRead();
+ fail("defl.reset() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (NullPointerException expected) {
+ } catch (IllegalStateException expected) {
+ }
+
+ // Methods where we expect NullPointerException to be thrown
+ try {
+ defl.getBytesWritten();
+ fail("defl.getBytesWritten() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (NullPointerException expected) {
+ } catch (IllegalStateException expected) {
+ }
+
+ // 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) {
+ }
+ }
+ }
+
+ /**
+ * java.util.zip.Deflater()
+ */
+ public void test_needsDictionary() {
+ Deflater inf = new Deflater();
+ assertEquals(0, inf.getTotalIn());
+ assertEquals(0, inf.getTotalOut());
+ assertEquals(0, inf.getBytesRead());
+ assertEquals(0, inf.getBytesWritten());
+ }
+
+ /**
+ * @throws DataFormatException
+ * @throws UnsupportedEncodingException
+ * java.util.zip.Deflater#getBytesRead()
+ */
+ public void test_getBytesRead() throws DataFormatException,
+ UnsupportedEncodingException {
+ // Regression test for HARMONY-158
+ Deflater def = new Deflater();
+ assertEquals(0, def.getTotalIn());
+ assertEquals(0, def.getTotalOut());
+ assertEquals(0, def.getBytesRead());
+ // Encode a String into bytes
+ String inputString = "blahblahblah??";
+ byte[] input = inputString.getBytes("UTF-8");
+
+ // Compress the bytes
+ byte[] output = new byte[100];
+ def.setInput(input);
+ def.finish();
+ int compressedDataLength = def.deflate(output);
+ assertEquals(14, def.getTotalIn());
+ assertEquals(compressedDataLength, def.getTotalOut());
+ assertEquals(14, def.getBytesRead());
+ }
+
+ /**
+ * @throws DataFormatException
+ * @throws UnsupportedEncodingException
+ * java.util.zip.Deflater#getBytesRead()
+ */
+ public void test_getBytesWritten() throws DataFormatException,
+ UnsupportedEncodingException {
+ // Regression test for HARMONY-158
+ Deflater def = new Deflater();
+ assertEquals(0, def.getTotalIn());
+ assertEquals(0, def.getTotalOut());
+ assertEquals(0, def.getBytesWritten());
+ // Encode a String into bytes
+ String inputString = "blahblahblah??";
+ byte[] input = inputString.getBytes("UTF-8");
+
+ // Compress the bytes
+ byte[] output = new byte[100];
+ def.setInput(input);
+ def.finish();
+ int compressedDataLength = def.deflate(output);
+ assertEquals(14, def.getTotalIn());
+ assertEquals(compressedDataLength, def.getTotalOut());
+ assertEquals(compressedDataLength, def.getBytesWritten());
+ }
+
+ //Regression Test for HARMONY-2481
+ public void test_deflate_beforeSetInput() throws Exception {
+ Deflater deflater = new Deflater();
+ deflater.finish();
+ byte[] buffer = new byte[1024];
+ assertEquals(8, deflater.deflate(buffer));
+ byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 };
+ for (int i = 0; i < expectedBytes.length; i++) {
+ assertEquals(expectedBytes[i], buffer[i]);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPInputStreamTest.java
new file mode 100644
index 0000000..567189d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPInputStreamTest.java
@@ -0,0 +1,301 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.zip.Checksum;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import tests.support.resource.Support_Resources;
+
+public class GZIPInputStreamTest extends junit.framework.TestCase {
+ File resources;
+
+ class TestGZIPInputStream extends GZIPInputStream {
+ TestGZIPInputStream(InputStream in) throws IOException {
+ super(in);
+ }
+
+ TestGZIPInputStream(InputStream in, int size) throws IOException {
+ super(in, size);
+ }
+
+ Checksum getChecksum() {
+ return crc;
+ }
+
+ boolean endofInput() {
+ return eos;
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ // test method java.util.zip.GZIPInputStream.constructor
+ try {
+ Support_Resources.copyFile(resources, null, "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString() + "/hyts_gInput.txt.gz").toURL();
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream());
+ assertNotNull("the constructor for GZIPInputStream is null",
+ inGZIP);
+ assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP
+ .getChecksum().getValue());
+ inGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to open the input file");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream,
+ *int)
+ */
+ public void test_ConstructorLjava_io_InputStreamI() {
+ // test method java.util.zip.GZIPInputStream.constructorI
+ try {
+ Support_Resources.copyFile(resources, null, "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString() + "/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();
+
+ try {
+ TestGZIPInputStream inGZIP1 = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream(), 0);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ioe) {
+ //expected
+ }
+
+ Support_Resources.copyFile(resources, null, "hyts_checkInput.txt");
+ final URL jarInput = new File(resources.toString() + "/hyts_checkInput.txt").toURL();
+ try {
+ TestGZIPInputStream inGZIP1 = new TestGZIPInputStream(jarInput
+ .openConnection().getInputStream(), 200);
+ fail("IOException expected");
+ } catch (IOException ex) {
+ //expected
+ }
+
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to open the input file");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ // test method java.util.zip.GZIPInputStream.readBII
+ byte orgBuf[] = { '3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
+ byte outBuf[] = new byte[100];
+ int result = 0;
+ Support_Resources.copyFile(resources, null, "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString() + "/hyts_gInput.txt.gz").toURL();
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream());
+ while (!(inGZIP.endofInput())) {
+ result += inGZIP.read(outBuf, result, outBuf.length - result);
+ }
+ assertEquals(
+ "the checkSum value of the compressed and decompressed data does not equal",
+ 2074883667L, inGZIP.getChecksum().getValue());
+ for (int i = 0; i < orgBuf.length; i++) {
+ assertEquals(
+ "the decompressed data does not equal the original data decompressed",
+ orgBuf[i], outBuf[i]);
+ // System.out.println(orgBuf[i] + " " + outBuf[i]);
+ }
+ int r = 0;
+ try {
+ inGZIP.read(outBuf, 100, 1);
+ } catch (IndexOutOfBoundsException e) {
+ r = 1;
+ }
+ inGZIP.close();
+ // line below fails on RI also, comment out.
+ // assertEquals("Boundary Check was not present", 1, r);
+
+ // Create compressed data which is exactly 512 bytes (after the
+ // header),
+ // the size of the InflaterStream internal buffer
+ byte[] test = new byte[507];
+ for (int i = 0; i < 256; i++) {
+ test[i] = (byte) i;
+ }
+ for (int i = 256; i < test.length; i++) {
+ test[i] = (byte) (256 - i);
+ }
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ GZIPOutputStream out = new GZIPOutputStream(bout);
+ out.write(test);
+ out.close();
+ byte[] comp = bout.toByteArray();
+ GZIPInputStream gin2 = new GZIPInputStream(new ByteArrayInputStream(
+ comp), 512);
+ int total = 0;
+ while ((result = gin2.read(test)) != -1) {
+ total += result;
+ }
+ assertEquals("Should return -1", -1, gin2.read());
+ gin2.close();
+ assertEquals("Incorrectly decompressed", test.length, total);
+
+ gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 512);
+ total = 0;
+ while ((result = gin2.read(new byte[200])) != -1) {
+ total += result;
+ }
+ assertEquals("Should return -1", -1, gin2.read());
+ gin2.close();
+ assertEquals("Incorrectly decompressed", test.length, total);
+
+ gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 516);
+ total = 0;
+ while ((result = gin2.read(new byte[200])) != -1) {
+ total += result;
+ }
+ assertEquals("Should return -1", -1, gin2.read());
+ gin2.close();
+ assertEquals("Incorrectly decompressed", test.length, total);
+
+ comp[40] = 0;
+ gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 512);
+ boolean exception = false;
+ try {
+ while (gin2.read(test) != -1) {
+ ;
+ }
+ } catch (IOException e) {
+ exception = true;
+ }
+ assertTrue("Exception expected", exception);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ GZIPOutputStream zipout = new GZIPOutputStream(baos);
+ zipout.write(test);
+ zipout.close();
+ outBuf = new byte[530];
+ GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(baos.toByteArray()));
+ try {
+ in.read(outBuf, 530, 1);
+ fail("Test failed IOOBE was not thrown");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ while (true) {
+ result = in.read(outBuf, 0, 5);
+ if (result == -1) {
+ //"EOF was reached";
+ break;
+ }
+ }
+ result = -10;
+ result = in.read(null, 100, 1);
+ result = in.read(outBuf, -100, 1);
+ result = in.read(outBuf, -1, 1);// 100, 1);
+ }
+
+ /**
+ * @tests java.util.zip.GZIPInputStream#close()
+ */
+ public void test_close() {
+ // test method java.util.zip.GZIPInputStream.close
+ byte outBuf[] = new byte[100];
+ try {
+ int result = 0;
+ Support_Resources.copyFile(resources, null, "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString() + "/hyts_gInput.txt.gz").toURL();
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream());
+ while (!(inGZIP.endofInput())) {
+ result += inGZIP.read(outBuf, result, outBuf.length - result);
+ }
+ assertEquals("the checkSum value of the compressed and decompressed data does not equal",
+ 2074883667L, inGZIP.getChecksum().getValue());
+ inGZIP.close();
+ int r = 0;
+ try {
+ inGZIP.read(outBuf, 0, 1);
+ } catch (IOException e) {
+ r = 1;
+ }
+ assertEquals("GZIPInputStream can still be used after close is called",
+ 1, r);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail("unexpected: " + e);
+ }
+ }
+
+ /**
+ * Regression test for HARMONY-3703.
+ *
+ * @tests java.util.zip.GZIPInputStream#read()
+ */
+ public void test_read() throws IOException {
+ GZIPInputStream gis = null;
+ int result = 0;
+ byte[] buffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ File f = new File(resources.getAbsolutePath() + "test.gz");
+ FileOutputStream out = new FileOutputStream(f);
+ GZIPOutputStream gout = new GZIPOutputStream(out);
+
+ // write 100 bytes to the stream
+ for (int i = 0; i < 10; i++) {
+ gout.write(buffer);
+ }
+ gout.finish();
+ out.write(1);
+ out.close();
+
+ gis = new GZIPInputStream(new FileInputStream(f));
+ buffer = new byte[100];
+ gis.read(buffer);
+ result = gis.read();
+ gis.close();
+ f.delete();
+
+ assertEquals("Incorrect value returned at the end of the file", -1, result);
+ }
+
+ @Override
+ protected void setUp() {
+ resources = Support_Resources.createTempFolder();
+ }
+
+ @Override
+ protected void tearDown() {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPOutputStreamTest.java
new file mode 100644
index 0000000..30a94f0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/GZIPOutputStreamTest.java
@@ -0,0 +1,187 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.zip.Checksum;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+public class GZIPOutputStreamTest extends junit.framework.TestCase {
+
+ class TestGZIPOutputStream extends GZIPOutputStream {
+ TestGZIPOutputStream(OutputStream out) throws IOException {
+ super(out);
+ }
+
+ TestGZIPOutputStream(OutputStream out, int size) throws IOException {
+ super(out, size);
+ }
+
+ Checksum getChecksum() {
+ return crc;
+ }
+ }
+
+ /**
+ * java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ try {
+ FileOutputStream outFile = new FileOutputStream(
+ File.createTempFile("GZIPCon", ".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");
+ }
+ }
+
+ /**
+ * java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream,
+ *int)
+ */
+ 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");
+ }
+ }
+
+ /**
+ * 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(
+ File.createTempFile("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");
+ }
+ }
+
+ /**
+ * 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(
+ File.createTempFile("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");
+ }
+ }
+
+ /**
+ * 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(
+ File.createTempFile("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");
+ }
+ }
+
+ public void testSyncFlush() throws IOException {
+ PipedOutputStream pout = new PipedOutputStream();
+ PipedInputStream pin = new PipedInputStream(pout);
+ GZIPOutputStream out = new GZIPOutputStream(pout, true /* syncFlush */);
+ GZIPInputStream in = new GZIPInputStream(pin);
+
+ out.write(1);
+ out.write(2);
+ out.write(3);
+ out.flush();
+ // flush() is guaranteed to flush data only if syncFlush is true.
+ // The default flush param is NO_FLUSH so it's up to the deflater to
+ // decide how much input it wants to read before generating a compressed
+ // block.
+ assertEquals(1, in.read());
+ assertEquals(2, in.read());
+ assertEquals(3, in.read());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterInputStreamTest.java
new file mode 100644
index 0000000..71871a0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterInputStreamTest.java
@@ -0,0 +1,480 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.Inflater;
+import java.util.zip.InflaterInputStream;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class InflaterInputStreamTest extends TestCase {
+
+ // files hyts_construO,hyts_construOD,hyts_construODI 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();
+ }
+ }
+
+ /**
+ * 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_construO.bin");
+
+ InflaterInputStream inflatIP = new InflaterInputStream(infile);
+
+ int i = 0;
+ while ((result = inflatIP.read()) != -1) {
+ buffer[i] = result;
+ i++;
+ }
+ inflatIP.close();
+ */
+ }
+
+ /**
+ * 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_construOD.bin");
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile,
+ inflate);
+
+ inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes
+ inflatIP.close();
+ }
+
+ /**
+ * 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_construODI.bin");
+ 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();
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
+ *java.util.zip.Inflater, int)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI_1() throws IOException {
+ InputStream infile = Support_Resources.getStream("hyts_construODI.bin");
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = null;
+ try {
+ inflatIP = new InflaterInputStream(infile, null, 1);
+ fail("NullPointerException expected");
+ } catch (NullPointerException NPE) {
+ //expected
+ }
+
+ try {
+ inflatIP = new InflaterInputStream(null, inflate, 1);
+ fail("NullPointerException expected");
+ } catch (NullPointerException NPE) {
+ //expected
+ }
+
+ try {
+ inflatIP = new InflaterInputStream(infile, inflate, -1);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#mark(int)
+ */
+ public void test_markI() {
+ InputStream is = new ByteArrayInputStream(new byte[10]);
+ InflaterInputStream iis = new InflaterInputStream(is);
+ // mark do nothing, do no check
+ iis.mark(0);
+ iis.mark(-1);
+ iis.mark(10000000);
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#markSupported()
+ */
+ public void test_markSupported() {
+ InputStream is = new ByteArrayInputStream(new byte[10]);
+ InflaterInputStream iis = new InflaterInputStream(is);
+ assertFalse(iis.markSupported());
+ assertTrue(is.markSupported());
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#read()
+ */
+ public void test_read() throws IOException {
+ int result = 0;
+ int buffer[] = new int[500];
+ byte orgBuffer[] = { 1, 3, 4, 7, 8 };
+ InputStream infile = Support_Resources
+ .getStream("hyts_construOD.bin");
+ 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++) {
+ assertEquals(
+ "original compressed data did not equal decompressed data",
+ orgBuffer[j], buffer[j]);
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#read(byte [], int, int)
+ */
+ public void test_read_LBII() throws IOException {
+ int result = 0;
+ InputStream infile = Support_Resources.getStream("hyts_construOD.bin");
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate);
+
+ byte[] b = new byte[3];
+ try {
+ result = inflatIP.read(null, 0, 1);
+ fail("NullPointerException expected");
+ } catch (NullPointerException npe) {
+ //expected
+ }
+
+ assertEquals(0, inflatIP.read(b, 0, 0));
+
+ try {
+ result = inflatIP.read(b, 5, 2); //offset higher
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException iobe) {
+ //expected
+ }
+
+ inflatIP.close();
+ try {
+ inflatIP.read(b, 0, 1); //read after close
+ fail("IOException expected");
+ } catch (IOException ioe) {
+ //expected
+ }
+ }
+
+ public void testAvailableNonEmptySource() throws Exception {
+ // this byte[] is a deflation of these bytes: { 1, 3, 4, 6 }
+ byte[] deflated = { 72, -119, 99, 100, 102, 97, 3, 0, 0, 31, 0, 15, 0 };
+ InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
+ // InflaterInputStream.available() returns either 1 or 0, even though
+ // that contradicts the behavior defined in InputStream.available()
+ assertEquals(1, in.read());
+ assertEquals(1, in.available());
+ assertEquals(3, in.read());
+ assertEquals(1, in.available());
+ assertEquals(4, in.read());
+ assertEquals(1, in.available());
+ assertEquals(6, in.read());
+ assertEquals(0, in.available());
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ }
+
+ public void testAvailableSkip() throws Exception {
+ // this byte[] is a deflation of these bytes: { 1, 3, 4, 6 }
+ byte[] deflated = { 72, -119, 99, 100, 102, 97, 3, 0, 0, 31, 0, 15, 0 };
+ InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
+ assertEquals(1, in.available());
+ assertEquals(4, in.skip(4));
+ assertEquals(0, in.available());
+ }
+
+ public void testAvailableEmptySource() throws Exception {
+ // this byte[] is a deflation of the empty file
+ byte[] deflated = { 120, -100, 3, 0, 0, 0, 0, 1 };
+ InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ assertEquals(0, in.available());
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ byte[] test = new byte[507];
+ for (int i = 0; i < 256; i++) {
+ test[i] = (byte) i;
+ }
+ for (int i = 256; i < test.length; i++) {
+ test[i] = (byte) (256 - i);
+ }
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ DeflaterOutputStream dos = new DeflaterOutputStream(baos);
+ dos.write(test);
+ dos.close();
+ InputStream is = new ByteArrayInputStream(baos.toByteArray());
+ InflaterInputStream iis = new InflaterInputStream(is);
+ byte[] outBuf = new byte[530];
+ int result = 0;
+ while (true) {
+ result = iis.read(outBuf, 0, 5);
+ if (result == -1) {
+ //"EOF was reached";
+ break;
+ }
+ }
+ try {
+ iis.read(outBuf, -1, 10);
+ fail("should throw IOOBE.");
+ } catch (IndexOutOfBoundsException e) {
+ // expected;
+ }
+ }
+
+ public void test_read$BII2() throws IOException {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+ FileInputStream fis = new FileInputStream(new File(resources,
+ "Broken_manifest.jar"));
+ InflaterInputStream iis = new InflaterInputStream(fis);
+ byte[] outBuf = new byte[530];
+
+ iis.close();
+ try {
+ iis.read(outBuf, 0, 5);
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected.
+ }
+ }
+
+ public void test_read$BII3() throws IOException {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+ FileInputStream fis = new FileInputStream(new File(resources,
+ "Broken_manifest.jar"));
+ InflaterInputStream iis = new InflaterInputStream(fis);
+ byte[] outBuf = new byte[530];
+
+ try {
+ iis.read();
+ fail("IOException expected.");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#reset()
+ */
+ public void test_reset() {
+ InputStream is = new ByteArrayInputStream(new byte[10]);
+ InflaterInputStream iis = new InflaterInputStream(is);
+ try {
+ iis.reset();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // correct
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ InputStream is = Support_Resources.getStream("hyts_available.tst");
+ InflaterInputStream iis = new InflaterInputStream(is);
+
+ // Tests for skipping a negative number of bytes.
+ try {
+ iis.skip(-3);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ assertEquals("Incorrect Byte Returned.", 5, iis.read());
+
+ try {
+ iis.skip(Integer.MIN_VALUE);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ assertEquals("Incorrect Byte Returned.", 4, iis.read());
+
+ // Test to make sure the correct number of bytes were skipped
+ assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3));
+
+ // Test to see if the number of bytes skipped returned is true.
+ assertEquals("Incorrect Byte Returned.", 7, iis.read());
+
+ assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0));
+ assertEquals("Incorrect Byte Returned.", 0, iis.read());
+
+ // Test for skipping more bytes than available in the stream
+ assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4));
+ assertEquals("Incorrect Byte Returned.", -1, iis.read());
+ iis.close();
+ }
+
+ /**
+ * 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_construOD.bin");
+ 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_construOD.bin");
+ 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_construOD.bin");
+ 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++) {
+ assertEquals(
+ "original compressed data did not equal decompressed data",
+ orgBuffer[j], buffer[j - 2]);
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#available()
+ */
+ public void test_available() throws IOException {
+ InputStream is = Support_Resources.getStream("hyts_available.tst");
+ InflaterInputStream iis = new InflaterInputStream(is);
+
+ int available;
+ for (int i = 0; i < 11; i++) {
+ iis.read();
+ available = iis.available();
+ if (available == 0) {
+ assertEquals("Expected no more bytes to read", -1, iis.read());
+ } else {
+ assertEquals("Bytes Available Should Return 1.", 1, available);
+ }
+ }
+
+ iis.close();
+ try {
+ iis.available();
+ fail("available after close should throw IOException.");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterInputStream#close()
+ */
+ public void test_close() throws IOException {
+ InflaterInputStream iin = new InflaterInputStream(
+ new ByteArrayInputStream(new byte[0]));
+ iin.close();
+
+ // test for exception
+ iin.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterOutputStreamTest.java
new file mode 100644
index 0000000..ab856b1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterOutputStreamTest.java
@@ -0,0 +1,392 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.zip.Deflater;
+import java.util.zip.Inflater;
+import java.util.zip.InflaterOutputStream;
+import java.util.zip.ZipException;
+
+import junit.framework.TestCase;
+
+public class InflaterOutputStreamTest extends TestCase {
+
+ private ByteArrayOutputStream os = new ByteArrayOutputStream();
+
+ private byte[] compressedBytes = new byte[100];
+
+ private String testString = "Hello world";
+
+ /**
+ * java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() throws IOException {
+ new InflaterOutputStream(os);
+
+ try {
+ new InflaterOutputStream(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream, Inflater)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Inflater() {
+ new InflaterOutputStream(os, new Inflater());
+
+ try {
+ new InflaterOutputStream(null, new Inflater());
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(os, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream, Inflater, int)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_InflaterI() {
+ new InflaterOutputStream(os, new Inflater(), 20);
+
+ try {
+ new InflaterOutputStream(null, null, 10);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(null, new Inflater(), -1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(os, null, -1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(null, null, -1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(os, new Inflater(), 0);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ new InflaterOutputStream(os, new Inflater(), -10000);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#close()
+ */
+ public void test_close() throws IOException {
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ ios.close();
+ // multiple close
+ ios.close();
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#flush()
+ */
+ public void test_flush() throws IOException {
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ ios.close();
+ try {
+ ios.flush();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ ios = new InflaterOutputStream(os);
+ ios.flush();
+ ios.flush();
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#finish()
+ */
+ public void test_finish() throws IOException {
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ ios.close();
+ try {
+ ios.finish();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ ios = new InflaterOutputStream(os);
+ ios.finish();
+ ios.finish();
+ ios.flush();
+ ios.flush();
+ ios.finish();
+
+ byte[] bytes1 = { 10, 20, 30, 40, 50 };
+ Deflater defaultDeflater = new Deflater(Deflater.BEST_SPEED);
+ defaultDeflater.setInput(bytes1);
+ defaultDeflater.finish();
+ int length1 = defaultDeflater.deflate(compressedBytes);
+
+ byte[] bytes2 = { 100, 90, 80, 70, 60 };
+ Deflater bestDeflater = new Deflater(Deflater.BEST_COMPRESSION);
+ bestDeflater.setInput(bytes2);
+ bestDeflater.finish();
+ int length2 = bestDeflater.deflate(compressedBytes, length1, compressedBytes.length - length1);
+
+ ios = new InflaterOutputStream(os);
+ for (int i = 0; i < length1; i++) {
+ ios.write(compressedBytes[i]);
+ }
+ ios.finish();
+ ios.close();
+
+ byte[] result = os.toByteArray();
+ for (int i = 0; i < bytes1.length; i++) {
+ assertEquals(bytes1[i], result[i]);
+ }
+
+ ios = new InflaterOutputStream(os);
+ for (int i = length1; i < length2 * 2; i++) {
+ ios.write(compressedBytes[i]);
+ }
+ ios.finish();
+ ios.close();
+
+ result = os.toByteArray();
+ for (int i = 0; i < bytes2.length; i++) {
+ assertEquals(bytes2[i], result[bytes1.length + i]);
+ }
+
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#write(int)
+ */
+ public void test_write_I() throws IOException {
+ int length = compressToBytes(testString);
+
+ // uncompress the data stored in the compressedBytes
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ for (int i = 0; i < length; i++) {
+ ios.write(compressedBytes[i]);
+ }
+
+ String result = new String(os.toByteArray());
+ assertEquals(testString, result);
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#write(int)
+ */
+ public void test_write_I_Illegal() throws IOException {
+
+ // write after close
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ ios.close();
+ try {
+ ios.write(-1);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII() throws IOException {
+ int length = compressToBytes(testString);
+
+ // uncompress the data stored in the compressedBytes
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ ios.write(compressedBytes, 0, length);
+
+ String result = new String(os.toByteArray());
+ assertEquals(testString, result);
+ }
+
+ /**
+ * java.util.zip.InflaterOutputStream#write(byte[], int, int)
+ */
+ public void test_write_$BII_Illegal() throws IOException {
+ // write error compression (ZIP) format
+ InflaterOutputStream ios = new InflaterOutputStream(os);
+ byte[] bytes = { 0, 1, 2, 3 };
+ try {
+ ios.write(bytes, 0, 4);
+ fail("Should throw ZipException");
+ } catch (ZipException e) {
+ // expected
+ }
+ try {
+ ios.flush();
+ fail("Should throw ZipException");
+ } catch (ZipException e) {
+ // expected
+ }
+
+ // write after close
+ ios = new InflaterOutputStream(os);
+ ios.close();
+ try {
+ ios.write(bytes, 0, 4);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, -1, 4);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, -1, -4);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, 0, 400);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ try {
+ ios.write(null, -1, 4);
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ ios = new InflaterOutputStream(os);
+ try {
+ ios.write(null, 0, 4);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ ios.write(null, -1, 4);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ ios.write(null, 0, -4);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ ios.write(null, 0, 1000);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, -1, 4);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, 0, -4);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, 0, 100);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ios.write(bytes, -100, 100);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ ios = new InflaterOutputStream(os);
+ ios.finish();
+
+ try {
+ ios.write(bytes, -1, -100);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ios.write(null, -1, -100);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ios = new InflaterOutputStream(os);
+ ios.flush();
+ try {
+ ios.write(bytes, 0, 4);
+ fail("Should throw ZipException");
+ } catch (ZipException e) {
+ // expected
+ }
+ }
+
+ // Compress the test string into compressedBytes
+ private int compressToBytes(String string) {
+ byte[] input = string.getBytes();
+ Deflater deflater = new Deflater();
+ deflater.setInput(input);
+ deflater.finish();
+ return deflater.deflate(compressedBytes);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterTest.java
new file mode 100644
index 0000000..a16fab7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/InflaterTest.java
@@ -0,0 +1,1135 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.zip.Adler32;
+import java.util.zip.DataFormatException;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.Inflater;
+import java.util.zip.ZipException;
+import tests.support.resource.Support_Resources;
+
+public class InflaterTest extends junit.framework.TestCase {
+ byte outPutBuff1[] = new byte[500];
+
+ byte outPutDiction[] = new byte[500];
+
+ /**
+ * java.util.zip.Inflater#end()
+ */
+ public void test_end() throws Exception {
+ // 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();
+
+ // Note that the RI throws an NPE here instead of an ISE (???).
+ try {
+ inflate.reset();
+ inflate.setInput(byteArray);
+ } catch (IllegalStateException expected) {
+ }
+
+ Inflater i = new Inflater();
+ i.end();
+ // check for exception
+ i.end();
+ }
+
+ /**
+ * 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++) {
+ assertEquals(
+ "Final decompressed data does not equal the original data",
+ outPutInf[i], byteArray[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - finished()",
+ 0, outPutInf[byteArray.length]);
+ }
+
+ /**
+ * 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();
+ assertEquals(
+ "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
+ inflateDiction.getAdler(), checkSumR);
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ assertEquals(
+ "the total byte in outPutBuf did not equal the byte returned in getTotalIn",
+ deflate.getTotalOut(), inflate.getTotalIn());
+
+ 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);
+ assertEquals(
+ "total byte dictated by length did not equal byte returned in getTotalIn",
+ length, inflate2.getTotalIn());
+ }
+
+ /**
+ * 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");
+ }
+
+ assertEquals(
+ "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
+ inflate.getTotalOut(), y);
+ assertEquals(
+ "the total number of bytes to be compressed does not equal the total bytes decompressed",
+ deflate.getTotalIn(), inflate.getTotalOut());
+
+ // 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");
+ }
+ assertEquals(
+ "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
+ y, inflate.getTotalOut());
+ assertEquals(
+ "the total number of bytes to be compressed does not equal the total bytes decompressed",
+ deflate.getTotalIn(), inflate.getTotalOut());
+ }
+
+ /**
+ * 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++) {
+ assertEquals(
+ "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);
+ }
+ assertEquals(
+ "the total number of byte from deflate did not equal getTotalOut - inflate(byte)",
+ x, defEmpty.getTotalOut());
+ assertEquals(
+ "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)",
+ emptyArray.length, defEmpty.getTotalIn());
+ 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++) {
+ assertEquals(
+ "Final decompressed data does not equal the original data",
+ emptyArray[i], outPutInf[i]);
+ assertEquals("Final decompressed data does not equal zero",
+ 0, outPutInf[i]);
+ }
+ assertEquals("Final decompressed data contains more element than original data",
+ 0, outPutInf[emptyArray.length]);
+ }
+
+ public void test_inflate$B1() {
+ byte codedData[] = {
+ 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
+ 72, -50, -49, 43, 73, -52, -52, 43, 86, 72, 2, 10, 34, 99,
+ -123, -60, -68, 20, -80, 32, 0, -101, -69, 17, 84 };
+ String codedString = "blah string contains blahblahblahblah and blah";
+
+ Inflater infl1 = new Inflater();
+ Inflater infl2 = new Inflater();
+
+ byte[] result = new byte[100];
+ int decLen = 0;
+
+ infl1.setInput(codedData, 0, codedData.length);
+ try {
+ decLen = infl1.inflate(result);
+ } catch (DataFormatException e) {
+ fail("Unexpected DataFormatException");
+ }
+
+ infl1.end();
+ assertEquals(codedString, new String(result, 0, decLen));
+ codedData[5] = 0;
+
+ infl2.setInput(codedData, 0, codedData.length);
+ try {
+ decLen = infl2.inflate(result);
+ fail("Expected DataFormatException");
+ } catch (DataFormatException e) {
+ // expected
+ }
+
+ infl2.end();
+ }
+
+ /**
+ * 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()) {
+ assertEquals(0, inflate.inflate(outPutInf, 0, 1));
+ 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++) {
+ assertEquals(
+ "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);
+
+ try {
+ assertEquals(0, inflate.inflate(outPutInf, offSet, 0));
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ inflate.end();
+ try {
+ inflate.inflate(outPutInf, offSet, 1);
+ fail("IllegalStateException expected");
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ } catch (IllegalStateException e) {
+ //expected
+ }
+ }
+
+ public void test_inflate$BII1() {
+ byte codedData[] = {
+ 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
+ 72, -50, -49, 43, 73, -52, -52, 43, 86, 72, 2, 10, 34, 99,
+ -123, -60, -68, 20, -80, 32, 0, -101, -69, 17, 84 };
+ String codedString = "blah string";
+
+ Inflater infl1 = new Inflater();
+ Inflater infl2 = new Inflater();
+
+ byte[] result = new byte[100];
+ int decLen = 0;
+
+ infl1.setInput(codedData, 0, codedData.length);
+ try {
+ decLen = infl1.inflate(result, 10, 11);
+ } catch (DataFormatException e) {
+ fail("Unexpected DataFormatException");
+ }
+
+ infl1.end();
+ assertEquals(codedString, new String(result, 10, decLen));
+ codedData[5] = 0;
+
+ infl2.setInput(codedData, 0, codedData.length);
+ try {
+ decLen = infl2.inflate(result, 10, 11);
+ fail("Expected DataFormatException");
+ } catch (DataFormatException e) {
+ // expected
+ }
+
+ infl2.end();
+ }
+
+ /*
+ * Regression test for HARMONY-6637
+ */
+ public void testInflateZero() throws Exception {
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(
+ byteArrayOutputStream);
+ deflaterOutputStream.close();
+ byte[] input = byteArrayOutputStream.toByteArray();
+
+ Inflater inflater = new Inflater();
+ inflater.setInput(input);
+ byte[] buffer = new byte[0];
+ int numRead = 0;
+ while (!inflater.finished()) {
+ int inflatedChunkSize = inflater.inflate(buffer, numRead,
+ buffer.length - numRead);
+ numRead += inflatedChunkSize;
+ }
+ inflater.end();
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+
+ }
+
+ /**
+ * 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());
+ assertEquals(1, inf.getAdler());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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++) {
+ assertEquals(
+ "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++) {
+ assertEquals(
+ "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]);
+
+ }
+
+ /**
+ * 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]);
+ */
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ assertEquals(
+ "setInputBII did not deliver the right number of bytes to the input buffer",
+ length, inflate.getRemaining());
+ // 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.bin");
+ BufferedInputStream inflatIP = new BufferedInputStream(infile);
+ inflatIP.read(outPutBuff1, 0, outPutBuff1.length);
+ inflatIP.close();
+
+ java.io.InputStream infile2 = Support_Resources
+ .getStream("hyts_compDiction.bin");
+ 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() {
+ }
+
+ /**
+ * java.util.zip.Deflater#getBytesRead()
+ */
+ public void test_getBytesRead() throws DataFormatException,
+ UnsupportedEncodingException {
+ // Regression test for HARMONY-158
+ Deflater def = new Deflater();
+ Inflater inf = new Inflater();
+ assertEquals(0, def.getTotalIn());
+ assertEquals(0, def.getTotalOut());
+ assertEquals(0, def.getBytesRead());
+ // Encode a String into bytes
+ String inputString = "blahblahblah??";
+ byte[] input = inputString.getBytes("UTF-8");
+
+ // Compress the bytes
+ byte[] output = new byte[100];
+ def.setInput(input);
+ def.finish();
+ def.deflate(output);
+ inf.setInput(output);
+ int compressedDataLength = inf.inflate(input);
+ assertEquals(16, inf.getTotalIn());
+ assertEquals(compressedDataLength, inf.getTotalOut());
+ assertEquals(16, inf.getBytesRead());
+ }
+
+ /**
+ * java.util.zip.Deflater#getBytesRead()
+ */
+ public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException {
+ // Regression test for HARMONY-158
+ Deflater def = new Deflater();
+ Inflater inf = new Inflater();
+ assertEquals(0, def.getTotalIn());
+ assertEquals(0, def.getTotalOut());
+ assertEquals(0, def.getBytesWritten());
+ // Encode a String into bytes
+ String inputString = "blahblahblah??";
+ byte[] input = inputString.getBytes("UTF-8");
+
+ // Compress the bytes
+ byte[] output = new byte[100];
+ def.setInput(input);
+ def.finish();
+ def.deflate(output);
+ inf.setInput(output);
+ int compressedDataLength = inf.inflate(input);
+ assertEquals(16, inf.getTotalIn());
+ assertEquals(compressedDataLength, inf.getTotalOut());
+ assertEquals(14, inf.getBytesWritten());
+ }
+
+ /**
+ * java.util.zip.Deflater#inflate(byte[], int, int)
+ */
+ public void testInflate() throws Exception {
+ // Regression for HARMONY-81
+ Inflater inf = new Inflater();
+ int res = inf.inflate(new byte[0], 0, 0);
+
+ assertEquals(0, res);
+
+ // Regression for HARMONY-2508
+ Inflater inflater = new Inflater();
+ byte[] b = new byte[1024];
+ assertEquals(0, inflater.inflate(b));
+ inflater.end();
+
+ // Regression for HARMONY-2510
+ inflater = new Inflater();
+ inflater.setInput(new byte[] { -1 });
+ try {
+ inflater.inflate(b);
+
+ // The RI detects malformed data on the malformed input { -1 }. Both
+ // this implementation and the native zlib API return "need input"
+ // on that data. This is an error if the stream is exhausted, but
+ // not one that results in an exception in the Inflater API.
+ assertTrue(inflater.needsInput());
+ } catch (DataFormatException e) {
+ // expected
+ }
+
+ inflater = new Inflater();
+ inflater.setInput(new byte[] { -1, -1, -1 });
+ try {
+ inflater.inflate(b);
+ } catch (DataFormatException e) {
+ // expected
+ }
+ }
+
+ public void testSetDictionary$B() throws Exception {
+ int i = 0;
+ String inputString = "blah string contains blahblahblahblah and blah";
+ String dictionary1 = "blah";
+ String dictionary2 = "1234";
+
+ byte[] outputNo = new byte[100];
+ byte[] output1 = new byte[100];
+ byte[] output2 = new byte[100];
+ Deflater defDictNo = new Deflater(9);
+ Deflater defDict1 = new Deflater(9);
+ Deflater defDict2 = new Deflater(9);
+
+ defDict1.setDictionary(dictionary1.getBytes());
+ defDict2.setDictionary(dictionary2.getBytes());
+
+ defDictNo.setInput(inputString.getBytes());
+ defDict1.setInput(inputString.getBytes());
+ defDict2.setInput(inputString.getBytes());
+
+ defDictNo.finish();
+ defDict1.finish();
+ defDict2.finish();
+
+ int dataLenNo = defDictNo.deflate(outputNo);
+ int dataLen1 = defDict1.deflate(output1);
+ int dataLen2 = defDict2.deflate(output2);
+
+ boolean passNo1 = false;
+ boolean passNo2 = false;
+ boolean pass12 = false;
+
+ for (i = 0; i < (dataLenNo < dataLen1 ? dataLenNo : dataLen1); i++) {
+ if (outputNo[i] != output1[i]) {
+ passNo1 = true;
+ break;
+ }
+ }
+ for (i = 0; i < (dataLenNo < dataLen1 ? dataLenNo : dataLen2); i++) {
+ if (outputNo[i] != output2[i]) {
+ passNo2 = true;
+ break;
+ }
+ }
+ for (i = 0; i < (dataLen1 < dataLen2 ? dataLen1 : dataLen2); i++) {
+ if (output1[i] != output2[i]) {
+ pass12 = true;
+ break;
+ }
+ }
+
+ assertTrue(
+ "Compressed data the same for stream with dictionary and without it.",
+ passNo1);
+ assertTrue(
+ "Compressed data the same for stream with dictionary and without it.",
+ passNo2);
+ assertTrue(
+ "Compressed data the same for stream with different dictionaries.",
+ pass12);
+
+ Inflater inflNo = new Inflater();
+ Inflater infl1 = new Inflater();
+ Inflater infl2 = new Inflater();
+
+ byte[] result = new byte[100];
+ int decLen;
+
+ inflNo.setInput(outputNo, 0, dataLenNo);
+ decLen = inflNo.inflate(result);
+
+ assertFalse(inflNo.needsDictionary());
+ inflNo.end();
+ assertEquals(inputString, new String(result, 0, decLen));
+
+ infl1.setInput(output1, 0, dataLen1);
+ decLen = infl1.inflate(result);
+
+ assertTrue(infl1.needsDictionary());
+ infl1.setDictionary(dictionary1.getBytes());
+ decLen = infl1.inflate(result);
+ infl1.end();
+ assertEquals(inputString, new String(result, 0, decLen));
+
+ infl2.setInput(output2, 0, dataLen2);
+ decLen = infl2.inflate(result);
+
+ assertTrue(infl2.needsDictionary());
+ infl2.setDictionary(dictionary2.getBytes());
+ decLen = infl2.inflate(result);
+ infl2.end();
+ assertEquals(inputString, new String(result, 0, decLen));
+
+
+ inflNo = new Inflater();
+ infl1 = new Inflater();
+ inflNo.setInput(outputNo, 0, dataLenNo);
+ try {
+ infl1.setDictionary(dictionary1.getBytes());
+ fail("IllegalArgumentException expected.");
+ } catch (IllegalArgumentException ee) {
+ // expected.
+ }
+ inflNo.end();
+
+ infl1.setInput(output1, 0, dataLen1);
+ decLen = infl1.inflate(result);
+
+ assertTrue(infl1.needsDictionary());
+ try {
+ infl1.setDictionary(dictionary2.getBytes());
+ fail("IllegalArgumentException expected.");
+ } catch (IllegalArgumentException ee) {
+ // expected.
+ }
+ infl1.end();
+ try {
+ infl1.setDictionary(dictionary2.getBytes());
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException ise) {
+ //expected
+ }
+ }
+
+ public void testSetDictionary$BII() throws Exception {
+ int i = 0;
+ String inputString = "blah string contains blahblahblahblah and blah";
+ String dictionary1 = "blah";
+ String dictionary2 = "blahblahblah";
+
+ byte[] output1 = new byte[100];
+ byte[] output2 = new byte[100];
+ byte[] output3 = new byte[100];
+
+ Deflater defDict1 = new Deflater(9);
+ Deflater defDict2 = new Deflater(9);
+ Deflater defDict3 = new Deflater(9);
+
+ defDict1.setDictionary(dictionary1.getBytes());
+ defDict2.setDictionary(dictionary2.getBytes());
+ defDict3.setDictionary(dictionary2.getBytes(), 4, 4);
+
+ defDict1.setInput(inputString.getBytes());
+ defDict2.setInput(inputString.getBytes());
+ defDict3.setInput(inputString.getBytes());
+
+ defDict1.finish();
+ defDict2.finish();
+ defDict3.finish();
+
+ int dataLen1 = defDict1.deflate(output1);
+ int dataLen2 = defDict2.deflate(output2);
+ int dataLen3 = defDict3.deflate(output3);
+
+ boolean pass12 = false;
+ boolean pass23 = false;
+ boolean pass13 = true;
+
+ for (i = 0; i < (dataLen1 < dataLen2 ? dataLen1 : dataLen2); i++) {
+ if (output1[i] != output2[i]) {
+ pass12 = true;
+ break;
+ }
+ }
+ for (i = 0; i < (dataLen2 < dataLen3 ? dataLen2 : dataLen3); i++) {
+ if (output2[i] != output3[i]) {
+ pass23 = true;
+ break;
+ }
+ }
+ for (i = 0; i < (dataLen1 < dataLen3 ? dataLen1 : dataLen3); i++) {
+ if (output1[i] != output3[i]) {
+ pass13 = false;
+ break;
+ }
+ }
+
+ assertTrue(
+ "Compressed data the same for stream with different dictionaries.",
+ pass12);
+ assertTrue(
+ "Compressed data the same for stream with different dictionaries.",
+ pass23);
+ assertTrue(
+ "Compressed data the differs for stream with the same dictionaries.",
+ pass13);
+
+ Inflater infl1 = new Inflater();
+ Inflater infl2 = new Inflater();
+ Inflater infl3 = new Inflater();
+ Inflater infl4 = new Inflater();
+
+ byte[] result = new byte[100];
+ int decLen;
+
+ infl1.setInput(output1, 0, dataLen1);
+ decLen = infl1.inflate(result);
+
+ assertTrue(infl1.needsDictionary());
+ infl1.setDictionary(dictionary2.getBytes(), 4, 4);
+ decLen = infl1.inflate(result);
+ infl1.end();
+ assertEquals(inputString, new String(result, 0, decLen));
+
+ infl2.setInput(output2, 0, dataLen2);
+ decLen = infl2.inflate(result);
+
+ assertTrue(infl2.needsDictionary());
+ try {
+ infl2.setDictionary(dictionary1.getBytes());
+ fail("IllegalArgumentException expected.");
+ } catch (IllegalArgumentException ee) {
+ // expected
+ }
+ infl2.end();
+
+ infl3.setInput(output3, 0, dataLen3);
+ decLen = infl3.inflate(result);
+
+ assertTrue(infl3.needsDictionary());
+ infl3.setDictionary(dictionary1.getBytes());
+ decLen = infl3.inflate(result);
+ infl3.end();
+ assertEquals(inputString, new String(result, 0, decLen));
+
+ //exception test
+ infl4.setInput(output3, 0, dataLen3);
+ decLen = infl4.inflate(result);
+ assertTrue(infl4.needsDictionary());
+
+ try {
+ infl4.setDictionary(dictionary1.getBytes(), 4, 4);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException aiob) {
+ //expected
+ }
+ }
+
+ public void testExceptions() throws Exception {
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+
+ int r = 0;
+ Inflater inflate = new Inflater();
+ inflate.setInput(byteArray);
+ inflate.end();
+
+ try {
+ inflate.getAdler();
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException expected) {
+ //expected
+ }
+
+ try {
+ inflate.getBytesRead();
+ fail("NullPointerException expected");
+ } catch (IllegalStateException expected) {
+ } catch (NullPointerException expected) {
+ //expected
+ }
+
+ try {
+ inflate.getBytesWritten();
+ fail("NullPointerException expected");
+ } catch (NullPointerException expected) {
+ } catch (IllegalStateException expected) {
+ //expected
+ }
+
+
+ try {
+ inflate.getTotalIn();
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException ise) {
+ //expected
+ }
+
+ try {
+ inflate.getTotalOut();
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException ise) {
+ //expected
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipEntryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipEntryTest.java
new file mode 100644
index 0000000..f034639
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipEntryTest.java
@@ -0,0 +1,453 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.TimeZone;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import libcore.io.Streams;
+import tests.support.resource.Support_Resources;
+
+public class ZipEntryTest extends junit.framework.TestCase {
+ // zip file hyts_ZipFile.zip must be included as a resource
+ private ZipEntry zentry;
+ private ZipFile zfile;
+
+ private long orgSize;
+ private long orgCompressedSize;
+ private long orgCrc;
+ private long orgTime;
+
+ /**
+ * java.util.zip.ZipEntry#ZipEntry(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.zip.ZipEntry(java.lang.String)
+ zentry = zfile.getEntry("File3.txt");
+ assertNotNull("Failed to create ZipEntry", zentry);
+ try {
+ zentry = zfile.getEntry(null);
+ fail("NullPointerException not thrown");
+ } catch (NullPointerException e) {
+ }
+ StringBuffer s = new StringBuffer();
+ for (int i = 0; i < 65535; i++) {
+ s.append('a');
+ }
+ try {
+ zentry = new ZipEntry(s.toString());
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException During Test.");
+ }
+ try {
+ s.append('a');
+ zentry = new ZipEntry(s.toString());
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ String n = null;
+ zentry = new ZipEntry(n);
+ fail("NullPointerException not thrown");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * java.util.zip.ZipEntry#getCrc()
+ */
+ public void test_getCrc() {
+ // Test for method long java.util.zip.ZipEntry.getCrc()
+ assertEquals("Failed to get Crc", orgCrc, zentry.getCrc());
+ }
+
+ /**
+ * 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);
+ assertEquals("Incorrect Extra Information Returned.",
+ ba, zentry.getExtra());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#getMethod()
+ */
+ public void test_getMethod() {
+ // Test for method int java.util.zip.ZipEntry.getMethod()
+ zentry = zfile.getEntry("File1.txt");
+ assertEquals("Incorrect compression method returned",
+ java.util.zip.ZipEntry.STORED, zentry.getMethod());
+ zentry = zfile.getEntry("File3.txt");
+ assertEquals("Incorrect compression method returned",
+ java.util.zip.ZipEntry.DEFLATED, zentry.getMethod());
+ zentry = new ZipEntry("test.tst");
+ assertEquals("Incorrect Method Returned.", -1, zentry.getMethod());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#getSize()
+ */
+ public void test_getSize() {
+ // Test for method long java.util.zip.ZipEntry.getSize()
+ assertEquals("Incorrect size returned", orgSize, zentry.getSize());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#getTime()
+ */
+ public void test_getTime() {
+ // Test for method long java.util.zip.ZipEntry.getTime()
+ assertEquals("Failed to get time", orgTime, zentry.getTime());
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#setComment(java.lang.String)
+ */
+ public void test_setCommentLjava_lang_String() {
+ // Test for method void
+ // java.util.zip.ZipEntry.setComment(java.lang.String)
+ zentry = zfile.getEntry("File1.txt");
+ zentry.setComment("Set comment using api");
+ assertEquals("Comment not correctly set",
+ "Set comment using api", zentry.getComment());
+ String n = null;
+ zentry.setComment(n);
+ assertNull("Comment not correctly set", zentry.getComment());
+ StringBuffer s = new StringBuffer();
+ for (int i = 0; i < 0xFFFF; i++) {
+ s.append('a');
+ }
+ try {
+ zentry.setComment(s.toString());
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException During Test.");
+ }
+ try {
+ s.append('a');
+ zentry.setComment(s.toString());
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.zip.ZipEntry#setCompressedSize(long)
+ */
+ public void test_setCompressedSizeJ() {
+ // Test for method void java.util.zip.ZipEntry.setCompressedSize(long)
+ zentry.setCompressedSize(orgCompressedSize + 10);
+ assertEquals("Set compressed size failed",
+ (orgCompressedSize + 10), zentry.getCompressedSize());
+ 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);
+ assertEquals("Set compressed size failed",
+ 4294967296l, zentry.getCompressedSize());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#setCrc(long)
+ */
+ public void test_setCrcJ() {
+ // Test for method void java.util.zip.ZipEntry.setCrc(long)
+ zentry.setCrc(orgCrc + 100);
+ assertEquals("Failed to set Crc", (orgCrc + 100), zentry.getCrc());
+ 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) {
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ assertEquals("Failed to set compression method",
+ ZipEntry.STORED, zentry.getMethod());
+ zentry.setMethod(ZipEntry.DEFLATED);
+ assertEquals("Failed to set compression method",
+ ZipEntry.DEFLATED, zentry.getMethod());
+ try {
+ int error = 1;
+ zentry = new ZipEntry("test.tst");
+ zentry.setMethod(error);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * java.util.zip.ZipEntry#setSize(long)
+ */
+ public void test_setSizeJ() {
+ // Test for method void java.util.zip.ZipEntry.setSize(long)
+ zentry.setSize(orgSize + 10);
+ assertEquals("Set size failed", (orgSize + 10), zentry.getSize());
+ 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) {
+ }
+ }
+
+ /**
+ * java.util.zip.ZipEntry#setTime(long)
+ */
+ public void test_setTimeJ() {
+ // Test for method void java.util.zip.ZipEntry.setTime(long)
+ zentry.setTime(orgTime + 10000);
+ assertEquals("Test 1: Failed to set time: " + zentry.getTime(), (orgTime + 10000),
+ zentry.getTime());
+ zentry.setTime(orgTime - 10000);
+ assertEquals("Test 2: Failed to set time: " + zentry.getTime(), (orgTime - 10000),
+ zentry.getTime());
+ TimeZone zone = TimeZone.getDefault();
+ try {
+ TimeZone.setDefault(TimeZone.getTimeZone("EST"));
+ zentry.setTime(0);
+ assertEquals("Test 3: Failed to set time: " + zentry.getTime(),
+ 315550800000L, zentry.getTime());
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ assertEquals("Test 3a: Failed to set time: " + zentry.getTime(),
+ 315532800000L, zentry.getTime());
+ zentry.setTime(0);
+ TimeZone.setDefault(TimeZone.getTimeZone("EST"));
+ assertEquals("Test 3b: Failed to set time: " + zentry.getTime(),
+ 315550800000L, zentry.getTime());
+
+ zentry.setTime(-25);
+ assertEquals("Test 4: Failed to set time: " + zentry.getTime(),
+ 315550800000L, zentry.getTime());
+ zentry.setTime(4354837200000L);
+ assertEquals("Test 5: Failed to set time: " + zentry.getTime(),
+ 315550800000L, zentry.getTime());
+ } finally {
+ TimeZone.setDefault(zone);
+ }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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());
+ assertEquals("ZipEntry Created With Incorrect Crc.",
+ orgCrc, zentry2.getCrc());
+ assertEquals("ZipEntry Created With Incorrect Time.",
+ orgTime, zentry2.getTime());
+ }
+
+ /**
+ * java.util.zip.ZipEntry#clone()
+ */
+ public void test_clone() {
+ // Test for method java.util.zip.ZipEntry.clone()
+ Object obj = zentry.clone();
+ assertEquals("toString()", zentry.toString(), obj.toString());
+ assertEquals("hashCode()", zentry.hashCode(), obj.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);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ // Create a local copy of the file since some tests want to alter
+ // information.
+ final File f = File.createTempFile("ZipEntryTest", ".zip");
+ InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
+
+ FileOutputStream fos = new java.io.FileOutputStream(f);
+ Streams.copy(is, fos);
+ is.close();
+ fos.close();
+
+ zfile = new ZipFile(f);
+ zentry = zfile.getEntry("File1.txt");
+
+ orgSize = zentry.getSize();
+ orgCompressedSize = zentry.getCompressedSize();
+ orgCrc = zentry.getCrc();
+ orgTime = zentry.getTime();
+ }
+
+ @Override
+ protected void tearDown() {
+ try {
+ if (zfile != null) {
+ zfile.close();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipErrorTest.java
new file mode 100644
index 0000000..6b5125a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipErrorTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.IOException;
+import java.util.zip.ZipError;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import junit.framework.TestCase;
+
+public class ZipErrorTest extends TestCase {
+
+ /**
+ * {@link java.util.zip.ZipError#ZipError(String)}
+ */
+ public void test_constructor() {
+ ZipError error = new ZipError("ZipError");
+ assertEquals("ZipError", error.getMessage());
+ }
+
+ /**
+ * java.util.zip.ZipError#Serialization()
+ */
+ public void test_serialization() throws Exception {
+ ZipError error = new ZipError("serialization test");
+ SerializationTest.verifySelf(error);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ ZipError error = new ZipError("serialization test");
+ SerializationTest.verifyGolden(this, error);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipFileTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipFileTest.java
new file mode 100644
index 0000000..5b96633
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipFileTest.java
@@ -0,0 +1,421 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import libcore.io.Streams;
+import libcore.java.lang.ref.FinalizationTester;
+import tests.support.resource.Support_Resources;
+
+public class ZipFileTest extends junit.framework.TestCase {
+
+ // the file hyts_zipFile.zip in setup must be included as a resource
+ private String tempFileName;
+ private ZipFile zfile;
+
+ /**
+ * java.util.zip.ZipFile#ZipFile(java.io.File, int)
+ */
+ public void test_ConstructorLjava_io_FileI() throws IOException {
+ zfile.close(); // about to reopen the same temp file
+
+ File file = new File(tempFileName);
+ ZipFile zip = new ZipFile(file, ZipFile.OPEN_DELETE | ZipFile.OPEN_READ);
+ zip.close();
+ assertTrue("Zip should not exist", !file.exists());
+
+ file = new File(tempFileName);
+ try {
+ zip = new ZipFile(file, ZipFile.OPEN_READ);
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ file = new File(tempFileName);
+ try {
+ zip = new ZipFile(file, -1);
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException ee) {
+ // expected
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.zip.ZipFile#ZipFile(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() throws IOException {
+ zfile.close(); // about to reopen the same temp file
+ ZipFile zip = new ZipFile(tempFileName);
+ zip.close();
+ File file = File.createTempFile("zip", "tmp");
+ try {
+ zip = new ZipFile(file.getAbsolutePath());
+ fail("ZipException expected");
+ } catch (ZipException ee) {
+ // expected
+ }
+ file.delete();
+ }
+
+ protected ZipEntry test_finalize1(ZipFile zip) {
+ return zip.getEntry("File1.txt");
+ }
+
+ protected ZipFile test_finalize2(File file) throws IOException {
+ return new ZipFile(file);
+ }
+
+ /**
+ * java.util.zip.ZipFile#finalize()
+ */
+ public void test_finalize() throws IOException {
+ InputStream in = Support_Resources.getStream("hyts_ZipFile.zip");
+ File file = Support_Resources.createTempFile(".jar");
+ OutputStream out = new FileOutputStream(file);
+ int result;
+ byte[] buf = new byte[4096];
+ while ((result = in.read(buf)) != -1) {
+ out.write(buf, 0, result);
+ }
+ in.close();
+ out.close();
+ /*
+ * ZipFile zip = new ZipFile(file); ZipEntry entry1 =
+ * zip.getEntry("File1.txt"); assertNotNull("Did not find entry",
+ * entry1); entry1 = null; zip = null;
+ */
+
+ assertNotNull("Did not find entry", test_finalize1(test_finalize2(file)));
+ FinalizationTester.induceFinalization();
+ file.delete();
+ assertTrue("Zip should not exist", !file.exists());
+ }
+
+ /**
+ * @throws IOException
+ * java.util.zip.ZipFile#close()
+ */
+ public void test_close() throws IOException {
+ // Test for method void java.util.zip.ZipFile.close()
+ File fl = new File(tempFileName);
+ ZipFile zf = new ZipFile(fl);
+ InputStream is1 = zf.getInputStream(zf.getEntry("File1.txt"));
+ InputStream is2 = zf.getInputStream(zf.getEntry("File2.txt"));
+
+ is1.read();
+ is2.read();
+
+ zf.close();
+
+ try {
+ is1.read();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+
+ try {
+ is2.read();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.ZipFile#entries()
+ */
+ public void test_entries() throws Exception {
+ // Test for method java.util.Enumeration java.util.zip.ZipFile.entries()
+ Enumeration<? extends ZipEntry> enumer = zfile.entries();
+ int c = 0;
+ while (enumer.hasMoreElements()) {
+ ++c;
+ enumer.nextElement();
+ }
+ assertTrue("Incorrect number of entries returned: " + c, c == 6);
+
+ Enumeration<? extends ZipEntry> enumeration = zfile.entries();
+ zfile.close();
+ try {
+ enumeration.nextElement();
+ fail("did not detect closed file");
+ } catch (IllegalStateException expected) {
+ }
+
+ try {
+ enumeration.hasMoreElements();
+ fail("did not detect closed file");
+ } catch (IllegalStateException expected) {
+ }
+
+ try {
+ zfile.entries();
+ fail("did not detect closed file");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * java.util.zip.ZipFile#getEntry(java.lang.String)
+ */
+ public void test_getEntryLjava_lang_String() throws IOException {
+ // Test for method java.util.zip.ZipEntry
+ // java.util.zip.ZipFile.getEntry(java.lang.String)
+ java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
+ assertNotNull("Could not obtain ZipEntry", zentry);
+ int r;
+ InputStream in;
+
+ zentry = zfile.getEntry("testdir1/File1.txt");
+ assertNotNull("Could not obtain ZipEntry: testdir1/File1.txt", zentry);
+ zentry = zfile.getEntry("testdir1/");
+ assertNotNull("Could not obtain ZipEntry: testdir1/", zentry);
+ in = zfile.getInputStream(zentry);
+ assertNotNull("testdir1/ should not have null input stream", in);
+ r = in.read();
+ in.close();
+ assertEquals("testdir1/ should not contain data", -1, r);
+
+ zentry = zfile.getEntry("testdir1/testdir1");
+ assertNotNull("Could not obtain ZipEntry: testdir1/testdir1", zentry);
+ in = zfile.getInputStream(zentry);
+ byte[] buf = new byte[256];
+ r = in.read(buf);
+ in.close();
+ assertEquals("incorrect contents", "This is also text", new String(buf,
+ 0, r));
+ }
+
+ public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException {
+ java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
+ assertNotNull("Could not obtain ZipEntry", zentry);
+ int r;
+ InputStream in;
+
+ zentry = zfile.getEntry("testdir1");
+ assertNotNull("Must be able to obtain ZipEntry: testdir1", zentry);
+ in = zfile.getInputStream(zentry);
+ /*
+ * Android delivers empty InputStream, RI no InputStream at all. The
+ * spec doesn't clarify this, so we need to deal with both situations.
+ */
+ int data = -1;
+ if (in != null) {
+ data = in.read();
+ in.close();
+ }
+ assertEquals("Must not be able to read directory data", -1, data);
+ }
+
+ public void test_getEntryLjava_lang_String_Ex() throws IOException {
+ java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
+ assertNotNull("Could not obtain ZipEntry", zentry);
+
+ zfile.close();
+ try {
+ zfile.getEntry("File2.txt");
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException ee) {
+ }
+ }
+
+ /**
+ * @throws IOException
+ * java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry)
+ */
+ public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException {
+ // Test for method java.io.InputStream
+ // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry)
+ ZipEntry zentry = null;
+ InputStream is = null;
+ try {
+ zentry = zfile.getEntry("File1.txt");
+ is = zfile.getInputStream(zentry);
+ byte[] rbuf = new byte[1000];
+ int r;
+ is.read(rbuf, 0, r = (int) zentry.getSize());
+ assertEquals("getInputStream read incorrect data", "This is text",
+ new String(rbuf, 0, r));
+ } catch (java.io.IOException e) {
+ fail("IOException during getInputStream");
+ } finally {
+ try {
+ is.close();
+ } catch (java.io.IOException e) {
+ fail("Failed to close input stream");
+ }
+ }
+
+ zentry = zfile.getEntry("File2.txt");
+ zfile.close();
+ try {
+ is = zfile.getInputStream(zentry);
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException ee) {
+ // expected
+ }
+
+ // ZipException can not be checked. Stream object returned or null.
+ }
+
+ /**
+ * java.util.zip.ZipFile#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.util.zip.ZipFile.getName()
+ assertTrue("Returned incorrect name: " + zfile.getName(), zfile
+ .getName().equals(tempFileName));
+ }
+
+ /**
+ * @throws IOException
+ * java.util.zip.ZipFile#size()
+ */
+ public void test_size() throws IOException {
+ assertEquals(6, zfile.size());
+ zfile.close();
+ try {
+ zfile.size();
+ fail("IllegalStateException expected");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * java.io.InputStream#reset()
+ */
+ public void test_reset() throws IOException {
+ // read an uncompressed entry
+ ZipEntry zentry = zfile.getEntry("File1.txt");
+ InputStream is = zfile.getInputStream(zentry);
+ byte[] rbuf1 = new byte[6];
+ byte[] rbuf2 = new byte[6];
+ int r1, r2;
+ r1 = is.read(rbuf1);
+ assertEquals(rbuf1.length, r1);
+ r2 = is.read(rbuf2);
+ assertEquals(rbuf2.length, r2);
+
+ try {
+ is.reset();
+ fail();
+ } catch (IOException expected) {
+ }
+ is.close();
+
+ // read a compressed entry
+ byte[] rbuf3 = new byte[4185];
+ ZipEntry zentry2 = zfile.getEntry("File3.txt");
+ is = zfile.getInputStream(zentry2);
+ r1 = is.read(rbuf3);
+ assertEquals(4183, r1);
+ try {
+ is.reset();
+ fail();
+ } catch (IOException expected) {
+ }
+ is.close();
+
+ is = zfile.getInputStream(zentry2);
+ r1 = is.read(rbuf3, 0, 3000);
+ assertEquals(3000, r1);
+ try {
+ is.reset();
+ fail();
+ } catch (IOException expected) {
+ }
+ is.close();
+ }
+
+ /**
+ * java.io.InputStream#reset()
+ */
+ public void test_reset_subtest0() throws IOException {
+ // read an uncompressed entry
+ ZipEntry zentry = zfile.getEntry("File1.txt");
+ InputStream is = zfile.getInputStream(zentry);
+ byte[] rbuf1 = new byte[12];
+ byte[] rbuf2 = new byte[12];
+ int r = is.read(rbuf1, 0, 4);
+ assertEquals(4, r);
+ is.mark(0);
+ r = is.read(rbuf1);
+ assertEquals(8, r);
+ assertEquals(-1, is.read());
+
+ try {
+ is.reset();
+ fail();
+ } catch (IOException expected) {
+ }
+
+ is.close();
+
+ // read a compressed entry
+ byte[] rbuf3 = new byte[4185];
+ ZipEntry zentry2 = zfile.getEntry("File3.txt");
+ is = zfile.getInputStream(zentry2);
+ r = is.read(rbuf3, 0, 3000);
+ assertEquals(3000, r);
+ is.mark(0);
+ r = is.read(rbuf3);
+ assertEquals(1183, r);
+ assertEquals(-1, is.read());
+
+ try {
+ is.reset();
+ fail();
+ } catch (IOException expected) {
+ }
+
+ is.close();
+ }
+
+ @Override
+ protected void setUp() throws IOException {
+ // Create a local copy of the file since some tests want to alter information.
+ File tempFile = File.createTempFile("OldZipFileTest", "zip");
+ tempFileName = tempFile.getAbsolutePath();
+
+
+ InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
+ FileOutputStream fos = new FileOutputStream(tempFile);
+ Streams.copy(is, fos);
+
+ is.close();
+ fos.close();
+ zfile = new ZipFile(tempFile);
+ }
+
+ @Override
+ protected void tearDown() throws IOException {
+ if (zfile != null) {
+ zfile.close();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipInputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipInputStreamTest.java
new file mode 100644
index 0000000..adfe7e1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipInputStreamTest.java
@@ -0,0 +1,245 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class ZipInputStreamTest extends TestCase {
+ // the file hyts_zipFile.zip used in setup needs to included as a resource
+ private ZipEntry zentry;
+
+ private ZipInputStream zis;
+
+ private byte[] zipBytes;
+
+ private byte[] dataBytes = "Some data in my file".getBytes();
+
+ @Override
+ protected void setUp() {
+ try {
+ InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
+ if (is == null) {
+ System.out.println("file hyts_ZipFile.zip can not be found");
+ }
+ zis = new ZipInputStream(is);
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ZipOutputStream zos = new ZipOutputStream(bos);
+ ZipEntry entry = new ZipEntry("myFile");
+ zos.putNextEntry(entry);
+ zos.write(dataBytes);
+ zos.closeEntry();
+ zos.close();
+ zipBytes = bos.toByteArray();
+ } catch (Exception e) {
+ System.out.println("Exception during ZipFile setup:");
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ protected void tearDown() {
+ if (zis != null) {
+ try {
+ zis.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#ZipInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() throws Exception {
+ zentry = zis.getNextEntry();
+ zis.closeEntry();
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#close()
+ */
+ public void test_close() {
+ try {
+ zis.close();
+ byte[] rbuf = new byte[10];
+ zis.read(rbuf, 0, 1);
+ } catch (IOException e) {
+ return;
+ }
+ fail("Read data after stream was closed");
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#close()
+ */
+ public void test_close2() throws Exception {
+ // Regression for HARMONY-1101
+ zis.close();
+ // another call to close should NOT cause an exception
+ zis.close();
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#closeEntry()
+ */
+ public void test_closeEntry() throws Exception {
+ zentry = zis.getNextEntry();
+ zis.closeEntry();
+ }
+
+ public void test_closeAfterException() throws Exception {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+ FileInputStream fis = new FileInputStream(new File(resources,
+ "Broken_manifest.jar"));
+
+ ZipInputStream zis1 = new ZipInputStream(fis);
+
+ try {
+ for (int i = 0; i < 6; i++) {
+ zis1.getNextEntry();
+ }
+ fail("ZipException expected");
+ } catch (ZipException ee) {
+ // expected
+ }
+
+ zis1.close();
+ try {
+ zis1.getNextEntry();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#getNextEntry()
+ */
+ public void test_getNextEntry() throws Exception {
+ assertNotNull("getNextEntry failed", zis.getNextEntry());
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws Exception {
+ zentry = zis.getNextEntry();
+ byte[] rbuf = new byte[(int) zentry.getSize()];
+ int r = zis.read(rbuf, 0, rbuf.length);
+ new String(rbuf, 0, r);
+ assertEquals("Failed to read entry", 12, r);
+ }
+
+ public void testReadOneByteAtATime() throws IOException {
+ InputStream in = new FilterInputStream(Support_Resources.getStream("hyts_ZipFile.zip")) {
+ @Override
+ public int read(byte[] buffer, int offset, int count) throws IOException {
+ return super.read(buffer, offset, 1); // one byte at a time
+ }
+
+ @Override
+ public int read(byte[] buffer) throws IOException {
+ return super.read(buffer, 0, 1); // one byte at a time
+ }
+ };
+
+ zis = new ZipInputStream(in);
+ while ((zentry = zis.getNextEntry()) != null) {
+ zentry.getName();
+ }
+ zis.close();
+ }
+
+ /**
+ * java.util.zip.ZipInputStream#skip(long)
+ */
+ public void test_skipJ() throws Exception {
+ zentry = zis.getNextEntry();
+ byte[] rbuf = new byte[(int) zentry.getSize()];
+ zis.skip(2);
+ int r = zis.read(rbuf, 0, rbuf.length);
+ assertEquals("Failed to skip data", 10, r);
+
+ zentry = zis.getNextEntry();
+ zentry = zis.getNextEntry();
+ long s = zis.skip(1025);
+ assertEquals("invalid skip: " + s, 1025, s);
+
+ ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes));
+ zis.getNextEntry();
+ long skipLen = dataBytes.length / 2;
+ assertEquals("Assert 0: failed valid skip", skipLen, zis.skip(skipLen));
+ zis.skip(dataBytes.length);
+ assertEquals("Assert 1: performed invalid skip", 0, zis.skip(1));
+ assertEquals("Assert 2: failed zero len skip", 0, zis.skip(0));
+ try {
+ zis.skip(-1);
+ fail("Assert 3: Expected Illegal argument exception");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void test_available() throws Exception {
+
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, "hyts_ZipFile.zip");
+ File fl = new File(resources, "hyts_ZipFile.zip");
+ FileInputStream fis = new FileInputStream(fl);
+
+ ZipInputStream zis1 = new ZipInputStream(fis);
+ ZipEntry entry = zis1.getNextEntry();
+ assertNotNull("No entry in the archive.", entry);
+ long entrySize = entry.getSize();
+ assertTrue("Entry size was < 1", entrySize > 0);
+ int i = 0;
+ while (zis1.available() > 0) {
+ zis1.skip(1);
+ i++;
+ }
+ if (i != entrySize) {
+ fail("ZipInputStream.available or ZipInputStream.skip does not " +
+ "working properly. Only skipped " + i +
+ " bytes instead of " + entrySize);
+ }
+ assertEquals(0, zis1.skip(1));
+ assertEquals(0, zis1.available());
+ zis1.closeEntry();
+ assertEquals(1, zis.available());
+ zis1.close();
+ try {
+ zis1.available();
+ fail("IOException expected");
+ } catch (IOException ee) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipOutputStreamTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipOutputStreamTest.java
new file mode 100644
index 0000000..7f42fa8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/ZipOutputStreamTest.java
@@ -0,0 +1,292 @@
+/*
+ * 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.tests.java.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.CRC32;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+public class ZipOutputStreamTest extends junit.framework.TestCase {
+
+ ZipOutputStream zos;
+
+ ByteArrayOutputStream bos;
+
+ ZipInputStream zis;
+
+ static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld";
+
+ /**
+ * java.util.zip.ZipOutputStream#close()
+ */
+ public void test_close() throws Exception {
+ zos = new ZipOutputStream(bos);
+ zos.putNextEntry(new ZipEntry("XX"));
+ zos.closeEntry();
+ zos.close();
+
+ // Regression for HARMONY-97
+ ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
+ zos.putNextEntry(new ZipEntry("myFile"));
+ zos.close();
+ zos.close(); // Should be a no-op
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#closeEntry()
+ */
+ public void test_closeEntry() throws IOException {
+ ZipEntry ze = new ZipEntry("testEntry");
+ ze.setTime(System.currentTimeMillis());
+ zos.putNextEntry(ze);
+ zos.write("Hello World".getBytes("UTF-8"));
+ zos.closeEntry();
+ assertTrue("closeEntry failed to update required fields",
+ ze.getSize() == 11 && ze.getCompressedSize() == 13);
+
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#finish()
+ */
+ public void test_finish() throws Exception {
+ ZipEntry ze = new ZipEntry("test");
+ zos.putNextEntry(ze);
+ zos.write("Hello World".getBytes());
+ zos.finish();
+ assertEquals("Finish failed to closeCurrentEntry", 11, ze.getSize());
+
+ ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
+ zos.putNextEntry(new ZipEntry("myFile"));
+ zos.finish();
+ zos.close();
+ try {
+ zos.finish();
+ fail("Assert 0: Expected IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#putNextEntry(java.util.zip.ZipEntry)
+ */
+ public void test_putNextEntryLjava_util_zip_ZipEntry() throws IOException {
+ ZipEntry ze = new ZipEntry("testEntry");
+ ze.setTime(System.currentTimeMillis());
+ zos.putNextEntry(ze);
+ zos.write("Hello World".getBytes());
+ zos.closeEntry();
+ zos.close();
+ zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ ZipEntry ze2 = zis.getNextEntry();
+ zis.closeEntry();
+ assertEquals("Failed to write correct entry", ze.getName(), ze2.getName());
+ assertEquals("Failed to write correct entry", ze.getCrc(), ze2.getCrc());
+ try {
+ zos.putNextEntry(ze);
+ fail("Entry with incorrect setting failed to throw exception");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#setComment(java.lang.String)
+ */
+ public void test_setCommentLjava_lang_String() {
+ // There is no way to get the comment back, so no way to determine if
+ // the comment is set correct
+ zos.setComment("test setComment");
+
+ try {
+ zos.setComment(new String(new byte[0xFFFF + 1]));
+ fail("Comment over 0xFFFF in length should throw exception");
+ } catch (IllegalArgumentException e) {
+ // Passed
+ }
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#setLevel(int)
+ */
+ public void test_setLevelI() throws IOException {
+ ZipEntry ze = new ZipEntry("test");
+ zos.putNextEntry(ze);
+ zos.write(data.getBytes());
+ zos.closeEntry();
+ long csize = ze.getCompressedSize();
+ zos.setLevel(9); // Max Compression
+ zos.putNextEntry(ze = new ZipEntry("test2"));
+ zos.write(data.getBytes());
+ zos.closeEntry();
+ assertTrue("setLevel failed", csize <= ze.getCompressedSize());
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#setMethod(int)
+ */
+ public void test_setMethodI() throws IOException {
+ ZipEntry ze = new ZipEntry("test");
+ zos.setMethod(ZipOutputStream.STORED);
+ CRC32 tempCrc = new CRC32();
+ tempCrc.update(data.getBytes());
+ ze.setCrc(tempCrc.getValue());
+ ze.setSize(new String(data).length());
+ zos.putNextEntry(ze);
+ zos.write(data.getBytes());
+ zos.closeEntry();
+ long csize = ze.getCompressedSize();
+ zos.setMethod(ZipOutputStream.DEFLATED);
+ zos.putNextEntry(ze = new ZipEntry("test2"));
+ zos.write(data.getBytes());
+ zos.closeEntry();
+ assertTrue("setLevel failed", csize >= ze.getCompressedSize());
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ ZipEntry ze = new ZipEntry("test");
+ zos.putNextEntry(ze);
+ zos.write(data.getBytes());
+ zos.closeEntry();
+ zos.close();
+ zos = null;
+ zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ zis.getNextEntry();
+ byte[] b = new byte[data.length()];
+ int r = 0;
+ int count = 0;
+ while (count != b.length && (r = zis.read(b, count, b.length)) != -1) {
+ count += r;
+ }
+ zis.closeEntry();
+ assertEquals("Write failed to write correct bytes", new String(b), data);
+
+ File f = File.createTempFile("testZip", "tst");
+ f.deleteOnExit();
+ FileOutputStream stream = new FileOutputStream(f);
+ ZipOutputStream zip = new ZipOutputStream(stream);
+ zip.setMethod(ZipEntry.STORED);
+
+ try {
+ zip.putNextEntry(new ZipEntry("Second"));
+ fail("Not set an entry. Should have thrown ZipException.");
+ } catch (ZipException e) {
+ // expected -- We have not set an entry
+ }
+
+ try {
+ // We try to write data without entry
+ zip.write(new byte[2]);
+ fail("Writing data without an entry. Should have thrown IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ // Try to write without an entry and with nonsense offset and
+ // length
+ zip.write(new byte[2], 0, 12);
+ fail("Writing data without an entry. Should have thrown IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ // Regression for HARMONY-4405
+ try {
+ zip.write(null, 0, -2);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ zip.write(null, 0, 2);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ zip.write(new byte[2], 0, -2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // Close stream because ZIP is invalid
+ stream.close();
+ }
+
+ /**
+ * java.util.zip.ZipOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII_2() throws IOException {
+ // Regression for HARMONY-577
+ File f1 = File.createTempFile("testZip1", "tst");
+ f1.deleteOnExit();
+ FileOutputStream stream1 = new FileOutputStream(f1);
+ ZipOutputStream zip1 = new ZipOutputStream(stream1);
+ zip1.putNextEntry(new ZipEntry("one"));
+ zip1.setMethod(ZipOutputStream.STORED);
+ zip1.setMethod(ZipEntry.STORED);
+
+ zip1.write(new byte[2]);
+
+ try {
+ zip1.putNextEntry(new ZipEntry("Second"));
+ fail("ZipException expected");
+ } catch (ZipException e) {
+ // expected - We have not set an entry
+ }
+
+ try {
+ zip1.write(new byte[2]); // try to write data without entry
+ fail("expected IOE there");
+ } catch (IOException e2) {
+ // expected
+ }
+
+ zip1.close();
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ zos = new ZipOutputStream(bos = new ByteArrayOutputStream());
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ try {
+ if (zos != null) {
+ zos.close();
+ }
+ if (zis != null) {
+ zis.close();
+ }
+ } catch (Exception e) {
+ }
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ServerSocketFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ServerSocketFactoryTest.java
new file mode 100644
index 0000000..34d7aed
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ServerSocketFactoryTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Boris V. Kuznetsov
+* @version $Revision$
+*/
+
+package tests.api.javax.net;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.SocketException;
+import javax.net.ServerSocketFactory;
+
+import junit.framework.TestCase;
+
+public class ServerSocketFactoryTest extends TestCase {
+
+ public void test_Constructor() {
+ ServerSocketFactory sf = new MyServerSocketFactory();
+ }
+
+ public final void test_createServerSocket() throws Exception {
+ ServerSocketFactory sf = ServerSocketFactory.getDefault();
+ ServerSocket ss = sf.createServerSocket();
+ assertNotNull(ss);
+ ss.close();
+ }
+
+ public final void test_createServerSocket_I() throws Exception {
+ ServerSocketFactory sf = ServerSocketFactory.getDefault();
+ ServerSocket ss = sf.createServerSocket(0);
+ assertNotNull(ss);
+
+ try {
+ sf.createServerSocket(ss.getLocalPort());
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ ss.close();
+
+ try {
+ sf.createServerSocket(-1);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public final void test_createServerSocket_II() throws Exception {
+ ServerSocketFactory sf = ServerSocketFactory.getDefault();
+ ServerSocket ss = sf.createServerSocket(0, 0);
+ assertNotNull(ss);
+
+ try {
+ sf.createServerSocket(ss.getLocalPort(), 0);
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ ss.close();
+
+ try {
+ sf.createServerSocket(65536, 0);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public final void test_createServerSocket_IIInetAddress() throws Exception {
+ ServerSocketFactory sf = ServerSocketFactory.getDefault();
+
+ ServerSocket ss = sf.createServerSocket(0, 0, InetAddress.getLocalHost());
+ assertNotNull(ss);
+
+ try {
+ sf.createServerSocket(ss.getLocalPort(), 0, InetAddress.getLocalHost());
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ ss.close();
+
+ try {
+ sf.createServerSocket(Integer.MAX_VALUE, 0, InetAddress.getLocalHost());
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+}
+class MyServerSocketFactory extends ServerSocketFactory {
+
+ public MyServerSocketFactory() {
+ super();
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int port) throws IOException {
+ return null;
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int port, int backlog)
+ throws IOException {
+ return null;
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int port, int backlog,
+ InetAddress address) throws IOException {
+ return null;
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/SocketFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/SocketFactoryTest.java
new file mode 100644
index 0000000..d566ee3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/SocketFactoryTest.java
@@ -0,0 +1,267 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Boris V. Kuznetsov
+* @version $Revision$
+*/
+
+package tests.api.javax.net;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketException;
+import java.net.UnknownHostException;
+
+import javax.net.SocketFactory;
+
+import junit.framework.TestCase;
+
+public class SocketFactoryTest extends TestCase {
+
+ public void test_Constructor() throws Exception {
+ new MySocketFactory();
+ }
+
+ public final void test_createSocket() throws Exception {
+ SocketFactory sf = SocketFactory.getDefault();
+
+ Socket s = sf.createSocket();
+ assertNotNull(s);
+ assertEquals(-1, s.getLocalPort());
+ assertEquals(0, s.getPort());
+
+ MySocketFactory msf = new MySocketFactory();
+ try {
+ msf.createSocket();
+ fail("No expected SocketException");
+ } catch (SocketException expected) {
+ }
+ }
+
+ public final void test_createSocket_StringI() throws Exception {
+ SocketFactory sf = SocketFactory.getDefault();
+ int sport = new ServerSocket(0).getLocalPort();
+ int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
+
+ Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport);
+ assertNotNull(s);
+ assertTrue("Failed to create socket", s.getPort() == sport);
+
+ try {
+ sf.createSocket("1.2.3.4hello", sport);
+ fail("UnknownHostException wasn't thrown");
+ } catch (UnknownHostException expected) {
+ }
+
+ for (int i = 0; i < invalidPorts.length; i++) {
+ try {
+ sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i]);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ sf.createSocket(InetAddress.getLocalHost().getHostName(), s.getLocalPort());
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ SocketFactory f = SocketFactory.getDefault();
+ try {
+ f.createSocket(InetAddress.getLocalHost().getHostName(), 8082);
+ fail("IOException wasn't thrown ...");
+ } catch (IOException expected) {
+ }
+ }
+
+ public final void test_createSocket_InetAddressI() throws Exception {
+ SocketFactory sf = SocketFactory.getDefault();
+ int sport = new ServerSocket(0).getLocalPort();
+ int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
+
+ Socket s = sf.createSocket(InetAddress.getLocalHost(), sport);
+ assertNotNull(s);
+ assertTrue("Failed to create socket", s.getPort() == sport);
+
+ for (int i = 0; i < invalidPorts.length; i++) {
+ try {
+ sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i]);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ sf.createSocket(InetAddress.getLocalHost(), s.getLocalPort());
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ SocketFactory f = SocketFactory.getDefault();
+ try {
+ f.createSocket(InetAddress.getLocalHost(), 8081);
+ fail("IOException wasn't thrown ...");
+ } catch (IOException expected) {
+ }
+ }
+
+ public final void test_createSocket_InetAddressIInetAddressI() throws Exception {
+ SocketFactory sf = SocketFactory.getDefault();
+ int sport = new ServerSocket(0).getLocalPort();
+ int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
+
+ Socket s = sf.createSocket(InetAddress.getLocalHost(), sport,
+ InetAddress.getLocalHost(), 0);
+ assertNotNull(s);
+ assertTrue("1: Failed to create socket", s.getPort() == sport);
+ int portNumber = s.getLocalPort();
+
+ for (int i = 0; i < invalidPorts.length; i++) {
+ try {
+ sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i],
+ InetAddress.getLocalHost(), portNumber);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sf.createSocket(InetAddress.getLocalHost(), sport,
+ InetAddress.getLocalHost(), invalidPorts[i]);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ sf.createSocket(InetAddress.getLocalHost(), sport,
+ InetAddress.getLocalHost(), portNumber);
+ fail("IOException wasn't thrown");
+ } catch (IOException expected) {
+ }
+
+ SocketFactory f = SocketFactory.getDefault();
+ try {
+ f.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
+ fail("IOException wasn't thrown ...");
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * javax.net.SocketFactory#createSocket(String host, int port,
+ * InetAddress localHost, int localPort)
+ */
+ public final void test_createSocket_05() throws Exception {
+ SocketFactory sf = SocketFactory.getDefault();
+ int sport = new ServerSocket(0).getLocalPort();
+ int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
+
+ Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
+ InetAddress.getLocalHost(), 0);
+ assertNotNull(s);
+ assertTrue("1: Failed to create socket", s.getPort() == sport);
+
+ try {
+ sf.createSocket("1.2.3.4hello", sport, InetAddress.getLocalHost(), 0);
+ fail("UnknownHostException wasn't thrown");
+ } catch (UnknownHostException expected) {
+ }
+
+ for (int i = 0; i < invalidPorts.length; i++) {
+ try {
+ sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i],
+ InetAddress.getLocalHost(), 0);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
+ InetAddress.getLocalHost(), invalidPorts[i]);
+ fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
+ fail("IOException wasn't thrown ...");
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * javax.net.SocketFactory#getDefault()
+ */
+ public final void test_getDefault() {
+ SocketFactory sf = SocketFactory.getDefault();
+ Socket s;
+ try {
+ s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8082);
+ s.close();
+ } catch (IOException e) {
+ }
+ try {
+ s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
+ s.close();
+ } catch (IOException e) {
+ }
+ try {
+ s = sf.createSocket(InetAddress.getLocalHost(), 8081);
+ s.close();
+ } catch (IOException e) {
+ }
+ try {
+ s = sf.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
+ s.close();
+ } catch (IOException e) {
+ }
+ }
+}
+
+class MySocketFactory extends SocketFactory {
+
+ public MySocketFactory() {
+ super();
+ }
+
+ @Override
+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
+ return null;
+ }
+
+ @Override
+ public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
+ throws IOException, UnknownHostException {
+ return null;
+ }
+
+ @Override
+ public Socket createSocket(InetAddress host, int port) throws IOException {
+ return null;
+ }
+
+ @Override
+ public Socket createSocket(InetAddress address, int port,
+ InetAddress localAddress, int localPort) throws IOException {
+ return null;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertPathTrustManagerParametersTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertPathTrustManagerParametersTest.java
new file mode 100644
index 0000000..41407e8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertPathTrustManagerParametersTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.security.cert.CertPathParameters;
+import javax.net.ssl.CertPathTrustManagerParameters;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>CertPathTrustManagerParameters</code> class constructors
+ * and methods.
+ *
+ */
+public class CertPathTrustManagerParametersTest extends TestCase {
+
+ /**
+ * javax.net.ssl.CertPathTrustManagerParameters#
+ * CertPathTrustManagerParameters(java.security.cert.CertPathParameters)
+ * Case 1: Try to construct object.
+ * Case 2: Check NullPointerException.
+ */
+ public void test_ConstructorLjava_security_cert_CertPathParameters() {
+ // case 1: Try to construct object.
+ try {
+ CertPathParameters parameters = new MyCertPathParameters();
+ CertPathTrustManagerParameters p =
+ new CertPathTrustManagerParameters(parameters);
+ assertNotSame("Parameters were cloned incorrectly",
+ parameters, p.getParameters());
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+
+ // case 2: Check NullPointerException.
+ try {
+ new CertPathTrustManagerParameters(null);
+ fail("Expected CertPathTrustManagerParameters was not thrown");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.net.ssl.CertPathTrustManagerParameters#getParameters()
+ */
+ public void test_getParameters() {
+ CertPathParameters parameters = new MyCertPathParameters();
+ CertPathTrustManagerParameters p = new CertPathTrustManagerParameters(
+ parameters);
+ if (!(p.getParameters() instanceof MyCertPathParameters)) {
+ fail("incorrect parameters");
+ }
+ assertNotSame("Parameters were cloned incorrectly",
+ parameters, p.getParameters());
+ }
+}
+
+class MyCertPathParameters implements CertPathParameters {
+ public Object clone() {
+ return new MyCertPathParameters();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertificatesToPlayWith.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertificatesToPlayWith.java
new file mode 100644
index 0000000..5bb6f06
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/CertificatesToPlayWith.java
@@ -0,0 +1,478 @@
+/*
+ * $HeadURL$
+ * $Revision$
+ * $Date$
+ *
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package tests.api.javax.net.ssl;
+
+/**
+ * Some X509 certificates to test against.
+ * <p/>
+ * Note: some of these certificates have Japanese Kanji in the "subjectAlt"
+ * field (UTF8). Not sure how realistic that is since international characters
+ * in DNS names usually get translated into ASCII using "xn--" style DNS
+ * entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to
+ * find &#x82b1;&#x5b50;.co.jp. So would the CN in the certificate contain
+ * "xn--i8s592g.co.jp" in ASCII, or "&#x82b1;&#x5b50;.co.jp" in UTF8? (Both?)
+ *
+ * @since 11-Dec-2006
+ */
+public interface CertificatesToPlayWith {
+
+ /**
+ * CN=foo.com
+ */
+ public final static byte[] X509_FOO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
+ "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
+ "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
+ "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
+ "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
+ "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
+ "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
+ "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
+ "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
+ "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
+ "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" +
+ "fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" +
+ "c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" +
+ "815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" +
+ "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" +
+ "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=&#x82b1;&#x5b50;.co.jp
+ */
+ public final static byte[] X509_HANAKO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" +
+ "FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" +
+ "MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" +
+ "g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" +
+ "wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" +
+ "7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" +
+ "AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" +
+ "qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" +
+ "CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" +
+ "HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" +
+ "rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" +
+ "ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" +
+ "spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" +
+ "a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" +
+ "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" +
+ "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=foo.com, subjectAlt=bar.com
+ */
+ public final static byte[] X509_FOO_BAR = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
+ "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
+ "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
+ "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
+ "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
+ "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
+ "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
+ "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" +
+ "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
+ "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
+ "A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" +
+ "dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" +
+ "zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" +
+ "3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" +
+ "88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" +
+ "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" +
+ "VbWx/uETImUu+NZg22ewEw==\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp
+ * (hanako.co.jp in kanji)
+ */
+ public final static byte[] X509_FOO_BAR_HANAKO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
+ "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
+ "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
+ "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
+ "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
+ "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
+ "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
+ "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" +
+ "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
+ "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
+ "A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" +
+ "SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" +
+ "++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" +
+ "PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" +
+ "12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" +
+ "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" +
+ "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=*.foo.com
+ */
+ public final static byte[] X509_WILD_FOO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
+ "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
+ "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
+ "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
+ "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
+ "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
+ "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
+ "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" +
+ "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
+ "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
+ "A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" +
+ "N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" +
+ "A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" +
+ "yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" +
+ "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" +
+ "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=*.co.jp
+ */
+ public final static byte[] X509_WILD_CO_JP = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" +
+ "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
+ "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
+ "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
+ "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
+ "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
+ "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
+ "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
+ "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
+ "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
+ "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" +
+ "CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" +
+ "1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" +
+ "S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" +
+ "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" +
+ "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp
+ * (*.hanako.co.jp in kanji)
+ */
+ public final static byte[] X509_WILD_FOO_BAR_HANAKO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
+ "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
+ "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
+ "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
+ "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
+ "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
+ "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
+ "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" +
+ "YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" +
+ "DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" +
+ "27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" +
+ "MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" +
+ "DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" +
+ "WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" +
+ "hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" +
+ "qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" +
+ "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp
+ */
+ public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" +
+ "MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" +
+ "loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" +
+ "bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" +
+ "Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" +
+ "h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" +
+ "TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" +
+ "3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" +
+ "Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" +
+ "tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" +
+ "DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" +
+ "y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" +
+ "uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" +
+ "EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" +
+ "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" +
+ "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * subjectAlt=foo.com
+ */
+ public final static byte[] X509_NO_CNS_FOO = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
+ "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
+ "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
+ "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" +
+ "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
+ "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
+ "cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" +
+ "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" +
+ "fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" +
+ "xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" +
+ "Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" +
+ "ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" +
+ "jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" +
+ "5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" +
+ "IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" +
+ "0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" +
+ "CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" +
+ "tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" +
+ "Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" +
+ "yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" +
+ "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" +
+ "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * Intermediate CA for all of these.
+ */
+ public final static byte[] X509_INTERMEDIATE_CA = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
+ "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
+ "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" +
+ "WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" +
+ "EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" +
+ "BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" +
+ "MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" +
+ "hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" +
+ "XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" +
+ "Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" +
+ "KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" +
+ "qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" +
+ "9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" +
+ "6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" +
+ "rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" +
+ "VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" +
+ "c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" +
+ "aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" +
+ "KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" +
+ "Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" +
+ "e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" +
+ "1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" +
+ "XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" +
+ "aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * Root CA for all of these.
+ */
+ public final static byte[] X509_ROOT_CA = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
+ "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
+ "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
+ "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" +
+ "WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" +
+ "FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" +
+ "A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" +
+ "Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" +
+ "79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" +
+ "w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" +
+ "mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" +
+ "jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" +
+ "JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" +
+ "EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" +
+ "9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" +
+ "hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" +
+ "Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" +
+ "MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" +
+ "rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" +
+ "S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" +
+ "VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" +
+ "lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" +
+ "hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" +
+ "Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" +
+ "2dDk0g==\n" +
+ "-----END CERTIFICATE-----\n").getBytes();
+
+ /**
+ * Below is the private key for all the server certificates above (but
+ * not the intermediate CA or the root CA). All of those server certs
+ * came from the same private key.
+ */
+ public final static String RSA_PUBLIC_MODULUS =
+ "00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" +
+ "8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" +
+ "41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" +
+ "f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" +
+ "9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" +
+ "56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" +
+ "713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" +
+ "cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" +
+ "4caab29bddf085893dde5de87047b9e5cd";
+
+ public final static String RSA_PUBLIC_EXPONENT = "65537";
+
+ public final static String RSA_PRIVATE_EXPONENT =
+ "577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" +
+ "7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" +
+ "8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" +
+ "f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" +
+ "a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" +
+ "d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" +
+ "a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" +
+ "c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" +
+ "44e6b355c1df581f50997175166eef39";
+
+ public final static String RSA_PRIME1 =
+ "00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" +
+ "a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" +
+ "b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" +
+ "350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" +
+ "fef7d8b532608d2513";
+
+ public final static String RSA_PRIME2 =
+ "00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" +
+ "db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" +
+ "af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" +
+ "529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" +
+ "c18d320510d79f859f";
+
+ public final static String RSA_EXPONENT1 =
+ "029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" +
+ "47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" +
+ "6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" +
+ "c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" +
+ "106467da112ce389";
+
+ public final static String RSA_EXPONENT2 =
+ "00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" +
+ "7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" +
+ "4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" +
+ "9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" +
+ "e997f079b0f6314eb7";
+
+ public final static String RSA_COEFFICIENT =
+ "00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" +
+ "1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" +
+ "a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" +
+ "001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" +
+ "2b8a9c7d91c7d175ae";
+
+ /**
+ * cat cert.cnf
+ * [req]
+ * distinguished_name=distinguished_name
+ * req_extensions=req_extensions
+ * x509_extensions=x509_extensions
+ * [distinguished_name]
+ * [req_extensions]
+ * [x509_extensions]
+ * subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1
+ *
+ * $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \
+ * -newkey rsa:512 -out cert.pem
+ */
+ public final static byte[] X509_MULTIPLE_SUBJECT_ALT = (
+ "-----BEGIN CERTIFICATE-----\n" +
+ "MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" +
+ "BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow\n" +
+ "FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt\n" +
+ "atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg\n" +
+ "PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv\n" +
+ "Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL\n" +
+ "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n" +
+ "X8YKH52fnHsCrhSD\n" +
+ "-----END CERTIFICATE-----").getBytes();
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HandshakeCompletedEventTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HandshakeCompletedEventTest.java
new file mode 100644
index 0000000..c075cea
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HandshakeCompletedEventTest.java
@@ -0,0 +1,613 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import dalvik.annotation.AndroidOnly;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import javax.net.ssl.HandshakeCompletedEvent;
+import javax.net.ssl.HandshakeCompletedListener;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import javax.security.cert.X509Certificate;
+import junit.framework.TestCase;
+import libcore.io.Base64;
+import org.apache.harmony.xnet.tests.support.mySSLSession;
+
+/**
+ * Tests for <code>HandshakeCompletedEvent</code> class constructors and methods.
+ *
+ */
+public class HandshakeCompletedEventTest extends TestCase {
+
+ private String certificate = "-----BEGIN CERTIFICATE-----\n"
+ + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n"
+ + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n"
+ + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n"
+ + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n"
+ + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n"
+ + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n"
+ + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n"
+ + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n"
+ + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n"
+ + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n"
+ + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n"
+ + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n"
+ + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n"
+ + "-----END CERTIFICATE-----\n";
+
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#HandshakeCompletedEvent(SSLSocket sock, SSLSession s)
+ */
+ public final void test_Constructor() throws Exception {
+ mySSLSession session = new mySSLSession();
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ try {
+ new HandshakeCompletedEvent(null, null);
+ fail("Any exception wasn't thrown for null parameters");
+ } catch (Exception expected) {
+ }
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getCipherSuite()
+ */
+ public final void test_getCipherSuite() throws Exception {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ assertEquals("SuiteName", event.getCipherSuite());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates()
+ */
+ public final void test_getLocalCertificates() throws Exception {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ assertNull(event.getLocalCertificates());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getLocalPrincipal()
+ */
+ public final void test_getLocalPrincipal() throws Exception {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ assertNull(event.getLocalPrincipal());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificateChain()
+ */
+ public final void test_getPeerCertificateChain() throws Exception {
+ ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getBytes());
+ mySSLSession session = new mySSLSession((X509Certificate[]) null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ try {
+ event.getPeerCertificateChain();
+ fail("SSLPeerUnverifiedException wasn't thrown");
+ } catch (SSLPeerUnverifiedException expected) {
+ }
+
+ X509Certificate xc = X509Certificate.getInstance(bis);
+ X509Certificate[] xcs = {xc};
+ session = new mySSLSession(xcs);
+ event = new HandshakeCompletedEvent(socket, session);
+
+ X509Certificate[] res = event.getPeerCertificateChain();
+ assertEquals(1, res.length);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificates()
+ */
+ public final void test_getPeerCertificates() throws IOException {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ try {
+ event.getPeerCertificates();
+ fail("SSLPeerUnverifiedException wasn't thrown");
+ } catch (SSLPeerUnverifiedException expected) {
+ }
+
+ session = new mySSLSession((X509Certificate[]) null);
+ event = new HandshakeCompletedEvent(socket, session);
+ Certificate[] res = event.getPeerCertificates();
+ assertEquals(3, res.length);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getPeerPrincipal()
+ */
+ public final void test_getPeerPrincipal() throws IOException {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ assertNull(event.getPeerPrincipal());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getSession()
+ */
+ public final void test_getSession() throws IOException {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
+ SSLSession ss = event.getSession();
+ assertNotNull(ss);
+ assertEquals(session, ss);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.HandshakeCompletedEvent#getSocket()
+ */
+ public final void test_getSocket() throws IOException {
+ SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, null);
+ SSLSocket ss = event.getSocket();
+ assertNotNull(ss);
+ assertEquals(socket, ss);
+ }
+
+
+ // Regression test for CompletedHandshakeEvent not firing with a custom
+ // TrustManager
+
+
+ private SSLSocket socket;
+ private SSLServerSocket serverSocket;
+ private MyHandshakeListener listener;
+ private String host = "localhost";
+
+ private String PASSWORD = "android";
+
+ /**
+ * Defines the keystore contents for the server, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_BKS =
+ "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
+ + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
+ + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
+ + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
+ + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
+ + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
+ + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
+ + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
+ + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
+ + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
+ + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
+ + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
+ + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
+ + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
+ + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
+ + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
+ + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
+ + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
+ + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
+ + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
+ + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
+ + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
+ + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
+ + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
+
+ /**
+ * Defines the keystore contents for the server, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_JKS =
+ "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
+ + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
+ + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
+ + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
+ + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
+ + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
+ + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
+ + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
+ + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
+ + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
+ + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
+ + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
+ + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
+ + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
+ + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
+ + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
+ + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
+ + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
+ + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
+ + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
+ + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
+ + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
+ + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
+ + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
+
+ /**
+ * Defines the keystore contents for the client, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Client".
+ */
+ private static final String CLIENT_KEYS_JKS =
+ "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC"
+ + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5"
+ + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw"
+ + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY"
+ + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4"
+ + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit"
+ + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY"
+ + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O"
+ + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS"
+ + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4"
+ + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi"
+ + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL"
+ + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41"
+ + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV"
+ + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB"
+ + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5"
+ + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN"
+ + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w"
+ + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR"
+ + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5"
+ + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE"
+ + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng"
+ + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp"
+ + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
+
+ /**
+ * Defines the keystore contents for the client, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Client".
+ */
+ private static final String CLIENT_KEYS_BKS =
+ "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41"
+ + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
+ + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
+ + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw"
+ + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
+ + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu"
+ + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva"
+ + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD"
+ + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG"
+ + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F"
+ + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg"
+ + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx"
+ + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi"
+ + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD"
+ + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO"
+ + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz"
+ + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5"
+ + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8"
+ + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1"
+ + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9"
+ + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB"
+ + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9"
+ + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef"
+ + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
+
+
+ /**
+ * Implements the actual test case. Launches a server and a client, requires
+ * client authentication and checks the certificates afterwards (not in the
+ * usual sense, we just make sure that we got the expected certificates,
+ * because our self-signed test certificates are not valid.)
+ */
+
+ @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
+ public void testClientAuth() throws Exception {
+
+ boolean useBKS = true;
+
+ listener = new MyHandshakeListener();
+ String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
+ String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
+ TestServer server = new TestServer(true,
+ TestServer.CLIENT_AUTH_WANTED, serverKeys);
+ TestClient client = new TestClient(true, clientKeys);
+
+ Thread serverThread = new Thread(server);
+ Thread clientThread = new Thread(client);
+
+ serverThread.start();
+ Thread.currentThread().sleep(3000);
+ clientThread.start();
+
+ serverThread.join();
+ clientThread.join();
+
+ // The server must have completed without an exception.
+ Exception e = server.getException();
+ if (e != null) {
+ e.printStackTrace();
+ }
+
+ // The client must have completed without an exception.
+ e = client.getException();
+ if (e != null) {
+ e.printStackTrace();
+ }
+
+ assertNull(e);
+
+ assertTrue(listener.completeDone);
+ }
+
+ /**
+ * Implements a test SSL socket server. It wait for a connection on a given
+ * port, requests client authentication (if specified), reads 256 bytes
+ * from the socket, and writes 256 bytes to the socket.
+ */
+ class TestServer implements Runnable {
+
+ public static final int CLIENT_AUTH_NONE = 0;
+
+ public static final int CLIENT_AUTH_WANTED = 1;
+
+ public static final int CLIENT_AUTH_NEEDED = 2;
+
+ private TestTrustManager trustManager;
+
+ private Exception exception;
+
+ String keys;
+
+ private int clientAuth;
+
+ private boolean provideKeys;
+
+ public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception {
+ this.keys = keys;
+ this.clientAuth = clientAuth;
+ this.provideKeys = provideKeys;
+
+ trustManager = new TestTrustManager();
+
+ KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
+ TrustManager[] trustManagers = new TrustManager[] { trustManager };
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, null);
+
+ serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
+
+ if (clientAuth == CLIENT_AUTH_WANTED) {
+ serverSocket.setWantClientAuth(true);
+ } else if (clientAuth == CLIENT_AUTH_NEEDED) {
+ serverSocket.setNeedClientAuth(true);
+ } else {
+ serverSocket.setWantClientAuth(false);
+ }
+
+ serverSocket.bind(new InetSocketAddress(0));
+ }
+
+ public void run() {
+ try {
+ SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
+
+ InputStream istream = clientSocket.getInputStream();
+
+ for (int i = 0; i < 256; i++) {
+ int j = istream.read();
+ assertEquals(i, j);
+ }
+
+ istream.close();
+
+ OutputStream ostream = clientSocket.getOutputStream();
+
+ for (int i = 0; i < 256; i++) {
+ ostream.write(i);
+ }
+
+ ostream.flush();
+ ostream.close();
+
+ clientSocket.close();
+ serverSocket.close();
+
+ } catch (Exception ex) {
+ exception = ex;
+ }
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public X509Certificate[] getChain() {
+ return trustManager.getChain();
+ }
+
+ }
+
+ /**
+ * Implements a test SSL socket client. It open a connection to localhost on
+ * a given port, writes 256 bytes to the socket, and reads 256 bytes from the
+ * socket.
+ */
+ class TestClient implements Runnable {
+
+ private TestTrustManager trustManager;
+
+ private Exception exception;
+
+ private String keys;
+
+ private boolean provideKeys;
+
+ public TestClient(boolean provideKeys, String keys) {
+ this.keys = keys;
+ this.provideKeys = provideKeys;
+
+ trustManager = new TestTrustManager();
+ }
+
+ public void run() {
+ try {
+ KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
+ TrustManager[] trustManagers = new TrustManager[] { trustManager };
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, null);
+
+ SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket();
+
+ socket.connect(serverSocket.getLocalSocketAddress());
+ socket.addHandshakeCompletedListener(listener);
+ socket.startHandshake();
+
+ OutputStream ostream = socket.getOutputStream();
+
+ for (int i = 0; i < 256; i++) {
+ ostream.write(i);
+ }
+
+ ostream.flush();
+ ostream.close();
+
+ InputStream istream = socket.getInputStream();
+
+ for (int i = 0; i < 256; i++) {
+ int j = istream.read();
+ assertEquals(i, j);
+ }
+
+ istream.close();
+
+ socket.close();
+
+ } catch (Exception ex) {
+ exception = ex;
+ }
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public X509Certificate[] getChain() {
+ return trustManager.getChain();
+ }
+ }
+
+ /**
+ * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
+ * for the result.
+ */
+ private KeyManager[] getKeyManagers(String keys) throws Exception {
+ byte[] bytes = Base64.decode(keys.getBytes());
+ InputStream inputStream = new ByteArrayInputStream(bytes);
+
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(inputStream, PASSWORD.toCharArray());
+ inputStream.close();
+
+ String algorithm = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
+ keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
+
+ return keyManagerFactory.getKeyManagers();
+ }
+
+
+ /**
+ * Implements basically a dummy TrustManager. It stores the certificate
+ * chain it sees, so it can later be queried.
+ */
+ public static class TestTrustManager implements X509TrustManager {
+
+ private X509Certificate[] chain;
+
+ private String authType;
+
+ public void checkClientTrusted(X509Certificate[] chain, String authType) {
+ this.chain = chain;
+ this.authType = authType;
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain, String authType) {
+ this.chain = chain;
+ this.authType = authType;
+ }
+
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return new java.security.cert.X509Certificate[0];
+ }
+
+ public X509Certificate[] getChain() {
+ return chain;
+ }
+
+ public String getAuthType() {
+ return authType;
+ }
+
+ public void checkClientTrusted(
+ java.security.cert.X509Certificate[] chain, String authType)
+ throws CertificateException {
+
+ }
+
+ public void checkServerTrusted(
+ java.security.cert.X509Certificate[] chain, String authType)
+ throws CertificateException {
+
+ }
+
+ }
+
+ class MyHandshakeListener implements HandshakeCompletedListener {
+
+ public boolean completeDone;
+
+ MyHandshakeListener() {
+ completeDone = false;
+ }
+
+ public void handshakeCompleted(HandshakeCompletedEvent event) {
+ if (event != null) completeDone = true;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HostnameVerifierTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HostnameVerifierTest.java
new file mode 100644
index 0000000..839f3b5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HostnameVerifierTest.java
@@ -0,0 +1,290 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.security.auth.x500.X500Principal;
+import junit.framework.TestCase;
+import org.apache.harmony.xnet.tests.support.mySSLSession;
+
+public class HostnameVerifierTest extends TestCase implements
+ CertificatesToPlayWith {
+
+ /**
+ * javax.net.ssl.HostnameVerifier#verify(String hostname, SSLSession
+ * session)
+ */
+ public final void test_verify() throws Exception {
+ mySSLSession session = new mySSLSession("localhost", 1080, null);
+ HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
+ assertFalse(hv.verify("localhost", session));
+ }
+
+ // copied and modified from apache http client test suite.
+ public void testVerify() throws Exception {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in;
+ X509Certificate x509;
+ in = new ByteArrayInputStream(X509_FOO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
+
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+ assertTrue(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ assertFalse(verifier.verify("bar.com", session));
+
+ in = new ByteArrayInputStream(X509_HANAKO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
+ assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
+
+ in = new ByteArrayInputStream(X509_FOO_BAR);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertFalse(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ assertTrue(verifier.verify("bar.com", session));
+ assertFalse(verifier.verify("a.bar.com", session));
+
+ in = new ByteArrayInputStream(X509_FOO_BAR_HANAKO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ // these checks test alternative subjects. The test data contains an
+ // alternative subject starting with a japanese kanji character. This is
+ // not supported by Android because the underlying implementation from
+ // harmony follows the definition from rfc 1034 page 10 for alternative
+ // subject names. This causes the code to drop all alternative subjects.
+ // assertTrue(verifier.verify("bar.com", session));
+ // assertFalse(verifier.verify("a.bar.com", session));
+ // assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
+
+ in = new ByteArrayInputStream(X509_NO_CNS_FOO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+
+ in = new ByteArrayInputStream(X509_NO_CNS_FOO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+
+ in = new ByteArrayInputStream(X509_THREE_CNS_FOO_BAR_HANAKO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertFalse(verifier.verify("foo.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ assertFalse(verifier.verify("bar.com", session));
+ assertFalse(verifier.verify("a.bar.com", session));
+ assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
+ assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
+
+ in = new ByteArrayInputStream(X509_WILD_FOO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("foo.com", session));
+ assertTrue(verifier.verify("www.foo.com", session));
+ assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
+ assertFalse(verifier.verify("a.b.foo.com", session));
+
+ in = new ByteArrayInputStream(X509_WILD_CO_JP);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ assertTrue(verifier.verify("foo.co.jp", session));
+ assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
+
+ in = new ByteArrayInputStream(X509_WILD_FOO_BAR_HANAKO);
+ x509 = (X509Certificate) cf.generateCertificate(in);
+ session = new mySSLSession(new X509Certificate[] {x509});
+ // try the foo.com variations
+ assertTrue(verifier.verify("foo.com", session));
+ assertTrue(verifier.verify("www.foo.com", session));
+ assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
+ assertFalse(verifier.verify("a.b.foo.com", session));
+ // these checks test alternative subjects. The test data contains an
+ // alternative subject starting with a japanese kanji character. This is
+ // not supported by Android because the underlying implementation from
+ // harmony follows the definition from rfc 1034 page 10 for alternative
+ // subject names. This causes the code to drop all alternative subjects.
+ // assertFalse(verifier.verify("bar.com", session));
+ // assertTrue(verifier.verify("www.bar.com", session));
+ // assertTrue(verifier.verify("\u82b1\u5b50.bar.com", session));
+ // assertTrue(verifier.verify("a.b.bar.com", session));
+ }
+
+ public void testSubjectAlt() throws Exception {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT);
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
+
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+ assertEquals(new X500Principal("CN=localhost"), x509.getSubjectX500Principal());
+
+ assertTrue(verifier.verify("localhost", session));
+ assertTrue(verifier.verify("localhost.localdomain", session));
+ assertFalse(verifier.verify("local.host", session));
+ }
+
+ public void testVerifyIpAddress() throws Exception {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT);
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+
+ assertTrue(verifier.verify("127.0.0.1", session));
+ assertFalse(verifier.verify("127.0.0.2", session));
+ }
+
+ public void testWildcardsCannotMatchIpAddresses() throws Exception {
+ // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem
+ String cert = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV\n"
+ + "BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx\n"
+ + "EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt\n"
+ + "YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+\n"
+ + "cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt\n"
+ + "JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV\n"
+ + "BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB\n"
+ + "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n"
+ + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n"
+ + "-----END CERTIFICATE-----";
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+
+ assertFalse(verifier.verify("127.0.0.1", session));
+ }
+
+ /**
+ * Earlier implementations of Android's hostname verifier required that
+ * wildcard names wouldn't match "*.com" or similar. This was a nonstandard
+ * check that we've since dropped. It is the CA's responsibility to not hand
+ * out certificates that match so broadly.
+ */
+ public void testWildcardsDoesNotNeedTwoDots() throws Exception {
+ // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem
+ String cert = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV\n"
+ + "BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w\n"
+ + "DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz\n"
+ + "ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe\n"
+ + "1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA\n"
+ + "BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF\n"
+ + "Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA\n"
+ + "U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n"
+ + "qUYo4ES548JdpQtcLrW2sA==\n"
+ + "-----END CERTIFICATE-----";
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+
+ assertTrue(verifier.verify("google.com", session));
+ }
+
+ public void testSubjectAltName() throws Exception {
+ /*
+ * $ cat ./cert.cnf
+ * [req]
+ * distinguished_name=distinguished_name
+ * req_extensions=req_extensions
+ * x509_extensions=x509_extensions
+ * [distinguished_name]
+ * [req_extensions]
+ * [x509_extensions]
+ * subjectAltName=DNS:bar.com,DNS:baz.com
+ *
+ * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \
+ * -newkey rsa:512 -out cert.pem
+ */
+ String cert = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n"
+ + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ\n"
+ + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8\n"
+ + "hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp\n"
+ + "y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w\n"
+ + "DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n"
+ + "oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n"
+ + "-----END CERTIFICATE-----";
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+
+ assertFalse(verifier.verify("foo.com", session));
+ assertTrue(verifier.verify("bar.com", session));
+ assertTrue(verifier.verify("baz.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ assertFalse(verifier.verify("quux.com", session));
+ }
+
+ public void testSubjectAltNameWithWildcard() throws Exception {
+ /*
+ * $ cat ./cert.cnf
+ * [req]
+ * distinguished_name=distinguished_name
+ * req_extensions=req_extensions
+ * x509_extensions=x509_extensions
+ * [distinguished_name]
+ * [req_extensions]
+ * [x509_extensions]
+ * subjectAltName=DNS:bar.com,DNS:*.baz.com
+ *
+ * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \
+ * -newkey rsa:512 -out cert.pem
+ */
+ String cert = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n"
+ + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ\n"
+ + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog\n"
+ + "YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3\n"
+ + "nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv\n"
+ + "bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n"
+ + "Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n"
+ + "-----END CERTIFICATE-----";
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
+ X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
+ mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
+ HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
+
+ assertFalse(verifier.verify("foo.com", session));
+ assertTrue(verifier.verify("bar.com", session));
+ assertTrue(verifier.verify("a.baz.com", session));
+ assertTrue(verifier.verify("baz.com", session));
+ assertFalse(verifier.verify("a.foo.com", session));
+ assertFalse(verifier.verify("a.bar.com", session));
+ assertFalse(verifier.verify("quux.com", session));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HttpsURLConnectionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HttpsURLConnectionTest.java
new file mode 100644
index 0000000..e2ebdbd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/HttpsURLConnectionTest.java
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package tests.api.javax.net.ssl;
+
+import java.io.ByteArrayInputStream;
+import java.net.URL;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+
+import org.apache.harmony.security.tests.support.cert.TestUtils;
+
+import junit.framework.TestCase;
+
+
+
+/**
+ * Tests for <code>HttpsURLConnection</code> class constructors and methods.
+ *
+ */
+public class HttpsURLConnectionTest extends TestCase {
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#HttpsURLConnection(java_net_URL)
+ */
+ public final void test_Constructor() throws Exception {
+ new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
+ new MyHttpsURLConnection(null);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getCipherSuite()
+ */
+ public final void test_getCipherSuite() throws Exception {
+ URL url = new URL("https://localhost:55555");
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ try {
+ connection.getCipherSuite();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+
+ HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
+ assertEquals("CipherSuite", con.getCipherSuite());
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getLocalCertificates()
+ */
+ public final void test_getLocalCertificates() throws Exception {
+ URL url = new URL("https://localhost:55555");
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ try {
+ connection.getLocalCertificates();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+
+ HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
+ assertNull(con.getLocalCertificates());
+ con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
+ Certificate[] cert = con.getLocalCertificates();
+ assertNotNull(cert);
+ assertEquals(1, cert.length);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier()
+ */
+ public final void test_getDefaultHostnameVerifier() {
+ HostnameVerifier verifyer =
+ HttpsURLConnection.getDefaultHostnameVerifier();
+ assertNotNull("Default hostname verifyer is null", verifyer);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getDefaultSSLSocketFactory()
+ */
+ public final void test_getDefaultSSLSocketFactory() {
+ SSLSocketFactory sf = HttpsURLConnection.getDefaultSSLSocketFactory();
+ if (!sf.equals(SSLSocketFactory.getDefault())) {
+ fail("incorrect DefaultSSLSocketFactory");
+ }
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getHostnameVerifier()
+ */
+ public final void test_getHostnameVerifier()
+ throws Exception {
+ HttpsURLConnection con = new MyHttpsURLConnection(
+ new URL("https://www.fortify.net/"));
+ HostnameVerifier verifyer = con.getHostnameVerifier();
+ assertNotNull("Hostname verifyer is null", verifyer);
+ assertEquals("Incorrect value of hostname verirfyer",
+ HttpsURLConnection.getDefaultHostnameVerifier(), verifyer);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getLocalPrincipal()
+ */
+ public final void test_getLocalPrincipal() throws Exception {
+ URL url = new URL("https://localhost:55555");
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ try {
+ connection.getLocalPrincipal();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+
+ HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
+ assertNull(con.getLocalPrincipal());
+ con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
+ assertNotNull("Local principal is null", con.getLocalPrincipal());
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getPeerPrincipal()
+ */
+ public final void test_getPeerPrincipal() throws Exception {
+ URL url = new URL("https://localhost:55555");
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ try {
+ connection.getPeerPrincipal();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
+ try {
+ Principal p = con.getPeerPrincipal();
+ fail("SSLPeerUnverifiedException wasn't thrown");
+ } catch (SSLPeerUnverifiedException expected) {
+ }
+
+ con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
+ Principal p = con.getPeerPrincipal();
+ assertNotNull(p);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getServerCertificates()
+ */
+ public final void test_getServerCertificates() throws Exception {
+ URL url = new URL("https://localhost:55555");
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ try {
+ connection.getServerCertificates();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+
+ HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
+ try {
+ con.getServerCertificates();
+ fail("SSLPeerUnverifiedException wasn't thrown");
+ } catch (SSLPeerUnverifiedException expected) {
+ }
+
+ con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
+ Certificate[] cert = con.getServerCertificates();
+ assertNotNull(cert);
+ assertEquals(1, cert.length);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#getSSLSocketFactory()
+ */
+ public final void test_getSSLSocketFactory() {
+ HttpsURLConnection con = new MyHttpsURLConnection(null);
+ SSLSocketFactory sf = con.getSSLSocketFactory();
+ if (!sf.equals(SSLSocketFactory.getDefault())) {
+ fail("incorrect DefaultSSLSocketFactory");
+ }
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier()
+ */
+ public final void test_setDefaultHostnameVerifier() {
+ try {
+ HttpsURLConnection.setDefaultHostnameVerifier(null);
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ HostnameVerifier def = HttpsURLConnection.getDefaultHostnameVerifier();
+ try {
+ myHostnameVerifier hnv = new myHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ assertEquals(hnv, HttpsURLConnection.getDefaultHostnameVerifier());
+ } finally {
+ HttpsURLConnection.setDefaultHostnameVerifier(def);
+ }
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#setHostnameVerifier()
+ */
+ public final void test_setHostnameVerifier() {
+ HttpsURLConnection con = new MyHttpsURLConnection(null);
+ try {
+ con.setHostnameVerifier(null);
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ myHostnameVerifier hnv = new myHostnameVerifier();
+ con.setHostnameVerifier(hnv);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory()
+ */
+ public final void test_setDefaultSSLSocketFactory() {
+ try {
+ HttpsURLConnection.setDefaultSSLSocketFactory(null);
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
+ .getDefault();
+ HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
+ }
+
+ /**
+ * javax.net.ssl.HttpsURLConnection#setSSLSocketFactory()
+ */
+ public final void test_setSSLSocketFactory() {
+ HttpsURLConnection con = new MyHttpsURLConnection(null);
+ try {
+ con.setSSLSocketFactory(null);
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ }
+ SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
+ .getDefault();
+ con.setSSLSocketFactory(ssf);
+ }
+}
+
+class MyHttpsURLConnection extends javax.net.ssl.HttpsURLConnection {
+
+ private String typeDone;
+
+ public MyHttpsURLConnection(URL url) {
+ super(url);
+ }
+
+ public MyHttpsURLConnection(URL url, String type) {
+ super(url);
+ typeDone = type;
+ }
+
+ /*
+ * @see javax.net.ssl.HttpsURLConnection#getCipherSuite()
+ */
+ public String getCipherSuite() {
+ return "CipherSuite";
+ }
+
+ /*
+ * @see javax.net.ssl.HttpsURLConnection#getLocalCertificates()
+ */
+ public Certificate[] getLocalCertificates() {
+ try {
+ CertificateFactory cf = CertificateFactory.getInstance(typeDone);
+ byte[] barr = TestUtils.getX509Certificate_v1();
+ ByteArrayInputStream bis = new ByteArrayInputStream(barr);
+ Certificate cert = cf.generateCertificate(bis);
+ return new Certificate[] { cert };
+ } catch (CertificateException se) {
+ return null;
+ }
+ }
+
+ /*
+ * @see javax.net.ssl.HttpsURLConnection#getServerCertificates()
+ */
+ public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
+ try {
+ CertificateFactory cf = CertificateFactory.getInstance(typeDone);
+ byte[] barr = TestUtils.getX509Certificate_v3();
+ ByteArrayInputStream bis = new ByteArrayInputStream(barr);
+ Certificate cert = cf.generateCertificate(bis);
+ return new Certificate[] { cert };
+ } catch (CertificateException se) {
+ throw new SSLPeerUnverifiedException("No server's end-entity certificate");
+ }
+ }
+
+ /*
+ * @see java.net.HttpURLConnection#disconnect()
+ */
+ public void disconnect() {
+ }
+
+ /*
+ * @see java.net.HttpURLConnection#usingProxy()
+ */
+ public boolean usingProxy() {
+ return false;
+ }
+
+ public void connect() {
+ }
+
+}
+
+class myHostnameVerifier implements HostnameVerifier {
+
+ myHostnameVerifier() {
+ }
+
+ public boolean verify(String hostname, SSLSession session) {
+ if (hostname == session.getPeerHost()) {
+ return true;
+ } else return false;
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory1Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory1Test.java
new file mode 100644
index 0000000..b369ed9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory1Test.java
@@ -0,0 +1,532 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Security;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.net.ssl.KeyStoreBuilderParameters;
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.KeyManagerFactorySpi;
+
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>KeyManagerFactory</code> class constructors and methods.
+ *
+ */
+public class KeyManagerFactory1Test extends TestCase {
+
+ private static final String srvKeyManagerFactory = "KeyManagerFactory";
+
+ private static String defaultAlgorithm = null;
+
+ private static String defaultProviderName = null;
+
+ private static Provider defaultProvider = null;
+
+ private static boolean DEFSupported = false;
+
+ private static final String NotSupportedMsg = "There is no suitable provider for KeyManagerFactory";
+
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+
+ private static String[] validValues = new String[3];
+ static {
+ defaultAlgorithm = Security
+ .getProperty("ssl.KeyManagerFactory.algorithm");
+ if (defaultAlgorithm != null) {
+ defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm,
+ srvKeyManagerFactory);
+ DEFSupported = (defaultProvider != null);
+ defaultProviderName = (DEFSupported ? defaultProvider.getName()
+ : null);
+ validValues[0] = defaultAlgorithm;
+ validValues[1] = defaultAlgorithm.toUpperCase();
+ validValues[2] = defaultAlgorithm.toLowerCase();
+ }
+ }
+
+ protected KeyManagerFactory[] createKMFac() {
+ if (!DEFSupported) {
+ fail(defaultAlgorithm + " algorithm is not supported");
+ return null;
+ }
+ KeyManagerFactory[] kMF = new KeyManagerFactory[3];
+ try {
+ kMF[0] = KeyManagerFactory.getInstance(defaultAlgorithm);
+ kMF[1] = KeyManagerFactory.getInstance(defaultAlgorithm,
+ defaultProvider);
+ kMF[2] = KeyManagerFactory.getInstance(defaultAlgorithm,
+ defaultProviderName);
+ return kMF;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * avax.net.ssl.KeyManagerFactory#getAlgorithm()
+ */
+ public void test_getAlgorithm()
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ if (!DEFSupported) fail(NotSupportedMsg);
+ assertEquals("Incorrect algorithm",
+ defaultAlgorithm,
+ KeyManagerFactory
+ .getInstance(defaultAlgorithm).getAlgorithm());
+ assertEquals("Incorrect algorithm",
+ defaultAlgorithm,
+ KeyManagerFactory
+ .getInstance(defaultAlgorithm, defaultProviderName)
+ .getAlgorithm());
+ assertEquals("Incorrect algorithm",
+ defaultAlgorithm,
+ KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
+ .getAlgorithm());
+ }
+
+ /**
+ * Test for <code>getDefaultAlgorithm()</code> method
+ * Assertion: returns value which is specifoed in security property
+ */
+ public void test_getDefaultAlgorithm() {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ String def = KeyManagerFactory.getDefaultAlgorithm();
+ if (defaultAlgorithm == null) {
+ assertNull("DefaultAlgorithm must be null", def);
+ } else {
+ assertEquals("Invalid default algorithm", def, defaultAlgorithm);
+ }
+ String defA = "Proba.keymanagerfactory.defaul.type";
+ Security.setProperty("ssl.KeyManagerFactory.algorithm", defA);
+ assertEquals("Incorrect defaultAlgorithm",
+ KeyManagerFactory.getDefaultAlgorithm(), defA);
+ if (def == null) {
+ def = "";
+ }
+ Security.setProperty("ssl.KeyManagerFactory.algorithm", def);
+ assertEquals("Incorrect defaultAlgorithm",
+ KeyManagerFactory.getDefaultAlgorithm(), def);
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertions:
+ * returns security property "ssl.KeyManagerFactory.algorithm";
+ * returns instance of KeyManagerFactory
+ */
+ public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ KeyManagerFactory keyMF;
+ for (int i = 0; i < validValues.length; i++) {
+ keyMF = KeyManagerFactory.getInstance(validValues[i]);
+ assertNotNull("No KeyManagerFactory created", keyMF);
+ assertEquals("Invalid algorithm", keyMF.getAlgorithm(),
+ validValues[i]);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_String02() {
+ try {
+ KeyManagerFactory.getInstance(null);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
+ .concat(invalidValues[i]));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion: throws IllegalArgumentException when provider is null or empty
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
+ NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ String provider = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i], provider);
+ fail("Expected IllegalArgumentException was not thrown for null provider");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ KeyManagerFactory.getInstance(validValues[i], "");
+ fail("Expected IllegalArgumentException was not thrown for empty provider");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ try {
+ KeyManagerFactory.getInstance(null, defaultProviderName);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(invalidValues[i],
+ defaultProviderName);
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion: throws NoSuchProviderException when provider has
+ * invalid value
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String03()
+ throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ for (int i = 0; i < validValues.length; i++) {
+ for (int j = 1; j < invalidValues.length; j++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i],
+ invalidValues[j]);
+ fail("NuSuchProviderException must be thrown (algorithm: "
+ + validValues[i] + " provider: " + invalidValues[j]
+ + ")");
+ } catch (NoSuchProviderException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method Assertion: returns instance of KeyManagerFactory
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String04()
+ throws NoSuchProviderException,
+ NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ KeyManagerFactory kMF;
+ for (int i = 0; i < validValues.length; i++) {
+ kMF = KeyManagerFactory.getInstance(validValues[i],
+ defaultProviderName);
+ assertNotNull("No KeyManagerFactory created", kMF);
+ assertEquals("Incorrect algorithm", kMF.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", kMF.getProvider().getName(),
+ defaultProviderName);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion: throws IllegalArgumentException when provider is null
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider01()
+ throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ Provider provider = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i], provider);
+ fail("Expected IllegalArgumentException was not thrown when provider is null");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ try {
+ KeyManagerFactory.getInstance(null, defaultProvider);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory
+ .getInstance(invalidValues[i], defaultProvider);
+ fail("Expected NuSuchAlgorithmException was not thrown");
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion: returns instance of KeyManagerFactory
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider03()
+ throws NoSuchAlgorithmException,
+ IllegalArgumentException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ KeyManagerFactory kMF;
+ for (int i = 0; i < validValues.length; i++) {
+ kMF = KeyManagerFactory
+ .getInstance(validValues[i], defaultProvider);
+ assertNotNull("No KeyManagerFactory created", kMF);
+ assertEquals(kMF.getAlgorithm(), validValues[i]);
+ assertEquals(kMF.getProvider(), defaultProvider);
+ }
+ }
+
+ /**
+ * Test for <code>KeyManagerFactory</code> constructor
+ * Assertion: returns KeyManagerFactory object
+ */
+ public void test_Constructor() throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi();
+ KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider,
+ defaultAlgorithm);
+ assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
+ defaultAlgorithm);
+ assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider);
+ try {
+ keyMF.init(null, new char[1]);
+ fail("UnrecoverableKeyException must be thrown");
+ } catch (UnrecoverableKeyException e) {
+ } catch (Exception e) {
+ fail("Unexpected: "+e.toString()+" was thrown");
+ }
+ keyMF = new myKeyManagerFactory(null, null, null);
+ assertNull("Aalgorithm must be null", keyMF.getAlgorithm());
+ assertNull("Provider must be null", keyMF.getProvider());
+ try {
+ keyMF.getKeyManagers();
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * avax.net.ssl.KeyManagerFactory#getKeyManagers()
+ * @throws NoSuchAlgorithmException
+ * @throws KeyStoreException
+ * @throws IOException
+ * @throws CertificateException
+ * @throws UnrecoverableKeyException
+ */
+ public void test_getKeyManagers()
+ throws Exception {
+ if (!DEFSupported) fail(NotSupportedMsg);
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
+ char[] pass = "password".toCharArray();
+ kmf.init(null, pass);
+ assertNotNull("Key manager array is null", kmf.getKeyManagers());
+ assertEquals("Incorrect size of array",
+ 1, kmf.getKeyManagers().length);
+ }
+
+ /**
+ * avax.net.ssl.KeyManagerFactory#getProvider()
+ */
+ public void test_getProvider()
+ throws Exception {
+ if (!DEFSupported) fail(NotSupportedMsg);
+ assertEquals("Incorrect provider",
+ defaultProvider,
+ KeyManagerFactory
+ .getInstance(defaultAlgorithm).getProvider());
+ assertEquals("Incorrect provider",
+ defaultProvider,
+ KeyManagerFactory
+ .getInstance(defaultAlgorithm, defaultProviderName)
+ .getProvider());
+ assertEquals("Incorrect provider",
+ defaultProvider,
+ KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
+ .getProvider());
+ }
+
+ /**
+ * Test for <code>init(KeyStore keyStore, char[] password)</code> and
+ * <code>getKeyManagers()</code>
+ * Assertion: returns not empty KeyManager array
+ */
+ public void test_initLjava_security_KeyStore$C()
+ throws NoSuchAlgorithmException,
+ KeyStoreException, UnrecoverableKeyException {
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ KeyManagerFactory[] keyMF = createKMFac();
+ assertNotNull("KeyManagerFactory object were not created", keyMF);
+ KeyStore ksNull = null;
+ KeyManager[] km;
+ for (int i = 0; i < keyMF.length; i++) {
+ keyMF[i].init(ksNull, new char[10]);
+ km = keyMF[i].getKeyManagers();
+ assertNotNull("Result should not be null", km);
+ assertTrue("Length of result KeyManager array should not be 0",
+ (km.length > 0));
+ }
+ KeyStore ks;
+ try {
+ ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ } catch (KeyStoreException e) {
+ fail(e.toString() + "default KeyStore type is not supported");
+ return;
+ } catch (Exception e) {
+ fail("Unexpected: " + e.toString());
+ return;
+ }
+ for (int i = 0; i < keyMF.length; i++) {
+ try {
+ keyMF[i].init(ks, new char[10]);
+ } catch (KeyStoreException e) {
+ }
+ km = keyMF[i].getKeyManagers();
+ assertNotNull("Result has not be null", km);
+ assertTrue("Length of result KeyManager array should not be 0",
+ (km.length > 0));
+ }
+
+ }
+
+ /**
+ * Test for <code>init(ManagerFactoryParameters params)</code>
+ * Assertion:
+ * throws InvalidAlgorithmParameterException when params is null
+ */
+ public void test_initLjavax_net_ssl_ManagerFactoryParameters()
+ throws NoSuchAlgorithmException {
+
+ if (!DEFSupported) {
+ fail(NotSupportedMsg);
+ return;
+ }
+ ManagerFactoryParameters par = null;
+ KeyManagerFactory[] keyMF = createKMFac();
+ assertNotNull("KeyManagerFactory object were not created", keyMF);
+ for (int i = 0; i < keyMF.length; i++) {
+ try {
+ keyMF[i].init(par);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ }
+
+ KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
+ KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
+ assertNotNull("Null object KeyStore.Builder", bld);
+
+ try {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
+ KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
+ assertNotNull(ksp.getParameters());
+ kmf.init(ksp);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ }
+
+}
+
+/**
+ * Additional class for KeyManagerFactory constructor verification
+ */
+class myKeyManagerFactory extends KeyManagerFactory {
+ public myKeyManagerFactory(KeyManagerFactorySpi spi, Provider prov,
+ String alg) {
+ super(spi, prov, alg);
+ }
+}
+
+class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
+ ProtectionParameterImpl(){}
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory2Test.java
new file mode 100644
index 0000000..3d44396
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactory2Test.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Security;
+import java.security.UnrecoverableKeyException;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.ManagerFactoryParameters;
+
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
+import junit.framework.TestCase;
+
+/**
+ * Tests for KeyManagerFactory class constructors and methods
+ *
+ */
+public class KeyManagerFactory2Test extends TestCase {
+ private static final String srvKeyManagerFactory = "KeyManagerFactory";
+
+ private static final String defaultAlg = "KeyMF";
+
+ private static final String KeyManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi";
+
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+
+ private static final String[] validValues;
+
+ static {
+ validValues = new String[4];
+ validValues[0] = defaultAlg;
+ validValues[1] = defaultAlg.toLowerCase();
+ validValues[2] = "Keymf";
+ validValues[3] = "kEYMF";
+ }
+
+ Provider mProv;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ mProv = (new SpiEngUtils()).new MyProvider("MyKMFProvider",
+ "Provider for testing", srvKeyManagerFactory.concat(".")
+ .concat(defaultAlg), KeyManagerFactoryProviderClass);
+ Security.insertProviderAt(mProv, 2);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ Security.removeProvider(mProv.getName());
+ }
+
+ private void checkResult(KeyManagerFactory keyMF)
+ throws Exception {
+ KeyStore kStore = null;
+ ManagerFactoryParameters mfp = null;
+
+ char[] pass = { 'a', 'b', 'c' };
+
+ try {
+ keyMF.init(kStore, null);
+ fail("KeyStoreException must be thrown");
+ } catch (KeyStoreException e) {
+ }
+ try {
+ keyMF.init(kStore, pass);
+ fail("UnrecoverableKeyException must be thrown");
+ } catch (UnrecoverableKeyException e) {
+ }
+ try {
+ keyMF.init(mfp);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ assertNull("getKeyManagers() should return null object", keyMF
+ .getKeyManagers());
+
+ try {
+ kStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ kStore.load(null, null);
+ } catch (KeyStoreException e) {
+ fail("default keystore is not supported");
+ return;
+ }
+ keyMF.init(kStore, pass);
+
+ mfp = new MyKeyManagerFactorySpi.Parameters(kStore, null);
+ try {
+ keyMF.init(mfp);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ mfp = new MyKeyManagerFactorySpi.Parameters(kStore, pass);
+ keyMF.init(mfp);
+ }
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * returns KeyManagerFactory object
+ */
+ public void test_getInstanceLjava_lang_String() throws Exception {
+ try {
+ KeyManagerFactory.getInstance(null);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ KeyManagerFactory keyMF;
+ for (int i = 0; i < validValues.length; i++) {
+ keyMF = KeyManagerFactory.getInstance(validValues[i]);
+ assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
+ checkResult(keyMF);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * throws IllegalArgumentException when provider is null or empty;
+ * throws NoSuchProviderException when provider is available;
+ * returns KeyManagerFactory object
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String()
+ throws Exception
+ {
+ try {
+ KeyManagerFactory.getInstance(null, mProv.getName());
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory
+ .getInstance(invalidValues[i], mProv.getName());
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ String prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ KeyManagerFactory.getInstance(validValues[i], "");
+ fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ for (int i = 0; i < validValues.length; i++) {
+ for (int j = 1; j < invalidValues.length; j++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i],
+ invalidValues[j]);
+ fail("NoSuchProviderException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(" provider: ")
+ .concat(invalidValues[j]).concat(")"));
+ } catch (NoSuchProviderException e) {
+ }
+ }
+ }
+ KeyManagerFactory keyMF;
+ for (int i = 0; i < validValues.length; i++) {
+ keyMF = KeyManagerFactory.getInstance(validValues[i], mProv
+ .getName());
+ assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", keyMF.getProvider().getName(),
+ mProv.getName());
+ checkResult(keyMF);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * throws IllegalArgumentException when provider is null;
+ * returns KeyManagerFactory object
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider()
+ throws Exception
+ {
+ try {
+ KeyManagerFactory.getInstance(null, mProv);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(invalidValues[i], mProv);
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ Provider prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ KeyManagerFactory.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ KeyManagerFactory keyMF;
+ for (int i = 0; i < validValues.length; i++) {
+ keyMF = KeyManagerFactory.getInstance(validValues[i], mProv);
+ assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
+ checkResult(keyMF);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactorySpiTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactorySpiTest.java
new file mode 100644
index 0000000..fd44fda
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyManagerFactorySpiTest.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactorySpi;
+import javax.net.ssl.ManagerFactoryParameters;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.xnet.tests.support.KeyManagerFactorySpiImpl;
+
+public class KeyManagerFactorySpiTest extends TestCase {
+
+ /**
+ * javax.net.ssl.KeyManagerFactorySpi#KeyManagerFactorySpi()
+ */
+ public void test_Constructor() {
+ try {
+ KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
+ assertTrue(kmf instanceof KeyManagerFactorySpi);
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.KeyManagerFactorySpi#KengineInit(KeyStore ks, char[] password)
+ */
+ public void test_engineInit_01() {
+ KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
+ KeyStore ks;
+ char[] psw = "password".toCharArray();
+
+ try {
+ kmf.engineInit(null, null);
+ fail("NoSuchAlgorithmException wasn't thrown");
+ } catch (NoSuchAlgorithmException kse) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of NoSuchAlgorithmException");
+ }
+
+ try {
+ kmf.engineInit(null, psw);
+ fail("KeyStoreException wasn't thrown");
+ } catch (KeyStoreException uke) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of KeyStoreException");
+ }
+
+ try {
+ ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ kmf.engineInit(ks, null);
+ fail("UnrecoverableKeyException wasn't thrown");
+ } catch (UnrecoverableKeyException uke) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of UnrecoverableKeyException");
+ }
+
+ try {
+ KeyStore kst = KeyStore.getInstance(KeyStore.getDefaultType());
+ kst.load(null, null);
+ kmf.engineInit(kst, psw);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+
+ /**
+ * javax.net.ssl.KeyManagerFactorySpi#KengineInit(ManagerFactoryParameters spec)
+ */
+ public void test_engineInit_02() {
+ KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
+
+ try {
+ kmf.engineInit(null);
+ fail("InvalidAlgorithmParameterException wasn't thrown");
+ } catch (InvalidAlgorithmParameterException iape) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of InvalidAlgorithmParameterException");
+ }
+
+ try {
+ char[] psw = "password".toCharArray();
+ Parameters pr = new Parameters(psw);
+ kmf.engineInit(pr);
+ } catch (Exception e) {
+ fail(e + " unexpected exception was thrown");
+ }
+ }
+
+ /**
+ * javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers()
+ */
+ public void test_engineGetKeyManagers() {
+ KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
+
+ try {
+ KeyManager[] km = kmf.engineGetKeyManagers();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException ise) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of IllegalStateException");
+ }
+
+ try {
+ char[] psw = "password".toCharArray();
+ Parameters pr = new Parameters(psw);
+ kmf.engineInit(pr);
+ KeyManager[] km = kmf.engineGetKeyManagers();
+ assertNull("Object is not NULL", km);
+ } catch (Exception e) {
+ fail(e + " unexpected exception was thrown");
+ }
+ }
+
+ public class Parameters implements ManagerFactoryParameters {
+ private char[] passWD;
+
+ public Parameters (char[] pass) {
+ this.passWD = pass;
+ }
+ public char[] getPassword() {
+ return passWD;
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyStoreBuilderParametersTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyStoreBuilderParametersTest.java
new file mode 100644
index 0000000..a2fe49c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/KeyStoreBuilderParametersTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.KeyManagerFactorySpi;
+import javax.net.ssl.KeyStoreBuilderParameters;
+import java.security.KeyStore;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+public class KeyStoreBuilderParametersTest extends TestCase {
+
+ /**
+ * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(KeyStore.Builder builder)
+ */
+ public void test_Constructor01() {
+ // Null parameter
+ try {
+ new KeyStoreBuilderParameters((KeyStore.Builder) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // Not null parameter
+ KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
+ KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
+ assertNotNull("Null object KeyStore.Builder", bld);
+ KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
+ assertNotNull(ksp.getParameters());
+ }
+
+ /**
+ * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(List parameters)
+ */
+ public void test_Constructor02() {
+
+ // Null parameter
+ try {
+ KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters((List) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // Empty parameter
+ List lsEmpty = new ArrayList<String>();
+ try {
+ KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(lsEmpty);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ // Not null parameter
+ List lsFiled = new ArrayList<String>();
+ lsFiled.add("Parameter1");
+ lsFiled.add("Parameter2");
+ new KeyStoreBuilderParameters(lsFiled);
+ }
+
+ /**
+ * javax.net.ssl.KeyStoreBuilderParameters#getParameters()
+ */
+ public void test_getParameters() {
+ String[] param = {"Parameter1", "Parameter2", "Parameter3"};
+ List ls = new ArrayList<String>();
+ for (int i = 0; i < param.length; i++) {
+ ls.add(param[i]);
+ }
+ KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(ls);
+ List res_list = ksp.getParameters();
+ try {
+ res_list.add("test");
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ Object[] res = res_list.toArray();
+ assertEquals(res.length, param.length);
+ for (int i = 0; i < res.length; i++) {
+ assertEquals(param[i], res[i]);
+ }
+ }
+
+ private static class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
+ private ProtectionParameterImpl() {}
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext1Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext1Test.java
new file mode 100644
index 0000000..ee51cc0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext1Test.java
@@ -0,0 +1,599 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.io.FileNotFoundException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLContextSpi;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.xnet.tests.support.MySSLContextSpi;
+
+/**
+ * Tests for <code>SSLContext</code> class constructors and methods.
+ *
+ */
+public class SSLContext1Test extends TestCase {
+
+ private static String srvSSLContext = "SSLContext";
+ public static String defaultProtocol = "TLS";
+ private static final String NotSupportMsg = "Default protocol is not supported";
+ private static String defaultProviderName = null;
+ private static Provider defaultProvider = null;
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+ private static boolean DEFSupported = false;
+ private static String[] validValues = new String[3];
+ static {
+ defaultProvider = SpiEngUtils.isSupport(defaultProtocol, srvSSLContext);
+ DEFSupported = (defaultProvider != null);
+ if (DEFSupported) {
+ defaultProviderName = (DEFSupported ? defaultProvider.getName()
+ : null);
+ validValues[0] = defaultProtocol;
+ validValues[1] = defaultProtocol.toUpperCase();
+ validValues[2] = defaultProtocol.toLowerCase();
+ } else {
+ defaultProtocol = null;
+ }
+ }
+
+ protected SSLContext[] createSSLCon() {
+ if (!DEFSupported) {
+ fail(defaultProtocol + " protocol is not supported");
+ return null;
+ }
+ SSLContext[] sslC = new SSLContext[3];
+ try {
+ sslC[0] = SSLContext.getInstance(defaultProtocol);
+ sslC[1] = SSLContext.getInstance(defaultProtocol, defaultProvider);
+ sslC[2] = SSLContext.getInstance(defaultProtocol,
+ defaultProviderName);
+ return sslC;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Test for <code>SSLContext</code> constructor Assertion: returns
+ * SSLContext object
+ */
+ public void test_ConstructorLjavax_net_ssl_SSLContextSpiLjava_security_ProviderLjava_lang_String()
+ throws NoSuchAlgorithmException,
+ KeyManagementException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ assertEquals("Incorrect protocol", defaultProtocol,
+ sslContext.getProtocol());
+ assertEquals("Incorrect provider", defaultProvider,
+ sslContext.getProvider());
+ TrustManager[] tm = null;
+ KeyManager[] km = null;
+ sslContext.init(km, tm, new SecureRandom());
+ assertNotNull("No SSLEngine created",
+ sslContext.createSSLEngine());
+ assertNotNull("No SSLEngine created",
+ sslContext.createSSLEngine("host", 8888));
+ try {
+ sslContext.init(km, tm, null);
+ fail("KeyManagementException should be thrown for null "
+ + "SecureRandom");
+ } catch (KeyManagementException e) {
+ }
+
+ sslContext = new MySslContext(null, null, null);
+ assertNull("Incorrect protocol", sslContext.getProtocol());
+ assertNull("Incorrect provider", sslContext.getProvider());
+ try {
+ sslContext.createSSLEngine();
+ fail("NullPointerException should be thrown");
+ } catch (NullPointerException e) {
+ }
+ try {
+ sslContext.getSocketFactory();
+ fail("NullPointerException should be thrown");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLContext#createSSLEngine()
+ */
+ public void test_createSSLEngine() throws KeyManagementException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ sslContext.init(null, null, new SecureRandom());
+ SSLEngine sslEngine = sslContext.createSSLEngine();
+ assertNotNull("SSL engine is null", sslEngine);
+ }
+
+ /**
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLContext#createSSLEngine(java.lang.String, int)
+ */
+ public void test_createSSLEngineLjava_lang_StringI()
+ throws KeyManagementException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ sslContext.init(null, null, new SecureRandom());
+ SSLEngine sslEngine = sslContext.createSSLEngine("www.fortify.net", 80);
+ assertNotNull("SSL engine is null", sslEngine);
+ }
+
+ /**
+ * Test for <code>getClientSessionContext()</code>
+ * <code>getServiceSessionContext()</code>
+ * methods Assertion: returns correspondent object
+ * @throws KeyManagementException
+ */
+ public void test_getClientSessionContext() throws NoSuchAlgorithmException, KeyManagementException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContext[] sslC = createSSLCon();
+ assertNotNull("SSLContext objects were not created", sslC);
+ for (int i = 0; i < sslC.length; i++) {
+ sslC[i].init(null, null, null);
+ assertNotNull("Client session is incorrectly instantiated: " + i,
+ sslC[i].getClientSessionContext());
+ assertNotNull("Server session is incorrectly instantiated: " + i,
+ sslC[i].getServerSessionContext());
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol)</code> method Assertion:
+ * returns SSLContext object
+ */
+ public void test_getInstanceLjava_lang_String01()
+ throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContext sslContext;
+ for (int i = 0; i < validValues.length; i++) {
+ sslContext = SSLContext.getInstance(validValues[i]);
+ assertNotNull("No SSLContext created", sslContext);
+ assertEquals("Invalid protocol", validValues[i],
+ sslContext.getProtocol());
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol)</code> method Assertion:
+ * throws NullPointerException when protocol is null; throws
+ * NoSuchAlgorithmException when protocol is not correct;
+ */
+ public void test_getInstanceLjava_lang_String02() {
+ try {
+ SSLContext.getInstance(null);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException was not thrown as expected for provider: "
+ .concat(invalidValues[i]));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, String provider)</code>
+ * method Assertion: throws IllegalArgumentException when provider is null
+ * or empty
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
+ NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ String provider = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ SSLContext.getInstance(defaultProtocol, provider);
+ fail("IllegalArgumentException must be thrown when provider is null");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ SSLContext.getInstance(defaultProtocol, "");
+ fail("IllegalArgumentException must be thrown when provider is empty");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, String provider)</code>
+ * method Assertion: throws NullPointerException when protocol is null;
+ * throws NoSuchAlgorithmException when protocol is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ try {
+ SSLContext.getInstance(null, defaultProviderName);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i], defaultProviderName);
+ fail("NoSuchAlgorithmException was not thrown as expected (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, String provider)</code>
+ * method Assertion: throws NoSuchProviderException when provider has
+ * invalid value
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ for (int i = 1; i < invalidValues.length; i++) {
+ for (int j = 0; j < validValues.length; j++) {
+ try {
+ SSLContext.getInstance(validValues[j], invalidValues[i]);
+ fail("NuSuchProviderException must be thrown (protocol: "
+ .concat(validValues[j]).concat(" provider: ")
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchProviderException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, String provider)</code>
+ * method Assertion: returns instance of SSLContext
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws NoSuchAlgorithmException,
+ NoSuchProviderException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContext sslContext;
+ for (int i = 0; i < validValues.length; i++) {
+ sslContext = SSLContext.getInstance(validValues[i],
+ defaultProviderName);
+ assertNotNull("Not SSLContext created", sslContext);
+ assertEquals("Invalid protocol",
+ validValues[i], sslContext.getProtocol());
+ assertEquals("Invalid provider",
+ defaultProvider, sslContext.getProvider());
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, Provider provider)</code>
+ * method Assertion: throws IllegalArgumentException when provider is null
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ Provider provider = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ SSLContext.getInstance(validValues[i], provider);
+ fail("IllegalArgumentException must be thrown when provider is null");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, Provider provider)</code>
+ * method Assertion: throws NullPointerException when protocol is null;
+ * throws NoSuchAlgorithmException when protocol is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ try {
+ SSLContext.getInstance(null, defaultProvider);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i], defaultProvider);
+ fail("Expected NoSuchAlgorithmException was not thrown as expected");
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, Provider provider)</code>
+ * method Assertion: returns instance of SSLContext
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws NoSuchAlgorithmException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContext sslContext;
+ for (int i = 0; i < validValues.length; i++) {
+ sslContext = SSLContext
+ .getInstance(validValues[i], defaultProvider);
+ assertNotNull("Not SSLContext created", sslContext);
+ assertEquals("Invalid protocol", validValues[i], sslContext.getProtocol());
+ assertEquals("Invalid provider", defaultProvider, sslContext.getProvider());
+ }
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ * javax.net.ssl.SSLContext#getProtocol()
+ */
+ public void test_getProtocol()
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ assertEquals("Incorrect protocol",
+ defaultProtocol, sslContext.getProtocol());
+ sslContext = new MySslContext(spi, defaultProvider,
+ null);
+ assertNull("Incorrect protocol", sslContext.getProtocol());
+ sslContext = SSLContext.getInstance(defaultProtocol);
+ assertEquals("Incorrect protocol",
+ defaultProtocol, sslContext.getProtocol());
+ sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
+ assertEquals("Incorrect protocol",
+ defaultProtocol, sslContext.getProtocol());
+ sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
+ assertEquals("Incorrect protocol",
+ defaultProtocol, sslContext.getProtocol());
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ * javax.net.ssl.SSLContext#getProvider()
+ */
+ public void test_getProvider()
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ assertEquals("Incorrect provider",
+ defaultProvider, sslContext.getProvider());
+ sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
+ assertEquals("Incorrect provider",
+ defaultProvider, sslContext.getProvider());
+ sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
+ assertEquals("Incorrect provider",
+ defaultProvider, sslContext.getProvider());
+ }
+
+ /**
+ * javax.net.ssl.SSLContext#getServletSessionContext()
+ */
+ public void test_getServerSessionContext() throws NoSuchAlgorithmException,
+ KeyManagementException, KeyStoreException,
+ UnrecoverableKeyException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContext[] sslC = createSSLCon();
+ assertNotNull("SSLContext objects were not created", sslC);
+ String tAlg = TrustManagerFactory.getDefaultAlgorithm();
+ String kAlg = KeyManagerFactory.getDefaultAlgorithm();
+ if (tAlg == null)
+ fail("TrustManagerFactory default algorithm is not defined");
+ if (kAlg == null)
+ fail("KeyManagerFactory default algorithm is not defined");
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
+ kmf.init(null, new char[11]);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ tmf.init(ks);
+ TrustManager[] tms = tmf.getTrustManagers();
+ for (SSLContext sslCi : sslC) {
+ sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
+ assertNotNull("Server context is incorrectly instantiated", sslCi
+ .getServerSessionContext());
+ }
+ }
+
+ /**
+ * Test for <code>getServerSocketFactory()</code>
+ * <code>getSocketFactory()</code>
+ * <code>init(KeyManager[] km, TrustManager[] tm, SecureRandom random)</code>
+ * methods Assertion: returns correspondent object
+ *
+ */
+ public void test_getServerSocketFactory() throws NoSuchAlgorithmException,
+ KeyManagementException, KeyStoreException,
+ UnrecoverableKeyException {
+ if (!DEFSupported) {
+ fail(NotSupportMsg);
+ return;
+ }
+ SSLContext[] sslC = createSSLCon();
+ assertNotNull("SSLContext objects were not created", sslC);
+ String tAlg = TrustManagerFactory.getDefaultAlgorithm();
+ String kAlg = KeyManagerFactory.getDefaultAlgorithm();
+ if (tAlg == null) {
+ fail("TrustManagerFactory default algorithm is not defined");
+ return;
+ }
+ if (kAlg == null) {
+ fail("KeyManagerFactory default algorithm is not defined");
+ return;
+ }
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ try {
+ ks.load(null, null);
+ } catch (Exception e) {
+ fail(e + " was thrown for method load(null, null)");
+ }
+ kmf.init(ks, new char[10]);
+ KeyManager[] kms = kmf.getKeyManagers();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
+ tmf.init(ks);
+ TrustManager[] tms = tmf.getTrustManagers();
+ for (int i = 0; i < sslC.length; i++) {
+ sslC[i].init(kms, tms, new SecureRandom());
+ assertNotNull("No SSLServerSocketFactory available",
+ sslC[i].getServerSocketFactory());
+ assertNotNull("No SSLSocketFactory available",
+ sslC[i].getSocketFactory());
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLContext#getSocketFactory()
+ */
+ public void test_getSocketFactory() throws NoSuchAlgorithmException,
+ KeyManagementException, KeyStoreException,
+ UnrecoverableKeyException {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContext[] sslC = createSSLCon();
+ assertNotNull("SSLContext objects were not created", sslC);
+ String tAlg = TrustManagerFactory.getDefaultAlgorithm();
+ String kAlg = KeyManagerFactory.getDefaultAlgorithm();
+ if (tAlg == null)
+ fail("TrustManagerFactory default algorithm is not defined");
+ if (kAlg == null)
+ fail("KeyManagerFactory default algorithm is not defined");
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
+ kmf.init(null, new char[11]);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ tmf.init(ks);
+ TrustManager[] tms = tmf.getTrustManagers();
+ for (SSLContext sslCi : sslC) {
+ sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
+ assertNotNull("Socket factory is incorrectly instantiated",
+ sslCi.getSocketFactory());
+ }
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyStoreException
+ * @throws FileNotFoundException
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLContext#
+ * init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[],
+ * java.security.SecureRandom)
+ */
+ public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom()
+ throws Exception {
+ if (!DEFSupported) fail(NotSupportMsg);
+ SSLContextSpi spi = new MySSLContextSpi();
+ SSLContext sslContext = new MySslContext(spi, defaultProvider,
+ defaultProtocol);
+ try {
+ sslContext.createSSLEngine();
+ fail("Expected RuntimeException was not thrown");
+ } catch (RuntimeException rte) {
+ // expected
+ }
+
+ try {
+ sslContext.init(null, null, null);
+ fail("KeyManagementException wasn't thrown");
+ } catch (KeyManagementException kme) {
+ //expected
+ }
+
+ try {
+ String tAlg = TrustManagerFactory.getDefaultAlgorithm();
+ String kAlg = KeyManagerFactory.getDefaultAlgorithm();
+ if (tAlg == null)
+ fail("TrustManagerFactory default algorithm is not defined");
+ if (kAlg == null)
+ fail("KeyManagerFactory default algorithm is not defined");
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
+ kmf.init(null, new char[11]);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ tmf.init(ks);
+ TrustManager[] tms = tmf.getTrustManagers();
+ sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
+ } catch (Exception e) {
+ System.out.println("EE = " + e);
+ }
+ }
+}
+
+/**
+ * Addifional class to verify SSLContext constructor
+ */
+
+class MySslContext extends SSLContext {
+ public MySslContext(SSLContextSpi spi, Provider prov, String alg) {
+ super(spi, prov, alg);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext2Test.java
new file mode 100644
index 0000000..0881615
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContext2Test.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManager;
+import junit.framework.TestCase;
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.xnet.tests.support.MySSLContextSpi;
+
+/**
+ * Tests for SSLContext class constructors and methods
+ *
+ */
+public class SSLContext2Test extends TestCase {
+
+ private static String srvSSLContext = "SSLContext";
+
+ private static final String defaultProtocol = "S+S+L";
+
+ public static final String SSLContextProviderClass = MySSLContextSpi.class.getName();
+
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+
+ private static final String[] validValues;
+ static {
+ validValues = new String[4];
+ validValues[0] = defaultProtocol;
+ validValues[1] = defaultProtocol.toLowerCase();
+ validValues[2] = "s+S+L";
+ validValues[3] = "S+s+L";
+ }
+
+ Provider mProv;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ mProv = (new SpiEngUtils()).new MyProvider("MySSLContextProvider", "Provider for testing",
+ srvSSLContext.concat(".").concat(defaultProtocol),
+ SSLContextProviderClass);
+ Security.insertProviderAt(mProv, 1);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ Security.removeProvider(mProv.getName());
+ }
+
+ private void checkSSLContext(SSLContext sslC)
+ throws KeyManagementException {
+
+ try {
+ sslC.getSocketFactory();
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ try {
+ sslC.getServerSocketFactory();
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ try {
+ sslC.getServerSessionContext();
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ try {
+ sslC.getClientSessionContext();
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ try {
+ sslC.createSSLEngine();
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ try {
+ sslC.createSSLEngine("host",1);
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
+ }
+ TrustManager [] tm = new TManager[10];
+ KeyManager [] km = new KManager[5];
+ try {
+ sslC.init(km, tm, null);
+ fail("KeyManagementException must be thrown");
+ } catch (KeyManagementException e) {
+ }
+ sslC.init(km, tm, new SecureRandom());
+
+ SSLEngine sslE = sslC.createSSLEngine();
+ assertTrue("Not null result",sslE instanceof SSLEngine);
+ assertNull("Incorrect host", sslE.getPeerHost());
+ assertEquals("Incorrect port", 0, sslE.getPeerPort());
+ String host = "ZZZ";
+ int port = 8080;
+ sslE = sslC.createSSLEngine(host, port);
+ assertTrue("Not null result",sslE instanceof SSLEngine);
+ assertEquals("Incorrect host", sslE.getPeerHost(), host);
+ assertEquals("Incorrect port", sslE.getPeerPort(), port);
+ try {
+ assertNull("Not null result", sslC.getServerSessionContext());
+ } catch (NullPointerException e) {
+ }
+ try {
+ assertNull("Not null result", sslC.getClientSessionContext());
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol)</code> method
+ * Assertions:
+ * throws NullPointerException when protocol is null;
+ * throws NoSuchAlgorithmException when protocol is not correct;
+ * returns SSLContext object
+ */
+ public void test_getInstanceLjava_lang_String() throws NoSuchAlgorithmException,
+ KeyManagementException {
+ try {
+ SSLContext.getInstance(null);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown "
+ + "(protocol is null)");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException must be thrown (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ SSLContext sslC;
+ for (int i = 0; i < validValues.length; i++) {
+ sslC = SSLContext.getInstance(validValues[i]);
+ assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
+ assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
+ assertEquals("Incorrect provider", sslC.getProvider(), mProv);
+ checkSSLContext(sslC);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, String provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when protocol is null;
+ * throws NoSuchAlgorithmException when protocol is not correct;
+ * throws IllegalArgumentException when provider is null or empty;
+ * throws NoSuchProviderException when provider is available;
+ * returns SSLContext object
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String()
+ throws NoSuchAlgorithmException, NoSuchProviderException,
+ IllegalArgumentException, KeyManagementException {
+ try {
+ SSLContext.getInstance(null, mProv.getName());
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown "
+ + "(protocol is null)");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i], mProv.getName());
+ fail("NoSuchAlgorithmException must be thrown (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ String prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ SSLContext.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ SSLContext.getInstance(validValues[i], "");
+ fail("IllegalArgumentException must be thrown when provider is empty (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ for (int i = 0; i < validValues.length; i++) {
+ for (int j = 1; j < invalidValues.length; j++) {
+ try {
+ SSLContext.getInstance(validValues[i], invalidValues[j]);
+ fail("NoSuchProviderException must be thrown (protocol: "
+ .concat(invalidValues[i]).concat(" provider: ")
+ .concat(invalidValues[j]).concat(")"));
+ } catch (NoSuchProviderException e) {
+ }
+ }
+ }
+ SSLContext sslC;
+ for (int i = 0; i < validValues.length; i++) {
+ sslC = SSLContext.getInstance(validValues[i], mProv.getName());
+ assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
+ assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
+ assertEquals("Incorrect provider", sslC.getProvider().getName(), mProv.getName());
+ checkSSLContext(sslC);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String protocol, Provider provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when protocol is null;
+ * throws NoSuchAlgorithmException when protocol is not correct;
+ * throws IllegalArgumentException when provider is null;
+ * returns SSLContext object
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider()
+ throws NoSuchAlgorithmException,
+ IllegalArgumentException, KeyManagementException {
+ try {
+ SSLContext.getInstance(null, mProv);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown "
+ + "(protocol is null)");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ SSLContext.getInstance(invalidValues[i], mProv);
+ fail("NoSuchAlgorithmException must be thrown (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ Provider prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ SSLContext.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (protocol: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ SSLContext sslC;
+ for (int i = 0; i < validValues.length; i++) {
+ sslC = SSLContext.getInstance(validValues[i], mProv);
+ assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
+ assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
+ assertEquals("Incorrect provider", sslC.getProvider(), mProv);
+ checkSSLContext(sslC);
+ }
+ }
+
+ class TManager implements TrustManager {
+
+ }
+ class KManager implements KeyManager {
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContextSpiTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContextSpiTest.java
new file mode 100644
index 0000000..45a1c14
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLContextSpiTest.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContextSpi;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import java.security.KeyManagementException;
+
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.Security;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.xnet.tests.support.SSLContextSpiImpl;
+
+public class SSLContextSpiTest extends TestCase {
+
+ /**
+ * javax.net.ssl.SSLContextSpi#SSLContextSpi()
+ */
+ public void test_Constructor() {
+ try {
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+ assertTrue(ssl instanceof SSLContextSpi);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine()
+ * Verify exception when SSLContextSpi object wasn't initialiazed.
+ */
+ public void test_engineCreateSSLEngine_01() {
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+ try {
+ SSLEngine sleng = ssl.engineCreateSSLEngine();
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine(String host, int port)
+ * Verify exception when SSLContextSpi object wasn't initialiazed.
+ */
+ public void test_engineCreateSSLEngine_02() {
+ int[] invalid_port = {Integer.MIN_VALUE, -65535, -1, 65536, Integer.MAX_VALUE};
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+ try {
+ SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+
+ for (int i = 0; i < invalid_port.length; i++) {
+ try {
+ SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", invalid_port[i]);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+ }
+
+ /**
+ * SSLContextSpi#engineGetClientSessionContext()
+ * SSLContextSpi#engineGetServerSessionContext()
+ * SSLContextSpi#engineGetServerSocketFactory()
+ * SSLContextSpi#engineGetSocketFactory()
+ * Verify exception when SSLContextSpi object wasn't initialiazed.
+ */
+ public void test_commonTest_01() {
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+
+ try {
+ SSLSessionContext slsc = ssl.engineGetClientSessionContext();
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+
+ try {
+ SSLSessionContext slsc = ssl.engineGetServerSessionContext();
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+
+ try {
+ SSLServerSocketFactory sssf = ssl.engineGetServerSocketFactory();
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+
+ try {
+ SSLSocketFactory ssf = ssl.engineGetSocketFactory();
+ fail("RuntimeException wasn't thrown");
+ } catch (RuntimeException re) {
+ String str = re.getMessage();
+ if (!str.equals("Not initialiazed"))
+ fail("Incorrect exception message: " + str);
+ } catch (Exception e) {
+ fail("Incorrect exception " + e + " was thrown");
+ }
+ }
+
+ /**
+ * SSLContextSpi#engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
+ */
+ public void test_engineInit() {
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+ String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
+ try {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
+ char[] pass = "password".toCharArray();
+ kmf.init(null, pass);
+ KeyManager[] km = kmf.getKeyManagers();
+ defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ trustMF.init(ks);
+ TrustManager[] tm = trustMF.getTrustManagers();
+ SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
+ try {
+ ssl.engineInit(km, tm, sr);
+ } catch (KeyManagementException kme) {
+ fail(kme + " was throw for engineInit method");
+ }
+ try {
+ ssl.engineInit(km, tm, null);
+ fail("KeyManagementException wasn't thrown");
+ } catch (KeyManagementException kme) {
+ //expected
+ }
+ } catch (Exception ex) {
+ fail(ex + " unexpected exception");
+ }
+ }
+
+ /**
+ * SSLContextSpi#engineCreateSSLEngine()
+ * SSLContextSpi#engineCreateSSLEngine(String host, int port)
+ * SSLContextSpi#engineGetClientSessionContext()
+ * SSLContextSpi#engineGetServerSessionContext()
+ * SSLContextSpi#engineGetServerSocketFactory()
+ * SSLContextSpi#engineGetSocketFactory()
+ */
+ public void test_commonTest_02() {
+ SSLContextSpiImpl ssl = new SSLContextSpiImpl();
+ String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
+ try {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
+ char[] pass = "password".toCharArray();
+ kmf.init(null, pass);
+ KeyManager[] km = kmf.getKeyManagers();
+ defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ trustMF.init(ks);
+ TrustManager[] tm = trustMF.getTrustManagers();
+ SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
+ ssl.engineInit(km, tm, sr);
+ } catch (Exception ex) {
+ fail(ex + " unexpected exception");
+ }
+
+ try {
+ assertNotNull("Subtest_01: Object is NULL", ssl.engineCreateSSLEngine());
+ SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
+ assertNotNull("Subtest_02: Object is NULL", sleng);
+ assertEquals(sleng.getPeerPort(), 1080);
+ assertEquals(sleng.getPeerHost(), "localhost");
+ assertNull("Subtest_03: Object not NULL", ssl.engineGetClientSessionContext());
+ assertNull("Subtest_04: Object not NULL", ssl.engineGetServerSessionContext());
+ assertNull("Subtest_05: Object not NULL", ssl.engineGetServerSocketFactory());
+ assertNull("Subtest_06: Object not NULL", ssl.engineGetSocketFactory());
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
new file mode 100644
index 0000000..3b13673
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLEngineResult;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for SSLEngineResult.Status class
+ *
+ */
+public class SSLEngineResultHandshakeStatusTest extends TestCase {
+
+ /**
+ * Test for <code> SSLEngineResult.HandshakeStatus.values() </code>
+ */
+ public void test_SSLEngineResultHandshakeStatus_values() {
+ String[] str = {"NOT_HANDSHAKING", "FINISHED", "NEED_TASK", "NEED_WRAP", "NEED_UNWRAP"};
+ SSLEngineResult.HandshakeStatus[] enS = SSLEngineResult.HandshakeStatus.values();
+ if (enS.length == str.length) {
+ for (int i = 0; i < enS.length; i++) {
+ //System.out.println("enS[" + i + "] = " + enS[i]);
+ assertEquals("Incorrect Status", enS[i].toString(), str[i]);
+ }
+ } else {
+ fail("Incorrect number of enum constant was returned");
+ }
+ }
+
+ /**
+ * Test for <code> SSLEngineResult.HandshakeStatus.valueOf(String name) </code>
+ */
+ public void test_SSLEngineResultStatus_valueOf() {
+ String[] str = {"FINISHED", "NEED_TASK", "NEED_UNWRAP", "NEED_WRAP", "NOT_HANDSHAKING"};
+ String[] str_invalid = {"", "FINISHED1", "NEED_task", "NEED_UN",
+ "NEED_WRAP_WRAP", "not_HANDSHAKING", "Bad string for verification valueOf method"};
+ SSLEngineResult.HandshakeStatus enS;
+
+ //Correct parameter
+ for (int i = 0; i < str.length; i++) {
+ try {
+ enS = SSLEngineResult.HandshakeStatus.valueOf(str[i]);
+ assertEquals("Incorrect Status", enS.toString(), str[i]);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e + " was thrown for " + str[i]);
+ }
+ }
+
+ //Incorrect parameter
+ for (int i = 0; i < str_invalid.length; i++) {
+ try {
+ enS = SSLEngineResult.HandshakeStatus.valueOf(str_invalid[i]);
+ fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ //Null parameter
+ try {
+ enS = SSLEngineResult.HandshakeStatus.valueOf(null);
+ fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
+ } catch (NullPointerException npe) {
+ //expected
+ } catch (IllegalArgumentException iae) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultStatusTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultStatusTest.java
new file mode 100644
index 0000000..05c8f03
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultStatusTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLEngineResult;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for SSLEngineResult.Status class
+ *
+ */
+public class SSLEngineResultStatusTest extends TestCase {
+
+ /**
+ * Test for <code> SSLEngineResult.Status.values() </code>
+ */
+ public void test_SSLEngineResultStatus_values() {
+ boolean flag = false;
+ String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
+ SSLEngineResult.Status[] enS = SSLEngineResult.Status.values();
+ if (enS.length == str.length) {
+ for (int i = 0; i < enS.length; i++) {
+ flag = false;
+ for (int j = 0; j < str.length; j++) {
+ if (enS[i].toString() == str[j]) {
+ flag = true;
+ break;
+ }
+ }
+ }
+ assertTrue("Incorrect Status", flag);
+ } else {
+ fail("Incorrect number of enum constant was returned");
+ }
+ }
+
+ /**
+ * Test for <code> SSLEngineResult.Status.valueOf(String name) </code>
+ */
+ public void test_SSLEngineResultStatus_valueOf() {
+ String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
+ String[] str_invalid = {"", "OK1", "BUFFER_overflow", "BUFFER_UND",
+ "CLOSED_CLOSED", "Bad string for verification valueOf method"};
+ SSLEngineResult.Status enS;
+
+ //Correct parameter
+ for (int i = 0; i < str.length; i++) {
+ try {
+ enS = SSLEngineResult.Status.valueOf(str[i]);
+ assertEquals("Incorrect Status", enS.toString(), str[i]);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e + " was thrown for " + str[i]);
+ }
+ }
+
+ //Incorrect parameter
+ for (int i = 0; i < str_invalid.length; i++) {
+ try {
+ enS = SSLEngineResult.Status.valueOf(str_invalid[i]);
+ fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ //Null parameter
+ try {
+ enS = SSLEngineResult.Status.valueOf(null);
+ fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
+ } catch (NullPointerException npe) {
+ //expected
+ } catch (IllegalArgumentException iae) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultTest.java
new file mode 100644
index 0000000..7a2ac78
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineResultTest.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLEngineResult;
+import junit.framework.TestCase;
+
+
+/**
+ * Tests for SSLEngineResult class
+ *
+ */
+public class SSLEngineResultTest extends TestCase {
+
+ /**
+ * Test for <code>SSLEngineResult(SSLEngineResult.Status status,
+ * SSLEngineResult.HandshakeStatus handshakeStatus,
+ * int bytesConsumed,
+ * int bytesProduced) </code> constructor and
+ * <code>getHandshakeStatus()</code>
+ * <code>getStatus()</code>
+ * <code>bytesConsumed()</code>
+ * <code>bytesProduced()</code>
+ * <code>toString()</code>
+ * methods
+ * Assertions:
+ * constructor throws IllegalArgumentException when bytesConsumed
+ * or bytesProduced is negative or when status or handshakeStatus
+ * is null
+ *
+ */
+ public void test_ConstructorLjavax_net_ssl_SSLEngineResult_StatusLjavax_net_ssl_SSLEngineResult_HandshakeStatusII() {
+
+ int[] neg = { -1, -10, -1000, Integer.MIN_VALUE,
+ (Integer.MIN_VALUE + 1) };
+ try {
+ new SSLEngineResult(null, SSLEngineResult.HandshakeStatus.FINISHED,
+ 1, 1);
+ fail("IllegalArgumentException must be thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, null,
+ 1, 1);
+ fail("IllegalArgumentException must be thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ for (int i = 0; i < neg.length; i++) {
+ try {
+ new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
+ SSLEngineResult.HandshakeStatus.FINISHED, neg[i], 1);
+ fail("IllegalArgumentException must be thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ for (int i = 0; i < neg.length; i++) {
+ try {
+ new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
+ SSLEngineResult.HandshakeStatus.FINISHED, 1, neg[i]);
+ fail("IllegalArgumentException must be thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ try {
+ SSLEngineResult res = new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
+ SSLEngineResult.HandshakeStatus.FINISHED, 1, 2);
+ assertNotNull("Null object", res);
+ assertEquals(1, res.bytesConsumed());
+ assertEquals(2, res.bytesProduced());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * Test for <code>bytesConsumed()</code> method
+ */
+ public void test_bytesConsumed() {
+ int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
+ SSLEngineResult.Status [] enS =
+ SSLEngineResult.Status.values();
+ SSLEngineResult.HandshakeStatus [] enHS =
+ SSLEngineResult.HandshakeStatus.values();
+ for (int i = 0; i < enS.length; i++) {
+ for (int j = 0; j < enHS.length; j++) {
+ for (int n = 0; n < pos.length; n++) {
+ for (int l = 0; l < pos.length; l++) {
+ SSLEngineResult res = new SSLEngineResult(enS[i],
+ enHS[j], pos[n], pos[l]);
+ assertEquals("Incorrect bytesConsumed", pos[n],
+ res.bytesConsumed());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>bytesProduced()</code> method
+ */
+ public void test_bytesProduced() {
+ int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
+ SSLEngineResult.Status [] enS =
+ SSLEngineResult.Status.values();
+ SSLEngineResult.HandshakeStatus [] enHS =
+ SSLEngineResult.HandshakeStatus.values();
+ for (int i = 0; i < enS.length; i++) {
+ for (int j = 0; j < enHS.length; j++) {
+ for (int n = 0; n < pos.length; n++) {
+ for (int l = 0; l < pos.length; ++l) {
+ SSLEngineResult res = new SSLEngineResult(enS[i],
+ enHS[j], pos[n], pos[l]);
+ assertEquals("Incorrect bytesProduced", pos[l],
+ res.bytesProduced());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getHandshakeStatus()</code> method
+ */
+ public void test_getHandshakeStatus() {
+ int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
+ SSLEngineResult.Status [] enS =
+ SSLEngineResult.Status.values();
+ SSLEngineResult.HandshakeStatus [] enHS =
+ SSLEngineResult.HandshakeStatus.values();
+ for (int i = 0; i < enS.length; i++) {
+ for (int j = 0; j < enHS.length; j++) {
+ for (int n = 0; n < pos.length; n++) {
+ for (int l = 0; l < pos.length; ++l) {
+ SSLEngineResult res = new SSLEngineResult(enS[i],
+ enHS[j], pos[n], pos[l]);
+ assertEquals("Incorrect HandshakeStatus", enHS[j],
+ res.getHandshakeStatus());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getStatus()</code> method
+ */
+ public void test_getStatus() {
+ int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
+ SSLEngineResult.Status [] enS =
+ SSLEngineResult.Status.values();
+ SSLEngineResult.HandshakeStatus [] enHS =
+ SSLEngineResult.HandshakeStatus.values();
+ for (int i = 0; i < enS.length; i++) {
+ for (int j = 0; j < enHS.length; j++) {
+ for (int n = 0; n < pos.length; n++) {
+ for (int l = 0; l < pos.length; ++l) {
+ SSLEngineResult res = new SSLEngineResult(enS[i],
+ enHS[j], pos[n], pos[l]);
+ assertEquals("Incorrect Status", enS[i],
+ res.getStatus());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>toString()</code> method
+ */
+ public void test_toString() {
+ int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
+ SSLEngineResult.Status [] enS =
+ SSLEngineResult.Status.values();
+ SSLEngineResult.HandshakeStatus [] enHS =
+ SSLEngineResult.HandshakeStatus.values();
+ for (int i = 0; i < enS.length; i++) {
+ for (int j = 0; j < enHS.length; j++) {
+ for (int n = 0; n < pos.length; n++) {
+ for (int l = 0; l < pos.length; ++l) {
+ SSLEngineResult res = new SSLEngineResult(enS[i],
+ enHS[j], pos[n], pos[l]);
+ assertNotNull("Result of toSring() method is null",
+ res.toString());
+ }
+ }
+ }
+ }
+ }
+
+ private boolean findEl(Object[] arr, Object el) {
+ boolean ok = false;
+ for (int i = 0; i < arr.length; i++) {
+ if (arr[i].equals(el)) {
+ ok = true;
+ break;
+ }
+ }
+ return ok;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineTest.java
new file mode 100644
index 0000000..31f5881
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLEngineTest.java
@@ -0,0 +1,1210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.nio.channels.Pipe;
+import java.nio.channels.Pipe.SinkChannel;
+import java.nio.channels.Pipe.SourceChannel;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.Status;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
+
+/**
+ * Tests for SSLEngine class
+ *
+ */
+public class SSLEngineTest extends TestCase {
+ private static final int MAX_TLS_RECORD_SIZE = 32768;
+
+ private HandshakeHandler clientEngine;
+ private HandshakeHandler serverEngine;
+
+ @Override protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ /**
+ * Test for <code>SSLEngine()</code> constructor Assertion: creates
+ * SSLEngine object with null host and -1 port
+ */
+ public void test_Constructor() throws Exception {
+ SSLEngine e = getEngine();
+ assertNull(e.getPeerHost());
+ assertEquals(-1, e.getPeerPort());
+ String[] suites = e.getSupportedCipherSuites();
+ e.setEnabledCipherSuites(suites);
+ assertEquals(e.getEnabledCipherSuites().length, suites.length);
+ }
+
+ /**
+ * Test for <code>SSLEngine(String host, int port)</code> constructor
+ */
+ public void test_ConstructorLjava_lang_StringI01() throws Exception {
+ int port = 1010;
+ SSLEngine e = getEngine(null, port);
+ assertNull(e.getPeerHost());
+ assertEquals(e.getPeerPort(), port);
+ try {
+ e.beginHandshake();
+ fail("should throw IllegalStateException");
+ } catch (IllegalStateException expected) {
+ }
+
+ e = getEngine(null, port);
+ e.setUseClientMode(true);
+ e.beginHandshake();
+
+ e = getEngine(null, port);
+ e.setUseClientMode(false);
+ e.beginHandshake();
+ }
+
+ /**
+ * Test for <code>SSLEngine(String host, int port)</code> constructor
+ */
+ public void test_ConstructorLjava_lang_StringI02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ SSLEngine e = getEngine(host, port);
+ assertEquals(e.getPeerHost(), host);
+ assertEquals(e.getPeerPort(), port);
+ String[] suites = e.getSupportedCipherSuites();
+ e.setEnabledCipherSuites(suites);
+ assertEquals(e.getEnabledCipherSuites().length, suites.length);
+ e.setUseClientMode(true);
+ assertTrue(e.getUseClientMode());
+ }
+
+ /**
+ * Test for <code>getPeerHost()</code> method
+ */
+ public void test_getPeerHost() throws Exception {
+ SSLEngine e = getEngine();
+ assertNull(e.getPeerHost());
+ e = getEngine("www.fortify.net", 80);
+ assertEquals("Incorrect host name", "www.fortify.net", e.getPeerHost());
+ }
+
+ /**
+ * Test for <code>getPeerPort()</code> method
+ */
+ public void test_getPeerPort() throws Exception {
+ SSLEngine e = getEngine();
+ assertEquals("Incorrect default value of peer port",
+ -1 ,e.getPeerPort());
+ e = getEngine("www.fortify.net", 80);
+ assertEquals("Incorrect peer port", 80, e.getPeerPort());
+ }
+
+ public void test_getSupportedProtocols() throws Exception {
+ SSLEngine sse = getEngine();
+
+ String[] res = sse.getSupportedProtocols();
+ assertNotNull(res);
+ assertTrue(res.length > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setEnabledProtocols(String[] protocols)
+ * javax.net.ssl.SSLEngine#getEnabledProtocols()
+ */
+ public void test_EnabledProtocols() throws Exception {
+ SSLEngine sse = getEngine();
+ String[] pr = sse.getSupportedProtocols();
+
+ sse.setEnabledProtocols(pr);
+ String[] res = sse.getEnabledProtocols();
+ assertNotNull("Null array was returned", res);
+ assertEquals("Incorrect array length", res.length, pr.length);
+ assertTrue("Incorrect array was returned", Arrays.equals(res, pr));
+
+ try {
+ sse.setEnabledProtocols(null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#getSupportedCipherSuites()
+ */
+ public void test_getSupportedCipherSuites() throws Exception {
+ SSLEngine sse = getEngine();
+
+ String[] res = sse.getSupportedCipherSuites();
+ assertNotNull(res);
+ assertTrue(res.length > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[] suites)
+ * javax.net.ssl.SSLEngine#getEnabledCipherSuites()
+ */
+ public void test_EnabledCipherSuites() throws Exception {
+ SSLEngine sse = getEngine();
+ String[] st = sse.getSupportedCipherSuites();
+
+ sse.setEnabledCipherSuites(st);
+ String[] res = sse.getEnabledCipherSuites();
+ assertNotNull("Null array was returned", res);
+ assertEquals("Incorrect array length", res.length, st.length);
+ assertTrue("Incorrect array was returned", Arrays.equals(res, st));
+
+ try {
+ sse.setEnabledCipherSuites(null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean flag)
+ * javax.net.ssl.SSLEngine#getEnableSessionCreation()
+ */
+ public void test_EnableSessionCreation() throws Exception {
+ SSLEngine sse = getEngine();
+ try {
+ assertTrue(sse.getEnableSessionCreation());
+ sse.setEnableSessionCreation(false);
+ assertFalse(sse.getEnableSessionCreation());
+ sse.setEnableSessionCreation(true);
+ assertTrue(sse.getEnableSessionCreation());
+ } catch (Exception ex) {
+ fail("Unexpected exception " + ex);
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setNeedClientAuth(boolean need)
+ * javax.net.ssl.SSLEngine#getNeedClientAuth()
+ */
+ public void test_NeedClientAuth() throws Exception {
+ SSLEngine sse = getEngine();
+ try {
+ sse.setNeedClientAuth(false);
+ assertFalse(sse.getNeedClientAuth());
+ sse.setNeedClientAuth(true);
+ assertTrue(sse.getNeedClientAuth());
+ } catch (Exception ex) {
+ fail("Unexpected exception " + ex);
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setWantClientAuth(boolean want)
+ * javax.net.ssl.SSLEngine#getWantClientAuth()
+ */
+ public void test_WantClientAuth() throws Exception {
+ SSLEngine sse = getEngine();
+ sse.setWantClientAuth(false);
+ assertFalse(sse.getWantClientAuth());
+ sse.setWantClientAuth(true);
+ assertTrue(sse.getWantClientAuth());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#beginHandshake()
+ */
+ public void test_beginHandshake() throws Exception {
+ SSLEngine sse = getEngine();
+ try {
+ sse.beginHandshake();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ sse = getEngine("new host", 1080);
+ try {
+ sse.beginHandshake();
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ sse = getEngine();
+ sse.setUseClientMode(true);
+ sse.beginHandshake();
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#setUseClientMode(boolean mode)
+ * javax.net.ssl.SSLEngine#getUseClientMode()
+ */
+ public void test_UseClientMode() throws Exception {
+ SSLEngine sse = getEngine();
+ sse.setUseClientMode(false);
+ assertFalse(sse.getUseClientMode());
+ sse.setUseClientMode(true);
+ assertTrue(sse.getUseClientMode());
+
+ sse = getEngine(null, 1080);
+ sse.setUseClientMode(true);
+ sse.beginHandshake();
+ try {
+ sse.setUseClientMode(false);
+ fail("IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#getSession()
+ */
+ public void test_getSession() throws Exception {
+ SSLEngine sse = getEngine();
+ assertNotNull(sse.getSession());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#getHandshakeStatus()
+ */
+ public void test_getHandshakeStatus() throws Exception {
+ SSLEngine sse = getEngine();
+ assertEquals(sse.getHandshakeStatus().toString(), "NOT_HANDSHAKING");
+ sse.setUseClientMode(true);
+ sse.beginHandshake();
+ assertEquals(sse.getHandshakeStatus().toString(), "NEED_WRAP");
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#getDelegatedTask()
+ */
+ public void test_getDelegatedTask() throws Exception {
+ SSLEngine sse = getEngine();
+ assertNull(sse.getDelegatedTask());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ * Exception case: SSLException should be thrown.
+ */
+ public void test_unwrap_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+
+ ByteBuffer bbs = ByteBuffer.wrap(new byte[] {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,31,2,3,1,2,3,1,2,3,1,2,3});
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+ try {
+ clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd }, 0, 1);
+ fail("SSLException wasn't thrown");
+ } catch (SSLException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ * Exception case: IndexOutOfBoundsException should be thrown.
+ */
+ public void test_unwrap_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bb, bbA, -1, 3);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.unwrap(bb, bbA, 0, -3);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.unwrap(bb, bbA, bbA.length + 1, bbA.length);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.unwrap(bb, bbA, 0, bbA.length + 1);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ * Exception case: ReadOnlyBufferException should be thrown.
+ */
+ public void test_unwrap_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
+ ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bb, bbA, 0, bbA.length);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ * Exception case: IllegalArgumentException should be thrown.
+ */
+ public void test_unwrap_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
+ ByteBuffer[] bbAN = {ByteBuffer.allocate(100), null, ByteBuffer.allocate(100)};
+ ByteBuffer[] bbN = null;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ ByteBuffer bN = null;
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bN, bbA, 0, 3);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ sse.unwrap(bb, bbAN, 0, 3);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ sse.unwrap(bb, bbN, 0, 0);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ sse.unwrap(bN, bbN, 0, 0);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ * Exception case: IllegalStateException should be thrown.
+ */
+ public void test_unwrap_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+
+ try {
+ SSLEngineResult result = sse.unwrap(bb, bbA, 0, bbA.length);
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
+ * int offset, int length)
+ */
+ public void test_unwrap_06() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult res = sse.unwrap(bb, bbA, 0, bbA.length);
+ assertEquals(0, res.bytesConsumed());
+ assertEquals(0, res.bytesProduced());
+ }
+
+ public void test_wrap_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+ ByteBuffer bbs = ByteBuffer.allocate(100);
+ ByteBuffer bbd = ByteBuffer.allocate(MAX_TLS_RECORD_SIZE);
+ clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
+ * int length, ByteBuffer dst)
+ * Exception case: IndexOutOfBoundsException should be thrown.
+ */
+ public void test_wrap_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbA, -1, 3, bb);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.wrap(bbA, 0, -3, bb);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.wrap(bbA, bbA.length + 1, bbA.length, bb);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ sse.wrap(bbA, 0, bbA.length + 1, bb);
+ fail("IndexOutOfBoundsException wasn't thrown");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
+ * int length, ByteBuffer dst)
+ * Exception case: ReadOnlyBufferException should be thrown.
+ */
+ public void test_wrap_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(MAX_TLS_RECORD_SIZE).asReadOnlyBuffer();
+ ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbA, 0, bbA.length, bb);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
+ * int length, ByteBuffer dst)
+ * Exception case: IllegalArgumentException should be thrown.
+ */
+ public void test_wrap_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
+ ByteBuffer[] bbN = null;
+ ByteBuffer bN = null;
+ SSLEngine e = getEngine(host, port);
+ e.setUseClientMode(true);
+
+ try {
+ e.wrap(bbA, 0, 3, bN);
+ fail("IllegalArgumentException must be thrown for null srcs byte buffer array");
+ } catch (IllegalArgumentException ex) {
+ }
+
+ try {
+ e.wrap(bbN, 0, 0, bN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException ex) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
+ * int length, ByteBuffer dst)
+ * Exception case: IllegalStateException should be thrown.
+ */
+ public void test_wrap_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(MAX_TLS_RECORD_SIZE);
+ ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
+ SSLEngine sse = getEngine(host, port);
+
+ try {
+ SSLEngineResult result = sse.wrap(bbA, 0, bbA.length, bb);
+ fail("Should fail since mode not set yet");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
+ * int length, ByteBuffer dst)
+ */
+ public void test_wrap_06() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(MAX_TLS_RECORD_SIZE);
+ ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult result = sse.wrap(bbA, 0, bbA.length, bb);
+ assertEquals(SSLEngineResult.Status.OK, result.getStatus());
+ assertEquals(0, result.bytesConsumed());
+ assertTrue(result.bytesProduced() > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#closeOutbound()
+ * javax.net.ssl.SSLEngine#isOutboundDone()
+ */
+ public void test_closeOutbound() throws Exception {
+ SSLEngine sse = getEngine();
+
+ assertFalse(sse.isOutboundDone());
+ sse.closeOutbound();
+ assertTrue(sse.isOutboundDone());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#closeInbound()
+ * javax.net.ssl.SSLEngine#isInboundDone()
+ */
+ public void test_closeInbound() throws Exception {
+ SSLEngine sse = getEngine();
+
+ assertFalse(sse.isInboundDone());
+ sse.closeInbound();
+ assertTrue(sse.isInboundDone());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
+ * SSLException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer_ByteBuffer_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+ ByteBuffer bbs = ByteBuffer.allocate(100);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+
+ try {
+ SSLEngineResult unwrap = clientEngine.engine.unwrap(bbs, bbd);
+ fail("SSLException wasn't thrown");
+ } catch (SSLException ex) {
+ //expected
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
+ * ReadOnlyBufferException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer_ByteBuffer_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bbs, bbd);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException iobe) {
+ //expected
+ } catch (Exception e) {
+ fail(e + " was thrown instead of ReadOnlyBufferException");
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
+ * IllegalArgumentException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer_ByteBuffer_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbsN = null;
+ ByteBuffer bbdN = null;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bbsN, bbd);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.unwrap(bbs, bbdN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.unwrap(bbsN, bbdN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
+ * IllegalStateException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer_ByteBuffer_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+ SSLEngine sse = getEngine(host, port);
+
+ try {
+ sse.unwrap(bbs, bbd);
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
+ */
+ public void test_unwrap_ByteBuffer_ByteBuffer_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult res = sse.unwrap(bbs, bbd);
+ assertEquals(0, res.bytesConsumed());
+ assertEquals(0, res.bytesProduced());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
+ * SSLException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer$ByteBuffer_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+
+ ByteBuffer bbs = ByteBuffer.allocate(100);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+
+ try {
+ clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd });
+ fail("SSLException wasn't thrown");
+ } catch (SSLException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
+ * ReadOnlyBufferException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer$ByteBuffer_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
+ ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bbs, bbA);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
+ * IllegalArgumentException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer$ByteBuffer_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+ ByteBuffer[] bbN = { ByteBuffer.allocate(100), null, ByteBuffer.allocate(100) };
+ ByteBuffer[] bbAN = null;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ ByteBuffer bN = null;
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.unwrap(bN, bbA);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.unwrap(bb, bbAN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.unwrap(bb, bbN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.unwrap(bN, bbAN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
+ * IllegalStateException should be thrown.
+ */
+ public void test_unwrap_ByteBuffer$ByteBuffer_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+ SSLEngine sse = getEngine(host, port);
+
+ try {
+ sse.unwrap(bbs, bbd);
+ fail("IllegalStateException wasn't thrown");
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
+ */
+ public void test_unwrap_ByteBuffer$ByteBuffer_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult res = sse.unwrap(bbs, bbd);
+ assertEquals(0, res.bytesConsumed());
+ assertEquals(0, res.bytesProduced());
+ }
+
+ public void test_wrap_ByteBuffer_ByteBuffer_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+ ByteBuffer bbs = ByteBuffer.allocate(20);
+ ByteBuffer bbd = ByteBuffer.allocate(20000);
+ clientEngine.engine.wrap(bbs, bbd);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
+ * ReadOnlyBufferException should be thrown.
+ */
+ public void test_wrap_ByteBuffer_ByteBuffer_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbs, bbd);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
+ * IllegalArgumentException should be thrown.
+ */
+ public void test_wrap_ByteBuffer_ByteBuffer_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbsN = null;
+ ByteBuffer bbdN = null;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(100);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbsN, bbd);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.wrap(bbs, bbdN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.wrap(bbsN, bbdN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
+ * IllegalStateException should be thrown.
+ */
+ public void test_wrap_ByteBuffer_ByteBuffer_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bbs = ByteBuffer.allocate(10);
+ ByteBuffer bbd = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+
+ try {
+ SSLEngineResult result = sse.wrap(bbs, bbd);
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
+ */
+ public void test_wrap_ByteBuffer_ByteBuffer_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult res = sse.wrap(bb, ByteBuffer.allocate(10));
+ assertEquals(Status.BUFFER_OVERFLOW, res.getStatus());
+ assertEquals(0, res.bytesConsumed());
+ assertEquals(0, res.bytesProduced());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
+ * SSLException should be thrown.
+ */
+ public void test_wrap_ByteBuffer$ByteBuffer_01() throws Exception {
+ prepareEngines();
+ doHandshake();
+ ByteBuffer bbs = ByteBuffer.allocate(100);
+ ByteBuffer bbd = ByteBuffer.allocate(20000);
+
+ clientEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
+ serverEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
+ * ReadOnlyBufferException should be thrown.
+ */
+ public void test_wrap_ByteBuffer$ByteBuffer_02() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer();
+ ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbA, bb);
+ fail("ReadOnlyBufferException wasn't thrown");
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
+ * IllegalArgumentException should be thrown.
+ */
+ public void test_wrap_ByteBuffer$ByteBuffer_03() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
+ ByteBuffer[] bbAN = null;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ ByteBuffer bN = null;
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ try {
+ sse.wrap(bbA, bN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.wrap(bbAN, bb);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ sse.wrap(bbAN, bN);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
+ * IllegalStateException should be thrown.
+ */
+ public void test_wrap_ByteBuffer$ByteBuffer_04() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
+ SSLEngine sse = getEngine(host, port);
+
+ SSLEngineResult result = sse.wrap(bbA, bb);
+ assertEquals(Status.BUFFER_OVERFLOW, result.getStatus());
+ }
+
+ /**
+ * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
+ */
+ public void test_wrap_ByteBuffer$ByteBuffer_05() throws Exception {
+ String host = "new host";
+ int port = 8080;
+ ByteBuffer bb = ByteBuffer.allocate(2000);
+ ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
+ SSLEngine sse = getEngine(host, port);
+ sse.setUseClientMode(true);
+
+ SSLEngineResult res = sse.wrap(bbA, bb);
+ assertEquals(0, res.bytesConsumed());
+ assertEquals(0, res.bytesProduced());
+ }
+
+ private SSLEngine getEngine() throws Exception {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ return context.createSSLEngine();
+ }
+
+ private SSLEngine getEngine(String host, int port) throws Exception {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ return context.createSSLEngine(host, port);
+ }
+
+ class HandshakeHandler implements Runnable {
+
+ private final SSLEngine engine;
+
+ private final SourceChannel in;
+
+ private final SinkChannel out;
+
+ private final ByteBuffer EMPTY = ByteBuffer.allocate(0);
+
+ @SuppressWarnings("unused")
+ private final String LOGTAG;
+
+ private SSLEngineResult.HandshakeStatus status;
+
+ private ByteBuffer readBuffer;
+
+ private ByteBuffer writeBuffer;
+
+ HandshakeHandler(boolean clientMode, SourceChannel in, SinkChannel out) throws Exception {
+ this.in = in;
+ this.out = out;
+ engine = getEngine();
+ engine.setUseClientMode(clientMode);
+ String[] cipherSuites = engine.getSupportedCipherSuites();
+ Set<String> enabledSuites = new HashSet<String>();
+ for (String cipherSuite : cipherSuites) {
+ if (cipherSuite.contains("anon")) {
+ enabledSuites.add(cipherSuite);
+ }
+ }
+ engine.setEnabledCipherSuites((String[]) enabledSuites.toArray(
+ new String[enabledSuites.size()]));
+
+ engine.beginHandshake();
+ status = engine.getHandshakeStatus();
+
+ if (clientMode) {
+ LOGTAG = "CLIENT: ";
+ } else {
+ LOGTAG = "SERVER: ";
+ }
+
+ log("CipherSuites: " + Arrays.toString(engine.getEnabledCipherSuites()));
+ log(status);
+
+ readBuffer = ByteBuffer.allocate(200000);
+ writeBuffer = ByteBuffer.allocate(20000);
+ }
+
+ public SSLEngineResult.HandshakeStatus getStatus() {
+ return status;
+ }
+
+ private void log(Object o) {
+ //System.out.print(LOGTAG);
+ //System.out.println(o);
+ }
+
+ private ByteBuffer read() throws IOException {
+ if (readBuffer == null || readBuffer.remaining() == 0 || readBuffer.position() == 0) {
+ readBuffer.clear();
+ int read = in.read(readBuffer);
+ log("read: " + read);
+ readBuffer.rewind();
+ readBuffer.limit(read);
+ }
+ return readBuffer;
+ }
+
+ public void run() {
+ try {
+ while (true) {
+ switch (status) {
+ case FINISHED: {
+ log(status);
+ return;
+ }
+ case NEED_TASK: {
+ log(status);
+ Runnable task;
+ while ((task = engine.getDelegatedTask()) != null) {
+ task.run();
+ }
+ status = engine.getHandshakeStatus();
+ break;
+ }
+ case NEED_UNWRAP: {
+ log(status);
+ ByteBuffer source = read();
+ writeBuffer.clear();
+
+ while (status == HandshakeStatus.NEED_UNWRAP) {
+ SSLEngineResult result = engine.unwrap(source, writeBuffer);
+ status = result.getHandshakeStatus();
+ log(result);
+ }
+ break;
+ }
+ case NEED_WRAP: {
+ log(status);
+ writeBuffer.clear();
+
+ int produced = 0;
+ SSLEngineResult result = null;
+ while (status == HandshakeStatus.NEED_WRAP) {
+ result = engine.wrap(EMPTY, writeBuffer);
+ status = result.getHandshakeStatus();
+ produced += result.bytesProduced();
+ log(result);
+ }
+ writeBuffer.rewind();
+ writeBuffer.limit(produced);
+ log("write: " + produced);
+ out.write(writeBuffer);
+ break;
+ }
+ case NOT_HANDSHAKING: {
+ log("Not Handshaking");
+ return;
+ }
+ }
+ }
+ } catch (IOException e) {
+ log(e);
+ } catch (RuntimeException e) {
+ // ignore;
+ }
+ }
+ }
+
+ public void testHandshake() throws Exception {
+
+ prepareEngines();
+
+ assertTrue("handshake failed", doHandshake());
+
+ System.out.println(clientEngine.engine.getSession().getCipherSuite());
+
+ assertEquals("Handshake not finished",
+ SSLEngineResult.HandshakeStatus.FINISHED,
+ clientEngine.getStatus());
+ assertEquals("Handshake not finished",
+ SSLEngineResult.HandshakeStatus.FINISHED,
+ serverEngine.getStatus());
+ }
+
+ void prepareEngines() throws Exception {
+ Pipe clientSendPipe = Pipe.open();
+ Pipe serverSendPipe = Pipe.open();
+
+ SinkChannel clientSink = clientSendPipe.sink();
+ SourceChannel serverSource = clientSendPipe.source();
+ SinkChannel serverSink = serverSendPipe.sink();
+ SourceChannel clientSource = serverSendPipe.source();
+
+ clientEngine = new HandshakeHandler(true, clientSource, clientSink);
+ serverEngine = new HandshakeHandler(false, serverSource, serverSink);
+ }
+
+ boolean doHandshake() throws InterruptedException {
+ Thread clientThread = new Thread(clientEngine);
+ clientThread.start();
+
+ Thread serverThread = new Thread(serverEngine);
+ serverThread.start();
+
+ int i = 0;
+ while (clientThread.isAlive() && serverThread.isAlive() && i < 20) {
+ Thread.sleep(500);
+ i++;
+ }
+
+ if (clientThread.isAlive()) {
+ clientThread.interrupt();
+ }
+
+ if (serverThread.isAlive()) {
+ serverThread.interrupt();
+ }
+
+ return clientEngine.getStatus() == HandshakeStatus.FINISHED && serverEngine.getStatus() == HandshakeStatus.FINISHED;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLExceptionTest.java
new file mode 100644
index 0000000..9b4ae35
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLExceptionTest.java
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLException;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>SSLException</code> class constructors and methods.
+ *
+ */
+public class SSLExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ private static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>SSLException(String)</code> constructor Assertion:
+ * constructs SSLException with detail message msg. Parameter
+ * <code>msg</code> is not null.
+ */
+ public void testSSLException01() {
+ SSLException sE;
+ for (int i = 0; i < msgs.length; i++) {
+ sE = new SSLException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), sE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", sE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLException(String)</code> constructor Assertion:
+ * constructs SSLException when <code>msg</code> is null
+ */
+ public void testSSLException02() {
+ String msg = null;
+ SSLException sE = new SSLException(msg);
+ assertNull("getMessage() must return null.", sE.getMessage());
+ assertNull("getCause() must return null", sE.getCause());
+ }
+
+ /**
+ * Test for <code>SSLException(Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is null
+ */
+ public void testSSLException03() {
+ Throwable cause = null;
+ SSLException sE = new SSLException(cause);
+ assertNull("getMessage() must return null.", sE.getMessage());
+ assertNull("getCause() must return null", sE.getCause());
+ }
+
+ /**
+ * Test for <code>SSLException(Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is not
+ * null
+ */
+ public void testSSLException04() {
+ SSLException sE = new SSLException(tCause);
+ if (sE.getMessage() != null) {
+ String toS = tCause.toString();
+ String getM = sE.getMessage();
+ assertTrue("getMessage() should contain ".concat(toS), (getM
+ .indexOf(toS) != -1));
+ }
+ assertNotNull("getCause() must not return null", sE.getCause());
+ assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
+ }
+
+ /**
+ * Test for <code>SSLException(String, Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is null
+ * <code>msg</code> is null
+ */
+ public void testSSLException05() {
+ SSLException sE = new SSLException(null, null);
+ assertNull("getMessage() must return null", sE.getMessage());
+ assertNull("getCause() must return null", sE.getCause());
+ }
+
+ /**
+ * Test for <code>SSLException(String, Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is null
+ * <code>msg</code> is not null
+ */
+ public void testSSLException06() {
+ SSLException sE;
+ for (int i = 0; i < msgs.length; i++) {
+ sE = new SSLException(msgs[i], null);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), sE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", sE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLException(String, Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is not
+ * null <code>msg</code> is null
+ */
+ public void testSSLException07() {
+ SSLException sE = new SSLException(null, tCause);
+ if (sE.getMessage() != null) {
+ String toS = tCause.toString();
+ String getM = sE.getMessage();
+ assertTrue("getMessage() must should ".concat(toS), (getM
+ .indexOf(toS) != -1));
+ }
+ assertNotNull("getCause() must not return null", sE.getCause());
+ assertEquals("getCause() must return ".concat(tCause.toString()), sE
+ .getCause(), tCause);
+ }
+
+ /**
+ * Test for <code>SSLException(String, Throwable)</code> constructor
+ * Assertion: constructs SSLException when <code>cause</code> is not
+ * null <code>msg</code> is not null
+ */
+ public void testSSLException08() {
+ SSLException sE;
+ for (int i = 0; i < msgs.length; i++) {
+ sE = new SSLException(msgs[i], tCause);
+ String getM = sE.getMessage();
+ String toS = tCause.toString();
+ if (msgs[i].length() > 0) {
+ assertTrue("getMessage() must contain ".concat(msgs[i]), getM
+ .indexOf(msgs[i]) != -1);
+ if (!getM.equals(msgs[i])) {
+ assertTrue("getMessage() should contain ".concat(toS), getM
+ .indexOf(toS) != -1);
+ }
+ }
+ assertNotNull("getCause() must not return null", sE.getCause());
+ assertEquals("getCause() must return ".concat(tCause.toString()),
+ sE.getCause(), tCause);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLHandshakeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLHandshakeExceptionTest.java
new file mode 100644
index 0000000..a2d0ec5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLHandshakeExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLHandshakeException;
+
+import junit.framework.TestCase;
+
+public class SSLHandshakeExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
+ * constructs SSLHandshakeException with detail message msg. Parameter
+ * <code>msg</code> is not null.
+ */
+ public void test_Constructor01() {
+ SSLHandshakeException sslE;
+ for (int i = 0; i < msgs.length; i++) {
+ sslE = new SSLHandshakeException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
+ * constructs SSLHandshakeException with detail message msg. Parameter
+ * <code>msg</code> is null.
+ */
+ public void test_Constructor02() {
+ String msg = null;
+ SSLHandshakeException sslE = new SSLHandshakeException(msg);
+ assertNull("getMessage() must return null.", sslE.getMessage());
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLKeyExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLKeyExceptionTest.java
new file mode 100644
index 0000000..d6ba998
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLKeyExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLKeyException;
+
+import junit.framework.TestCase;
+
+public class SSLKeyExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * Test for <code>SSLKeyException(String)</code> constructor Assertion:
+ * constructs SSLKeyException with detail message msg. Parameter
+ * <code>msg</code> is not null.
+ */
+ public void test_Constructor01() {
+ SSLKeyException skE;
+ for (int i = 0; i < msgs.length; i++) {
+ skE = new SSLKeyException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), skE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", skE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
+ * constructs SSLPeerUnverifiedException with detail message msg. Parameter
+ * <code>msg</code> is null.
+ */
+ public void test_Constructor02() {
+ String msg = null;
+ SSLKeyException skE = new SSLKeyException(msg);
+ assertNull("getMessage() must return null.", skE.getMessage());
+ assertNull("getCause() must return null", skE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
new file mode 100644
index 0000000..a8b9ac4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+import junit.framework.TestCase;
+
+public class SSLPeerUnverifiedExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
+ * constructs SSLPeerUnverifiedException with detail message msg. Parameter
+ * <code>msg</code> is not null.
+ */
+ public void test_Constructor01() {
+ SSLPeerUnverifiedException sslE;
+ for (int i = 0; i < msgs.length; i++) {
+ sslE = new SSLPeerUnverifiedException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
+ * constructs SSLPeerUnverifiedException with detail message msg. Parameter
+ * <code>msg</code> is null.
+ */
+ public void test_Constructor02() {
+ String msg = null;
+ SSLPeerUnverifiedException sslE = new SSLPeerUnverifiedException(msg);
+ assertNull("getMessage() must return null.", sslE.getMessage());
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLProtocolExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLProtocolExceptionTest.java
new file mode 100644
index 0000000..14b562d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLProtocolExceptionTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLProtocolException;
+
+import junit.framework.TestCase;
+
+public class SSLProtocolExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
+ * constructs SSLProtocolException with detail message msg. Parameter
+ * <code>msg</code> is not null.
+ */
+ public void test_Constructor01() {
+ SSLProtocolException sslE;
+ for (int i = 0; i < msgs.length; i++) {
+ sslE = new SSLProtocolException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
+ * constructs SSLProtocolException with detail message msg. Parameter
+ * <code>msg</code> is null.
+ */
+ public void test_Constructor02() {
+ String msg = null;
+ SSLProtocolException sslE = new SSLProtocolException(msg);
+ assertNull("getMessage() must return null.", sslE.getMessage());
+ assertNull("getCause() must return null", sslE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketFactoryTest.java
new file mode 100644
index 0000000..5958ecb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketFactoryTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+
+import javax.net.ssl.SSLServerSocketFactory;
+
+import junit.framework.TestCase;
+
+public class SSLServerSocketFactoryTest extends TestCase {
+
+ private class MockSSLServerSocketFactory extends SSLServerSocketFactory {
+ public MockSSLServerSocketFactory() {
+ super();
+ }
+
+ @Override
+ public String[] getDefaultCipherSuites() {
+ return null;
+ }
+
+ @Override
+ public String[] getSupportedCipherSuites() {
+ return null;
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int arg0) throws IOException {
+ return null;
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int arg0, int arg1)
+ throws IOException {
+ return null;
+ }
+
+ @Override
+ public ServerSocket createServerSocket(int arg0, int arg1,
+ InetAddress arg2) throws IOException {
+ return null;
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocketFactory#SSLServerSocketFactory()
+ */
+ public void test_Constructor() {
+ try {
+ MockSSLServerSocketFactory ssf = new MockSSLServerSocketFactory();
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocketFactory#getDefault()
+ */
+ public void test_getDefault() {
+ assertNotNull("Incorrect default socket factory",
+ SSLServerSocketFactory.getDefault());
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocketFactory#getDefaultCipherSuites()
+ */
+ public void test_getDefaultCipherSuites() {
+ SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
+ .getDefault();
+ try {
+ assertTrue(ssf.getDefaultCipherSuites().length > 0);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocketFactory#getSupportedCipherSuites()
+ */
+ public void test_getSupportedCipherSuites() {
+ SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
+ .getDefault();
+ try {
+ assertTrue(ssf.getSupportedCipherSuites().length > 0);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketTest.java
new file mode 100644
index 0000000..5086f65
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLServerSocketTest.java
@@ -0,0 +1,431 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import junit.framework.TestCase;
+
+import libcore.io.Base64;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.util.Arrays;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+
+public class SSLServerSocketTest extends TestCase {
+
+ // set to true if on Android, false if on RI
+ boolean useBKS = true;
+
+ /**
+ * Additional class for SSLServerSocket constructor verification
+ */
+ class mySSLServerSocket extends SSLServerSocket {
+
+ public mySSLServerSocket() throws IOException{
+ super();
+ }
+
+ public mySSLServerSocket(int port) throws IOException{
+ super(port);
+ }
+
+ public mySSLServerSocket(int port, int backlog) throws IOException{
+ super(port, backlog);
+ }
+
+ public mySSLServerSocket(int port, int backlog, InetAddress address) throws IOException{
+ super(port, backlog, address);
+ }
+
+ public String[] getSupportedCipherSuites() {
+ return null;
+ }
+
+ public void setEnabledCipherSuites(String[] suites) {
+
+ }
+
+ public String[] getEnabledCipherSuites() {
+ return null;
+ }
+
+ public String[] getSupportedProtocols() {
+ return null;
+ }
+
+ public String[] getEnabledProtocols() {
+ return null;
+ }
+
+ public void setEnabledProtocols(String[] protocols) {
+
+ }
+
+ public void setEnableSessionCreation(boolean flag) {
+
+ }
+
+ public boolean getEnableSessionCreation() {
+ return false;
+ }
+
+ public void setNeedClientAuth(boolean need) {
+
+ }
+
+ public boolean getNeedClientAuth() {
+ return false;
+ }
+
+ public boolean getUseClientMode() {
+ return false;
+ }
+
+ public void setUseClientMode(boolean mode) {
+
+ }
+
+ public boolean getWantClientAuth() {
+ return false;
+ }
+ public void setWantClientAuth(boolean mode) {
+
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocket#SSLServerSocket()
+ */
+ public void testConstructor() throws Exception {
+ SSLServerSocket ssl = new mySSLServerSocket();
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
+ */
+ public void testConstructor_I() throws Exception {
+ int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
+
+ SSLServerSocket ssl = new mySSLServerSocket(0);
+
+ for (int i = 0; i < port_invalid.length; i++) {
+ try {
+ new mySSLServerSocket(port_invalid[i]);
+ fail("IllegalArgumentException should be thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ new mySSLServerSocket(ssl.getLocalPort());
+ fail("IOException Expected when opening an already opened port");
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog)
+ */
+ public void testConstructor_II() throws Exception {
+ mySSLServerSocket ssl = new mySSLServerSocket(0, 1);
+ int[] port_invalid = {-1, Integer.MIN_VALUE, Integer.MAX_VALUE};
+
+ for (int i = 0; i < port_invalid.length; i++) {
+ try {
+ new mySSLServerSocket(port_invalid[i], 1);
+ fail("IllegalArgumentException should be thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ new mySSLServerSocket(ssl.getLocalPort(), 1);
+ fail("IOException should be thrown");
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog, InetAddress address)
+ */
+ public void testConstructor_IIInetAddress() throws Exception {
+ // A null InetAddress is okay.
+ new mySSLServerSocket(0, 0, null);
+
+ int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
+
+ mySSLServerSocket ssl = new mySSLServerSocket(0, 0, InetAddress.getLocalHost());
+
+ for (int i = 0; i < port_invalid.length; i++) {
+ try {
+ new mySSLServerSocket(port_invalid[i], 1, InetAddress.getLocalHost());
+ fail("IllegalArgumentException should be thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ new mySSLServerSocket(ssl.getLocalPort(), 0, InetAddress.getLocalHost());
+ fail("IOException should be thrown for");
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * @throws Exception
+ * javax.net.ssl.SSLServerSocket#getSupportedCipherSuites()
+ */
+ public void test_getSupportedCipherSuites() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ String[] res = sss.getSupportedCipherSuites();
+ assertNotNull("NULL result", res);
+ assertTrue("no supported cipher suites available.", res.length > 0);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#getEnabledCipherSuites()
+ * javax.net.ssl.SSLServerSocket#setEnabledCipherSuites(String[] suites)
+ */
+ public void test_EnabledCipherSuites() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ try {
+ sss.setEnabledCipherSuites(null);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ String[] unsupportedCipherSuites = {"unsupported"};
+ try {
+ sss.setEnabledCipherSuites(unsupportedCipherSuites);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ int count = sss.getSupportedCipherSuites().length;
+ assertTrue("No supported cipher suites", count > 0);
+ sss.setEnabledCipherSuites(sss.getSupportedCipherSuites());
+ String[] res = sss.getEnabledCipherSuites();
+ assertNotNull("NULL result", res);
+ assertEquals("not all supported cipher suites were enabled",
+ Arrays.asList(sss.getSupportedCipherSuites()),
+ Arrays.asList(res));
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#getSupportedProtocols()
+ */
+ public void test_getSupportedProtocols() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ String[] res = sss.getSupportedCipherSuites();
+ assertNotNull("NULL result", res);
+ assertTrue("no supported protocols available.", res.length > 0);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#getEnabledProtocols()
+ * javax.net.ssl.SSLServerSocket#setEnabledProtocols(String[] protocols)
+ */
+ public void test_EnabledProtocols() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ try {
+ sss.setEnabledProtocols(null);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ String[] unsupportedProtocols = {"unsupported"};
+ try {
+ sss.setEnabledProtocols(unsupportedProtocols);
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ int count = sss.getSupportedProtocols().length;
+ assertTrue("No supported protocols", count > 0);
+ sss.setEnabledProtocols(sss.getSupportedProtocols());
+ String[] res = sss.getEnabledProtocols();
+ assertNotNull("NULL result", res);
+ assertTrue("no enabled protocols.", res.length == count);
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#setEnableSessionCreation(boolean flag)
+ * javax.net.ssl.SSLServerSocket#getEnableSessionCreation()
+ */
+ public void test_EnableSessionCreation() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ assertTrue(sss.getEnableSessionCreation());
+ sss.setEnableSessionCreation(false);
+ assertFalse(sss.getEnableSessionCreation());
+ sss.setEnableSessionCreation(true);
+ assertTrue(sss.getEnableSessionCreation());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#setNeedClientAuth(boolean need)
+ * javax.net.ssl.SSLServerSocket#getNeedClientAuthCreation()
+ */
+ public void test_NeedClientAuth() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ sss.setNeedClientAuth(true);
+ assertTrue(sss.getNeedClientAuth());
+ sss.setNeedClientAuth(false);
+ assertFalse(sss.getNeedClientAuth());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#getUseClientMode()
+ * javax.net.ssl.SSLServerSocket#setUseClientMode(boolean mode)
+ */
+ public void test_UseClientMode() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ sss.setUseClientMode(false);
+ assertFalse(sss.getUseClientMode());
+ sss.setUseClientMode(true);
+ assertTrue(sss.getUseClientMode());
+ }
+
+ /**
+ * @throws IOException
+ * javax.net.ssl.SSLServerSocket#setWantClientAuth(boolean want)
+ * javax.net.ssl.SSLServerSocket#getWantClientAuthCreation()
+ */
+ public void test_WantClientAuth() throws Exception {
+ SSLServerSocket sss = getSSLServerSocket();
+ sss.setWantClientAuth(true);
+ assertTrue(sss.getWantClientAuth());
+ sss.setWantClientAuth(false);
+ assertFalse(sss.getWantClientAuth());
+ }
+
+
+ /**
+ * Defines the keystore contents for the server, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_BKS =
+ "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
+ "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
+ "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
+ "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
+ "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
+ "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
+ "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
+ "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
+ "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
+ "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
+ "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
+ "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
+ "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
+ "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
+ "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
+ "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
+ "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
+ "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
+ "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
+ "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
+ "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
+ "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
+ "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
+ "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
+
+ /**
+ * Defines the keystore contents for the server, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_JKS =
+ "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
+ "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
+ "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
+ "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
+ "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
+ "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
+ "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
+ "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
+ "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
+ "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
+ "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
+ "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
+ "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
+ "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
+ "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
+ "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
+ "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
+ "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
+ "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
+ "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
+ "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
+ "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
+ "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
+ "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
+
+ private String PASSWORD = "android";
+
+ /**
+ * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
+ * for the result.
+ */
+ private KeyManager[] getKeyManagers() throws Exception {
+ String keys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
+ byte[] bytes = Base64.decode(keys.getBytes());
+ InputStream inputStream = new ByteArrayInputStream(bytes);
+
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(inputStream, PASSWORD.toCharArray());
+ inputStream.close();
+
+ String algorithm = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
+ keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
+
+ return keyManagerFactory.getKeyManagers();
+ }
+
+ private SSLServerSocket getSSLServerSocket() throws Exception {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(getKeyManagers(), null, null);
+ SSLServerSocket sss = (SSLServerSocket) context.getServerSocketFactory()
+ .createServerSocket();
+ return sss;
+ }
+
+ public void test_creationStressTest() throws Exception {
+ KeyManager[] keyManagers = getKeyManagers();
+ // Test the default codepath, which uses /dev/urandom.
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, null, null);
+ for (int i = 0; i < 2048; ++i) {
+ sslContext.getServerSocketFactory().createServerSocket().close();
+ }
+
+ // Test the other codepath, which copies a seed from a byte[].
+ sslContext.init(keyManagers, null, new SecureRandom());
+ for (int i = 0; i < 2048; ++i) {
+ sslContext.getServerSocketFactory().createServerSocket().close();
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingEventTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingEventTest.java
new file mode 100644
index 0000000..dfccf68
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingEventTest.java
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.security.Principal;
+import java.security.cert.Certificate;
+
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSessionBindingEvent;
+import javax.security.cert.X509Certificate;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>SSLSessionBindingEvent</code> class constructors and methods.
+ *
+ */
+public class SSLSessionBindingEventTest extends TestCase {
+
+ public final void test_ConstructorLjavax_net_ssl_SSLSessionLjava_lang_String() {
+ SSLSession ses = new MySSLSession();
+
+ try {
+ SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
+ if (!"test".equals(event.getName())) {
+ fail("incorrect name");
+ }
+ if (!event.getSession().equals(ses)) {
+ fail("incorrect session");
+ }
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+
+ try {
+ SSLSessionBindingEvent event = new SSLSessionBindingEvent(null, "test");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, null);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException: " + e);
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSessionBindingEvent#getName()
+ */
+ public void test_getName() {
+ SSLSession ses = new MySSLSession();
+ SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
+ assertEquals("Incorrect session name", "test", event.getName());
+ event = new SSLSessionBindingEvent(ses, null);
+ assertEquals("Incorrect session name", null, event.getName());
+ }
+
+ /**
+ * javax.net.ssl.SSLSessionBindingEvent#getSession()
+ */
+ public void test_getSession() {
+ SSLSession ses = new MySSLSession();
+ SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
+ assertEquals("Incorrect session", ses, event.getSession());
+ }
+}
+
+class MySSLSession implements SSLSession {
+ /*
+ * @see javax.net.ssl.SSLSession#getApplicationBufferSize()
+ */
+ public int getApplicationBufferSize() {
+ return 0;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getCipherSuite()
+ */
+ public String getCipherSuite() {
+ return "MyTestCipherSuite";
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getCreationTime()
+ */
+ public long getCreationTime() {
+ return 0;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getId()
+ */
+ public byte[] getId() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getLastAccessedTime()
+ */
+ public long getLastAccessedTime() {
+ return 0;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getLocalCertificates()
+ */
+ public Certificate[] getLocalCertificates() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getLocalPrincipal()
+ */
+ public Principal getLocalPrincipal() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPacketBufferSize()
+ */
+ public int getPacketBufferSize() {
+ return 0;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPeerCertificateChain()
+ */
+ public X509Certificate[] getPeerCertificateChain()
+ throws SSLPeerUnverifiedException {
+ throw new SSLPeerUnverifiedException("test exception");
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPeerCertificates()
+ */
+ public Certificate[] getPeerCertificates()
+ throws SSLPeerUnverifiedException {
+ throw new SSLPeerUnverifiedException("test exception");
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPeerHost()
+ */
+ public String getPeerHost() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPeerPort()
+ */
+ public int getPeerPort() {
+ return 0;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getPeerPrincipal()
+ */
+ public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getProtocol()
+ */
+ public String getProtocol() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getSessionContext()
+ */
+ public SSLSessionContext getSessionContext() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getValue(java.lang.String)
+ */
+ public Object getValue(String name) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#getValueNames()
+ */
+ public String[] getValueNames() {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#invalidate()
+ */
+ public void invalidate() {
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#isValid()
+ */
+ public boolean isValid() {
+ return false;
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#putValue(java.lang.String,
+ * java.lang.Object)
+ */
+ public void putValue(String name, Object value) {
+ }
+
+ /*
+ * @see javax.net.ssl.SSLSession#removeValue(java.lang.String)
+ */
+ public void removeValue(String name) {
+ }
+
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingListenerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingListenerTest.java
new file mode 100644
index 0000000..a006a83
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionBindingListenerTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionBindingEvent;
+import javax.net.ssl.SSLSessionBindingListener;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
+import java.io.IOException;
+import java.net.UnknownHostException;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for SSLSessionBindingListener class
+ *
+ */
+public class SSLSessionBindingListenerTest extends TestCase {
+
+ public class mySSLSessionBindingListener implements SSLSessionBindingListener {
+
+ public boolean boundDone = false;
+ public boolean unboundDone = false;
+
+ mySSLSessionBindingListener() {
+ }
+
+ public void valueBound(SSLSessionBindingEvent event) {
+ if (event != null) boundDone = true;
+ }
+ public void valueUnbound(SSLSessionBindingEvent event) {
+ if (event != null) unboundDone = true;
+ }
+ }
+
+ /**
+ * @throws IOException
+ * @throws UnknownHostException
+ * @throws InterruptedException
+ * javax.net.ssl.SSLSessionBindingListener#valueBound(SSLSessionBindingEvent event)
+ */
+ public void test_valueBound() throws UnknownHostException, IOException,
+ InterruptedException {
+ SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
+ .createSocket();
+ SSLSession ss = sock.getSession();
+ mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
+ ss.putValue("test", sbl);
+ assertTrue("valueBound was not called.", sbl.boundDone);
+ }
+
+ /**
+ * @throws IOException
+ * @throws UnknownHostException
+ * javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event)
+ */
+ public void test_valueUnbound() throws UnknownHostException, IOException {
+ SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
+ .createSocket();
+ SSLSession ss = sock.getSession();
+ mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
+ ss.putValue("test", sbl);
+ ss.removeValue("test");
+ assertTrue("valueUnbound was not called.", sbl.unboundDone);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionContextTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionContextTest.java
new file mode 100644
index 0000000..aa95eb8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionContextTest.java
@@ -0,0 +1,95 @@
+package tests.api.javax.net.ssl;
+
+import junit.framework.TestCase;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSessionContext;
+
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Tests for <code>SSLSessionContext</code> class constructors and methods.
+ */
+public class SSLSessionContextTest extends TestCase {
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLSessionContex#getSessionCacheSize()
+ * javax.net.ssl.SSLSessionContex#setSessionCacheSize(int size)
+ */
+ public final void test_sessionCacheSize() throws NoSuchAlgorithmException, KeyManagementException {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ SSLSessionContext sc = context
+ .getClientSessionContext();
+ sc.setSessionCacheSize(10);
+ assertEquals("10 wasn't returned", 10, sc.getSessionCacheSize());
+ sc.setSessionCacheSize(5);
+ assertEquals("5 wasn't returned", 5, sc.getSessionCacheSize());
+
+ try {
+ sc.setSessionCacheSize(-1);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLSessionContex#getSessionTimeout()
+ * javax.net.ssl.SSLSessionContex#setSessionTimeout(int seconds)
+ */
+ public final void test_sessionTimeout() throws NoSuchAlgorithmException, KeyManagementException {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ SSLSessionContext sc = context
+ .getClientSessionContext();
+ sc.setSessionTimeout(100);
+ assertEquals("100 wasn't returned", 100, sc.getSessionTimeout());
+ sc.setSessionTimeout(5000);
+ assertEquals("5000 wasn't returned", 5000, sc.getSessionTimeout());
+
+ try {
+ sc.setSessionTimeout(-1);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLSessionContex#getSession(byte[] sessionId)
+ */
+ public final void test_getSession() throws NoSuchAlgorithmException, KeyManagementException {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ SSLSessionContext sc = context
+ .getClientSessionContext();
+ try {
+ sc.getSession(null);
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertNull(sc.getSession(new byte[5]));
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyManagementException
+ * javax.net.ssl.SSLSessionContex#getIds()
+ */
+ public final void test_getIds() throws NoSuchAlgorithmException, KeyManagementException {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, null, null);
+ SSLSessionContext sc = context
+ .getClientSessionContext();
+ assertFalse(sc.getIds().hasMoreElements());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionTest.java
new file mode 100644
index 0000000..2ba913d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSessionTest.java
@@ -0,0 +1,655 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import libcore.java.security.StandardNames;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionBindingEvent;
+import javax.net.ssl.SSLSessionBindingListener;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import junit.framework.TestCase;
+import libcore.io.Base64;
+import tests.api.javax.net.ssl.HandshakeCompletedEventTest.MyHandshakeListener;
+import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
+
+public class SSLSessionTest extends TestCase {
+
+ // set to true if on Android, false if on RI
+ boolean useBKS = true;
+
+ /**
+ * javax.net.ssl.SSLSession#getPeerHost()
+ * javax.net.ssl.SSLSession#getPeerPort()
+ */
+ public void test_getPeerHost() throws Exception {
+ SSLSession s = clientSession;
+ assertEquals(InetAddress.getLocalHost().getHostName(), s.getPeerHost());
+ assertEquals(serverSocket.getLocalPort(), s.getPeerPort());
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#invalidate()
+ * javax.net.ssl.SSLSession#isValid()
+ */
+ public void test_invalidate() {
+ SSLSession s = clientSession;
+ assertTrue(s.isValid());
+ s.invalidate();
+ assertFalse(s.isValid());
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getPeerPrincipal()
+ */
+ public void test_getPeerPrincipal() throws Exception {
+ Principal p1 = clientSession.getPeerPrincipal();
+ KeyStore store = server.getStore();
+ X509Certificate cert = (X509Certificate)store.getCertificate("mykey");
+ Principal p2 = cert.getSubjectX500Principal();
+ assertEquals(p1, p2);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getApplicationBufferSize()
+ */
+ public void test_getApplicationBufferSize() {
+ assertTrue(clientSession.getApplicationBufferSize() > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getCipherSuite()
+ */
+ public void test_getCipherSuite() {
+ // Identify the expected cipher suite from the expected list of cipher suites enabled by
+ // default.
+ // This test class initializes the server with an RSA key. Thus, only cipher suites that
+ // authenticate the server using RSA are expected to be used.
+ String expectedCipherSuite = null;
+ for (String cipherSuite : StandardNames.CIPHER_SUITES_DEFAULT) {
+ if (cipherSuite.contains("_RSA_")) {
+ expectedCipherSuite = cipherSuite;
+ break;
+ }
+ }
+ if (expectedCipherSuite == null) {
+ fail("Failed to identify expected cipher suite");
+ }
+ assertEquals(expectedCipherSuite, clientSession.getCipherSuite());
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getCreationTime()
+ */
+ public void test_getCreationTime() {
+ // check if creation time was in the last 10 seconds
+ long currentTime = System.currentTimeMillis();
+ long sessionTime = clientSession.getCreationTime();
+ long diff = currentTime - sessionTime;
+ assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000",
+ diff < 10000);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getId()
+ */
+ public void test_getId() {
+ byte[] id = clientSession.getId();
+ SSLSession sess = clientSslContext.getClientSessionContext().getSession(id);
+ assertNotNull("Could not find session for id " + id, sess);
+ assertEquals(clientSession, sess);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getLastAccessedTime()
+ */
+ public void test_getLastAccessedTime() {
+ // check if last access time was in the last 10 seconds
+ long currentTime = System.currentTimeMillis();
+ long sessionTime = clientSession.getLastAccessedTime();
+ long diff = currentTime - sessionTime;
+ assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000",
+ diff < 10000);
+ assertTrue ("diff should be < 10000 but is " + diff, diff < 10000);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getLocalCertificates()
+ */
+ public void test_getLocalCertificates() throws Exception {
+ KeyStore store = client.getStore();
+ Certificate cert = store.getCertificate("mykey");
+ Certificate[] certs = clientSession.getLocalCertificates();
+ assertEquals(cert, certs[0]);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getLocalPrincipal()
+ */
+ public void test_getLocalPrincipal() throws Exception {
+ Principal p1 = clientSession.getLocalPrincipal();
+ KeyStore store = client.getStore();
+ X509Certificate cert = (X509Certificate)store.getCertificate("mykey");
+ Principal p2 = cert.getSubjectX500Principal();
+ assertEquals(p1, p2);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getPacketBufferSize()
+ */
+ public void test_getPacketBufferSize() {
+ assertTrue(clientSession.getPacketBufferSize() > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getPeerCertificates()
+ */
+ public void test_getPeerCertificates() throws Exception {
+ Certificate[] res = clientSession.getPeerCertificates();
+ assertTrue(res.length > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getPeerCertificateChain()
+ */
+ public void test_getPeerCertificateChain() throws Exception {
+ javax.security.cert.X509Certificate[] res = clientSession.getPeerCertificateChain();
+ assertTrue(res.length > 0);
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getProtocol()
+ */
+ public void test_getProtocol() {
+ assertEquals("TLSv1.2", clientSession.getProtocol());
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getSessionContext()
+ */
+ public void test_getSessionContext() {
+ assertEquals(clientSession.getSessionContext(),
+ clientSslContext.getClientSessionContext());
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#putValue(String name, Object value)
+ * javax.net.ssl.SSLSession#removeValue(String name)
+ * javax.net.ssl.SSLSession#getValueNames()
+ */
+ public void test_putValue() {
+ SSLSession s = clientSession;
+ mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
+ assertNotNull(s.getValueNames());
+ assertEquals(0, s.getValueNames().length);
+ s.putValue("Name_01", sbl);
+ s.putValue("Name_02", sbl);
+ s.putValue("Name_03", sbl);
+ assertEquals(3, s.getValueNames().length);
+ s.removeValue("Name_01");
+ assertEquals(2, s.getValueNames().length);
+
+ try {
+ s.putValue(null, null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+ try {
+ s.putValue("ABC", null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+ try {
+ s.putValue(null, sbl);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+
+ try {
+ s.removeValue(null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSession#getValue(String name)
+ */
+ public void test_getValue() {
+ SSLSession s = clientSession;
+ mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
+
+ try {
+ s.getValue(null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ // expected
+ }
+
+ s.putValue("Name", sbl);
+ Object obj = s.getValue("Name");
+ assertTrue(obj instanceof SSLSessionBindingListener);
+ }
+
+ Thread serverThread, clientThread;
+ TestServer server;
+ TestClient client;
+
+ @Override
+ protected void setUp() throws Exception {
+ String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
+ String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
+ server = new TestServer(true, TestServer.CLIENT_AUTH_WANTED, serverKeys);
+ client = new TestClient(true, clientKeys);
+
+ serverThread = new Thread(server);
+ clientThread = new Thread(client);
+
+ serverThread.start();
+ try {
+ Thread.currentThread().sleep(1000);
+ clientThread.start();
+ } catch (InterruptedException e) {
+ fail("Could not create server or cient " + e.getMessage());
+ }
+ while (clientSession == null
+ && server.exception == null
+ && client.exception == null) {
+ try {
+ Thread.currentThread().sleep(500);
+ } catch (InterruptedException e) {
+ fail("couldn't create session");
+ }
+ }
+ if (server.exception != null) {
+ server.exception.printStackTrace();
+ }
+ assertNull("server thread has a pending exception: " + server.exception,
+ server.exception);
+ if (client.exception != null) {
+ client.exception.printStackTrace();
+ }
+ assertNull("client thread has a pending exception: " + client.exception,
+ client.exception);
+ assertNotNull("Could not initialize session", clientSession);
+ }
+
+ @Override
+ protected void tearDown() {
+ notFinished = false;
+ try {
+ serverThread.join();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ try {
+ clientThread.join();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+
+ // The server must have completed without an exception.
+ if (server.getException() != null) {
+ throw new RuntimeException(server.getException());
+ }
+
+ // The client must have completed without an exception.
+ if (client.getException() != null) {
+ throw new RuntimeException(client.getException());
+ }
+ }
+
+ public class mySSLSessionBindingListener implements
+ SSLSessionBindingListener {
+ mySSLSessionBindingListener() {
+ }
+ public void valueBound(SSLSessionBindingEvent event) {}
+ public void valueUnbound(SSLSessionBindingEvent event) {}
+ }
+
+ /**
+ * Defines the keystore contents for the server, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_BKS =
+ "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
+ + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
+ + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
+ + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
+ + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
+ + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
+ + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
+ + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
+ + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
+ + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
+ + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
+ + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
+ + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
+ + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
+ + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
+ + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
+ + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
+ + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
+ + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
+ + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
+ + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
+ + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
+ + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
+ + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
+
+ /**
+ * Defines the keystore contents for the client, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Client".
+ */
+ private static final String CLIENT_KEYS_BKS =
+ "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41"
+ + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
+ + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
+ + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw"
+ + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
+ + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu"
+ + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva"
+ + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD"
+ + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG"
+ + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F"
+ + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg"
+ + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx"
+ + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi"
+ + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD"
+ + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO"
+ + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz"
+ + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5"
+ + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8"
+ + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1"
+ + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9"
+ + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB"
+ + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9"
+ + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef"
+ + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
+
+ /**
+ * Defines the keystore contents for the server, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_JKS =
+ "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
+ + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
+ + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
+ + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
+ + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
+ + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
+ + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
+ + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
+ + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
+ + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
+ + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
+ + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
+ + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
+ + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
+ + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
+ + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
+ + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
+ + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
+ + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
+ + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
+ + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
+ + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
+ + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
+ + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
+
+ /**
+ * Defines the keystore contents for the client, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Client".
+ */
+ private static final String CLIENT_KEYS_JKS =
+ "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC"
+ + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5"
+ + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw"
+ + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY"
+ + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4"
+ + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit"
+ + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY"
+ + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O"
+ + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS"
+ + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4"
+ + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi"
+ + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL"
+ + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41"
+ + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV"
+ + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB"
+ + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5"
+ + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN"
+ + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w"
+ + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR"
+ + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5"
+ + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE"
+ + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng"
+ + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp"
+ + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
+
+
+ SSLServerSocket serverSocket;
+ MyHandshakeListener listener;
+ String host = "localhost";
+ boolean notFinished = true;
+ SSLSession clientSession = null;
+ SSLContext clientSslContext = null;
+ String testData = "PING";
+
+ private String PASSWORD = "android";
+
+ /**
+ * Implements a test SSL socket server. It waits for a connection on a given
+ * port, requests client authentication (if specified), reads from the socket,
+ * and writes to the socket.
+ */
+ class TestServer implements Runnable {
+
+ public static final int CLIENT_AUTH_NONE = 0;
+
+ public static final int CLIENT_AUTH_WANTED = 1;
+
+ public static final int CLIENT_AUTH_NEEDED = 2;
+
+ private TestTrustManager trustManager;
+
+ private Exception exception;
+
+ String keys;
+
+ private int clientAuth;
+
+ private boolean provideKeys;
+
+ private KeyStore store;
+
+ public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception {
+ this.keys = keys;
+ this.clientAuth = clientAuth;
+ this.provideKeys = provideKeys;
+
+ trustManager = new TestTrustManager();
+
+ store = provideKeys ? getKeyStore(keys) : null;
+ KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
+ TrustManager[] trustManagers = new TrustManager[] { trustManager };
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, null);
+
+ serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket();
+
+ if (clientAuth == CLIENT_AUTH_WANTED) {
+ serverSocket.setWantClientAuth(true);
+ } else if (clientAuth == CLIENT_AUTH_NEEDED) {
+ serverSocket.setNeedClientAuth(true);
+ } else {
+ serverSocket.setWantClientAuth(false);
+ }
+
+ serverSocket.bind(null);
+ }
+
+ public void run() {
+ try {
+ SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
+
+ InputStream istream = clientSocket.getInputStream();
+ byte[] buffer = new byte[1024];
+ istream.read(buffer);
+
+ OutputStream ostream = clientSocket.getOutputStream();
+ ostream.write(testData.getBytes());
+ ostream.flush();
+
+ while (notFinished) {
+ Thread.currentThread().sleep(500);
+ }
+
+ clientSocket.close();
+ serverSocket.close();
+
+ } catch (Exception ex) {
+ exception = ex;
+ }
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public javax.security.cert.X509Certificate[] getChain() {
+ return trustManager.getChain();
+ }
+
+ public KeyStore getStore() {
+ return store;
+ }
+
+ }
+
+ /**
+ * Implements a test SSL socket client. It opens a connection to localhost on
+ * a given port, writes to the socket, and reads from the socket.
+ */
+ class TestClient implements Runnable {
+
+ private TestTrustManager trustManager;
+
+ private Exception exception;
+
+ private String keys;
+
+ private boolean provideKeys;
+
+ private KeyStore store;
+
+ public TestClient(boolean provideKeys, String keys) {
+ this.keys = keys;
+ this.provideKeys = provideKeys;
+
+ trustManager = new TestTrustManager();
+ }
+
+ public void run() {
+ try {
+ store = provideKeys ? getKeyStore(keys) : null;
+ KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
+ TrustManager[] trustManagers = new TrustManager[] { trustManager };
+
+ clientSslContext = SSLContext.getInstance("TLS");
+ clientSslContext.init(keyManagers, trustManagers, null);
+
+ SSLSocket socket = (SSLSocket)clientSslContext.getSocketFactory().createSocket();
+
+ socket.connect(serverSocket.getLocalSocketAddress());
+ OutputStream ostream = socket.getOutputStream();
+ ostream.write(testData.getBytes());
+ ostream.flush();
+
+ InputStream istream = socket.getInputStream();
+ byte[] buffer = new byte[1024];
+ istream.read(buffer);
+
+ clientSession = socket.getSession();
+ while (notFinished) {
+ Thread.currentThread().sleep(500);
+ }
+ socket.close();
+
+ } catch (Exception ex) {
+ exception = ex;
+ }
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public javax.security.cert.X509Certificate[] getChain() {
+ return trustManager.getChain();
+ }
+
+ public KeyStore getStore() {
+ return store;
+ }
+ }
+
+ /**
+ * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
+ * for the result.
+ */
+ private KeyStore getKeyStore(String keys) throws Exception {
+ byte[] bytes = Base64.decode(keys.getBytes());
+ InputStream inputStream = new ByteArrayInputStream(bytes);
+
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(inputStream, PASSWORD.toCharArray());
+ inputStream.close();
+ return keyStore;
+ }
+
+ /**
+ * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
+ * for the result.
+ */
+ private KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
+ String algorithm = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
+ keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
+
+ return keyManagerFactory.getKeyManagers();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketFactoryTest.java
new file mode 100644
index 0000000..e890032
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketFactoryTest.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLSocketFactory;
+
+import junit.framework.TestCase;
+
+public class SSLSocketFactoryTest extends TestCase {
+
+ private ServerSocket ss;
+
+ protected int startServer(String name) {
+ try {
+ ss = new ServerSocket(0);
+ } catch (IOException e) {
+ fail(name + ": " + e);
+ }
+ return ss.getLocalPort();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocketFactory#SSLSocketFactory()
+ */
+ public void test_Constructor() {
+ try {
+ SocketFactory sf = SSLSocketFactory.getDefault();
+ assertTrue(sf instanceof SSLSocketFactory);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocketFactory#getDefault()
+ */
+ public void test_getDefault() {
+ assertNotNull("Incorrect default socket factory",
+ SSLSocketFactory.getDefault());
+ }
+
+ /**
+ * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
+ */
+ public void test_createSocket() throws Exception {
+ SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
+ int sport = startServer("test_createSocket()");
+ int[] invalid = {
+ Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE
+ };
+
+
+ Socket st = new Socket("localhost", sport);
+ Socket s = sf.createSocket(st, "localhost", sport, false);
+ assertFalse(s.isClosed());
+
+ st = new Socket("localhost", sport);
+ s = sf.createSocket(st, "localhost", sport, true);
+ s.close();
+ assertTrue(st.isClosed());
+
+ try {
+ sf.createSocket(null, "localhost", sport, true);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ for (int i = 0; i < invalid.length; i++) {
+ try {
+ s = sf.createSocket(new Socket(), "localhost", 1080, false);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ try {
+ st = new Socket("1.2.3.4hello", sport);
+ s = sf.createSocket(st, "1.2.3.4hello", sport, false);
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites()
+ */
+ public void test_getDefaultCipherSuites() {
+ try {
+ SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
+ assertTrue("no default cipher suites returned",
+ sf.getDefaultCipherSuites().length > 0);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites()
+ */
+ public void test_getSupportedCipherSuites() {
+ try {
+ SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
+ assertTrue("no supported cipher suites returned",
+ sf.getSupportedCipherSuites().length > 0);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketTest.java
new file mode 100644
index 0000000..950d534
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/SSLSocketTest.java
@@ -0,0 +1,631 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import dalvik.annotation.AndroidOnly;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import javax.net.ssl.HandshakeCompletedEvent;
+import javax.net.ssl.HandshakeCompletedListener;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.security.cert.X509Certificate;
+import junit.framework.TestCase;
+import libcore.io.Base64;
+import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
+import libcore.java.security.StandardNames;
+
+public class SSLSocketTest extends TestCase {
+
+ public class HandshakeCL implements HandshakeCompletedListener {
+ public void handshakeCompleted(HandshakeCompletedEvent event) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#SSLSocket()
+ */
+ public void testConstructor() throws Exception {
+ SSLSocket ssl = getSSLSocket();
+ assertNotNull(ssl);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port)
+ */
+ public void testConstructor_InetAddressI() throws Exception {
+ int sport = startServer("Cons InetAddress,I");
+ int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
+
+ SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport);
+ assertNotNull(ssl);
+ assertEquals(sport, ssl.getPort());
+ ssl.close();
+
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), sport + 1);
+ fail();
+ } catch (IOException expected) {
+ }
+
+ for (int i = 0; i < invalidPort.length; i++) {
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), invalidPort[i]);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port,
+ * InetAddress clientAddress, int clientPort)
+ */
+ public void testConstructor_InetAddressIInetAddressI() throws Exception {
+ int sport = startServer("Cons InetAddress,I,InetAddress,I");
+
+ SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
+ InetAddress.getLocalHost(), 0);
+ assertNotNull(ssl);
+ assertEquals(sport, ssl.getPort());
+ ssl.close();
+
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
+ fail();
+ } catch (IOException expected) {
+ }
+
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), -1, InetAddress.getLocalHost(), sport + 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), sport, InetAddress.getLocalHost(), -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), Integer.MIN_VALUE,
+ InetAddress.getLocalHost(), sport + 1);
+ fail();
+ } catch (IOException expectedOnRI) {
+ assertTrue(StandardNames.IS_RI);
+ } catch (IllegalArgumentException expectedOnAndroid) {
+ assertFalse(StandardNames.IS_RI);
+ }
+ try {
+ getSSLSocket(InetAddress.getLocalHost(), sport,
+ InetAddress.getLocalHost(), Integer.MAX_VALUE);
+ fail();
+ } catch (IllegalArgumentException expectedOnAndroid) {
+ assertFalse(StandardNames.IS_RI);
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#SSLSocket(String host, int port)
+ */
+ public void testConstructor_StringI() throws Exception {
+ int sport = startServer("Cons String,I");
+ int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
+
+ SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport);
+ assertNotNull(ssl);
+ assertEquals(sport, ssl.getPort());
+ ssl.close();
+
+ try {
+ getSSLSocket("localhost", 8082);
+ fail();
+ } catch (IOException expected) {
+ }
+
+ for (int i = 0; i < invalidPort.length; i++) {
+ try {
+ getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i]);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ getSSLSocket("1.2.3.4hello", sport);
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#SSLSocket(String host, int port, InetAddress clientAddress,
+ * int clientPort)
+ */
+ public void testConstructor_StringIInetAddressI() throws Exception {
+ int sport = startServer("Cons String,I,InetAddress,I");
+ int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
+
+ SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
+ InetAddress.getLocalHost(), 0);
+ assertNotNull(ssl);
+ assertEquals(sport, ssl.getPort());
+
+ try {
+ getSSLSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
+ fail();
+ } catch (IOException expected) {
+ }
+
+ for (int i = 0; i < invalidPort.length; i++) {
+ try {
+ getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i],
+ InetAddress.getLocalHost(), 0);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
+ InetAddress.getLocalHost(), invalidPort[i]);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ try {
+ getSSLSocket("1.2.3.4hello", sport, InetAddress.getLocalHost(), 0);
+ fail();
+ } catch (UnknownHostException expected) {
+ }
+ }
+
+ public void test_creationStressTest() throws Exception {
+ // Test the default codepath, which uses /dev/urandom.
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, null, null);
+ for (int i = 0; i < 2048; ++i) {
+ sslContext.getSocketFactory().createSocket().close();
+ }
+
+ // Test the other codepath, which copies a seed from a byte[].
+ sslContext.init(null, null, new SecureRandom());
+ for (int i = 0; i < 2048; ++i) {
+ sslContext.getSocketFactory().createSocket().close();
+ }
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener)
+ */
+ @AndroidOnly("RI doesn't throw the specified IAE")
+ public void test_addHandshakeCompletedListener() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ HandshakeCompletedListener ls = new HandshakeCL();
+ try {
+ ssl.addHandshakeCompletedListener(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.addHandshakeCompletedListener(ls);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
+ */
+ public void test_removeHandshakeCompletedListener() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ HandshakeCompletedListener ls = new HandshakeCL();
+ try {
+ ssl.removeHandshakeCompletedListener(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ ssl.removeHandshakeCompletedListener(ls);
+ } catch (IllegalArgumentException expected) {
+ }
+
+ ssl.addHandshakeCompletedListener(ls);
+ ssl.removeHandshakeCompletedListener(ls);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag)
+ * javax.net.ssl.SSLSocket#getEnableSessionCreation()
+ */
+ public void test_EnableSessionCreation() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ assertTrue(ssl.getEnableSessionCreation());
+ ssl.setEnableSessionCreation(false);
+ assertFalse(ssl.getEnableSessionCreation());
+ ssl.setEnableSessionCreation(true);
+ assertTrue(ssl.getEnableSessionCreation());
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#setNeedClientAuth(boolean need)
+ * javax.net.ssl.SSLSocket#getNeedClientAuthCreation()
+ */
+ public void test_NeedClientAuth() throws UnknownHostException, IOException {
+ SSLSocket ssl = getSSLSocket();
+ ssl.setNeedClientAuth(true);
+ assertTrue(ssl.getNeedClientAuth());
+ ssl.setNeedClientAuth(false);
+ assertFalse(ssl.getNeedClientAuth());
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#setWantClientAuth(boolean want)
+ * javax.net.ssl.SSLSocket#getWantClientAuthCreation()
+ */
+ public void test_WantClientAuth() throws UnknownHostException, IOException {
+ SSLSocket ssl = getSSLSocket();
+ ssl.setWantClientAuth(true);
+ assertTrue(ssl.getWantClientAuth());
+ ssl.setWantClientAuth(false);
+ assertFalse(ssl.getWantClientAuth());
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getSupportedProtocols()
+ */
+ public void test_getSupportedProtocols() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ String[] res = ssl.getSupportedProtocols();
+ assertTrue("No supported protocols found", res.length > 0);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getEnabledProtocols()
+ * javax.net.ssl.SSLSocket#setEnabledProtocols(String[] protocols)
+ */
+ public void test_EnabledProtocols() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ try {
+ ssl.setEnabledProtocols(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.setEnabledProtocols(new String[] {});
+ try {
+ ssl.setEnabledProtocols(new String[] {"blubb"});
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.setEnabledProtocols(ssl.getEnabledProtocols());
+ String[] res = ssl.getEnabledProtocols();
+ assertEquals("no enabled protocols set",
+ ssl.getEnabledProtocols().length, res.length);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getSession()
+ */
+ public void test_getSession() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ assertNotNull(ssl.getSession());
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getSupportedCipherSuites()
+ */
+ public void test_getSupportedCipherSuites() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ String[] res = ssl.getSupportedCipherSuites();
+ assertTrue("no supported cipher suites", res.length > 0);
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getEnabledCipherSuites()
+ * javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[] suites)
+ */
+ public void test_EnabledCipherSuites() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ try {
+ ssl.setEnabledCipherSuites(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.setEnabledCipherSuites(new String[] {});
+ try {
+ ssl.setEnabledCipherSuites(new String[] {"blubb"});
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
+ String[] res = ssl.getEnabledCipherSuites();
+ assertNotNull("NULL result", res);
+ assertEquals("not all supported cipher suites were enabled",
+ Arrays.asList(ssl.getSupportedCipherSuites()),
+ Arrays.asList(res));
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#getUseClientMode()
+ * javax.net.ssl.SSLSocket#setUseClientMode(boolean mode)
+ */
+ public void test_UseClientMode() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ assertTrue(ssl.getUseClientMode());
+ ssl.setUseClientMode(false);
+ assertFalse(ssl.getUseClientMode());
+ ssl.close();
+
+ ssl = getSSLSocket("localhost", startServer("UseClientMode"));
+ try {
+ ssl.startHandshake();
+ } catch (IOException ioe) {
+ //fail(ioe + " was thrown for method startHandshake()");
+ }
+ try {
+ ssl.setUseClientMode(false);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ ssl.close();
+ }
+
+ /**
+ * javax.net.ssl.SSLSocket#startHandshake()
+ */
+ public void test_startHandshake() throws IOException {
+ SSLSocket ssl = getSSLSocket();
+ try {
+ ssl.startHandshake();
+ fail();
+ } catch (IOException expected) {
+ }
+ ssl.close();
+ }
+
+ private boolean useBKS = !StandardNames.IS_RI;
+
+ private String PASSWORD = "android";
+
+ private boolean serverReady = false;
+
+ /**
+ * Defines the keystore contents for the server, BKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_BKS = ""
+ + "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
+ + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
+ + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
+ + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
+ + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
+ + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
+ + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
+ + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
+ + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
+ + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
+ + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
+ + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
+ + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
+ + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
+ + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
+ + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
+ + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
+ + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
+ + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
+ + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
+ + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
+ + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
+ + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
+ + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
+
+ /**
+ * Defines the keystore contents for the server, JKS version. Holds just a
+ * single self-generated key. The subject name is "Test Server".
+ */
+ private static final String SERVER_KEYS_JKS = ""
+ + "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
+ + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
+ + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
+ + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
+ + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
+ + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
+ + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
+ + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
+ + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
+ + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
+ + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
+ + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
+ + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
+ + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
+ + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
+ + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
+ + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
+ + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
+ + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
+ + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
+ + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
+ + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
+ + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
+ + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
+
+ protected int startServer(String name) {
+ String keys = useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS;
+ TestServer server = new TestServer(true, keys);
+ Thread serverThread = new Thread(server);
+ serverThread.start();
+ try {
+ while (!serverReady) {
+ Exception e = server.getException();
+ if (e != null) {
+ throw new AssertionError(e);
+ }
+ Thread.currentThread().sleep(50);
+ }
+ // give the server 100 millis to accept
+ Thread.currentThread().sleep(100);
+ } catch (InterruptedException ignore) {
+ }
+ return server.sport;
+ }
+
+ /**
+ * Implements a test SSL socket server. It wait for a connection on a given
+ * port, requests client authentication (if specified), and read 256 bytes
+ * from the socket.
+ */
+ class TestServer implements Runnable {
+
+ public static final int CLIENT_AUTH_NONE = 0;
+
+ public static final int CLIENT_AUTH_WANTED = 1;
+
+ public static final int CLIENT_AUTH_NEEDED = 2;
+
+ private TestTrustManager trustManager;
+
+ private Exception exception;
+
+ String keys;
+
+ private boolean provideKeys;
+
+ int sport;
+
+ public TestServer(boolean provideKeys, String keys) {
+ this.keys = keys;
+ this.provideKeys = provideKeys;
+
+ trustManager = new TestTrustManager();
+ }
+
+ public void run() {
+ try {
+ KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
+ TrustManager[] trustManagers = new TrustManager[] { trustManager };
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, null);
+
+ SSLServerSocket serverSocket = (SSLServerSocket)
+ sslContext.getServerSocketFactory().createServerSocket();
+ try {
+ serverSocket.bind(new InetSocketAddress(0));
+ sport = serverSocket.getLocalPort();
+ serverReady = true;
+
+ SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
+
+ try {
+ InputStream stream = clientSocket.getInputStream();
+ try {
+ for (int i = 0; i < 256; i++) {
+ int j = stream.read();
+ if (i != j) {
+ throw new RuntimeException("Error reading socket, expected " + i
+ + ", got " + j);
+ }
+ }
+ } finally {
+ stream.close();
+ }
+ } finally {
+ clientSocket.close();
+ }
+ } finally {
+ serverSocket.close();
+ }
+ } catch (Exception ex) {
+ exception = ex;
+ }
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public X509Certificate[] getChain() {
+ return trustManager.getChain();
+ }
+
+ }
+
+ /**
+ * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
+ * for the result.
+ */
+ private KeyManager[] getKeyManagers(String keys) throws Exception {
+ byte[] bytes = Base64.decode(keys.getBytes());
+ InputStream inputStream = new ByteArrayInputStream(bytes);
+
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(inputStream, PASSWORD.toCharArray());
+ inputStream.close();
+
+ String algorithm = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
+ keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
+
+ return keyManagerFactory.getKeyManagers();
+ }
+
+ private SSLSocket getSSLSocket() throws IOException {
+ return (SSLSocket) SSLSocketFactory.getDefault().createSocket();
+ }
+
+ private SSLSocket getSSLSocket(InetAddress host, int port) throws IOException {
+ return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
+ }
+
+ private SSLSocket getSSLSocket(String host, int port) throws UnknownHostException, IOException {
+ return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
+ }
+
+ private SSLSocket getSSLSocket(InetAddress host, int port, InetAddress localHost, int localPort)
+ throws IOException {
+ return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
+ port,
+ localHost,
+ localPort);
+ }
+
+ private SSLSocket getSSLSocket(String host, int port, InetAddress localHost, int localPort)
+ throws UnknownHostException, IOException {
+ return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
+ port,
+ localHost,
+ localPort);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory1Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory1Test.java
new file mode 100644
index 0000000..23b24e4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory1Test.java
@@ -0,0 +1,519 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import dalvik.annotation.KnownFailure;
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.cert.CertificateException;
+import java.security.cert.PKIXBuilderParameters;
+import java.security.cert.TrustAnchor;
+import java.security.cert.X509CertSelector;
+import java.util.HashSet;
+import java.util.Set;
+import javax.net.ssl.CertPathTrustManagerParameters;
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.TrustManagerFactorySpi;
+import junit.framework.TestCase;
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.security.tests.support.TestKeyPair;
+import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
+
+/**
+ * Tests for <code>TrustManagerFactory</code> class constructors and methods.
+ *
+ */
+public class TrustManagerFactory1Test extends TestCase {
+
+ private static final String srvTrustManagerFactory = "TrustManagerFactory";
+
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+
+ private static String DEFAULT_ALGORITHM;
+ private static String DEFAULT_PROVIDER_NAME;
+ private static Provider DEFAULT_PROVIDER;
+ private static String[] VALID_VALUES;
+
+ private static String getDefaultAlgorithm() {
+ init();
+ return DEFAULT_ALGORITHM;
+ }
+ private static String getDefaultProviderName() {
+ init();
+ return DEFAULT_PROVIDER_NAME;
+ }
+ private static Provider getDefaultProvider() {
+ init();
+ return DEFAULT_PROVIDER;
+ }
+ private static String[] getValidValues() {
+ init();
+ return VALID_VALUES;
+ }
+
+ private static synchronized void init() {
+ if (DEFAULT_ALGORITHM != null) {
+ return;
+ }
+ DEFAULT_ALGORITHM = Security.getProperty("ssl.TrustManagerFactory.algorithm");
+ assertNotNull(DEFAULT_ALGORITHM);
+ DEFAULT_PROVIDER = SpiEngUtils.isSupport(DEFAULT_ALGORITHM, srvTrustManagerFactory);
+ DEFAULT_PROVIDER_NAME = DEFAULT_PROVIDER.getName();
+ VALID_VALUES = new String[] { DEFAULT_ALGORITHM,
+ DEFAULT_ALGORITHM.toUpperCase(),
+ DEFAULT_ALGORITHM.toLowerCase() };
+ }
+
+ private static TrustManagerFactory[] createTMFac() throws Exception {
+ return new TrustManagerFactory[] {
+ TrustManagerFactory.getInstance(getDefaultAlgorithm()),
+ TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider()),
+ TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProviderName())
+ };
+ }
+
+ public void test_ConstructorLjavax_net_ssl_TrustManagerFactorySpiLjava_security_ProviderLjava_lang_String()
+ throws NoSuchAlgorithmException {
+ TrustManagerFactorySpi spi = new MyTrustManagerFactorySpi();
+ TrustManagerFactory tmF = new myTrustManagerFactory(spi, getDefaultProvider(),
+ getDefaultAlgorithm());
+ assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
+ assertEquals("Incorrect algorithm", tmF.getAlgorithm(),
+ getDefaultAlgorithm());
+ assertEquals("Incorrect provider", tmF.getProvider(), getDefaultProvider());
+ assertNull("Incorrect result", tmF.getTrustManagers());
+
+ tmF = new myTrustManagerFactory(null, null, null);
+ assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
+ assertNull("Provider must be null", tmF.getProvider());
+ assertNull("Algorithm must be null", tmF.getAlgorithm());
+ try {
+ tmF.getTrustManagers();
+ fail("NullPointerException must be thrown");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * Test for <code>getAlgorithm()</code> method
+ * Assertion: returns the algorithm name of this object
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ */
+ public void test_getAlgorithm()
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ assertEquals("Incorrect algorithm",
+ getDefaultAlgorithm(),
+ TrustManagerFactory
+ .getInstance(getDefaultAlgorithm()).getAlgorithm());
+ assertEquals("Incorrect algorithm",
+ getDefaultAlgorithm(),
+ TrustManagerFactory
+ .getInstance(getDefaultAlgorithm(), getDefaultProviderName())
+ .getAlgorithm());
+ assertEquals("Incorrect algorithm",
+ getDefaultAlgorithm(),
+ TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider())
+ .getAlgorithm());
+ }
+
+ /**
+ * Test for <code>getDefaultAlgorithm()</code> method
+ * Assertion: returns value which is specifoed in security property
+ */
+ public void test_getDefaultAlgorithm() {
+ String def = TrustManagerFactory.getDefaultAlgorithm();
+ if (getDefaultAlgorithm() == null) {
+ assertNull("DefaultAlgorithm must be null", def);
+ } else {
+ assertEquals("Invalid default algorithm", def, getDefaultAlgorithm());
+ }
+ String defA = "Proba.trustmanagerfactory.defaul.type";
+ Security.setProperty("ssl.TrustManagerFactory.algorithm", defA);
+ assertEquals("Incorrect getDefaultAlgorithm()",
+ TrustManagerFactory.getDefaultAlgorithm(), defA);
+ if (def == null) {
+ def = "";
+ }
+ Security.setProperty("ssl.TrustManagerFactory.algorithm", def);
+ assertEquals("Incorrect getDefaultAlgorithm()",
+ TrustManagerFactory.getDefaultAlgorithm(), def);
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertions: returns security property "ssl.TrustManagerFactory.algorithm";
+ * returns instance of TrustManagerFactory
+ */
+ public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
+ for (String validValue : getValidValues()) {
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue);
+ assertTrue("Not TrustManagerFactory object",
+ trustMF instanceof TrustManagerFactory);
+ assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_String02() {
+ try {
+ TrustManagerFactory.getInstance(null);
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
+ } catch (NullPointerException expected) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
+ .concat(invalidValues[i]));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion: throws IllegalArgumentException when provider is null
+ * or empty
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws Exception {
+ for (String validValue : getValidValues()) {
+ try {
+ TrustManagerFactory.getInstance(validValue, (String) null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ TrustManagerFactory.getInstance(validValue, "");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws Exception {
+ try {
+ TrustManagerFactory.getInstance(null, getDefaultProviderName());
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
+ } catch (NullPointerException expected) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i],
+ getDefaultProviderName());
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion: throws NoSuchProviderException when provider has
+ * invalid value
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws Exception {
+ for (String invalidValue : invalidValues) {
+ for (String validValue : getValidValues()) {
+ try {
+ TrustManagerFactory.getInstance(validValue, invalidValue);
+ fail("NoSuchProviderException must be thrown (algorithm: "
+ .concat(validValue).concat(" provider: ")
+ .concat(invalidValue).concat(")"));
+ } catch (NoSuchProviderException expected) {
+ assertFalse("".equals(invalidValue));
+ } catch (IllegalArgumentException expected) {
+ assertEquals("", invalidValue);
+ }
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertion: returns instance of TrustManagerFactory
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws Exception {
+ for (String validValue : getValidValues()) {
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue,
+ getDefaultProviderName());
+ assertTrue("Not TrustManagerFactory object",
+ trustMF instanceof TrustManagerFactory);
+ assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
+ assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider());
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion: throws IllegalArgumentException when provider is null
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws Exception {
+ for (String validValue : getValidValues()) {
+ try {
+ TrustManagerFactory.getInstance(validValue, (Provider) null);
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
+ try {
+ TrustManagerFactory.getInstance(null, getDefaultProvider());
+ fail("");
+ } catch (NoSuchAlgorithmException expected) {
+ } catch (NullPointerException expected) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i],
+ getDefaultProvider());
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertion: returns instance of TrustManagerFactory
+ */
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws Exception {
+ for (String validValue : getValidValues()) {
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue,
+ getDefaultProvider());
+ assertTrue("Not TrustManagerFactory object",
+ trustMF instanceof TrustManagerFactory);
+ assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
+ assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider());
+ }
+ }
+
+ /**
+ * Test for <code>getProvider()</code>
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ */
+ public void test_getProvider()
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ assertEquals("Incorrect provider",
+ getDefaultProvider(),
+ TrustManagerFactory
+ .getInstance(getDefaultAlgorithm()).getProvider());
+ assertEquals("Incorrect provider",
+ getDefaultProvider(),
+ TrustManagerFactory
+ .getInstance(getDefaultAlgorithm(), getDefaultProviderName())
+ .getProvider());
+ assertEquals("Incorrect provider",
+ getDefaultProvider(),
+ TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider())
+ .getProvider());
+ }
+
+ /**
+ * Test for <code>geTrustManagers()</code>
+ * @throws KeyStoreException
+ * @throws IOException
+ * @throws CertificateException
+ * @throws NoSuchAlgorithmException
+ */
+ public void test_getTrustManagers() {
+ try {
+ TrustManagerFactory trustMF = TrustManagerFactory.getInstance(getDefaultAlgorithm());
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ trustMF.init(ks);
+ TrustManager[] tm = trustMF.getTrustManagers();
+ assertNotNull("Result has not be null", tm);
+ assertTrue("Length of result TrustManager array should not be 0",
+ (tm.length > 0));
+ } catch (Exception ex) {
+ fail("Unexpected exception " + ex.toString());
+ }
+ }
+
+ /**
+ * Test for <code>init(KeyStore keyStore)</code>
+ * Assertion: call method with null parameter
+ */
+ public void test_initLjava_security_KeyStore_01() throws Exception {
+ KeyStore ksNull = null;
+ TrustManagerFactory[] trustMF = createTMFac();
+ assertNotNull("TrustManagerFactory objects were not created", trustMF);
+ // null parameter
+ try {
+ trustMF[0].init(ksNull);
+ } catch (Exception ex) {
+ fail(ex + " unexpected exception was thrown for null parameter");
+ }
+ }
+
+ /**
+ * Test for <code>init(KeyStore keyStore)</code>
+ * Assertion: call method with not null parameter
+ */
+ public void test_initLjava_security_KeyStore_02() throws Exception {
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ TrustManagerFactory[] trustMF = createTMFac();
+ assertNotNull("TrustManagerFactory objects were not created", trustMF);
+
+ // not null parameter
+ trustMF[0].init(ks);
+ }
+
+ /**
+ * Test for <code>init(ManagerFactoryParameters params)</code>
+ * Assertion:
+ * throws InvalidAlgorithmParameterException when params is null
+ */
+ @KnownFailure("ManagerFactoryParameters object is not supported "
+ + "and InvalidAlgorithmParameterException was thrown.")
+ public void test_initLjavax_net_ssl_ManagerFactoryParameters() throws Exception {
+ ManagerFactoryParameters par = null;
+ TrustManagerFactory[] trustMF = createTMFac();
+ assertNotNull("TrustManagerFactory objects were not created", trustMF);
+ for (int i = 0; i < trustMF.length; i++) {
+ try {
+ trustMF[i].init(par);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ }
+
+ String keyAlg = "DSA";
+ String validCaNameRfc2253 = ("CN=Test CA,"
+ + "OU=Testing Division,"
+ + "O=Test It All,"
+ + "L=Test Town,"
+ + "ST=Testifornia,"
+ + "C=Testland");
+
+ try {
+ KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ kStore.load(null, null);
+ PublicKey pk = new TestKeyPair(keyAlg).getPublic();
+ TrustAnchor ta = new TrustAnchor(validCaNameRfc2253, pk, getFullEncoding());
+ Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
+ trustAnchors.add(ta);
+ X509CertSelector xcs = new X509CertSelector();
+ PKIXBuilderParameters pkixBP = new PKIXBuilderParameters(trustAnchors, xcs);
+ CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pkixBP);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(getDefaultAlgorithm());
+ try {
+ tmf.init(cptmp);
+ } catch (Exception ex) {
+ fail(ex + " was thrown for init(ManagerFactoryParameters spec)");
+ }
+ } catch (Exception e) {
+ fail("Unexpected exception for configuration: " + e);
+ }
+
+ }
+
+ private static final byte[] getFullEncoding() {
+ // DO NOT MODIFY!
+ return new byte[] {
+ (byte)0x30,(byte)0x81,(byte)0x8c,(byte)0xa0,
+ (byte)0x44,(byte)0x30,(byte)0x16,(byte)0x86,
+ (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
+ (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
+ (byte)0x66,(byte)0x6f,(byte)0x6f,(byte)0x2e,
+ (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
+ (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
+ (byte)0x01,(byte)0x30,(byte)0x16,(byte)0x86,
+ (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
+ (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
+ (byte)0x62,(byte)0x61,(byte)0x72,(byte)0x2e,
+ (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
+ (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
+ (byte)0x01,(byte)0x30,(byte)0x12,(byte)0x86,
+ (byte)0x0a,(byte)0x66,(byte)0x69,(byte)0x6c,
+ (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
+ (byte)0x6d,(byte)0x75,(byte)0x75,(byte)0x80,
+ (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
+ (byte)0x01,(byte)0xa1,(byte)0x44,(byte)0x30,
+ (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
+ (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
+ (byte)0x2f,(byte)0x2f,(byte)0x66,(byte)0x6f,
+ (byte)0x6f,(byte)0x2e,(byte)0x63,(byte)0x6f,
+ (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
+ (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
+ (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
+ (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
+ (byte)0x2f,(byte)0x2f,(byte)0x62,(byte)0x61,
+ (byte)0x72,(byte)0x2e,(byte)0x63,(byte)0x6f,
+ (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
+ (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
+ (byte)0x12,(byte)0x86,(byte)0x0a,(byte)0x68,
+ (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
+ (byte)0x2f,(byte)0x2f,(byte)0x6d,(byte)0x75,
+ (byte)0x75,(byte)0x80,(byte)0x01,(byte)0x00,
+ (byte)0x81,(byte)0x01,(byte)0x01
+ };
+ }
+}
+
+/**
+ * Addifional class to verify TrustManagerFactory constructor
+ */
+
+class myTrustManagerFactory extends TrustManagerFactory {
+ public myTrustManagerFactory(TrustManagerFactorySpi spi, Provider prov,
+ String alg) {
+ super(spi, prov, alg);
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory2Test.java
new file mode 100644
index 0000000..0c0760f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactory2Test.java
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Security;
+
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
+import junit.framework.TestCase;
+
+/**
+ * Tests for TrustManagerFactory class constructors and methods
+ *
+ */
+public class TrustManagerFactory2Test extends TestCase {
+ private static final String srvTrustManagerFactory = "TrustManagerFactory";
+ private static final String defaultAlg = "TMF";
+ private static final String TrustManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi";
+
+ private static final String[] invalidValues = SpiEngUtils.invalidValues;
+
+ private static final String[] validValues;
+
+ static {
+ validValues = new String[4];
+ validValues[0] = defaultAlg;
+ validValues[1] = defaultAlg.toLowerCase();
+ validValues[2] = "Tmf";
+ validValues[3] = "tMF";
+ }
+
+ Provider mProv;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ mProv = (new SpiEngUtils()).new MyProvider("MyTMFProvider",
+ "Provider for testing", srvTrustManagerFactory.concat(".")
+ .concat(defaultAlg), TrustManagerFactoryProviderClass);
+ Security.insertProviderAt(mProv, 1);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ Security.removeProvider(mProv.getName());
+ }
+
+ private void checkResult(TrustManagerFactory tmf) throws Exception {
+ KeyStore kStore = null;
+ ManagerFactoryParameters mfp = null;
+
+ try {
+ tmf.init(kStore);
+ fail("KeyStoreException must be thrown");
+ } catch (KeyStoreException e) {
+ }
+ try {
+ tmf.init(mfp);
+ fail("InvalidAlgorithmParameterException must be thrown");
+ } catch (InvalidAlgorithmParameterException e) {
+ }
+ assertNull("getTrustManagers() should return null object", tmf
+ .getTrustManagers());
+
+ try {
+ kStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ kStore.load(null, null);
+ } catch (KeyStoreException e) {
+ fail("default keystore is not supported");
+ return;
+ }
+ tmf.init(kStore);
+ mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(null);
+ try {
+ tmf.init(mfp);
+ fail("RuntimeException must be thrown");
+ } catch (RuntimeException e) {
+ assertTrue("Incorrect exception", e.getCause() instanceof KeyStoreException);
+ }
+ mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(kStore);
+ tmf.init(mfp);
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm)</code> method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * returns TrustManagerFactory object
+ */
+ public void test_getInstanceLjava_lang_String() throws Exception {
+ try {
+ TrustManagerFactory.getInstance(null);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i]);
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ TrustManagerFactory tmf;
+ for (int i = 0; i < validValues.length; i++) {
+ tmf = TrustManagerFactory.getInstance(validValues[i]);
+ assertTrue("Not instanceof TrustManagerFactory object",
+ tmf instanceof TrustManagerFactory);
+ assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", tmf.getProvider(), mProv);
+ checkResult(tmf);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, String provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * throws IllegalArgumentException when provider is null or empty;
+ * throws NoSuchProviderException when provider is available;
+ * returns TrustManagerFactory object
+ */
+ public void test_getInstanceLjava_lang_StringLjava_lang_String() throws Exception {
+ try {
+ TrustManagerFactory.getInstance(null, mProv.getName());
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i], mProv
+ .getName());
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ String prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ TrustManagerFactory.getInstance(validValues[i], "");
+ fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ for (int i = 0; i < validValues.length; i++) {
+ for (int j = 1; j < invalidValues.length; j++) {
+ try {
+ TrustManagerFactory.getInstance(validValues[i],
+ invalidValues[j]);
+ fail("NoSuchProviderException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(" provider: ")
+ .concat(invalidValues[j]).concat(")"));
+ } catch (NoSuchProviderException e) {
+ }
+ }
+ }
+ TrustManagerFactory tmf;
+ for (int i = 0; i < validValues.length; i++) {
+ tmf = TrustManagerFactory.getInstance(validValues[i], mProv
+ .getName());
+ assertTrue("Not instanceof TrustManagerFactory object",
+ tmf instanceof TrustManagerFactory);
+ assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", tmf.getProvider().getName(),
+ mProv.getName());
+ checkResult(tmf);
+ }
+ }
+
+ /**
+ * Test for <code>getInstance(String algorithm, Provider provider)</code>
+ * method
+ * Assertions:
+ * throws NullPointerException when algorithm is null;
+ * throws NoSuchAlgorithmException when algorithm is not correct;
+ * throws IllegalArgumentException when provider is null;
+ * returns TrustManagerFactory object
+ */
+ public void testLjava_lang_StringLjava_security_Provider() throws Exception {
+ try {
+ TrustManagerFactory.getInstance(null, mProv);
+ fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
+ } catch (NoSuchAlgorithmException e) {
+ } catch (NullPointerException e) {
+ }
+ for (int i = 0; i < invalidValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(invalidValues[i], mProv);
+ fail("NoSuchAlgorithmException must be thrown (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (NoSuchAlgorithmException e) {
+ }
+ }
+ Provider prov = null;
+ for (int i = 0; i < validValues.length; i++) {
+ try {
+ TrustManagerFactory.getInstance(validValues[i], prov);
+ fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
+ .concat(invalidValues[i]).concat(")"));
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ TrustManagerFactory tmf;
+ for (int i = 0; i < validValues.length; i++) {
+ tmf = TrustManagerFactory.getInstance(validValues[i], mProv);
+ assertTrue("Not instanceof TrustManagerFactory object",
+ tmf instanceof TrustManagerFactory);
+ assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
+ validValues[i]);
+ assertEquals("Incorrect provider", tmf.getProvider(), mProv);
+ checkResult(tmf);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactorySpiTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactorySpiTest.java
new file mode 100644
index 0000000..7bdeb45
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/TrustManagerFactorySpiTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.net.ssl;
+
+import java.security.AccessController;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.TrustManagerFactorySpi;
+
+import junit.framework.TestCase;
+import org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl;
+import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi.Parameters;
+
+public class TrustManagerFactorySpiTest extends TestCase {
+
+ private TrustManagerFactorySpiImpl factory = new TrustManagerFactorySpiImpl();
+ /**
+ * javax.net.ssl.TrustManagerFactorySpi#TrustManagerFactorySpi()
+ */
+ public void test_Constructor() {
+ try {
+ TrustManagerFactorySpiImpl tmf = new TrustManagerFactorySpiImpl();
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * @throws KeyStoreException
+ * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
+ */
+ public void test_engineInit_01() throws NoSuchAlgorithmException,
+ KeyStoreException {
+ factory.reset();
+ Provider provider = new MyProvider();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
+ provider);
+ KeyStore ks = null;
+ try {
+ ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ tmf.init(ks);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ assertTrue(factory.isEngineInitCalled());
+ assertEquals(ks, factory.getKs());
+ factory.reset();
+ tmf.init((KeyStore) null);
+ assertTrue(factory.isEngineInitCalled());
+ assertNull(factory.getKs());
+ }
+
+ /**
+ * @throws InvalidAlgorithmParameterException
+ * @throws NoSuchAlgorithmException
+ * javax.net.ssl.TrustManagerFactorySpi#engineInit(ManagerFactoryParameters spec)
+ */
+ public void test_engineInit_02() throws InvalidAlgorithmParameterException,
+ NoSuchAlgorithmException {
+ factory.reset();
+ Provider provider = new MyProvider();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
+ provider);
+ Parameters pr = null;
+ try {
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ pr = new Parameters(ks);
+ tmf.init(pr);
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ assertTrue(factory.isEngineInitCalled());
+ assertEquals(pr, factory.getSpec());
+ factory.reset();
+ tmf.init((ManagerFactoryParameters) null);
+ assertTrue(factory.isEngineInitCalled());
+ assertNull(factory.getSpec());
+ }
+
+ /**
+ * @throws NoSuchAlgorithmException
+ * javax.net.ssl.TrustManagerFactorySpi#engineGetTrustManagers()
+ */
+ public void test_engineGetTrustManagers() throws NoSuchAlgorithmException {
+ factory.reset();
+ Provider provider = new MyProvider();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
+ provider);
+ TrustManager[] tm = tmf.getTrustManagers();
+ assertTrue(factory.isEngineGetTrustManagersCalled());
+ factory.reset();
+ try {
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, null);
+ tmf.init(ks);
+ tm = tmf.getTrustManagers();
+ assertTrue(factory.isEngineGetTrustManagersCalled());
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+}
+
+class MyProvider extends Provider {
+
+ public MyProvider() {
+ super("MyProvider", 1.0, "My Test Provider");
+ AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
+ public Void run() {
+ put("TrustManagerFactory.MyTMF",
+ "org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl");
+ return null;
+ }
+ });
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509ExtendedKeyManagerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509ExtendedKeyManagerTest.java
new file mode 100644
index 0000000..514fed8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509ExtendedKeyManagerTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.net.ssl;
+
+import java.net.Socket;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.X509ExtendedKeyManager;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>X509ExtendedKeyManager</code> class constructors and methods.
+ *
+ */
+public class X509ExtendedKeyManagerTest extends TestCase {
+
+ private class MockX509ExtendedKeyManager extends X509ExtendedKeyManager {
+ public MockX509ExtendedKeyManager() {
+ super();
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], java.security.Principal[], java.net.Socket)
+ */
+ public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
+ // it is a fake
+ return null;
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, java.security.Principal[], java.net.Socket)
+ */
+ public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
+ // it is a fake
+ return null;
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
+ */
+ public X509Certificate[] getCertificateChain(String arg0) {
+ // it is a fake
+ return null;
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, java.security.Principal[])
+ */
+ public String[] getClientAliases(String arg0, Principal[] arg1) {
+ // it is a fake
+ return null;
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
+ */
+ public PrivateKey getPrivateKey(String arg0) {
+ // it is a fake
+ return null;
+ }
+
+ /**
+ * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, java.security.Principal[])
+ */
+ public String[] getServerAliases(String arg0, Principal[] arg1) {
+ // it is a fake
+ return null;
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509ExtendedKeyManager#X509ExtendedKeyManager()
+ */
+ public final void test_Constructor() {
+ try {
+ new MockX509ExtendedKeyManager();
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509ExtendedKeyManager
+ * #chooseEngineClientAlias(java.lang.String[],
+ * java.security.Principal[], javax.net.ssl.SSLEngine)
+ */
+ public final void test_chooseEngineClientAlias() {
+ X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
+ if (km.chooseEngineClientAlias(null, null, null) != null) {
+ fail("non null result");
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509ExtendedKeyManager
+ * #chooseEngineServerAlias(java.lang.String,
+ * java.security.Principal[], javax.net.ssl.SSLEngine)
+ */
+ public final void test_chooseEngineServerAlias() {
+ X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
+ if (km.chooseEngineServerAlias(null, null, null) != null) {
+ fail("non null result");
+ }
+ }
+
+}
+
+class MyX509ExtendedKeyManager extends X509ExtendedKeyManager {
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[],
+ * java.security.Principal[], java.net.Socket)
+ */
+ public String chooseClientAlias(String[] keyType, Principal[] issuers,
+ Socket socket) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String,
+ * java.security.Principal[], java.net.Socket)
+ */
+ public String chooseServerAlias(String keyType, Principal[] issuers,
+ Socket socket) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
+ */
+ public X509Certificate[] getCertificateChain(String alias) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String,
+ * java.security.Principal[])
+ */
+ public String[] getClientAliases(String keyType, Principal[] issuers) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String,
+ * java.security.Principal[])
+ */
+ public String[] getServerAliases(String keyType, Principal[] issuers) {
+ return null;
+ }
+
+ /*
+ * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
+ */
+ public PrivateKey getPrivateKey(String alias) {
+ return null;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509KeyManagerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509KeyManagerTest.java
new file mode 100644
index 0000000..4dddbc6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509KeyManagerTest.java
@@ -0,0 +1,753 @@
+package tests.api.javax.net.ssl;
+
+import java.io.ByteArrayInputStream;
+import java.net.Socket;
+import java.security.KeyFactory;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.security.spec.PKCS8EncodedKeySpec;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.X509KeyManager;
+import junit.framework.TestCase;
+
+/**
+ * Tests for <code>X509KeyManager</code> class constructors and methods.
+ */
+public class X509KeyManagerTest extends TestCase {
+
+ private X509KeyManager manager;
+ private KeyManagerFactory factory;
+
+ private static final String CLIENT = "CLIENT";
+ private static final String SERVER = "SERVER";
+ private static final String TYPE_RSA = "RSA";
+ private static final char[] PASSWORD = "1234".toCharArray();
+
+ private String keyType;
+ private KeyStore keyTest;
+ private X509Certificate[] cert;
+ private PrivateKey[] keys;
+
+
+ /*
+ Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 0 (0x0)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Validity
+ Not Before: Mar 20 17:00:06 2009 GMT
+ Not After : Mar 19 17:00:06 2012 GMT
+ Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ RSA Public Key: (1024 bit)
+ Modulus (1024 bit):
+ 00:aa:42:40:ed:92:21:17:99:5f:0e:e4:42:b8:cb:
+ 66:3d:63:2a:16:34:3c:7b:d3:3e:1f:a8:3f:bd:9a:
+ eb:b3:24:6b:8c:e4:da:2f:31:bc:61:07:27:2e:28:
+ 71:77:58:ae:b4:89:7c:eb:b0:06:24:07:57:3c:54:
+ 71:db:71:41:05:ab:3d:9f:05:d2:ca:cb:1c:bf:9d:
+ 8a:21:96:8f:13:61:25:69:12:3b:77:bd:f7:34:b2:
+ 09:a9:e0:52:94:44:31:ce:db:3d:eb:64:f1:d6:ca:
+ c5:7d:2f:d6:6f:8d:e4:29:8b:06:98:8a:95:3d:7a:
+ 97:41:9a:f1:66:c5:09:82:0d
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Subject Key Identifier:
+ E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
+ X509v3 Authority Key Identifier:
+ keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
+ DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android@android.com
+ serial:00
+
+ X509v3 Basic Constraints:
+ CA:TRUE
+ Signature Algorithm: sha1WithRSAEncryption
+ 14:98:30:29:42:ef:ab:e6:b8:25:4b:55:85:04:a5:c4:dd:1d:
+ 8b:6a:c1:6f:6c:1c:1d:c3:61:34:30:07:34:4d:6a:8b:55:6f:
+ 75:55:6e:15:58:c5:f8:af:e0:be:73:ba:d9:a5:85:d7:b5:1a:
+ 85:44:2b:88:fd:cc:cb:d1:ed:46:69:43:ff:59:ae:9b:5c:17:
+ 26:da:ee:c8:bf:67:55:01:a0:0e:10:b9:85:49:54:d9:79:1e:
+ 7b:2e:6f:65:4f:d9:10:2e:9d:b8:92:63:67:74:8b:22:0d:6d:
+ d3:5d:9e:29:63:f9:36:93:1b:a7:80:e2:b1:f1:bf:29:19:81:
+ 3d:07
+ */
+ String certificate = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
+ + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
+ + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
+ + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ\n"
+ + "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw\n"
+ + "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB\n"
+ + "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
+ + "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3\n"
+ + "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU\n"
+ + "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G\n"
+ + "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q\n"
+ + "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu\n"
+ + "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV\n"
+ + "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C\n"
+ + "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF\n"
+ + "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL\n"
+ + "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T\n"
+ + "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n"
+ + "-----END CERTIFICATE-----";
+
+ ByteArrayInputStream certArray = new ByteArrayInputStream(certificate
+ .getBytes());
+
+ /*
+ * The key in DER format.
+ * Below is the same key in PEM format as reference
+ */
+ byte[] keyBytes = new byte[] {
+ (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x77, (byte)0x02, (byte)0x01, (byte)0x00,
+ (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
+ (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
+ (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x61, (byte)0x30, (byte)0x82,
+ (byte)0x02, (byte)0x5d, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
+ (byte)0x81, (byte)0x00, (byte)0xaa, (byte)0x42, (byte)0x40, (byte)0xed, (byte)0x92,
+ (byte)0x21, (byte)0x17, (byte)0x99, (byte)0x5f, (byte)0x0e, (byte)0xe4, (byte)0x42,
+ (byte)0xb8, (byte)0xcb, (byte)0x66, (byte)0x3d, (byte)0x63, (byte)0x2a, (byte)0x16,
+ (byte)0x34, (byte)0x3c, (byte)0x7b, (byte)0xd3, (byte)0x3e, (byte)0x1f, (byte)0xa8,
+ (byte)0x3f, (byte)0xbd, (byte)0x9a, (byte)0xeb, (byte)0xb3, (byte)0x24, (byte)0x6b,
+ (byte)0x8c, (byte)0xe4, (byte)0xda, (byte)0x2f, (byte)0x31, (byte)0xbc, (byte)0x61,
+ (byte)0x07, (byte)0x27, (byte)0x2e, (byte)0x28, (byte)0x71, (byte)0x77, (byte)0x58,
+ (byte)0xae, (byte)0xb4, (byte)0x89, (byte)0x7c, (byte)0xeb, (byte)0xb0, (byte)0x06,
+ (byte)0x24, (byte)0x07, (byte)0x57, (byte)0x3c, (byte)0x54, (byte)0x71, (byte)0xdb,
+ (byte)0x71, (byte)0x41, (byte)0x05, (byte)0xab, (byte)0x3d, (byte)0x9f, (byte)0x05,
+ (byte)0xd2, (byte)0xca, (byte)0xcb, (byte)0x1c, (byte)0xbf, (byte)0x9d, (byte)0x8a,
+ (byte)0x21, (byte)0x96, (byte)0x8f, (byte)0x13, (byte)0x61, (byte)0x25, (byte)0x69,
+ (byte)0x12, (byte)0x3b, (byte)0x77, (byte)0xbd, (byte)0xf7, (byte)0x34, (byte)0xb2,
+ (byte)0x09, (byte)0xa9, (byte)0xe0, (byte)0x52, (byte)0x94, (byte)0x44, (byte)0x31,
+ (byte)0xce, (byte)0xdb, (byte)0x3d, (byte)0xeb, (byte)0x64, (byte)0xf1, (byte)0xd6,
+ (byte)0xca, (byte)0xc5, (byte)0x7d, (byte)0x2f, (byte)0xd6, (byte)0x6f, (byte)0x8d,
+ (byte)0xe4, (byte)0x29, (byte)0x8b, (byte)0x06, (byte)0x98, (byte)0x8a, (byte)0x95,
+ (byte)0x3d, (byte)0x7a, (byte)0x97, (byte)0x41, (byte)0x9a, (byte)0xf1, (byte)0x66,
+ (byte)0xc5, (byte)0x09, (byte)0x82, (byte)0x0d, (byte)0x02, (byte)0x03, (byte)0x01,
+ (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x34, (byte)0x91,
+ (byte)0x8e, (byte)0x50, (byte)0x8b, (byte)0xfc, (byte)0xf1, (byte)0xb7, (byte)0x66,
+ (byte)0x35, (byte)0x47, (byte)0xdf, (byte)0x1e, (byte)0x05, (byte)0x97, (byte)0x44,
+ (byte)0xbe, (byte)0xf8, (byte)0x80, (byte)0xb0, (byte)0x92, (byte)0x38, (byte)0x3d,
+ (byte)0x4a, (byte)0x02, (byte)0x26, (byte)0x45, (byte)0xbf, (byte)0xfa, (byte)0x34,
+ (byte)0x6a, (byte)0x34, (byte)0x85, (byte)0x8c, (byte)0x94, (byte)0x20, (byte)0x95,
+ (byte)0xcf, (byte)0xca, (byte)0x75, (byte)0x3e, (byte)0xeb, (byte)0x27, (byte)0x02,
+ (byte)0x4f, (byte)0xbe, (byte)0x64, (byte)0xc0, (byte)0x54, (byte)0x77, (byte)0xda,
+ (byte)0xfd, (byte)0x3e, (byte)0x75, (byte)0x36, (byte)0xec, (byte)0x99, (byte)0x4f,
+ (byte)0xc4, (byte)0x56, (byte)0xff, (byte)0x45, (byte)0x61, (byte)0xa8, (byte)0xa8,
+ (byte)0x41, (byte)0xe4, (byte)0x42, (byte)0x71, (byte)0x7a, (byte)0x8c, (byte)0x84,
+ (byte)0xc2, (byte)0x02, (byte)0x40, (byte)0x0b, (byte)0x3d, (byte)0x42, (byte)0xe0,
+ (byte)0x8b, (byte)0x22, (byte)0xf7, (byte)0x4c, (byte)0xa3, (byte)0xbb, (byte)0xd8,
+ (byte)0x8f, (byte)0x45, (byte)0xa2, (byte)0x55, (byte)0xc7, (byte)0xd0, (byte)0x6a,
+ (byte)0x25, (byte)0xbf, (byte)0xda, (byte)0x54, (byte)0x57, (byte)0x14, (byte)0x91,
+ (byte)0x0c, (byte)0x09, (byte)0x0b, (byte)0x9a, (byte)0x50, (byte)0xca, (byte)0xe6,
+ (byte)0x9e, (byte)0x28, (byte)0xc3, (byte)0x78, (byte)0x39, (byte)0x10, (byte)0x06,
+ (byte)0x02, (byte)0x96, (byte)0x10, (byte)0x1a, (byte)0xd2, (byte)0x4b, (byte)0x7b,
+ (byte)0x6c, (byte)0x72, (byte)0x9e, (byte)0x1e, (byte)0xac, (byte)0xd2, (byte)0xc1,
+ (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xde, (byte)0x27, (byte)0xbd, (byte)0x43,
+ (byte)0xa4, (byte)0xbd, (byte)0x95, (byte)0x14, (byte)0x2e, (byte)0x1c, (byte)0xa0,
+ (byte)0x74, (byte)0xa5, (byte)0x3e, (byte)0xfa, (byte)0xf9, (byte)0x15, (byte)0xb2,
+ (byte)0x29, (byte)0x6a, (byte)0x2a, (byte)0x42, (byte)0x94, (byte)0x5a, (byte)0xf2,
+ (byte)0x81, (byte)0xf3, (byte)0xe1, (byte)0x76, (byte)0x49, (byte)0x11, (byte)0x9d,
+ (byte)0x18, (byte)0xc5, (byte)0xeb, (byte)0xb6, (byte)0xbc, (byte)0x81, (byte)0x3a,
+ (byte)0x14, (byte)0x9c, (byte)0x41, (byte)0x01, (byte)0x58, (byte)0x56, (byte)0xa9,
+ (byte)0x9b, (byte)0x73, (byte)0x2f, (byte)0xd9, (byte)0xa8, (byte)0x8e, (byte)0xc4,
+ (byte)0x48, (byte)0x69, (byte)0x35, (byte)0xe6, (byte)0xf4, (byte)0x73, (byte)0x2f,
+ (byte)0xf9, (byte)0x12, (byte)0x12, (byte)0x71, (byte)0x02, (byte)0x41, (byte)0x00,
+ (byte)0xc4, (byte)0x32, (byte)0x81, (byte)0x5d, (byte)0x19, (byte)0x54, (byte)0x2c,
+ (byte)0x29, (byte)0x5a, (byte)0x9f, (byte)0x36, (byte)0x4c, (byte)0x6f, (byte)0x2d,
+ (byte)0xfd, (byte)0x62, (byte)0x0e, (byte)0xe6, (byte)0x37, (byte)0xc2, (byte)0xf6,
+ (byte)0x69, (byte)0x64, (byte)0xf9, (byte)0x3a, (byte)0xcc, (byte)0xb2, (byte)0x63,
+ (byte)0x2f, (byte)0xa9, (byte)0xfe, (byte)0x7e, (byte)0x8b, (byte)0x2d, (byte)0x69,
+ (byte)0x13, (byte)0xe5, (byte)0x61, (byte)0x58, (byte)0xb7, (byte)0xfa, (byte)0x55,
+ (byte)0x74, (byte)0x2c, (byte)0xe8, (byte)0xa1, (byte)0xac, (byte)0xc3, (byte)0xdd,
+ (byte)0x5b, (byte)0x62, (byte)0xae, (byte)0x0a, (byte)0x27, (byte)0xce, (byte)0xb0,
+ (byte)0xf2, (byte)0x81, (byte)0x5f, (byte)0x9a, (byte)0x6f, (byte)0x5f, (byte)0x3f,
+ (byte)0x5d, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0x92, (byte)0x42, (byte)0xff,
+ (byte)0xac, (byte)0xe5, (byte)0x6d, (byte)0x9c, (byte)0x15, (byte)0x29, (byte)0x36,
+ (byte)0xd7, (byte)0xbd, (byte)0x74, (byte)0x7e, (byte)0x3e, (byte)0xa6, (byte)0x77,
+ (byte)0xce, (byte)0x50, (byte)0xce, (byte)0x00, (byte)0xfc, (byte)0xcc, (byte)0xc8,
+ (byte)0x04, (byte)0x19, (byte)0xe3, (byte)0x03, (byte)0x71, (byte)0xe9, (byte)0x31,
+ (byte)0x9b, (byte)0x88, (byte)0x8f, (byte)0xe6, (byte)0x5c, (byte)0xed, (byte)0x46,
+ (byte)0xf7, (byte)0x82, (byte)0x52, (byte)0x4d, (byte)0xca, (byte)0x20, (byte)0xeb,
+ (byte)0x0d, (byte)0xc7, (byte)0xb6, (byte)0xd2, (byte)0xae, (byte)0x2e, (byte)0xf7,
+ (byte)0xaf, (byte)0xeb, (byte)0x2c, (byte)0xb9, (byte)0xbc, (byte)0x50, (byte)0xfc,
+ (byte)0xf5, (byte)0x7c, (byte)0xba, (byte)0x95, (byte)0x41, (byte)0x02, (byte)0x40,
+ (byte)0x54, (byte)0xf8, (byte)0x46, (byte)0x9c, (byte)0x6a, (byte)0x5e, (byte)0xd0,
+ (byte)0xed, (byte)0x6c, (byte)0x08, (byte)0xed, (byte)0xfc, (byte)0x36, (byte)0x5e,
+ (byte)0x65, (byte)0x91, (byte)0x75, (byte)0x40, (byte)0x71, (byte)0x3f, (byte)0xe7,
+ (byte)0x76, (byte)0x07, (byte)0xbc, (byte)0x04, (byte)0xa2, (byte)0x28, (byte)0x53,
+ (byte)0xda, (byte)0x8d, (byte)0xb5, (byte)0xe1, (byte)0x5a, (byte)0x27, (byte)0x65,
+ (byte)0x8d, (byte)0xaf, (byte)0x56, (byte)0xf4, (byte)0x94, (byte)0x61, (byte)0x3f,
+ (byte)0x67, (byte)0x1c, (byte)0x17, (byte)0xf8, (byte)0x05, (byte)0x19, (byte)0xa2,
+ (byte)0xa1, (byte)0x74, (byte)0x60, (byte)0x49, (byte)0x97, (byte)0xa9, (byte)0xe5,
+ (byte)0x6a, (byte)0x71, (byte)0x6b, (byte)0x55, (byte)0x38, (byte)0x0c, (byte)0xb9,
+ (byte)0x25, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xae, (byte)0xf2, (byte)0xa8,
+ (byte)0x6d, (byte)0x1d, (byte)0x35, (byte)0x38, (byte)0x73, (byte)0x98, (byte)0x15,
+ (byte)0xc7, (byte)0x15, (byte)0x02, (byte)0x2f, (byte)0x29, (byte)0x5d, (byte)0x18,
+ (byte)0x4b, (byte)0x7d, (byte)0xb2, (byte)0x59, (byte)0xbe, (byte)0x5a, (byte)0xc7,
+ (byte)0x72, (byte)0xd0, (byte)0x80, (byte)0xd8, (byte)0x77, (byte)0xa1, (byte)0x7f,
+ (byte)0xb2, (byte)0x35, (byte)0x0d, (byte)0x78, (byte)0x92, (byte)0x91, (byte)0x35,
+ (byte)0x47, (byte)0xeb, (byte)0x4b, (byte)0x00, (byte)0x59, (byte)0xb4, (byte)0xc4,
+ (byte)0x2c, (byte)0x29, (byte)0xe7, (byte)0x39, (byte)0x9d, (byte)0x48, (byte)0x8b,
+ (byte)0x4f, (byte)0x46, (byte)0xe6, (byte)0xce, (byte)0xd3, (byte)0x6c, (byte)0x84,
+ (byte)0x9b, (byte)0xd2, (byte)0x10, (byte)0xb0, (byte)0xe1
+ };
+
+ /*
+ * The same key in PEM format.
+ * The DER version of this key was created using
+ *
+ * openssl pkcs8 -topk8 -nocrypt -in key1.pem
+ * -inform PEM -out key1.der -outform DER
+ *
+ * -----BEGIN RSA PRIVATE KEY-----
+ * Proc-Type: 4,ENCRYPTED
+ * DEK-Info: DES-EDE3-CBC,69E26FCC3A7F136E
+ *
+ * YKiLXOwf2teog4IoOvbbROy9vqp0EMt1KF9eNKeKFCWGCS4RFATaAGjKrdA26bOV
+ * MBdyB4V7qaxLC8/UwLlzFLpprouIfGqrEoR/NT0eKQ+4Pl25GlMvlPaR0pATBLZ2
+ * OEaB3zcNygOQ02Jdrmw2+CS9qVtGGXjn6Qp6TVFm6edNCoOVZODLP9kkzPLn8Mkm
+ * /isgsprwMELuth8Y5BC0brI5XYdMqZFI5dLz4wzVH81wBYbRmJqR7yOE1pzAJS9I
+ * gJ5YvcP7pSmoA2SHVN4v4qolM+GAM9YIp2bwEyWFRjbriNlF1yM+HflGMEZ1HNpZ
+ * FSFFA3G8EIH9ogbZ3j+7EujrndJC7GIibwiu5rd3eIHtcwrWprp+wEoPc/vM8OpR
+ * so9ms7iQYV6faYCWK4yeCfErYw7t+AhGqfLiqHO6bO2XAYJcD28RYV9gXmugZOhT
+ * 9471MOw94HWF5tBVjgIkyNBcbRyMF9iyQKafbkHYpmxaB4s2EqQr1SNZl3SLEwhX
+ * MEGy3/tyveuMLAvdTlSDZbt6memWoXXEX4Ep/q6r0ErCTY31awdP/XaJcJBGb9ni
+ * Iai8DICaG1v4bUuBVgaiacZlgw1O4Hhj8D2DWfVZsgpx5y8tBRM2lGWvyzEi5n2F
+ * PiR2UlT0DjCD1ObjCpWJ5insX/w8dXSHGZLLb9ccGRUrw/+5Bptn+AoEfdP+8S3j
+ * UdMdxl6qt2gneCYu1Lr3cQ+qKPqikQty2UQ6Yp8dJkheLJ2Tr+rnaytOCp2dAT9K
+ * KXTimIcXV+ftvUMbDPXYu4LJBldr2VokD+k3QbHDgFnfHIiNkwiPzA==
+ * -----END RSA PRIVATE KEY-----
+ */
+
+ /*
+ Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 1 (0x1)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Validity
+ Not Before: Mar 20 17:00:40 2009 GMT
+ Not After : Mar 20 17:00:40 2010 GMT
+ Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ RSA Public Key: (1024 bit)
+ Modulus (1024 bit):
+ 00:d0:44:5a:c4:76:ef:ae:ff:99:5b:c3:37:c1:09:
+ 33:c1:97:e5:64:7a:a9:7e:98:4b:3a:a3:33:d0:5c:
+ c7:56:ac:d8:42:e8:4a:ac:9c:d9:8f:89:84:c8:46:
+ 95:ce:22:f7:6a:09:de:91:47:9c:38:23:a5:4a:fc:
+ 08:af:5a:b4:6e:39:8e:e9:f5:0e:46:00:69:e1:e5:
+ cc:4c:81:b6:82:7b:56:fb:f4:dc:04:ff:61:e2:7e:
+ 5f:e2:f9:97:53:93:d4:69:9b:ba:79:20:cd:1e:3e:
+ d5:9a:44:95:7c:cf:c1:51:f2:22:fc:ec:cc:66:18:
+ 74:60:2a:a2:be:06:c2:9e:8d
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ Netscape Comment:
+ OpenSSL Generated Certificate
+ X509v3 Subject Key Identifier:
+ 95:3E:C3:46:69:52:78:08:05:46:B9:00:69:E5:E7:A7:99:E3:C4:67
+ X509v3 Authority Key Identifier:
+ keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
+
+ Signature Algorithm: sha1WithRSAEncryption
+ a3:5b:30:f5:28:3f:87:f6:1b:36:6a:22:6d:66:48:fa:cb:ee:
+ 4c:04:cf:11:14:e2:1f:b5:68:0c:e7:61:0e:bc:d3:69:19:02:
+ 8b:d5:d3:05:4a:c8:29:e8:e3:d0:e9:32:ad:6c:7d:9c:c4:46:
+ 6c:f9:66:e6:64:60:47:6b:ef:8e:c8:1c:67:5a:5a:cf:73:a3:
+ 7e:9d:6e:89:0c:67:99:17:3d:b2:b8:8e:41:95:9c:84:95:bf:
+ 57:95:24:22:8f:19:12:c1:fd:23:45:75:7f:4f:61:06:e3:9f:
+ 05:dc:e7:29:9a:6b:17:e1:e1:37:d5:8b:ba:b4:d0:8a:3c:dd:
+ 3f:6a
+ */
+ String certificate2 = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIC9jCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
+ + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
+ + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
+ + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwNDBaFw0xMDAzMjAxNzAwNDBaMIGLMQsw\n"
+ + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
+ + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
+ + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
+ + "hkiG9w0BAQEFAAOBjQAwgYkCgYEA0ERaxHbvrv+ZW8M3wQkzwZflZHqpfphLOqMz\n"
+ + "0FzHVqzYQuhKrJzZj4mEyEaVziL3agnekUecOCOlSvwIr1q0bjmO6fUORgBp4eXM\n"
+ + "TIG2gntW+/TcBP9h4n5f4vmXU5PUaZu6eSDNHj7VmkSVfM/BUfIi/OzMZhh0YCqi\n"
+ + "vgbCno0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
+ + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFJU+w0ZpUngIBUa5AGnl\n"
+ + "56eZ48RnMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
+ + "DQEBBQUAA4GBAKNbMPUoP4f2GzZqIm1mSPrL7kwEzxEU4h+1aAznYQ6802kZAovV\n"
+ + "0wVKyCno49DpMq1sfZzERmz5ZuZkYEdr747IHGdaWs9zo36dbokMZ5kXPbK4jkGV\n"
+ + "nISVv1eVJCKPGRLB/SNFdX9PYQbjnwXc5ymaaxfh4TfVi7q00Io83T9q\n\n"
+ + "-----END CERTIFICATE-----";
+
+ ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2
+ .getBytes());
+
+ /*
+ * The key in DER format.
+ * Below is the same key in PEM format as reference
+ */
+ byte[] key2Bytes = new byte[] {
+ (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x75, (byte)0x02, (byte)0x01, (byte)0x00,
+ (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
+ (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
+ (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x5f, (byte)0x30, (byte)0x82,
+ (byte)0x02, (byte)0x5b, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
+ (byte)0x81, (byte)0x00, (byte)0xd0, (byte)0x44, (byte)0x5a, (byte)0xc4, (byte)0x76,
+ (byte)0xef, (byte)0xae, (byte)0xff, (byte)0x99, (byte)0x5b, (byte)0xc3, (byte)0x37,
+ (byte)0xc1, (byte)0x09, (byte)0x33, (byte)0xc1, (byte)0x97, (byte)0xe5, (byte)0x64,
+ (byte)0x7a, (byte)0xa9, (byte)0x7e, (byte)0x98, (byte)0x4b, (byte)0x3a, (byte)0xa3,
+ (byte)0x33, (byte)0xd0, (byte)0x5c, (byte)0xc7, (byte)0x56, (byte)0xac, (byte)0xd8,
+ (byte)0x42, (byte)0xe8, (byte)0x4a, (byte)0xac, (byte)0x9c, (byte)0xd9, (byte)0x8f,
+ (byte)0x89, (byte)0x84, (byte)0xc8, (byte)0x46, (byte)0x95, (byte)0xce, (byte)0x22,
+ (byte)0xf7, (byte)0x6a, (byte)0x09, (byte)0xde, (byte)0x91, (byte)0x47, (byte)0x9c,
+ (byte)0x38, (byte)0x23, (byte)0xa5, (byte)0x4a, (byte)0xfc, (byte)0x08, (byte)0xaf,
+ (byte)0x5a, (byte)0xb4, (byte)0x6e, (byte)0x39, (byte)0x8e, (byte)0xe9, (byte)0xf5,
+ (byte)0x0e, (byte)0x46, (byte)0x00, (byte)0x69, (byte)0xe1, (byte)0xe5, (byte)0xcc,
+ (byte)0x4c, (byte)0x81, (byte)0xb6, (byte)0x82, (byte)0x7b, (byte)0x56, (byte)0xfb,
+ (byte)0xf4, (byte)0xdc, (byte)0x04, (byte)0xff, (byte)0x61, (byte)0xe2, (byte)0x7e,
+ (byte)0x5f, (byte)0xe2, (byte)0xf9, (byte)0x97, (byte)0x53, (byte)0x93, (byte)0xd4,
+ (byte)0x69, (byte)0x9b, (byte)0xba, (byte)0x79, (byte)0x20, (byte)0xcd, (byte)0x1e,
+ (byte)0x3e, (byte)0xd5, (byte)0x9a, (byte)0x44, (byte)0x95, (byte)0x7c, (byte)0xcf,
+ (byte)0xc1, (byte)0x51, (byte)0xf2, (byte)0x22, (byte)0xfc, (byte)0xec, (byte)0xcc,
+ (byte)0x66, (byte)0x18, (byte)0x74, (byte)0x60, (byte)0x2a, (byte)0xa2, (byte)0xbe,
+ (byte)0x06, (byte)0xc2, (byte)0x9e, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01,
+ (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x06, (byte)0x41,
+ (byte)0xd7, (byte)0x7c, (byte)0x49, (byte)0x9a, (byte)0x7f, (byte)0xe6, (byte)0x7c,
+ (byte)0x04, (byte)0x0e, (byte)0xc4, (byte)0x71, (byte)0x0f, (byte)0x46, (byte)0xb7,
+ (byte)0xcd, (byte)0x49, (byte)0x7e, (byte)0x10, (byte)0x55, (byte)0x61, (byte)0x51,
+ (byte)0x50, (byte)0x09, (byte)0x4d, (byte)0xf7, (byte)0xf3, (byte)0x8d, (byte)0xa6,
+ (byte)0x0b, (byte)0x8b, (byte)0x9b, (byte)0xdf, (byte)0xbe, (byte)0xbc, (byte)0xe7,
+ (byte)0x9c, (byte)0xba, (byte)0xc8, (byte)0x9e, (byte)0x38, (byte)0x18, (byte)0x10,
+ (byte)0x4e, (byte)0xd5, (byte)0xe7, (byte)0xa5, (byte)0x09, (byte)0x51, (byte)0x8c,
+ (byte)0x97, (byte)0x4e, (byte)0xd0, (byte)0x79, (byte)0xbb, (byte)0x50, (byte)0x6f,
+ (byte)0x05, (byte)0x4d, (byte)0x79, (byte)0x7f, (byte)0x3f, (byte)0x26, (byte)0x76,
+ (byte)0xc1, (byte)0xcc, (byte)0x40, (byte)0x0f, (byte)0xde, (byte)0x42, (byte)0x5d,
+ (byte)0xc1, (byte)0x5f, (byte)0x70, (byte)0x46, (byte)0x70, (byte)0x8d, (byte)0xff,
+ (byte)0x26, (byte)0x35, (byte)0x75, (byte)0x9a, (byte)0x97, (byte)0xd2, (byte)0x74,
+ (byte)0x53, (byte)0x11, (byte)0x2b, (byte)0xc1, (byte)0x76, (byte)0x9c, (byte)0x9f,
+ (byte)0x93, (byte)0xaa, (byte)0xa8, (byte)0x41, (byte)0x23, (byte)0x9a, (byte)0x04,
+ (byte)0x11, (byte)0x6e, (byte)0x56, (byte)0xea, (byte)0xf5, (byte)0xd6, (byte)0x1d,
+ (byte)0x49, (byte)0x2a, (byte)0x83, (byte)0x49, (byte)0x7d, (byte)0xb7, (byte)0xd1,
+ (byte)0xe6, (byte)0x8d, (byte)0x93, (byte)0x1a, (byte)0x81, (byte)0x8e, (byte)0xc2,
+ (byte)0xb9, (byte)0xbf, (byte)0xfd, (byte)0x00, (byte)0xe2, (byte)0xb5, (byte)0x01,
+ (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xea, (byte)0xce, (byte)0xc6, (byte)0x11,
+ (byte)0x1e, (byte)0xf6, (byte)0xcf, (byte)0x3a, (byte)0x8c, (byte)0xe7, (byte)0x80,
+ (byte)0x16, (byte)0x8f, (byte)0x1d, (byte)0xeb, (byte)0xa2, (byte)0xd2, (byte)0x23,
+ (byte)0x9e, (byte)0xf9, (byte)0xf1, (byte)0x14, (byte)0x16, (byte)0xc8, (byte)0x87,
+ (byte)0xf2, (byte)0x17, (byte)0xdf, (byte)0xc6, (byte)0xe4, (byte)0x1c, (byte)0x74,
+ (byte)0x74, (byte)0xb0, (byte)0xbb, (byte)0x40, (byte)0xeb, (byte)0xa6, (byte)0xb2,
+ (byte)0x5b, (byte)0x6d, (byte)0xf5, (byte)0x9a, (byte)0x85, (byte)0xf1, (byte)0x73,
+ (byte)0x84, (byte)0xec, (byte)0xdb, (byte)0x9b, (byte)0xf9, (byte)0xf8, (byte)0x3d,
+ (byte)0xba, (byte)0xeb, (byte)0xd7, (byte)0x6c, (byte)0x45, (byte)0x7b, (byte)0xca,
+ (byte)0x12, (byte)0x67, (byte)0x5f, (byte)0xcd, (byte)0x02, (byte)0x41, (byte)0x00,
+ (byte)0xe3, (byte)0x10, (byte)0x5b, (byte)0xd0, (byte)0xad, (byte)0x59, (byte)0x90,
+ (byte)0x18, (byte)0x17, (byte)0xdc, (byte)0x68, (byte)0xd4, (byte)0x75, (byte)0x55,
+ (byte)0xab, (byte)0x7d, (byte)0xd1, (byte)0xb5, (byte)0x5a, (byte)0xc4, (byte)0xb0,
+ (byte)0x2d, (byte)0xa9, (byte)0xd1, (byte)0x6f, (byte)0xe9, (byte)0x21, (byte)0x4a,
+ (byte)0x27, (byte)0xc4, (byte)0x98, (byte)0x89, (byte)0xfa, (byte)0x65, (byte)0xb6,
+ (byte)0x10, (byte)0x5d, (byte)0x66, (byte)0xdd, (byte)0x17, (byte)0xb3, (byte)0xf3,
+ (byte)0xd3, (byte)0xe3, (byte)0xa0, (byte)0x1a, (byte)0x93, (byte)0xe4, (byte)0xfb,
+ (byte)0x88, (byte)0xa7, (byte)0x3b, (byte)0x97, (byte)0x1b, (byte)0xf1, (byte)0x08,
+ (byte)0x0c, (byte)0x66, (byte)0xd0, (byte)0x86, (byte)0x5e, (byte)0x39, (byte)0xf9,
+ (byte)0xc1, (byte)0x02, (byte)0x40, (byte)0x24, (byte)0x7c, (byte)0xcd, (byte)0x3a,
+ (byte)0x8b, (byte)0xdd, (byte)0x3e, (byte)0x86, (byte)0x92, (byte)0xae, (byte)0xc6,
+ (byte)0xb0, (byte)0xba, (byte)0xbc, (byte)0xa3, (byte)0x89, (byte)0x41, (byte)0xae,
+ (byte)0x57, (byte)0x5d, (byte)0xef, (byte)0xa0, (byte)0x77, (byte)0x89, (byte)0xe1,
+ (byte)0xd6, (byte)0x34, (byte)0xef, (byte)0x89, (byte)0x30, (byte)0x99, (byte)0x5b,
+ (byte)0x5f, (byte)0x66, (byte)0xb7, (byte)0x32, (byte)0x77, (byte)0x6c, (byte)0x07,
+ (byte)0xfb, (byte)0x3d, (byte)0x33, (byte)0x15, (byte)0x38, (byte)0x0b, (byte)0x35,
+ (byte)0x30, (byte)0x4a, (byte)0xbe, (byte)0x35, (byte)0x96, (byte)0xba, (byte)0x84,
+ (byte)0x9d, (byte)0x2f, (byte)0x58, (byte)0xe2, (byte)0x72, (byte)0x49, (byte)0xb2,
+ (byte)0x34, (byte)0xf9, (byte)0xeb, (byte)0x61, (byte)0x02, (byte)0x40, (byte)0x2a,
+ (byte)0xd4, (byte)0x89, (byte)0x1d, (byte)0x21, (byte)0xb5, (byte)0xc5, (byte)0x32,
+ (byte)0x66, (byte)0x3d, (byte)0xd3, (byte)0x20, (byte)0x50, (byte)0x49, (byte)0xaa,
+ (byte)0xa1, (byte)0x7f, (byte)0x0f, (byte)0x20, (byte)0x61, (byte)0xfd, (byte)0x81,
+ (byte)0x7f, (byte)0x88, (byte)0xdb, (byte)0xfd, (byte)0x33, (byte)0xa4, (byte)0x53,
+ (byte)0x40, (byte)0x08, (byte)0x2d, (byte)0xee, (byte)0xa7, (byte)0x84, (byte)0xe2,
+ (byte)0x2d, (byte)0x5c, (byte)0x1b, (byte)0xd4, (byte)0x3e, (byte)0xc3, (byte)0x7d,
+ (byte)0x72, (byte)0x70, (byte)0x5e, (byte)0xd3, (byte)0x0a, (byte)0xdc, (byte)0x4f,
+ (byte)0x78, (byte)0x8c, (byte)0x0b, (byte)0x02, (byte)0xe0, (byte)0x42, (byte)0x4e,
+ (byte)0x64, (byte)0x8e, (byte)0x6c, (byte)0xea, (byte)0x15, (byte)0x31, (byte)0x81,
+ (byte)0x02, (byte)0x40, (byte)0x57, (byte)0x72, (byte)0xb9, (byte)0x78, (byte)0xc0,
+ (byte)0x1f, (byte)0x5b, (byte)0x1d, (byte)0xb2, (byte)0xcf, (byte)0x94, (byte)0x42,
+ (byte)0xed, (byte)0xbd, (byte)0xe7, (byte)0xaa, (byte)0x14, (byte)0x56, (byte)0xd0,
+ (byte)0x94, (byte)0x25, (byte)0x30, (byte)0x87, (byte)0x35, (byte)0x82, (byte)0xa0,
+ (byte)0x42, (byte)0xb5, (byte)0x7f, (byte)0x66, (byte)0x77, (byte)0xb0, (byte)0x13,
+ (byte)0xbe, (byte)0x57, (byte)0x06, (byte)0x7e, (byte)0x50, (byte)0x67, (byte)0x13,
+ (byte)0xa7, (byte)0x09, (byte)0xac, (byte)0xd6, (byte)0xbf, (byte)0x22, (byte)0x74,
+ (byte)0x6b, (byte)0x37, (byte)0x92, (byte)0x2b, (byte)0x91, (byte)0xbd, (byte)0x0a,
+ (byte)0xd8, (byte)0x0f, (byte)0x8d, (byte)0x86, (byte)0x4b, (byte)0x20, (byte)0x5e,
+ (byte)0x50, (byte)0x60, (byte)0x80
+ };
+
+ /*
+ * The same key in PEM format.
+ * The DER version of this key was created using
+ *
+ * openssl pkcs8 -topk8 -nocrypt -in key1.pem
+ * -inform PEM -out key1.der -outform DER
+ *
+ * -----BEGIN RSA PRIVATE KEY-----
+ * Proc-Type: 4,ENCRYPTED
+ * DEK-Info: DES-EDE3-CBC,370723FFDC1B1CFA
+ *
+ * KJ20ODBEQujoOpnzNfHNoo5DF/qENhw9IaApChGMj+WhqYuFfKfPQKuRli8sJSEk
+ * uoPmEqjJndHz5M5bI7wVxiafv/Up4+SaNKhn/vu6xjx/senJMX8HMUchqfvn0eCd
+ * 31NHQeNbQ67O73xGIdltLzwTRsavTu/hwhnnJxiXzXnYtI5HTZUaRbVJQNpdlkNW
+ * H91u70lwlT8W2MATBhl3R3wIbRHQG1I0RQX12O04gMfK1PBl9d/tnFOi4ESfth1W
+ * e06XV0U12g06V5/UUuicJANvgyf0Pix0xxPr2tqibWeGpFwCvJpNHl4L3tUocydF
+ * HYoUKx/r3VSmesnZ1zUMsuO2zXOuLLcwCSFN+73GBLWocCxBvag6HFvCemy5Tuhs
+ * 9MhfF+5lKER/9Ama/e7C61usaoUhR1OvpGWMfjewrFLCsyWlInscoZ1ad5YtcWGx
+ * MM7+BsTnK00fcXZuPHTPsiwQ0fMVeNM2a/e65aIivfzzHmb6gqUigNpfNYcqQsJJ
+ * Wwoc5hXVO92vugdHOHOiAUpfZZgNDZwgCTluMuI+KJ0QCb0dhF5w/TDA8z+vRwmW
+ * sz5WrA4F+T3LfwwLQfxJyHTnbAu38VlMMZP98iIobOX3AAkBw4+kTOCEedvmKt0f
+ * s7iSKrnnV6AyzRPEJUWknMF8xNFH7HDqkZf4Mv8cMM6e45K4kBGd17d3tcEFi2An
+ * 5l6S9hHtoyMhHjnAcyuHJbD9rGRgyOlbhSYTcbX/gKiECZj0kf8xHi20qntO3c+p
+ * jdpp97fIMnQTl5IDNxOy5h9MDLs/SYAR7iyF19RkIGc=
+ * -----END RSA PRIVATE KEY-----
+ */
+
+ /*
+ Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 2 (0x2)
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Validity
+ Not Before: Mar 20 17:02:32 2009 GMT
+ Not After : Mar 20 17:02:32 2010 GMT
+ Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ RSA Public Key: (1024 bit)
+ Modulus (1024 bit):
+ 00:b4:c5:ed:df:30:42:6d:8b:af:4b:e4:9c:13:5e:
+ 83:23:cd:2f:ce:34:e2:43:d7:6c:72:bb:03:b3:b9:
+ 24:02:e0:cc:b5:8d:d6:92:41:04:2b:5c:94:b2:c3:
+ 9c:9d:56:f0:99:bc:0f:81:af:eb:54:ed:80:a6:a0:
+ c7:c2:43:05:04:7c:9c:7e:07:03:10:b9:bd:c5:16:
+ cf:19:dd:e3:4f:73:83:72:c5:66:e4:5b:14:c4:96:
+ d1:e3:24:0b:b6:d4:f7:84:2e:b1:e7:93:02:9d:f5:
+ da:aa:c1:d9:cc:5e:36:e9:8f:bf:8b:da:a7:45:82:
+ f2:b0:f5:a7:e4:e1:80:a3:17
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints:
+ CA:FALSE
+ Netscape Comment:
+ OpenSSL Generated Certificate
+ X509v3 Subject Key Identifier:
+ 3B:5B:3D:DB:45:F5:8F:58:70:0B:FC:70:3E:31:2B:43:63:A9:FE:2B
+ X509v3 Authority Key Identifier:
+ keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
+
+ Signature Algorithm: sha1WithRSAEncryption
+ 1c:7f:93:1c:59:21:88:15:45:4b:e0:9c:78:3a:88:3e:55:19:
+ 86:31:e8:53:3d:74:e2:4a:34:9f:92:17:4e:13:46:92:54:f8:
+ 43:eb:5e:03:4f:14:51:61:d2:04:b8:04:5a:31:eb:14:6a:18:
+ b0:20:03:92:0c:7f:07:c4:1b:f9:9e:7f:5f:ec:03:7a:c8:e3:
+ df:d3:94:6e:68:8a:3a:3d:e4:61:f3:e0:87:5d:40:d8:cb:99:
+ 4d:9a:7b:bc:95:7c:d2:9d:b7:04:9a:9a:63:89:cd:39:ec:32:
+ 60:0a:97:da:e9:50:a5:73:4a:a2:aa:9c:9b:a8:7f:5a:20:d6:
+ 48:bd
+ */
+ String certificate3 = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIC9jCCAl+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
+ + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
+ + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
+ + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAyMzJaFw0xMDAzMjAxNzAyMzJaMIGLMQsw\n"
+ + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
+ + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
+ + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
+ + "hkiG9w0BAQEFAAOBjQAwgYkCgYEAtMXt3zBCbYuvS+ScE16DI80vzjTiQ9dscrsD\n"
+ + "s7kkAuDMtY3WkkEEK1yUssOcnVbwmbwPga/rVO2ApqDHwkMFBHycfgcDELm9xRbP\n"
+ + "Gd3jT3ODcsVm5FsUxJbR4yQLttT3hC6x55MCnfXaqsHZzF426Y+/i9qnRYLysPWn\n"
+ + "5OGAoxcCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
+ + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFDtbPdtF9Y9YcAv8cD4x\n"
+ + "K0Njqf4rMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
+ + "DQEBBQUAA4GBABx/kxxZIYgVRUvgnHg6iD5VGYYx6FM9dOJKNJ+SF04TRpJU+EPr\n"
+ + "XgNPFFFh0gS4BFox6xRqGLAgA5IMfwfEG/mef1/sA3rI49/TlG5oijo95GHz4Idd\n"
+ + "QNjLmU2ae7yVfNKdtwSammOJzTnsMmAKl9rpUKVzSqKqnJuof1og1ki9\n"
+ + "-----END CERTIFICATE-----";
+
+ ByteArrayInputStream certArray3 = new ByteArrayInputStream(certificate3
+ .getBytes());
+
+ /*
+ * The key in DER format.
+ * Below is the same key in PEM format as reference
+ */
+ byte[] key3Bytes = new byte[] {
+ (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x76, (byte)0x02, (byte)0x01, (byte)0x00,
+ (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
+ (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
+ (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x60, (byte)0x30, (byte)0x82,
+ (byte)0x02, (byte)0x5c, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
+ (byte)0x81, (byte)0x00, (byte)0xb4, (byte)0xc5, (byte)0xed, (byte)0xdf, (byte)0x30,
+ (byte)0x42, (byte)0x6d, (byte)0x8b, (byte)0xaf, (byte)0x4b, (byte)0xe4, (byte)0x9c,
+ (byte)0x13, (byte)0x5e, (byte)0x83, (byte)0x23, (byte)0xcd, (byte)0x2f, (byte)0xce,
+ (byte)0x34, (byte)0xe2, (byte)0x43, (byte)0xd7, (byte)0x6c, (byte)0x72, (byte)0xbb,
+ (byte)0x03, (byte)0xb3, (byte)0xb9, (byte)0x24, (byte)0x02, (byte)0xe0, (byte)0xcc,
+ (byte)0xb5, (byte)0x8d, (byte)0xd6, (byte)0x92, (byte)0x41, (byte)0x04, (byte)0x2b,
+ (byte)0x5c, (byte)0x94, (byte)0xb2, (byte)0xc3, (byte)0x9c, (byte)0x9d, (byte)0x56,
+ (byte)0xf0, (byte)0x99, (byte)0xbc, (byte)0x0f, (byte)0x81, (byte)0xaf, (byte)0xeb,
+ (byte)0x54, (byte)0xed, (byte)0x80, (byte)0xa6, (byte)0xa0, (byte)0xc7, (byte)0xc2,
+ (byte)0x43, (byte)0x05, (byte)0x04, (byte)0x7c, (byte)0x9c, (byte)0x7e, (byte)0x07,
+ (byte)0x03, (byte)0x10, (byte)0xb9, (byte)0xbd, (byte)0xc5, (byte)0x16, (byte)0xcf,
+ (byte)0x19, (byte)0xdd, (byte)0xe3, (byte)0x4f, (byte)0x73, (byte)0x83, (byte)0x72,
+ (byte)0xc5, (byte)0x66, (byte)0xe4, (byte)0x5b, (byte)0x14, (byte)0xc4, (byte)0x96,
+ (byte)0xd1, (byte)0xe3, (byte)0x24, (byte)0x0b, (byte)0xb6, (byte)0xd4, (byte)0xf7,
+ (byte)0x84, (byte)0x2e, (byte)0xb1, (byte)0xe7, (byte)0x93, (byte)0x02, (byte)0x9d,
+ (byte)0xf5, (byte)0xda, (byte)0xaa, (byte)0xc1, (byte)0xd9, (byte)0xcc, (byte)0x5e,
+ (byte)0x36, (byte)0xe9, (byte)0x8f, (byte)0xbf, (byte)0x8b, (byte)0xda, (byte)0xa7,
+ (byte)0x45, (byte)0x82, (byte)0xf2, (byte)0xb0, (byte)0xf5, (byte)0xa7, (byte)0xe4,
+ (byte)0xe1, (byte)0x80, (byte)0xa3, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x01,
+ (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x53, (byte)0xbc,
+ (byte)0x1f, (byte)0x1c, (byte)0x34, (byte)0x09, (byte)0x81, (byte)0x1e, (byte)0xa3,
+ (byte)0xfb, (byte)0x5e, (byte)0x90, (byte)0xa1, (byte)0x34, (byte)0x35, (byte)0x40,
+ (byte)0x9f, (byte)0x29, (byte)0xd6, (byte)0xb5, (byte)0x8e, (byte)0x5d, (byte)0x68,
+ (byte)0x6a, (byte)0xf6, (byte)0x96, (byte)0x03, (byte)0xf7, (byte)0xfa, (byte)0xf9,
+ (byte)0x60, (byte)0x4f, (byte)0xea, (byte)0xe2, (byte)0xea, (byte)0x29, (byte)0x8b,
+ (byte)0x23, (byte)0x8c, (byte)0x9f, (byte)0xdd, (byte)0x49, (byte)0x8f, (byte)0xa8,
+ (byte)0xa6, (byte)0x62, (byte)0x07, (byte)0x44, (byte)0x79, (byte)0xa1, (byte)0xaf,
+ (byte)0xf9, (byte)0x1d, (byte)0x98, (byte)0xbf, (byte)0x85, (byte)0x28, (byte)0x03,
+ (byte)0x87, (byte)0x14, (byte)0x20, (byte)0xba, (byte)0xd4, (byte)0x96, (byte)0x61,
+ (byte)0x2a, (byte)0xd0, (byte)0xaa, (byte)0x30, (byte)0x19, (byte)0x4b, (byte)0x40,
+ (byte)0x35, (byte)0xb0, (byte)0x79, (byte)0x0b, (byte)0x7f, (byte)0xd7, (byte)0xcd,
+ (byte)0x64, (byte)0xd9, (byte)0x93, (byte)0x38, (byte)0xe2, (byte)0x59, (byte)0xe0,
+ (byte)0x9e, (byte)0x3a, (byte)0x25, (byte)0x27, (byte)0xa2, (byte)0xd9, (byte)0x20,
+ (byte)0xb0, (byte)0x45, (byte)0x5f, (byte)0x6c, (byte)0x15, (byte)0x6f, (byte)0x10,
+ (byte)0x55, (byte)0xa7, (byte)0xf9, (byte)0x3d, (byte)0x92, (byte)0x3c, (byte)0x7c,
+ (byte)0x23, (byte)0x1b, (byte)0xc0, (byte)0xb5, (byte)0x17, (byte)0x41, (byte)0x5e,
+ (byte)0x8c, (byte)0xdc, (byte)0x25, (byte)0x1d, (byte)0x35, (byte)0x2b, (byte)0xd3,
+ (byte)0x97, (byte)0x1a, (byte)0x6f, (byte)0xae, (byte)0xeb, (byte)0xf5, (byte)0xf9,
+ (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd7, (byte)0x3e, (byte)0xed, (byte)0x70,
+ (byte)0xfe, (byte)0xee, (byte)0x0e, (byte)0x30, (byte)0x29, (byte)0xfa, (byte)0xd7,
+ (byte)0x38, (byte)0xcf, (byte)0x8e, (byte)0xc1, (byte)0x9c, (byte)0x78, (byte)0x06,
+ (byte)0x2d, (byte)0xda, (byte)0x33, (byte)0x58, (byte)0xa1, (byte)0x7b, (byte)0xbf,
+ (byte)0x00, (byte)0xb9, (byte)0xdf, (byte)0xea, (byte)0x65, (byte)0x86, (byte)0xbb,
+ (byte)0xcc, (byte)0x83, (byte)0xce, (byte)0xde, (byte)0xc3, (byte)0xf8, (byte)0x89,
+ (byte)0xf5, (byte)0x9f, (byte)0xa6, (byte)0x1d, (byte)0xc9, (byte)0xfb, (byte)0x98,
+ (byte)0xa1, (byte)0x2e, (byte)0xe0, (byte)0x57, (byte)0x6e, (byte)0xbd, (byte)0x57,
+ (byte)0x20, (byte)0xf9, (byte)0x6b, (byte)0x13, (byte)0x42, (byte)0x9d, (byte)0x8d,
+ (byte)0x66, (byte)0x4d, (byte)0x7a, (byte)0x2d, (byte)0x02, (byte)0x41, (byte)0x00,
+ (byte)0xd7, (byte)0x00, (byte)0x18, (byte)0x54, (byte)0xe8, (byte)0x37, (byte)0xdb,
+ (byte)0xf8, (byte)0x98, (byte)0x7b, (byte)0x18, (byte)0x33, (byte)0xf6, (byte)0x28,
+ (byte)0xa8, (byte)0x8c, (byte)0xd9, (byte)0xfd, (byte)0x4c, (byte)0x4e, (byte)0x41,
+ (byte)0x73, (byte)0x2e, (byte)0x79, (byte)0x31, (byte)0xcc, (byte)0x7d, (byte)0x42,
+ (byte)0xb7, (byte)0xa1, (byte)0xd2, (byte)0xbc, (byte)0x1f, (byte)0x62, (byte)0xcf,
+ (byte)0x15, (byte)0x7c, (byte)0x62, (byte)0x97, (byte)0x70, (byte)0xf1, (byte)0x15,
+ (byte)0xf1, (byte)0x33, (byte)0xa1, (byte)0x9d, (byte)0xbb, (byte)0x5f, (byte)0xd7,
+ (byte)0x5a, (byte)0xf9, (byte)0x24, (byte)0x58, (byte)0xac, (byte)0x86, (byte)0x6a,
+ (byte)0xed, (byte)0xd4, (byte)0x84, (byte)0xe4, (byte)0x3f, (byte)0xfe, (byte)0xb0,
+ (byte)0xd3, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd4, (byte)0xb7, (byte)0x84,
+ (byte)0xb2, (byte)0x39, (byte)0xce, (byte)0x0b, (byte)0x49, (byte)0x80, (byte)0x03,
+ (byte)0x3c, (byte)0xb5, (byte)0x11, (byte)0x32, (byte)0x34, (byte)0x96, (byte)0xac,
+ (byte)0x6a, (byte)0xf6, (byte)0xdf, (byte)0x80, (byte)0x04, (byte)0xe4, (byte)0x39,
+ (byte)0xc6, (byte)0x0e, (byte)0x32, (byte)0xa3, (byte)0x5e, (byte)0x23, (byte)0x0d,
+ (byte)0x9f, (byte)0x04, (byte)0xc3, (byte)0x72, (byte)0x2a, (byte)0xe6, (byte)0xa2,
+ (byte)0xf5, (byte)0xbc, (byte)0x3f, (byte)0x15, (byte)0x4c, (byte)0xb5, (byte)0x33,
+ (byte)0x26, (byte)0xa8, (byte)0x8c, (byte)0x09, (byte)0xfb, (byte)0x7e, (byte)0x1e,
+ (byte)0x32, (byte)0x40, (byte)0x0d, (byte)0x1d, (byte)0xcb, (byte)0x7f, (byte)0xf6,
+ (byte)0xf2, (byte)0x29, (byte)0x9b, (byte)0x01, (byte)0xd5, (byte)0x02, (byte)0x40,
+ (byte)0x24, (byte)0x26, (byte)0x1c, (byte)0xf1, (byte)0x31, (byte)0xb6, (byte)0x2a,
+ (byte)0xa3, (byte)0x0a, (byte)0xa8, (byte)0x2f, (byte)0xb2, (byte)0x94, (byte)0xe1,
+ (byte)0xd3, (byte)0x2d, (byte)0x13, (byte)0x7d, (byte)0xd6, (byte)0x35, (byte)0x96,
+ (byte)0x25, (byte)0x92, (byte)0x9b, (byte)0xc7, (byte)0xf6, (byte)0xb4, (byte)0xdc,
+ (byte)0xe1, (byte)0xd9, (byte)0x30, (byte)0x80, (byte)0x76, (byte)0xda, (byte)0x7b,
+ (byte)0x2d, (byte)0x06, (byte)0xa3, (byte)0xe1, (byte)0x08, (byte)0x99, (byte)0x50,
+ (byte)0x72, (byte)0x24, (byte)0x97, (byte)0x38, (byte)0xd9, (byte)0x07, (byte)0x4d,
+ (byte)0x43, (byte)0x3b, (byte)0x7e, (byte)0x93, (byte)0xf6, (byte)0x36, (byte)0x07,
+ (byte)0x86, (byte)0x83, (byte)0x63, (byte)0xf0, (byte)0xa8, (byte)0x9d, (byte)0xdf,
+ (byte)0x07, (byte)0x02, (byte)0x40, (byte)0x3e, (byte)0x58, (byte)0x03, (byte)0xbf,
+ (byte)0xea, (byte)0x3e, (byte)0x34, (byte)0x2c, (byte)0xb7, (byte)0xc3, (byte)0x09,
+ (byte)0xe9, (byte)0xf4, (byte)0x43, (byte)0x41, (byte)0xc4, (byte)0x7c, (byte)0x6e,
+ (byte)0x75, (byte)0x72, (byte)0x5d, (byte)0xfc, (byte)0xa3, (byte)0x75, (byte)0x1d,
+ (byte)0xa0, (byte)0xee, (byte)0xc2, (byte)0x1f, (byte)0x71, (byte)0xb0, (byte)0xf3,
+ (byte)0x1d, (byte)0xec, (byte)0x81, (byte)0xdb, (byte)0x45, (byte)0xe5, (byte)0x6a,
+ (byte)0xe8, (byte)0xe0, (byte)0x64, (byte)0x90, (byte)0xff, (byte)0xb9, (byte)0xf8,
+ (byte)0x12, (byte)0xed, (byte)0x55, (byte)0x5c, (byte)0x9b, (byte)0x81, (byte)0xcd,
+ (byte)0xbb, (byte)0x06, (byte)0x91, (byte)0xfe, (byte)0x27, (byte)0x2c, (byte)0x3a,
+ (byte)0xed, (byte)0x96, (byte)0x3b, (byte)0xfe
+ };
+
+ /*
+ * The same key in PEM format.
+ * The DER version of this key was created using
+ *
+ * openssl pkcs8 -topk8 -nocrypt -in key1.pem
+ * -inform PEM -out key1.der -outform DER
+ *
+ * -----BEGIN RSA PRIVATE KEY-----
+ * Proc-Type: 4,ENCRYPTED
+ * DEK-Info: DES-EDE3-CBC,0EE6B33EC2D92297
+ *
+ * r7lbWwtlmubgMG020XiOStqgrvPkP1hTrbOV7Gh2IVNTyXWyA8UriQlPyqBQNzy2
+ * 5+Z+JUqzYoLCGY0fQ95ck+ya/wHJQX4OSKFOZwQKpU7pEY9wN1YPa7U9ZnyCPGtB
+ * +ejvHuIMJhE5wq9Y1iEDIlON++onWTf4T36Sz3OQ8gEJbnx3x+UjcCINooj7kOeM
+ * giCi5yJEOJaf4fkRioUh6S7cm/msTH3ID33rrvTjk7cD8mGzzTy4hWyKaK4K9GbC
+ * dOvSORM9mVwTWMUdu1wJ5uyadwBhpSIhC/qpP8Je60nFy8YJlzB2FaMUpAuIOM7B
+ * EVN2uAMDNOpGzcOJPbLig8smk2lA4+y1T3gFd9paskSjD9B8+/3KuagWEEQQL7T4
+ * YK3xtjzXwEp6OdG2QjD4ZcK5D0MKuYPF3PszwzlCnBG/On6wIvIiTPWBn/G2u59D
+ * gJPV7V3Jipn0iYYN+i7T5TNoT7Vko8s3BRpVSrlFUFFhtQPad6NcxGNNH5L1g3fF
+ * +dp4TnG64PCQZtuu6I6gfuMXztOwQtEpxxHo9WktlCpwL0tT/tpx+zOVbLvgusjB
+ * QKYCIplbSI7VtpOfcJ3kTTAWSOGZli4FayB/Dplf/FXN6ZwwASw09ioVQc/CFdLk
+ * Xw05elxV8/AFvm+/VkUHK5JJSp32WMgAJA+XrUsOb5lw1Tl3Hlj9KHALp+Pt/i7N
+ * +LPnxrpuTry31APt8aRup/pWOLa+f97Hz+arp4wJa5LK+GtTTtoI4+QZp5qzR/jy
+ * oM+DoKtK+1WsCU7teJwEWXV/ayo1TEFEhcY0F7IAPCzDlG3XOFmulQ==
+ * -----END RSA PRIVATE KEY-----
+ */
+
+ @Override
+ protected void setUp() {
+ String defAlg = KeyManagerFactory.getDefaultAlgorithm();
+ try {
+ factory = KeyManagerFactory.getInstance(defAlg);
+ } catch (NoSuchAlgorithmException e) {
+ fail("could not get default KeyManagerFactory");
+ }
+ }
+
+ void init(String name) {
+ keyType = name;
+ try {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyTest.load(null, "1234".toCharArray());
+ if (keyType.equals(CLIENT)) {
+ keys = new PrivateKey[3];
+ keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
+ keys[1] = kf.generatePrivate(new PKCS8EncodedKeySpec(key2Bytes));
+ keys[2] = kf.generatePrivate(new PKCS8EncodedKeySpec(key3Bytes));
+ cert = new X509Certificate[3];
+ cert[0] = (X509Certificate) cf.generateCertificate(certArray);
+ cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
+ cert[2] = (X509Certificate) cf.generateCertificate(certArray3);
+ keyTest.setKeyEntry("clientKey_01", keys[0], PASSWORD, new X509Certificate[] {cert[0]});
+ keyTest.setKeyEntry("clientKey_02", keys[1], PASSWORD, new X509Certificate[] {cert[0], cert[1]});
+ keyTest.setKeyEntry("clientKey_03", keys[2], PASSWORD, new X509Certificate[] {cert[0], cert[2]});
+ keyTest.setCertificateEntry("clientAlias_01", cert[0]);
+ keyTest.setCertificateEntry("clientAlias_02", cert[0]);
+ keyTest.setCertificateEntry("clientAlias_03", cert[1]);
+ } else if (keyType.equals(SERVER)) {
+ keys = new PrivateKey[1];
+ keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
+ cert = new X509Certificate[1];
+ cert[0] = (X509Certificate) cf.generateCertificate(certArray3);
+ keyTest.setKeyEntry("serverKey_00", keys[0], PASSWORD, new X509Certificate[] {cert[0]});
+ keyTest.setCertificateEntry("serverAlias_00", cert[0]);
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ throw new IllegalArgumentException(ex.getMessage());
+ }
+ try {
+ factory.init(keyTest, "1234".toCharArray());
+ } catch (Exception e) {
+ fail("Could't init the KeyManagerFactory");
+ }
+ manager = (X509KeyManager) factory.getKeyManagers()[0];
+ }
+
+ /**
+ * X509KeyManager#getClientAliases(String keyType, Principal[] issuers)
+ */
+ public void test_getClientAliases() {
+ init(CLIENT);
+ assertNull(manager.getClientAliases(null, null));
+ assertNull(manager.getClientAliases("", null));
+ String[] resArray = manager.getClientAliases(TYPE_RSA, null);
+ assertNotNull(resArray);
+ assertEquals(3, resArray.length);
+ assertKnownAliases(resArray);
+ }
+
+ /**
+ * X509KeyManager#chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
+ */
+ public void test_chooseClientAlias() {
+ init(CLIENT);
+ assertNull(manager.chooseClientAlias(null, null, new Socket()));
+ assertNull(manager.chooseClientAlias(new String[0], null, new Socket()));
+ assertNull(manager.chooseClientAlias(new String[]{"BOGUS"}, null, new Socket()));
+ String res = manager.chooseClientAlias(new String[]{TYPE_RSA}, null, null);
+ assertNotNull(res);
+ assertKnownAlias(res);
+ }
+
+ /**
+ * X509KeyManager#getServerAliases(String keyType, Principal[] issuers)
+ */
+ public void test_getServerAliases() {
+ init(SERVER);
+ assertNull(manager.getServerAliases(null, null));
+ assertNull(manager.getServerAliases("", null));
+ String[] resArray = manager.getServerAliases(TYPE_RSA, null);
+ assertNotNull(resArray);
+ assertEquals("Incorrect length", 1, resArray.length);
+ assertEquals("Incorrect aliase", "serverkey_00", resArray[0].toLowerCase());
+ }
+
+ /**
+ * X509KeyManager#chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
+ */
+ public void test_chooseServerAlias() {
+ init(SERVER);
+ assertNull(manager.chooseServerAlias(null, null, new Socket()));
+ assertNull(manager.chooseServerAlias("", null, new Socket()));
+ String res = manager.chooseServerAlias(TYPE_RSA, null, null);
+ assertNotNull(res);
+ assertEquals("serverkey_00", res.toLowerCase());
+ res = manager.chooseServerAlias(TYPE_RSA, null, new Socket());
+ assertNotNull(res);
+ assertEquals("serverkey_00", res.toLowerCase());
+ }
+
+ /**
+ * X509KeyManager#getCertificateChain(String alias)
+ */
+ public void test_getCertificateChain() {
+ init(SERVER);
+ assertNull("Not NULL for NULL parameter", manager.getCertificateChain(null));
+ assertNull("Not NULL for empty parameter",manager.getCertificateChain(""));
+ assertNull("Not NULL for clientAlias_01 parameter", manager.getCertificateChain("clientAlias_01"));
+ assertNull("Not NULL for serverAlias_00 parameter", manager.getCertificateChain("serverAlias_00"));
+ }
+
+ /**
+ * X509KeyManager#getPrivateKey(String alias)
+ */
+ public void test_getPrivateKey() {
+ init(CLIENT);
+ assertNull("Not NULL for NULL parameter", manager.getPrivateKey(null));
+ assertNull("Not NULL for serverAlias_00 parameter", manager.getPrivateKey("serverAlias_00"));
+ assertNull("Not NULL for clientAlias_02 parameter", manager.getPrivateKey("clientAlias_02"));
+ }
+
+
+ private void assertKnownAliases(String[] aliases) {
+ for (String alias : aliases) {
+ assertKnownAlias(alias);
+ }
+ }
+
+ private void assertKnownAlias(String alias) {
+ String a = alias.toLowerCase();
+ boolean okay = a.equals("clientkey_01") || a.equals("clientkey_02") || a.equals("clientkey_03");
+ assertTrue("Expected one of clientkey_01, clientkey_02, clientkey_03. Received: " + alias, okay);
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509TrustManagerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509TrustManagerTest.java
new file mode 100644
index 0000000..ade0eca
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/net/ssl/X509TrustManagerTest.java
@@ -0,0 +1,149 @@
+package tests.api.javax.net.ssl;
+
+import java.io.ByteArrayInputStream;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import javax.net.ssl.X509TrustManager;
+import junit.framework.TestCase;
+import org.apache.harmony.security.tests.support.cert.TestUtils;
+import org.apache.harmony.xnet.tests.support.X509TrustManagerImpl;
+
+public class X509TrustManagerTest extends TestCase {
+
+ private X509Certificate[] setX509Certificate() throws Exception {
+ CertificateFactory certFact = CertificateFactory.getInstance("X.509");
+ X509Certificate pemCert = (X509Certificate) certFact.generateCertificate(
+ new ByteArrayInputStream(TestUtils.getX509Certificate_v3()));
+ X509Certificate[] xcert = { pemCert };
+ return xcert;
+ }
+
+ private X509Certificate[] setInvalid() throws Exception {
+ CertificateFactory certFact = CertificateFactory.getInstance("X.509");
+ X509Certificate pemCert = (X509Certificate) certFact.generateCertificate(
+ new ByteArrayInputStream(TestUtils.getX509Certificate_v1()));
+ X509Certificate[] xcert = { pemCert };
+ return xcert;
+ }
+
+ public void test_checkClientTrusted_01() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = null;
+
+ try {
+ xtm.checkClientTrusted(xcert, "SSL");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ xcert = new X509Certificate[0];
+ try {
+ xtm.checkClientTrusted(xcert, "SSL");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ xcert = setX509Certificate();
+ try {
+ xtm.checkClientTrusted(xcert, null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ xtm.checkClientTrusted(xcert, "");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
+ */
+ public void test_checkClientTrusted_02() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = setInvalid();
+
+ try {
+ xtm.checkClientTrusted(xcert, "SSL");
+ fail("CertificateException wasn't thrown");
+ } catch (CertificateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
+ */
+ public void test_checkClientTrusted_03() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = setX509Certificate();
+ xtm.checkClientTrusted(xcert, "SSL");
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
+ */
+ public void test_checkServerTrusted_01() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = null;
+
+ try {
+ xtm.checkServerTrusted(xcert, "SSL");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ xcert = new X509Certificate[0];
+ try {
+ xtm.checkServerTrusted(xcert, "SSL");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ xcert = setX509Certificate();
+ try {
+ xtm.checkServerTrusted(xcert, null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ xtm.checkServerTrusted(xcert, "");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
+ */
+ public void test_checkServerTrusted_02() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = setInvalid();
+
+ try {
+ xtm.checkServerTrusted(xcert, "SSL");
+ fail("CertificateException wasn't thrown");
+ } catch (CertificateException expected) {
+ }
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
+ */
+ public void test_checkServerTrusted_03() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ X509Certificate[] xcert = setX509Certificate();
+ xtm.checkServerTrusted(xcert, "SSL");
+ }
+
+ /**
+ * javax.net.ssl.X509TrustManager#getAcceptedIssuers()
+ */
+ public void test_getAcceptedIssuers() throws Exception {
+ X509TrustManagerImpl xtm = new X509TrustManagerImpl();
+ assertNotNull(xtm.getAcceptedIssuers());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyFailedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyFailedExceptionTest.java
new file mode 100644
index 0000000..e274c5c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyFailedExceptionTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.tests.javax.security.auth;
+
+import junit.framework.TestCase;
+import javax.security.auth.DestroyFailedException;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for <code>DestroyFailedException</code> class constructors and methods.
+ *
+ */
+public class DestroyFailedExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * javax.security.auth.DestroyFailedException#DestroyFailedException()
+ * Assertion: constructs DestroyFailedException with no detail message
+ */
+ public void testDestroyFailedException01() {
+ DestroyFailedException dfE = new DestroyFailedException();
+ assertNull("getMessage() must return null.", dfE.getMessage());
+ assertNull("getCause() must return null", dfE.getCause());
+ }
+
+ /**
+ * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg)
+ * Assertion: constructs with not null parameter.
+ */
+ public void testDestroyFailedException02() {
+ DestroyFailedException dfE;
+ for (int i = 0; i < msgs.length; i++) {
+ dfE = new DestroyFailedException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), dfE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", dfE.getCause());
+ }
+ }
+
+ /**
+ * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg)
+ * Assertion: constructs with null parameter.
+ */
+ public void testDestroyFailedException03() {
+ String msg = null;
+ DestroyFailedException dfE = new DestroyFailedException(msg);
+ assertNull("getMessage() must return null.", dfE.getMessage());
+ assertNull("getCause() must return null", dfE.getCause());
+ }
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(getSerializationData());
+ }
+
+ public void testSerializationGolden() throws Exception {
+ SerializationTest.verifyGolden(this, getSerializationData());
+ }
+
+ private Object[] getSerializationData() {
+ return new Object[] { new DestroyFailedException("message") };
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyableTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyableTest.java
new file mode 100644
index 0000000..c419f64
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/DestroyableTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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.tests.javax.security.auth;
+
+import junit.framework.TestCase;
+
+import javax.security.auth.Destroyable;
+import javax.security.auth.DestroyFailedException;
+
+
+/**
+ * Tests for <code>Destroyable</code> class constructors and methods.
+ *
+ */
+public class DestroyableTest extends TestCase {
+
+ /**
+ * javax.security.auth.Destroyable#destroy()
+ * javax.security.auth.Destroyable#isDestroyed()
+ */
+ public void test_destroy() {
+ myDestroyable md = new myDestroyable();
+ try {
+ assertFalse(md.isDestroyed());
+ md.destroy();
+ assertTrue(md.isDestroyed());
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+
+ private class myDestroyable implements Destroyable {
+
+ boolean destroyDone = false;
+
+ myDestroyable() {
+ }
+
+ public void destroy() throws DestroyFailedException {
+ destroyDone = true;
+ }
+
+ public boolean isDestroyed() {
+ return destroyDone;
+ }
+ }
+}
+
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/LoginExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/LoginExceptionTest.java
new file mode 100644
index 0000000..c0540bc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/LoginExceptionTest.java
@@ -0,0 +1,69 @@
+/*
+ * 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.tests.javax.security.auth;
+
+import junit.framework.TestCase;
+
+import javax.security.auth.login.LoginException;
+
+/**
+ * Tests for <code>LoginException</code> class constructors and methods.
+ *
+ */
+public class LoginExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException()
+ * Assertion: constructs LoginException with no detail message
+ */
+ public void testLoginException01() {
+ LoginException lE = new LoginException();
+ assertNull("getMessage() must return null.", lE.getMessage());
+ assertNull("getCause() must return null", lE.getCause());
+ }
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException(String msg)
+ * Assertion: constructs with not null parameter.
+ */
+ public void testLoginException02() {
+ LoginException lE;
+ for (int i = 0; i < msgs.length; i++) {
+ lE = new LoginException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), lE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", lE.getCause());
+ }
+ }
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException(String msg)
+ * Assertion: constructs with null parameter.
+ */
+ public void testLoginException03() {
+ String msg = null;
+ LoginException lE = new LoginException(msg);
+ assertNull("getMessage() must return null.", lE.getMessage());
+ assertNull("getCause() must return null", lE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/SubjectTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/SubjectTest.java
new file mode 100644
index 0000000..f2ef564
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/SubjectTest.java
@@ -0,0 +1,257 @@
+/*
+ * 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.tests.javax.security.auth;
+
+import junit.framework.TestCase;
+import javax.security.auth.Subject;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.ProtectionDomain;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for <code>Subject</code> class constructors and methods.
+ *
+ */
+public class SubjectTest extends TestCase {
+
+ /**
+ * javax.security.auth.Subject#Subject()
+ */
+ public void test_Constructor_01() {
+ try {
+ Subject s = new Subject();
+ assertNotNull("Null object returned", s);
+ assertTrue("Set of principal is not empty", s.getPrincipals().isEmpty());
+ assertTrue("Set of private credentials is not empty", s.getPrivateCredentials().isEmpty());
+ assertTrue("Set of public credentials is not empty", s.getPublicCredentials().isEmpty());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#doAs(Subject subject, PrivilegedAction action)
+ */
+ public void test_doAs_01() {
+ Subject subj = new Subject();
+ PrivilegedAction<Object> pa = new myPrivilegedAction();
+ PrivilegedAction<Object> paNull = null;
+
+ try {
+ Object obj = Subject.doAs(null, pa);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAs(subj, pa);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAs(subj, paNull);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#doAs(Subject subject, PrivilegedExceptionAction action)
+ */
+ public void test_doAs_02() {
+ Subject subj = new Subject();
+ PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction();
+ PrivilegedExceptionAction<Object> peaNull = null;
+
+ try {
+ Object obj = Subject.doAs(null, pea);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAs(subj, pea);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAs(subj, peaNull);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of NullPointerException");
+ }
+
+ try {
+ Subject.doAs(subj, new PrivilegedExceptionAction<Object>(){
+ public Object run() throws PrivilegedActionException {
+ throw new PrivilegedActionException(null);
+ }
+ });
+ fail("PrivilegedActionException wasn't thrown");
+ } catch (PrivilegedActionException e) {
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#doAsPrivileged(Subject subject,
+ * PrivilegedAction action,
+ * AccessControlContext acc)
+ */
+ public void test_doAsPrivileged_01() {
+ Subject subj = new Subject();
+ PrivilegedAction<Object> pa = new myPrivilegedAction();
+ PrivilegedAction<Object> paNull = null;
+ AccessControlContext acc = AccessController.getContext();
+
+ try {
+ Object obj = Subject.doAsPrivileged(null, pa, acc);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAsPrivileged(subj, pa, acc);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAsPrivileged(subj, paNull, acc);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#doAsPrivileged(Subject subject,
+ * PrivilegedExceptionAction action,
+ * AccessControlContext acc)
+ */
+ public void test_doAsPrivileged_02() {
+ Subject subj = new Subject();
+ PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction();
+ PrivilegedExceptionAction<Object> peaNull = null;
+ AccessControlContext acc = AccessController.getContext();
+
+ try {
+ Object obj = Subject.doAsPrivileged(null, pea, acc);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAsPrivileged(subj, pea, acc);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ Object obj = Subject.doAsPrivileged(subj, peaNull, acc);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of NullPointerException");
+ }
+
+ try {
+ Subject.doAsPrivileged(subj, new PrivilegedExceptionAction<Object>(){
+ public Object run() throws PrivilegedActionException {
+ throw new PrivilegedActionException(null);
+ }
+ }, acc);
+ fail("PrivilegedActionException wasn't thrown");
+ } catch (PrivilegedActionException e) {
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#getSubject(AccessControlContext acc)
+ */
+ public void test_getSubject() {
+ Subject subj = new Subject();
+ AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]);
+
+ try {
+ assertNull(Subject.getSubject(acc));
+ } catch (Exception e) {
+ fail("Unexpected exception " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#toString()
+ */
+ public void test_toString() {
+ Subject subj = new Subject();
+
+ try {
+ assertNotNull("Null returned", subj.toString());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.Subject#hashCode()
+ */
+ public void test_hashCode() {
+ Subject subj = new Subject();
+
+ try {
+ assertNotNull("Null returned", subj.hashCode());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(getSerializationData());
+ }
+
+ public void testSerializationGolden() throws Exception {
+ SerializationTest.verifyGolden(this, getSerializationData());
+ }
+
+ private Object[] getSerializationData() {
+ Subject subject = new Subject();
+ return new Object[] { subject, subject.getPrincipals(),
+ subject.getPrivateCredentials(), subject.getPublicCredentials() };
+ }
+}
+
+
+class myPrivilegedAction implements PrivilegedAction <Object> {
+ myPrivilegedAction(){}
+ public Object run() {
+ return new Object();
+ }
+}
+
+class myPrivilegedExceptionAction implements PrivilegedExceptionAction <Object> {
+ myPrivilegedExceptionAction(){}
+ public Object run() {
+ return new Object();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/CallbackHandlerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/CallbackHandlerTest.java
new file mode 100644
index 0000000..0b4d0fe
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/CallbackHandlerTest.java
@@ -0,0 +1,47 @@
+/*
+ * 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.tests.javax.security.auth.callback;
+
+import junit.framework.TestCase;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+
+/**
+ * Tests for <code>CallbackHandler</code> class constructors and methods.
+ *
+ */
+public class CallbackHandlerTest extends TestCase {
+
+ /**
+ * javax.security.auth.callback.CallbackHandler#handle(Callback[] callbacks)
+ */
+ public void test_CallbackHandler() {
+ CallbackHandlerImpl ch = new CallbackHandlerImpl();
+ assertFalse(ch.called);
+ ch.handle(null);
+ assertTrue(ch.called);
+ }
+
+ private class CallbackHandlerImpl implements CallbackHandler {
+ boolean called = false;
+ public void handle(Callback[] callbacks) {
+ called = true;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/PasswordCallbackTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/PasswordCallbackTest.java
new file mode 100644
index 0000000..024c9e9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/PasswordCallbackTest.java
@@ -0,0 +1,137 @@
+/*
+ * 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.tests.javax.security.auth.callback;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import javax.security.auth.callback.PasswordCallback;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for <code>PasswordCallback</code> class constructors and methods.
+ *
+ */
+public class PasswordCallbackTest extends TestCase {
+
+ /**
+ * javax.security.auth.callback.PasswordCallback#PasswordCallback(String prompt, boolean echoOn)
+ * javax.security.auth.callback.PasswordCallback#getPrompt()
+ * javax.security.auth.callback.PasswordCallback#isEchoOn()
+ */
+ public void test_PasswordCallback() {
+ String prompt = "promptTest";
+
+ try {
+ PasswordCallback pc = new PasswordCallback(prompt, true);
+ assertNotNull("Null object returned", pc);
+ assertEquals(prompt, pc.getPrompt());
+ assertEquals(true, pc.isEchoOn());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ PasswordCallback pc = new PasswordCallback(prompt, false);
+ assertNotNull("Null object returned", pc);
+ assertEquals(prompt, pc.getPrompt());
+ assertEquals(false, pc.isEchoOn());
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ PasswordCallback pc = new PasswordCallback(null, true);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ }
+
+ try {
+ PasswordCallback pc = new PasswordCallback("", true);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ }
+ }
+
+ /**
+ * javax.security.auth.callback.PasswordCallback#getPassword()
+ * javax.security.auth.callback.PasswordCallback#setPassword(char[] password)
+ * javax.security.auth.callback.PasswordCallback#clearPassword()
+ */
+ public void test_Password() {
+ String prompt = "promptTest";
+ char[] psw1 = "testPassword".toCharArray();
+ char[] psw2 = "newPassword".toCharArray();
+ PasswordCallback pc = new PasswordCallback(prompt, true);
+
+ try {
+ assertNull(pc.getPassword());
+ pc.setPassword(psw1);
+ assertEquals(psw1.length, pc.getPassword().length);
+ pc.setPassword(null);
+ assertNull(pc.getPassword());
+ pc.setPassword(psw2);
+ char[] res = pc.getPassword();
+ assertEquals(psw2.length, res.length);
+ for (int i = 0; i < res.length; i++) {
+ assertEquals("Incorrect password was returned", psw2[i], res[i]);
+ }
+ pc.clearPassword();
+ res = pc.getPassword();
+ if (res.equals(psw2)) {
+ fail("Incorrect password was returned after clear");
+ }
+ pc.setPassword(psw1);
+ res = pc.getPassword();
+ assertEquals(psw1.length, res.length);
+ for (int i = 0; i < res.length; i++) {
+ assertEquals("Incorrect result", psw1[i], res[i]);
+ }
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(getSerializationData(), new PasswordCallbackAssert());
+ }
+
+ public void testSerializationGolden() throws Exception {
+ SerializationTest.verifyGolden(this, getSerializationData(),
+ new PasswordCallbackAssert());
+ }
+
+ private Object[] getSerializationData() {
+ char[] pwd = { 'a', 'b', 'c' };
+ PasswordCallback p = new PasswordCallback("prmpt", true);
+ p.setPassword(pwd);
+ return new Object[] { new PasswordCallback("prompt", true), p };
+ }
+
+ public static final class PasswordCallbackAssert implements SerializationTest.SerializableAssert {
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ final PasswordCallback callback1 = (PasswordCallback) initial;
+ final PasswordCallback callback2 = (PasswordCallback) deserialized;
+
+ assertTrue(Arrays.equals(callback1.getPassword(), callback2.getPassword()));
+ assertEquals(callback1.getPrompt(), callback2.getPrompt());
+ assertEquals(callback1.isEchoOn(), callback2.isEchoOn());
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/UnsupportedCallbackExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/UnsupportedCallbackExceptionTest.java
new file mode 100644
index 0000000..defdbc7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/callback/UnsupportedCallbackExceptionTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.tests.javax.security.auth.callback;
+
+import junit.framework.TestCase;
+
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.callback.Callback;
+
+/**
+ * Tests for <code>UnsupportedCallbackException</code> class constructors and methods.
+ *
+ */
+public class UnsupportedCallbackExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback)
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback()
+ * Assertion: constructs with null parameter.
+ */
+ public void testUnsupportedCallbackException01() {
+ Callback c = null;
+ UnsupportedCallbackException ucE = new UnsupportedCallbackException(c);
+ assertNull("getMessage() must return null.", ucE.getMessage());
+ assertNull("getCallback() must return null", ucE.getCallback());
+ }
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback)
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback()
+ * Assertion: constructs with not null parameter.
+ */
+ public void testUnsupportedCallbackException02() {
+ myCallback c = new myCallback();
+ assertNotNull("Callback object is null", c);
+ UnsupportedCallbackException ucE = new UnsupportedCallbackException(c);
+ assertNull("getMessage() must return null.", ucE.getMessage());
+ assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
+ }
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
+ * Assertion: constructs with null callback parameter and null message.
+ */
+ public void testUnsupportedCallbackException03() {
+ UnsupportedCallbackException ucE = new UnsupportedCallbackException(null, null);
+ assertNull("getMessage() must return null.", ucE.getMessage());
+ assertNull("getCallback() must return null.", ucE.getCallback());
+ }
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
+ * Assertion: constructs with null callback parameter and not null message.
+ */
+ public void testUnsupportedCallbackException04() {
+ UnsupportedCallbackException ucE;
+ for (int i = 0; i < msgs.length; i++) {
+ ucE = new UnsupportedCallbackException(null, msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]);
+ assertNull("getCallback() must return null.", ucE.getCallback());
+ }
+ }
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
+ * Assertion: constructs with not null callback parameter and null message.
+ */
+ public void testUnsupportedCallbackException05() {
+ myCallback c = new myCallback();
+ assertNotNull("Callback object is null", c);
+ UnsupportedCallbackException ucE = new UnsupportedCallbackException(c, null);
+ assertNull("getMessage() must return null.", ucE.getMessage());
+ assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
+ }
+
+ /**
+ * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
+ * Assertion: constructs with not null parameters.
+ */
+ public void testUnsupportedCallbackException06() {
+ myCallback c = new myCallback();
+ assertNotNull("Callback object is null", c);
+ UnsupportedCallbackException ucE;
+ for (int i = 0; i < msgs.length; i++) {
+ ucE = new UnsupportedCallbackException(c, msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]);
+ assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
+ }
+ }
+}
+
+class myCallback implements Callback {
+ myCallback(){
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/login/LoginExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/login/LoginExceptionTest.java
new file mode 100644
index 0000000..2d63f16
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/login/LoginExceptionTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.tests.javax.security.auth.login;
+
+import junit.framework.TestCase;
+
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.login.LoginException;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for <code>LoginException</code> class constructors and methods.
+ *
+ */
+public class LoginExceptionTest extends TestCase {
+
+ private static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException()
+ * Assertion: constructs LoginException with no detail message
+ */
+ public void testLoginException01() {
+ LoginException lE = new LoginException();
+ assertNull("getMessage() must return null.", lE.getMessage());
+ assertNull("getCause() must return null", lE.getCause());
+ }
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException(String msg)
+ * Assertion: constructs with not null parameter.
+ */
+ public void testLoginException02() {
+ LoginException lE;
+ for (int i = 0; i < msgs.length; i++) {
+ lE = new LoginException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), lE.getMessage(), msgs[i]);
+ assertNull("getCause() must return null", lE.getCause());
+ }
+ }
+
+ /**
+ * javax.security.auth.login.LoginException#LoginException(String msg)
+ * Assertion: constructs with null parameter.
+ */
+ public void testLoginException03() {
+ String msg = null;
+ LoginException lE = new LoginException(msg);
+ assertNull("getMessage() must return null.", lE.getMessage());
+ assertNull("getCause() must return null", lE.getCause());
+ }
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(getSerializationData());
+ }
+
+ public void testSerializationGolden() throws Exception {
+ SerializationTest.verifyGolden(this, getSerializationData());
+ }
+
+ private Object[] getSerializationData() {
+ return new Object[] { new LoginException("message") };
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/x500/X500PrincipalTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/x500/X500PrincipalTest.java
new file mode 100644
index 0000000..34011c7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/auth/x500/X500PrincipalTest.java
@@ -0,0 +1,3094 @@
+/*
+ * 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.tests.javax.security.auth.x500;
+
+import javax.security.auth.x500.X500Principal;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.security.tests.support.cert.TestUtils;
+import tests.support.resource.Support_Resources;
+
+
+/**
+ * Tests for <code>X500Principal</code> class constructors and methods.
+ *
+ */
+public class X500PrincipalTest extends TestCase {
+
+ /**
+ * javax.security.auth.x500.X500Principal#X500Principal(String name)
+ */
+ public void test_X500Principal_01() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+
+ try {
+ X500Principal xpr = new X500Principal(name);
+ assertNotNull("Null object returned", xpr);
+ String resName = xpr.getName();
+ assertEquals(name, resName);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ X500Principal xpr = new X500Principal((String)null);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of NullPointerException");
+ }
+
+ try {
+ X500Principal xpr = new X500Principal("X500PrincipalName");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of IllegalArgumentException");
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#X500Principal(InputStream is)
+ */
+ public void test_X500Principal_02() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+ byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
+ ByteArrayInputStream is = new ByteArrayInputStream(ba);
+ InputStream isNull = null;
+
+ try {
+ X500Principal xpr = new X500Principal(is);
+ assertNotNull("Null object returned", xpr);
+ byte[] resArray = xpr.getEncoded();
+ assertEquals(ba.length, resArray.length);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ X500Principal xpr = new X500Principal(isNull);
+ fail("NullPointerException wasn't thrown");
+ } catch (NullPointerException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of NullPointerException");
+ }
+
+ is = new ByteArrayInputStream(name.getBytes());
+ try {
+ X500Principal xpr = new X500Principal(is);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of IllegalArgumentException");
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#X500Principal(byte[] name)
+ */
+ public void test_X500Principal_03() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+ byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
+ byte[] baNull = null;
+
+ try {
+ X500Principal xpr = new X500Principal(ba);
+ assertNotNull("Null object returned", xpr);
+ byte[] resArray = xpr.getEncoded();
+ assertEquals(ba.length, resArray.length);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ X500Principal xpr = new X500Principal(baNull);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of IllegalArgumentException");
+ }
+
+ ba = name.getBytes();
+ try {
+ X500Principal xpr = new X500Principal(ba);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException npe) {
+ } catch (Exception e) {
+ fail(e + " was thrown instead of IllegalArgumentException");
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#getName()
+ */
+ public void test_getName() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+ X500Principal xpr = new X500Principal(name);
+ try {
+ String resName = xpr.getName();
+ assertEquals(name, resName);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#getName(String format)
+ */
+ public void test_getName_Format() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+ String expectedName = "cn=duke,ou=javasoft,o=sun microsystems,c=us";
+ X500Principal xpr = new X500Principal(name);
+ try {
+ String resName = xpr.getName(X500Principal.CANONICAL);
+ assertEquals(expectedName, resName);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ expectedName = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
+ try {
+ String resName = xpr.getName(X500Principal.RFC1779);
+ assertEquals(expectedName, resName);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ String resName = xpr.getName(X500Principal.RFC2253);
+ assertEquals(name, resName);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+
+ try {
+ String resName = xpr.getName(null);
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException iae) {
+ }
+ try {
+ String resName = xpr.getName("RFC2254");
+ fail("IllegalArgumentException wasn't thrown");
+ } catch (IllegalArgumentException iae) {
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#hashCode()
+ */
+ public void test_hashCode() {
+ String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
+ X500Principal xpr = new X500Principal(name);
+ try {
+ int res = xpr.hashCode();
+ assertNotNull(res);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#toString()
+ */
+ public void test_toString() {
+ String name = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
+ X500Principal xpr = new X500Principal(name);
+ try {
+ String res = xpr.toString();
+ assertNotNull(res);
+ assertEquals(name, res);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#getEncoded()
+ */
+ public void test_getEncoded() {
+ byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
+ X500Principal xpr = new X500Principal(ba);
+ try {
+ byte[] res = xpr.getEncoded();
+ assertNotNull(res);
+ assertEquals(ba.length, res.length);
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ /**
+ * javax.security.auth.x500.X500Principal#equals(Object o)
+ */
+ public void test_equals() {
+ String name1 = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
+ String name2 = "cn=duke,ou=javasoft,o=sun microsystems,c=us";
+ String name3 = "CN=Alex Astapchuk, OU=SSG, O=Intel ZAO, C=RU";
+ X500Principal xpr1 = new X500Principal(name1);
+ X500Principal xpr2 = new X500Principal(name2);
+ X500Principal xpr3 = new X500Principal(name3);
+ try {
+ assertTrue("False returned", xpr1.equals(xpr2));
+ assertFalse("True returned", xpr1.equals(xpr3));
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e);
+ }
+ }
+
+ private byte[] getByteArray(byte[] array) {
+ byte[] x = null;
+ try {
+ ByteArrayInputStream is = new ByteArrayInputStream(array);
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate cert = (X509Certificate)cf.generateCertificate(is);
+ X500Principal xx = cert.getIssuerX500Principal();
+ x = xx.getEncoded();
+ } catch (Exception e) {
+ return null;
+ }
+ return x;
+ }
+
+ /**
+ * @tests javax.security.auth.x500.X500Principal#X500Principal(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ X500Principal principal = new X500Principal(
+ "CN=Hermione Granger, O=Apache Software Foundation, OU=Harmony, L=Hogwarts, ST=Hants, C=GB");
+ String name = principal.getName();
+ String expectedOuput = "CN=Hermione Granger,O=Apache Software Foundation,OU=Harmony,L=Hogwarts,ST=Hants,C=GB";
+ assertEquals("Output order precedence problem", expectedOuput, name);
+ }
+
+ /**
+ * @tests javax.security.auth.x500.X500Principal#X500Principal(java.lang.String, java.util.Map)
+ */
+ public void test_ConstructorLjava_lang_String_java_util_Map() {
+ Map<String, String> keyword = new HashMap<String, String>();
+ keyword.put("CN", "2.19");
+ keyword.put("OU", "1.2.5.19");
+ keyword.put("O", "1.2.5");
+ X500Principal X500p = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US ,CN=DD", keyword);
+ String name = X500p.getName();
+ String expectedOut = "2.19=#130444756b65,1.2.5.19=#13084a617661536f6674,1.2.5=#131053756e204d6963726f73797374656d73,C=US,2.19=#13024444";
+ assertEquals("Output order precedence problem", expectedOut, name);
+ }
+
+ /**
+ * @tests javax.security.auth.x500.X500Principal#getName(java.lang.String)
+ */
+ public void test_getNameLjava_lang_String() {
+ X500Principal principal = new X500Principal(
+ "CN=Dumbledore, OU=Administration, O=Hogwarts School, C=GB");
+ String canonical = principal.getName(X500Principal.CANONICAL);
+ String expected = "cn=dumbledore,ou=administration,o=hogwarts school,c=gb";
+ assertEquals("CANONICAL output differs from expected result", expected,
+ canonical);
+ }
+
+ /**
+ * @tests javax.security.auth.x500.X500Principal#getName(java.lang.String, java.util.Map)
+ */
+ public void test_getNameLjava_lang_String_java_util_Map() {
+ Map<String, String> keyword = new HashMap<String, String>();
+ keyword.put("CN", "2.19");
+ keyword.put("OU", "1.2.5.19");
+ keyword.put("O", "1.2.5");
+ X500Principal X500p = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US ,CN=DD", keyword);
+ keyword = new HashMap<String, String>();
+ keyword.put("2.19", "mystring");
+ String rfc1779Name = X500p.getName("RFC1779", keyword);
+ String rfc2253Name = X500p.getName("RFC2253", keyword);
+ String expected1779Out = "mystring=Duke, OID.1.2.5.19=JavaSoft, OID.1.2.5=Sun Microsystems, C=US, mystring=DD";
+ String expected2253Out = "mystring=Duke,1.2.5.19=#13084a617661536f6674,1.2.5=#131053756e204d6963726f73797374656d73,C=US,mystring=DD";
+ assertEquals("Output order precedence problem", expected1779Out, rfc1779Name);
+ assertEquals("Output order precedence problem", expected2253Out, rfc2253Name);
+ try {
+ X500p.getName("CANONICAL", keyword);
+ fail("Should throw IllegalArgumentException exception here");
+ } catch (IllegalArgumentException e) {
+ //expected IllegalArgumentException here
+ }
+ }
+
+ private boolean testing = false;
+
+ public void testStreamPosition() throws Exception {
+ //this encoding is read from the file
+ /*byte [] mess = {0x30, 0x30,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41,
+ 1, 2, 3//extra bytes
+ };
+ */
+
+ InputStream is = Support_Resources
+ .getResourceStream("X500PrincipalTest.0.dat");
+ X500Principal principal = new X500Principal(is);
+ String s = principal.toString();
+ assertEquals("CN=A, CN=B, CN=A, CN=B", s);
+ byte[] restBytes = new byte[] { 0, 0, 0 };
+ is.read(restBytes);
+ assertEquals(restBytes[0], 1);
+ assertEquals(restBytes[1], 2);
+ assertEquals(restBytes[2], 3);
+ is.close();
+ }
+
+ public void testStreamPosition_0() throws Exception {
+ //this encoding is read from the file
+ /*byte [] mess = {0x30, 0x30,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41,
+ };
+ */
+
+ InputStream is = Support_Resources
+ .getResourceStream("X500PrincipalTest.1.dat");
+ X500Principal principal = new X500Principal(is);
+ String s = principal.toString();
+ assertEquals("CN=A, CN=B, CN=A, CN=B", s);
+ assertEquals(0, is.available());
+ is.close();
+ }
+
+ public void testStreamPosition_1() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 2,
+ 3, 4 };
+
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ X500Principal principal = new X500Principal(is);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals(
+ "CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=Z",
+ s);
+ assertEquals(3, is.available());
+ assertEquals(2, is.read());
+ assertEquals(3, is.read());
+ assertEquals(4, is.read());
+ }
+
+ public void testStreamPosition_2() throws Exception {
+ byte[] mess = { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x41, 2 };
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ X500Principal principal = new X500Principal(is);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A", s);
+ assertEquals(1, is.available());
+ assertEquals(2, is.read());
+ }
+
+ public void testEncodingFromFile() throws Exception {
+ //this encoding is read from the file
+ /*byte [] mess = {0x30, 0x30,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41
+ };
+ */
+ InputStream is = Support_Resources
+ .getResourceStream("X500PrincipalTest.1.dat");
+ X500Principal principal = new X500Principal(is);
+ String s = principal.toString();
+ assertEquals("CN=A, CN=B, CN=A, CN=B", s);
+ is.close();
+ }
+
+ public void testEncodingFromEncoding() {
+ byte[] arr1 = new X500Principal("O=Org.").getEncoded();
+ byte[] arr2 = new X500Principal(new X500Principal("O=Org.")
+ .getEncoded()).getEncoded();
+ assertTrue(Arrays.equals(arr1, arr2));
+ }
+
+ /**
+ * tests if the encoding is backed
+ */
+ public void testSafeEncoding() {
+ byte[] mess = { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+ mess[mess.length - 1] = (byte) 0xFF;
+ byte[] enc = principal.getEncoded();
+ assertEquals(enc[mess.length - 1], 0x41);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets toString
+ * checks the result
+ */
+ public void testToString() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.toString();
+ assertNotNull(s);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets hashCode
+ * compares with expected value
+ */
+ public void testHashCode() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+ int hash = principal.hashCode();
+ assertEquals(principal.getName(X500Principal.CANONICAL).hashCode(),
+ hash);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * Inits other X500Principal with equivalent string
+ * checks if <code>equals</code> returns true for first against second one
+ */
+ public void testEquals() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+ X500Principal principal2 = new X500Principal("CN=A, CN=B");
+ assertTrue(principal.equals(principal2));
+ }
+
+ /**
+ * @tests javax.security.auth.x500.X500Principal#equals(Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ X500Principal xp1 = new X500Principal(
+ "C=US, ST=California, L=San Diego, O=Apache, OU=Project Harmony, CN=Test cert");
+ assertEquals(
+ "C=US,ST=California,L=San Diego,O=Apache,OU=Project Harmony,CN=Test cert",
+ xp1.getName());
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does fall into any keyword, but not given as a keyword
+ * Value is given as hex value
+ * (extra spaces are given)
+ * gets Name in RFC1779 format
+ * compares with expected value of name
+ */
+ public void testKWAsOid_RFC1779() throws Exception {
+ String dn = "CN=A, OID.2.5.4.3 = #130142";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A, CN=B", s);
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does fall into any keyword, but not given as a keyword
+ * Value is given as hex value
+ * (extra spaces are given)
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testKWAsOid_RFC2253() throws Exception {
+ String dn = "CN=A, OID.2.5.4.3 = #130142";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A,CN=B", s);
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does fall into any keyword, but not given as a keyword
+ * Value is given as hex value
+ * (extra spaces are given)
+ * gets Name in CANONICAL format
+ * compares with expected value of name
+ */
+ public void testKWAsOid_CANONICAL() throws Exception {
+ String dn = "CN=A, OID.2.5.4.3 = #130142";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a,cn=b", s);
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does not fall into any keyword
+ * gets Name in RFC1779 format
+ * compares with expected value of name
+ */
+ public void testOid_RFC1779() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[8] = 0x60;
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A, OID.2.16.4.3=B", s);
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does not fall into any keyword
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testOid_RFC2253() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x4F, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[8] = 0x60;
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A,2.16.4.3=#13014f", s);
+ }
+
+ /**
+ * Inits X500Principal with byte array, where Oid does not fall into any keyword
+ * gets Name in CANONICAL format
+ * compares with expected value of name
+ */
+ public void testOid_CANONICAL() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x4F, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[8] = 0x60;
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a,2.16.4.3=#13014f", s);
+ }
+
+ /**
+ * Inits X500Principal with a string
+ * gets encoded form
+ * compares with expected byte array
+ */
+ public void testNameGetEncoding() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ String dn = "CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=Z";
+ X500Principal principal = new X500Principal(dn);
+ byte[] s = principal.getEncoded();
+
+ assertTrue(Arrays.equals(mess, s));
+ }
+
+ /**
+ * Inits X500Principal with a string
+ * gets encoded form
+ * compares with expected byte array
+ */
+ public void testNameGetEncoding_01() throws Exception {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ String dn = "CN=A,CN=B";
+ X500Principal principal = new X500Principal(dn);
+ byte[] s = principal.getEncoded();
+
+ assertTrue(Arrays.equals(mess, s));
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in RFC1779 format
+ * compares with expected value of name
+ */
+ public void testGetName_RFC1779() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals(
+ "CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=Z",
+ s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testGetName_RFC2253() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals(
+ "CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=Z",
+ s);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in CANONICAL format
+ * compares with expected value of name
+ */
+ public void testGetName_CANONICAL() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ X500Principal principal = new X500Principal(mess);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals(
+ "CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=Z"
+ .toLowerCase(Locale.US), s);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in RFC1779 format
+ * compares with expected value of name
+ */
+ public void testStreamGetName_RFC1779() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ X500Principal principal = new X500Principal(is);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals(
+ "CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=A + ST=CA, O=B, L=C, C=D, OU=E, CN=Z",
+ s);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testStreamGetName_RFC2253() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ X500Principal principal = new X500Principal(is);
+
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals(
+ "CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=Z",
+ s);
+ }
+
+ /**
+ * Inits X500Principal with byte array
+ * gets Name in CANONICAL format
+ * compares with expected value of name
+ */
+ public void testStreamGetName_CANONICAL() throws Exception {
+ byte[] mess = { 0x30, (byte) 0x81, (byte) 0x9A, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x5A, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01, 0x45,
+ 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
+ 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30, 0x09,
+ 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41, 0x31,
+ 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x01,
+ 0x45, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x06,
+ 0x13, 0x01, 0x44, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x07, 0x13, 0x01, 0x43, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x0A, 0x13, 0x01, 0x42, 0x31, 0x15, 0x30,
+ 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02, 0x43, 0x41 };
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ X500Principal principal = new X500Principal(is);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals(
+ "CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=A+ST=CA,O=B,L=C,C=D,OU=E,CN=Z"
+ .toLowerCase(Locale.US), s);
+ }
+
+ /**
+ * Inits X500Principal with a string, where OID does not fall into any keyword
+ * gets encoded form
+ * inits new X500Principal with the encoding
+ * gets string in RFC1779 format
+ * compares with expected value
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_SeveralRDNs_RFC1779()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B; CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.RFC1779);
+ assertEquals("OID.2.16.4.3=B, CN=A", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, where OID does not fall into any keyword
+ * gets encoded form
+ * inits new X500Principal with the encoding
+ * gets string in RFC2253 format
+ * compares with expected value
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_SeveralRDNs_RFC2253()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B; CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.RFC2253);
+ assertEquals("2.16.4.3=#130142,CN=A", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, where OID does not fall into any keyword
+ * gets encoded form
+ * inits new X500Principal with the encoding
+ * gets string in CANONICAL format
+ * compares with expected value
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_SeveralRDNs_CANONICAL()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B; CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.CANONICAL);
+ assertEquals("2.16.4.3=#130142,cn=a", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, where OID does not fall into any keyword
+ * gets string in RFC1779 format
+ * compares with expected value
+ */
+ public void testGetName_wrongOidButGoodName_RFC1779() throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("OID.2.16.4.3=B + CN=A", s);
+ }
+
+ /**
+ * Inits X500Principal with a string, where OID does not fall into any keyword
+ * gets string in RFC2253 format
+ * compares with expected value
+ */
+ public void testGetName_wrongOidButGoodName_RFC2253() throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("2.16.4.3=#130142+CN=A", s);
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder() throws Exception {
+ String dn = "ST=C + CN=A; OU=B + CN=D";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a+st=c,cn=d+ou=b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and Oid which does not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_01() throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a+2.16.4.3=#130142", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and Oid which does not fall into any keyword, and value given in hex format
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_02() throws Exception {
+ String dn = "OID.2.16.4.3=#13024220+ CN=A";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a+2.16.4.3=#13024220", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and 2 Oids which do not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_03() throws Exception {
+ String dn = "OID.2.16.4.9=A + OID.2.16.4.3=B";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("2.16.4.3=#130142+2.16.4.9=#130141", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and 2 Oids which do not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_04() throws Exception {
+ String dn = "OID.2.2.2.2=A + OID.1.1.1.1=B";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("1.1.1.1=#130142+2.2.2.2=#130141", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and 2 Oids which do not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_05() throws Exception {
+ String dn = "OID.2.16.4.9=A + OID.2.16.4=B";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("2.16.4=#130142+2.16.4.9=#130141", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and 2 Oids which do not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_06() throws Exception {
+ String dn = "OID.1.1.2=A + OID.1.2=B";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("1.1.2=#130141+1.2=#130142", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and 2 Oids which do not fall into any keyword
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_CANONICAL_SortOrder_07() throws Exception {
+ String dn = "OID.1.1.1=A + OID.1.1=B";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("1.1=#130142+1.1.1=#130141", s);
+
+ }
+
+ /**
+ * FIXME test is failed - implement unicode normalization
+ *
+ * @throws Exception
+ */
+ public void testGetNameUnicodeNormalized() throws Exception {
+ String unicodeStr = "CN= \u0401\u0410";
+ X500Principal principal = new X500Principal(unicodeStr);
+ principal.getName(X500Principal.CANONICAL);
+ }
+
+ /**
+ * Inits X500Principal with empty string
+ * gets encoding
+ * compares with expected encoding
+ */
+ public void testEmptyInputName() {
+ String dn = "CN=\"\"";
+ byte[] mess = { 0x30, 0x0B, 0x31, 0x09, 0x30, 0x07, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x00 };
+ X500Principal principal = new X500Principal(dn);
+ assertTrue(Arrays.equals(mess, principal.getEncoded()));
+ }
+
+ /**
+ * Inits X500Principal with string as single escaped space
+ * gets encoding
+ * compares with expected encoding
+ */
+ public void testNameSingleEscapedSpace() {
+ String dn = "CN=\\ ";
+ byte[] mess = { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x20 };
+ X500Principal principal = new X500Principal(dn);
+ assertTrue(Arrays.equals(mess, principal.getEncoded()));
+ }
+
+ /**
+ * Inits X500Principal with string with spaces
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testNameOnlySpaces_RFC1779() {
+ String dn = "CN=\" \"";
+ X500Principal principal = new X500Principal(dn);
+ assertEquals("CN=\" \"", principal.getName(X500Principal.RFC1779));
+ }
+
+ /**
+ * Inits X500Principal with string with spaces
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testNameOnlySpaces_RFC2253() {
+ String dn = "CN=\" \"";
+ X500Principal principal = new X500Principal(dn);
+ assertEquals("CN=\\ \\ ", principal.getName(X500Principal.RFC2253));
+ }
+
+ /**
+ * Inits X500Principal with string with only spaces,
+ * gets Name in CANONICAL format:leading and trailing white space
+ * chars are removed even string doesn't have other chars (bug???)
+ */
+ public void testNameOnlySpaces_CANONICAL() {
+ String dn = "CN=\" \"";
+ X500Principal principal = new X500Principal(dn);
+ assertEquals("cn=", principal.getName(X500Principal.CANONICAL));
+ }
+
+ ///*** Negative Tests ***///
+
+ /**
+ * Inits X500Principal with string, where DN name is improper "CNN"
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName() {
+ try {
+ String dn = "CNN=A";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper input name \"CNN\"");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where there is leading ';'
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_01() {
+ try {
+ String dn = ";CN=A";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on leading ';' in input name");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where there is leading '='
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_02() {
+ try {
+ String dn = "=CN=A";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on leading '=' in input name");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where there is no value
+ * checks if proper exception is thrown
+ */
+ public void testEmptyInputName_0() {
+ String dn = "CN=";
+ byte[] mess = { 0x30, 0x0B, 0x31, 0x09, 0x30, 0x07, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x00 };
+ X500Principal principal = new X500Principal(dn);
+ assertTrue(Arrays.equals(mess, principal.getEncoded()));
+ }
+
+ public void testEmptyInputName_1() {
+ String dn = "CN=\"\", C=\"\"";
+ X500Principal principal = new X500Principal(dn);
+ dn = "CN=, C=";
+ X500Principal principal2 = new X500Principal(dn);
+ assertTrue(Arrays.equals(principal.getEncoded(), principal2
+ .getEncoded()));
+
+ }
+
+ public void testEmptyInputName_2() {
+ String dn = "CN=\"\" + OU=A, C=\"\"";
+ X500Principal principal = new X500Principal(dn);
+ dn = "CN=+OU=A, C=";
+ X500Principal principal2 = new X500Principal(dn);
+ assertTrue(Arrays.equals(principal.getEncoded(), principal2
+ .getEncoded()));
+
+ }
+
+ public void testIllegalInputName_15() {
+ try {
+ String dn = "CN=,C";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ public void testIllegalInputName_16() {
+ try {
+ String dn = "CN=,C=+";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given in wrong hex format
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_04() {
+ try {
+ String dn = "CN=#XYZ";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper hex value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_05() {
+ try {
+ String dn = "CN=X+YZ";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * Compatibility issue: according RFC 2253 such string is invalid
+ * but we accept it, not string char is escaped
+ */
+ public void testIllegalInputName_06() {
+ String dn = "CN=X=YZ";
+ X500Principal p = new X500Principal(dn);
+ assertEquals("CN=X\\=YZ", p.getName(X500Principal.RFC2253));
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with not string chars
+ * Compatibility issue: according RFC 2253 such string is invalid
+ * but we accept it, not string char is escaped
+ */
+ public void testIllegalInputName_07() {
+ String dn = "CN=X\"YZ";
+ X500Principal p = new X500Principal(dn);
+ assertEquals("CN=X\\\"YZ", p.getName(X500Principal.RFC2253));
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * Compatibility issue: according RFC 2253 such string is invalid
+ * but we accept it, special char is escaped
+ */
+ public void testIllegalInputName_08() {
+ String dn = "CN=X<YZ";
+ X500Principal p = new X500Principal(dn);
+ assertEquals("CN=X\\<YZ", p.getName(X500Principal.RFC2253));
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_09() {
+ try {
+ String dn = "CN=#";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute hex value");
+ } catch (IllegalArgumentException e) {
+ //ignore
+ }
+
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_10() {
+ try {
+ String dn = "CN=#13";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute hex value");
+ } catch (IllegalArgumentException e) {
+ //ignore
+ }
+
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_11() {
+ try {
+ String dn = "CN=#1301";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute hex value");
+ } catch (IllegalArgumentException e) {
+ //ignore
+ }
+
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_12() {
+ try {
+ String dn = "CN=#13010101";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute hex value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given with special chars
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputName_13() {
+ try {
+ String dn = "CN=# 0";
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper attribute hex value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string, where value is given in hex format, but improper tag
+ * checks if it is ignored
+ */
+ public void testSemiIllegalInputName_14() {
+ String dn = "CN=#7E0142";
+ new X500Principal(dn);
+ }
+
+ public void testInitClause() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[3] = 0x12;//length field
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper length field");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array = null
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_0() {
+ try {
+ byte[] mess = null;
+ new X500Principal(mess);
+ fail("No IllegalArgumentException on input array with improper length field");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong length field
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[3] = 0x12;//length field
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper length field");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with input stream with wrong length field
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_is() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[3] = 0x12;//length field
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ new X500Principal(is);
+
+ fail("No IllegalArgumentException on input array with improper length field");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong inner Sequence tag field
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_01() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[4] = 0x12;//inner Sequence tag field
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper inner Sequence tag field");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong last byte of OID
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_02() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[10] = (byte) 0xFE;//last byte of OID
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper last byte of OID");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong length of OID
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_03() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[7] = 2;//length of OID
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper length of OID");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong tag of value
+ * checks if it is ignored
+ */
+ public void testSemiIllegalInputArray_04() {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08, 0x06,
+ 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[11] = (byte) 0x0F;//tag of value
+ new X500Principal(mess);
+ }
+
+ /**
+ * Inits X500Principal with byte array with wrong length of value
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_05() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[12] = 2;//length of value
+ new X500Principal(mess);
+
+ fail("No IllegalArgumentException on input array with improper length of value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with input stream with wrong length of value
+ * checks if proper exception is thrown
+ */
+ public void testIllegalInputArray_05_is() {
+ try {
+ byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
+ 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
+ mess[12] = 2;//length of value
+ ByteArrayInputStream is = new ByteArrayInputStream(mess);
+ new X500Principal(is);
+
+ fail("No IllegalArgumentException on input array with improper length of value");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with string
+ * Calls getName with improper parameter as format
+ * checks if proper exception is thrown
+ */
+ public void testIllegalFormat() {
+ try {
+ String dn = "CN=A";
+ X500Principal principal = new X500Principal(dn);
+ principal.getName("WRONG FORMAT");
+ fail("No IllegalArgumentException on improper parameter as format");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and Oid which does not fall into any keyword
+ * Gets encoding
+ * Inits other X500Principal with the encoding
+ * gets string in RFC1779 format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_MultAVA_RFC1779()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.RFC1779);
+ assertEquals("OID.2.16.4.3=B + CN=A", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and Oid which does not fall into any keyword
+ * Gets encoding
+ * Inits other X500Principal with the encoding
+ * gets string in RFC2253 format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_MultAVA_RFC2253()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.RFC2253);
+ assertEquals("2.16.4.3=#130142+CN=A", s);
+
+ }
+
+ /**
+ * Inits X500Principal with a string, there are multiple AVAs and Oid which does not fall into any keyword
+ * Gets encoding
+ * Inits other X500Principal with the encoding
+ * gets string in CANONICAL format
+ * compares with expected value paying attention on sorting order of AVAs
+ */
+ public void testGetName_EncodingWithWrongOidButGoodName_MultAVA_CANONICAL()
+ throws Exception {
+ String dn = "OID.2.16.4.3=B + CN=A";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ X500Principal principal2 = new X500Principal(enc);
+ String s = principal2.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a+2.16.4.3=#130142", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are leading and tailing spaces
+ * gets Name in RFC1779 format
+ * compares with expected value of name
+ */
+ public void testNameSpaceFromEncoding_RFC1779() throws Exception {
+ byte[] mess = { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x03, 0x20, 0x41, 0x20, };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\" A \"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are leading and tailing spaces
+ * gets Name in RFC2253 format
+ * compares with expected value of name
+ */
+ public void testNameSpaceFromEncoding_RFC2253() throws Exception {
+ byte[] mess = { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x03, 0x20, 0x41, 0x20, };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=\\ A\\ ", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are leading and tailing spaces
+ * gets Name in CANONICAL format
+ * compares with expected value of name
+ */
+ public void testNameSpaceFromEncoding_CANONICAL() throws Exception {
+ byte[] mess = { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x13, 0x03, 0x20, 0x41, 0x20, };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are special characters
+ * gets Name in RFC1779 format
+ * compares with expected value of name, checks if the string is in quotes
+ */
+ public void testNameSpecialCharsFromEncoding_RFC1779() throws Exception {
+ byte[] mess = { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x0C, 0x02, 0x3B, 0x2C };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\";,\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are special characters
+ * gets Name in RFC1779 format
+ * compares with expected value of name, checks if the characters are escaped
+ */
+ public void testNameSpecialCharsFromEncoding_RFC2253() throws Exception {
+ byte[] mess = { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x0C, 0x02, 0x3B, 0x2C };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=\\;\\,", s);
+
+ }
+
+ /**
+ * Inits X500Principal with byte array, where there are special characters
+ * gets Name in CANONICAL format
+ * compares with expected value of name, checks if the characters are escaped
+ */
+ public void testNameSpecialCharsFromEncoding_CANONICAL() throws Exception {
+ byte[] mess = { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x0C, 0x02, 0x3B, 0x2C };
+ X500Principal principal = new X500Principal(mess);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=\\;\\,", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \"B
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "\B"
+ */
+ public void testNameSpecialChars_RFC1779() throws Exception {
+ String dn = "CN=A,CN=\\\"B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A, CN=\"\\\"B\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \"B
+ * gets Name in RFC2253 format
+ * compares with expected value of name - "\B"
+ */
+ public void testNameSpecialChars_RFC2253() throws Exception {
+ String dn = "CN=A,CN=\\\"B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A,CN=\\\"B", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \"B
+ * gets Name in CANONICAL format
+ * compares with expected value of name - "\b"
+ */
+ public void testNameSpecialChars_CANONICAL() throws Exception {
+ String dn = "CN=A,CN=\\\"B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a,cn=\\\"b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\nB
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "\nB"
+ */
+ public void testNameSpecialChars_RFC1779_01() throws Exception {
+ //FIXME see testNameSpecialChars_RFC2253_01
+ // String dn = "CN=\\\nB";
+ // X500Principal principal = new X500Principal(dn);
+ // String s = principal.getName(X500Principal.RFC1779);
+ // assertEquals("CN=\"\nB\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\nB
+ * gets Name in RFC2253 format
+ * compares with expected value of name - \\nB
+ */
+ public void testNameSpecialChars_RFC2253_01() throws Exception {
+
+ try {
+ // compatibility issue:
+ // don't accept escaped \n because it is not a special char
+ new X500Principal("CN=\\\nB");
+ fail("No expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\nB
+ * gets Name in CANONICAL format
+ * compares with expected value of name - \\nb
+ */
+ public void testNameSpecialChars_CANONICAL_01() throws Exception {
+ //FIXME testNameSpecialChars_RFC2253_01
+ // String dn = "CN=\\\nB";
+ // X500Principal principal = new X500Principal(dn);
+ // String s = principal.getName(X500Principal.CANONICAL);
+ // assertEquals("cn=b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\B
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "\B"
+ */
+ public void testNameSpecialChars_RFC1779_02() throws Exception {
+ String dn = "CN=\\\\B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"\\\\B\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\B
+ * gets Name in RFC2253 format
+ * compares with expected value of name - \\B
+ */
+ public void testNameSpecialChars_RFC2253_02() throws Exception {
+ String dn = "CN=\\\\B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=\\\\B", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\B
+ * gets Name in CANONICAL format
+ * compares with expected value of name - \\b
+ */
+ public void testNameSpecialChars_CANONICAL_02() throws Exception {
+ String dn = "CN=\\\\B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=\\\\b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"DEF"
+ * gets encoding
+ * compares with expected encoding
+ */
+ public void testNameWithQuotation() throws Exception {
+ String dn = "CN=\"ABCDEF\"";
+
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ assertTrue(Arrays.equals(new byte[] { 0x30, 0x11, 0x31, 0x0F, 0x30,
+ 0x0D, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x06, 0x41, 0x42,
+ 0x43, 0x44, 0x45, 0x46 }, enc));
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "ABCDEF
+ * checks if the proper exception is thrown
+ */
+ public void testNameWithQuotation_01() throws Exception {
+ String dn = "CN=\"ABCDEF";
+ try {
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on string with no closing quotations");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"D#EF"
+ * gets encoding
+ * compares with expected encoding
+ */
+ public void testNameWithQuotation_02() throws Exception {
+ String dn = "CN=\"ABCD#EF\"";
+ X500Principal principal = new X500Principal(dn);
+ byte[] enc = principal.getEncoded();
+ assertTrue(Arrays.equals(new byte[] { 0x30, 0x12, 0x31, 0x10, 0x30,
+ 0x0E, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x07, 0x41, 0x42,
+ 0x43, 0x44, 0x23, 0x45, 0x46 }, enc));
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"DEF"
+ * Compatibility issue: according RFC 2253 such string is invalid
+ * but we accept it, not string char is escaped
+ */
+ public void testNameWithQuotation_03() throws Exception {
+ String dn = "CN=ABC\"DEF\"";
+ X500Principal principal = new X500Principal(dn);
+ assertEquals("CN=ABC\\\"DEF\\\"", principal
+ .getName(X500Principal.RFC2253));
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"DEF"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "ABCDEF"
+ */
+ public void testNameSpecialChars_RFC1779_03() throws Exception {
+ String dn = "CN=\"ABCDEF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=ABCDEF", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"DEF"
+ * gets Name in RFC2253 format
+ * compares with expected value of name - ABC"DEF"
+ */
+ public void testNameSpecialChars_RFC2253_03() throws Exception {
+ String dn = "CN=\"ABCDEF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=ABCDEF", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"DEF"
+ * gets Name in CANONICAL format
+ * compares with expected value of name - abc"def"
+ */
+ public void testNameSpecialChars_CANONICAL_03() throws Exception {
+ String dn = "CN=\"ABCDEF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=abcdef", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"D#EF"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "ABCD#EF"
+ */
+ public void testNameSpecialChars_RFC1779_04() throws Exception {
+ String dn = "CN=\"ABCD#EF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"ABCD#EF\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"D#EF"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - ABCD\#EF
+ */
+ public void testNameSpecialChars_RFC2253_04() throws Exception {
+ String dn = "CN=\"ABCD#EF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=ABCD\\#EF", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ABC"D#EF"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - abc"d#ef"
+ */
+ public void testNameSpecialChars_CANONICAL_04() throws Exception {
+ String dn = "CN=\"ABCD#EF\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=abcd#ef", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - X#YZ
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "X#YZ"
+ */
+ public void testNameSpecialChars_RFC1779_05() {
+ String dn = "CN=X#YZ";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"X#YZ\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - X#YZ
+ * gets Name in RFC2253 format
+ * compares with expected value of name - X\#YZ
+ */
+ public void testNameSpecialChars_RFC2253_05() {
+ String dn = "CN=X#YZ";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.RFC2253);
+
+ assertEquals("CN=X\\#YZ", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - X#YZ
+ * gets Name in CANONICAL format
+ * compares with expected value of name - x#yz
+ */
+ public void testNameSpecialChars_CANONICAL_05() {
+ String dn = "CN=X#YZ";
+ X500Principal principal = new X500Principal(dn);
+
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=x#yz", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=\#XYZ
+ * gets Name in RFC1779 format
+ * compares with expected value of name - CN="#XYZ"
+ */
+ public void testNameSpecialChars_RFC1779_6() throws Exception {
+ String dn = "CN=\\#XYZ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"#XYZ\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=\#XYZ
+ * gets Name in RFC2253 format
+ * compares with expected value of name - CN=\#XYZ
+ */
+ public void testNameSpecialChars_RFC2253_6() throws Exception {
+ String dn = "CN=\\#XYZ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=\\#XYZ", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=\#XYZ
+ * gets Name in CANONICAL format
+ * compares with expected value of name - cn=\#xyz
+ */
+ public void testNameSpecialChars_CANONICAL_6() throws Exception {
+ String dn = "CN=\\#XYZ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=\\#xyz", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - B\'space'
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "B "
+ */
+ public void testNameSpaces_RFC1779() throws Exception {
+ String dn = "CN=A,CN=B\\ ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A, CN=\"B \"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - B\'space'
+ * gets Name in RFC2253 format
+ * compares with expected value of name - B\'space'
+ */
+ public void testNameSpaces_RFC2253() throws Exception {
+ String dn = "CN=A,CN=B\\ ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A,CN=B\\ ", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - B\'space'
+ * gets Name in CANONICAL format
+ * compares with expected value of name - B\
+ */
+ public void testNameSpaces_CANONICAL() throws Exception {
+ String dn = "CN=A,CN=B\\ ";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a,cn=b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "B'space''space''space'A"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "B A"
+ */
+ public void testNameSpaces_RFC1779_01() throws Exception {
+ String dn = "CN=\"B A\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"B A\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "B'space''space''space'A"
+ * gets Name in 2253 format
+ * compares with expected value of name - B'space''space''space'A
+ */
+ public void testNameSpaces_RFC2253_01() throws Exception {
+ String dn = "CN=\"B A\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=B A", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "B'space''space''space'A"
+ * gets Name in CANONICAL format
+ * compares with expected value of name - b'space'a
+ */
+ public void testNameSpaces_CANONICAL_01() throws Exception {
+ String dn = "CN=\"B A\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=b a", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\'space''space'B
+ * gets Name in RFC1779 format
+ * compares with expected value of name - " B"
+ */
+ public void testNameSpaces_RFC1779_02() throws Exception {
+ String dn = "CN=\\ B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\" B\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\'space''space'B
+ * gets Name in RFC1779 format
+ * compares with expected value of name - \'space''space'B
+ */
+ public void testNameSpaces_RFC2253_02() throws Exception {
+ String dn = "CN=\\ B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=\\ \\ B", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - \\'space''space'B
+ * gets Name in CANONICAL format
+ * compares with expected value of name - \'space''space'b
+ */
+ public void testNameSpaces_CANONICAL_02() throws Exception {
+ String dn = "CN=\\ B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - ""B
+ * checks if the proper exception is thrown
+ */
+ public void testNameQu() throws Exception {
+ String dn = "CN=\"\"B";
+ try {
+ new X500Principal(dn);
+ fail("No IllegalArgumentException on improper string");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\"B"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "A\"B"
+ */
+ public void testNameQu_RFC1779_2() throws Exception {
+ String dn = "CN=\"A\\\"B\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"A\\\"B\"", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\"B"
+ * gets Name in RFC2253 format
+ * compares with expected value of name - A\"B
+ */
+ public void testNameQu_RFC2253_2() throws Exception {
+ String dn = "CN=\"A\\\"B\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A\\\"B", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\"B"
+ * gets Name in CANONICAL format
+ * compares with expected value of name - a\"b
+ */
+ public void testNameQu_CANONICAL_2() throws Exception {
+ String dn = "CN=\"A\\\"B\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a\\\"b", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\""
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "A\""
+ */
+ public void testNameQu_RFC1779_3() throws Exception {
+ String dn = "CN=\"A\\\"\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"A\\\"\"", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\""
+ * gets Name in RFC2253 format
+ * compares with expected value of name - A\"
+ */
+ public void testNameQu_RFC2253_3() throws Exception {
+ String dn = "CN=\"A\\\"\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A\\\"", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\""
+ * gets Name in CANONICAL format
+ * compares with expected value of name - A\"
+ */
+ public void testNameQu_CANONICAL_3() throws Exception {
+ String dn = "CN=\"A\\\"\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a\\\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - "A\", C=B"
+ * gets Name in RFC1779 format
+ * compares with expected value of name - "A\", C=B"
+ */
+ public void testNameQu_4() throws Exception {
+ String dn = "CN=\"A\\\", C=B\"";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"A\\\", C=B\"", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN="A\\", C=B
+ * gets Name in RFC1779 format
+ * compares with expected value of name - CN="A\\", C=B
+ */
+ public void testNameQu_5() throws Exception {
+ String dn = "CN=\"A\\\\\", C=B";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=\"A\\\\\", C=B", s);
+
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=A\nB
+ * gets Name in RFC1779 format
+ * compares with expected value of name - CN="A\nB"
+ */
+ public void testNameCR_RFC1779() throws Exception {
+ String dn = "CN=A\nB";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC1779);
+ assertEquals("CN=A\nB", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=A\nB
+ * gets Name in RFC2253 format
+ * compares with expected value of name - CN=A\nB
+ */
+ public void testNameCR_RFC2253() throws Exception {
+ String dn = "CN=A\nB";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.RFC2253);
+ assertEquals("CN=A\nB", s);
+ }
+
+ /**
+ * Inits X500Principal with the string with special characters - CN=A\nB
+ * gets Name in CANONICAL format
+ * compares with expected value of name - cn=a\nb
+ */
+ public void testNameCR_CANONICAL() throws Exception {
+ String dn = "CN=A\nB";
+ X500Principal principal = new X500Principal(dn);
+ String s = principal.getName(X500Principal.CANONICAL);
+ assertEquals("cn=a\nb", s);
+ }
+
+ public static final String[] RFC2253_SPECIAL = new String[] { ",", "=",
+ "+", "<", ">", "#", ";" };
+
+ public void testValidDN() throws Exception {
+
+ TestList list = new TestList();
+
+ list.add("", "", "", "", new byte[] { 0x30, 0x00 }); // empty RDN sequence
+
+ // sequence of RDN: RDN *("," RDN)
+ list.add("CN=A,C=B", "CN=A,C=B", "CN=A, C=B", "cn=a,c=b");
+ list.add("C=B,CN=A", "C=B,CN=A", "C=B, CN=A", "c=b,cn=a");
+ list.add("CN=A,CN=A", "CN=A,CN=A", "CN=A, CN=A", "cn=a,cn=a"); // duplicate RDNs
+
+ // sequence of RDN: RFC 1779 compatibility
+ list.add("CN=A , C=B", "CN=A,C=B", "CN=A, C=B");
+ list.add("CN=A , C=B", "CN=A,C=B", "CN=A, C=B");
+ list.add("CN=A;C=B", "CN=A,C=B", "CN=A, C=B");
+ list.add("CN=A ; C=B", "CN=A,C=B", "CN=A, C=B");
+ //FIXME list.add("CN=A\r,\rC=B", "CN=A,C=B"); // <CR> & comma => comma
+ list.add(" CN=A,C=B ", "CN=A,C=B", "CN=A, C=B"); // spaces at beg&end
+ list.add(" CN=A,C=\"B\" ", "CN=A,C=B", "CN=A, C=B"); // spaces at beg&end
+
+ // set of ATAV: ATAV *("+" ATAV)
+ list.add("CN=A+ST=CA", "CN=A+ST=CA", "CN=A + ST=CA", "cn=a+st=ca");
+ list.add("CN=A+CN=A", "CN=A+CN=A", "CN=A + CN=A", "cn=a+cn=a"); // duplicate AT
+ list
+ .add("2.5.4.3=A+2.5.4.3=A", "CN=A+CN=A", "CN=A + CN=A",
+ "cn=a+cn=a"); // duplicate AT
+
+ // set of ATAV: RFC 1779 compatibility
+ list.add("CN=A + ST=CA", "CN=A+ST=CA", "CN=A + ST=CA");
+ list.add("CN=A + ST=CA", "CN=A+ST=CA", "CN=A + ST=CA");
+ //FIXME list.add("CN=A\r+\rST=CA", "CN=A+ST=CA"); // <CR> & '+' => '+'
+
+ // ATAV = AttributeType "=" AttributeValue
+ list.add("CN=A", "CN=A", "CN=A");
+ list.add("cn=A", "CN=A", "CN=A"); // AT case insensitive
+ list.add("cN=A", "CN=A", "CN=A"); // AT case insensitive
+ list.add("cn=a", "CN=a", "CN=a"); // AT case insensitive
+
+ // ATAV : RFC 1779 compatibility
+ list.add("CN = A", "CN=A", "CN=A");
+ list.add("CN = A", "CN=A", "CN=A");
+ // FIXME list.add("CN\r=\rA", "CN=A"); // <CR> & '=' => '='
+
+ // AttributeType = <name string> | <OID>
+ // testing OID case : OID => <name string>
+ // tested all OIDs from RFC 2253 (2.3) and RFC 1779 (Table 1)
+
+ // different variants of 2.5.4.3 (CN) OID
+ list.add("OID.2.5.4.3=A", "CN=A", "CN=A");
+ list.add("oid.2.5.4.3=A", "CN=A", "CN=A");
+ list.add("2.5.4.3=A", "CN=A", "CN=A");
+ list.add("02.5.4.3=A", "CN=A", "CN=A"); // first: 02 => 2
+ list.add("2.5.4.0003=A", "CN=A", "CN=A"); // last: 0003 => 3
+
+ // the rest of OIDs
+ list.add("2.5.4.7=A", "L=A", "L=A", "l=a");
+ list.add("2.5.4.8=A", "ST=A", "ST=A", "st=a");
+ list.add("2.5.4.10=A", "O=A", "O=A", "o=a");
+ list.add("2.5.4.11=A", "OU=A", "OU=A", "ou=a");
+ list.add("2.5.4.6=A", "C=A", "C=A", "c=a");
+ list.add("2.5.4.9=A", "STREET=A", "STREET=A", "street=a");
+ list.add("0.9.2342.19200300.100.1.25=A", "DC=A",
+ "OID.0.9.2342.19200300.100.1.25=A", "dc=#160141");
+ list.add("0.9.2342.19200300.100.1.1=A", "UID=A",
+ "OID.0.9.2342.19200300.100.1.1=A", "uid=a");
+
+ // attribute types from RFC 2459 (see Appendix A)
+ // keywords are from the API spec
+ list.add("T=A", "2.5.4.12=#130141", "OID.2.5.4.12=A",
+ "2.5.4.12=#130141");
+ list.add("DNQ=A", "2.5.4.46=#130141", "OID.2.5.4.46=A",
+ "2.5.4.46=#130141");
+ list.add("DNQUALIFIER=A", "2.5.4.46=#130141", "OID.2.5.4.46=A",
+ "2.5.4.46=#130141");
+ list.add("SURNAME=A", "2.5.4.4=#130141", "OID.2.5.4.4=A",
+ "2.5.4.4=#130141");
+ list.add("GIVENNAME=A", "2.5.4.42=#130141", "OID.2.5.4.42=A",
+ "2.5.4.42=#130141");
+ list.add("INITIALS=A", "2.5.4.43=#130141", "OID.2.5.4.43=A",
+ "2.5.4.43=#130141");
+ list.add("GENERATION=A", "2.5.4.44=#130141", "OID.2.5.4.44=A",
+ "2.5.4.44=#130141");
+ list.add("EMAILADDRESS=A", "1.2.840.113549.1.9.1=#160141",
+ "OID.1.2.840.113549.1.9.1=A", "1.2.840.113549.1.9.1=#160141",
+ null, (byte) 0x05); //FIXME bug???
+ list.add("SERIALNUMBER=A", "2.5.4.5=#130141", "OID.2.5.4.5=A",
+ "2.5.4.5=#130141");
+
+ // AttributeValue => BER encoding (if OID in dotted-decimal form)
+ // see RFC 2253 (2.4)
+ list.add("OID.2.5.4.12=A", "2.5.4.12=#130141", "OID.2.5.4.12=A");
+ list.add("oid.2.5.4.12=A", "2.5.4.12=#130141", "OID.2.5.4.12=A");
+ list.add("2.5.4.12=A", "2.5.4.12=#130141", "OID.2.5.4.12=A");
+ list.add("1.1=A", "1.1=#130141", "OID.1.1=A");
+
+ //
+ // AttributeValue first alternative : *( stringchar / pair )
+ // testing pair characters.
+ //
+ // Note: for RFC1779 quoted string is returned (unspecified)
+ //
+ list.add("CN=", "CN=", "CN="); // zero string chars
+ list.add("CN= ", "CN=", "CN="); // zero string chars
+ list.add("CN=A+ST=", "CN=A+ST=", "CN=A + ST="); // zero string chars
+ list.add("CN=+ST=A", "CN=+ST=A", "CN= + ST=A"); // empty value for 1 RDN
+ list.add("CN=A+ST= ", "CN=A+ST=", "CN=A + ST="); // empty value for 1 RDN
+ list.add("CN=+ST=", "CN=+ST=", "CN= + ST="); // empty value for both RDNs
+ list.add("CN=,ST=B", "CN=,ST=B", "CN=, ST=B"); // empty value for 1 RDN
+ list.add("CN=,ST=", "CN=,ST=", "CN=, ST="); // empty value for both RDNs
+ list.add("CN=;ST=B", "CN=,ST=B", "CN=, ST=B"); // empty value for 1 RDN
+ list.add("CN=;ST=", "CN=,ST=", "CN=, ST="); // empty value for both RDNs
+ for (String element : RFC2253_SPECIAL) {
+ // \special
+ list.add("CN=\\" + element,
+ "CN=\\" + element, "CN=\"" + element
+ + "\"");
+
+ // A + \special + B
+ list.add("CN=A\\" + element + "B", "CN=A\\"
+ + element + "B", "CN=\"A" + element
+ + "B\"");
+ }
+
+ // pair = \"
+ list.add("CN=\\\"", "CN=\\\"", "CN=\"\\\"\"", null, (byte) 0x02);
+ list.add("CN=\\\"A", "CN=\\\"A", "CN=\"\\\"A\"", null, (byte) 0x02);
+ list.add("CN=\\\",C=\\\"", "CN=\\\",C=\\\"", "CN=\"\\\"\", C=\"\\\"\"",
+ null, (byte) 0x02); // 2 RDN
+ list.add("CN=A\\\"B", "CN=A\\\"B", "CN=\"A\\\"B\"", null, (byte) 0x02); // A\"B
+ list.add("CN=A ST=B", "CN=A ST\\=B", "CN=\"A ST=B\""); // no RDN separator
+
+ // pair = \space
+ list.add("CN=\\ ", "CN=\\ ", "CN=\" \"", "cn=");
+
+ // pair = \hexpair
+ list.add("CN=\\41", "CN=A", "CN=A"); // 0x41=='A'
+ list.add("CN=\\41\\2C", "CN=A\\,", "CN=\"A,\""); // 0x41=='A', 0x2C=','
+ list.add("CN=\\41\\2c", "CN=A\\,", "CN=\"A,\""); // 0x41=='A', 0x2c=','
+ list.add("CN=\\D0\\AF", "CN=" + ((char) 1071), "CN=" + ((char) 1071),
+ new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF }); // 0xD0AF == the last letter(capital) of Russian alphabet
+ list.add("CN=\\D0\\AFA\\41", "CN=" + ((char) 1071) + "AA", "CN="
+ + ((char) 1071) + "AA", new byte[] { 0x30, 0x0F, 0x31, 0x0D,
+ 0x30, 0x0B, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x04, (byte) 0xD0, (byte) 0xAF, 0x41, 0x41 }); // 0xD0AF == the last letter(capital) of Russian alphabet
+ // UTF-8(0xE090AF) is non-shortest form of UTF-8(0xD0AF)
+ //FIXME list.add("CN=\\E0\\90\\AF", "CN=" + ((char) 1071), "CN="
+ // + ((char) 1071), new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30,
+ // 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // // UTF8 String
+ // 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF });
+ // UTF-8(0xF08090AF) is non-shortest form of UTF-8(0xD0AF)
+ //FIXME list.add("CN=\\F0\\80\\90\\AF", "CN=" + ((char) 1071), "CN="
+ // + ((char) 1071), new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30,
+ // 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // // UTF8 String
+ // 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF });
+ //FIXME list.add("CN=\\D0", "CN=" + ((char) 65533), "CN=" + ((char) 65533),
+ // new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // UTF8 String
+ // 0x0C, 0x01, 0x3F }); // 0xD0 is not correct UTF8 char => '?'
+ list.add("CN=\\41+ST=A", "CN=A+ST=A", "CN=A + ST=A"); // 0x41=='A'
+ list.add("CN=\\41\\2C+ST=A", "CN=A\\,+ST=A", "CN=\"A,\" + ST=A"); // 0x41=='A', 0x2C=','
+ list.add("CN=\\41\\2c+ST=A", "CN=A\\,+ST=A", "CN=\"A,\" + ST=A"); // 0x41=='A', 0x2c=','
+
+ // stringchar '=' or not leading '#'
+ //FIXME RFC 2253 grammar violation: '=' and '#' is a special char
+ list.add("CN==", "CN=\\=", "CN=\"=\"");
+ list.add("CN=A=", "CN=A\\=", "CN=\"A=\"");
+ list.add("CN=A#", "CN=A\\#", "CN=\"A#\"");
+
+ // not leading or trailing spaces
+ list.add("CN=A B", "CN=A B", "CN=A B", "cn=a b");
+ list.add("CN=A\\ B", "CN=A B", "CN=A B", "cn=a b");
+ list.add("CN=A \\,B", "CN=A \\,B", "CN=\"A ,B\"", "cn=a \\,b");
+
+ //not alphabet chars
+ list.add("CN=$", "CN=$", "CN=$", new byte[] { 0x30, 0x0C, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
+ //UTF-8 String: "$"
+ 0x0C, 0x01, 0x24 });
+ list.add("CN=(", "CN=(", "CN=(", new byte[] { 0x30, 0x0C, 0x31, 0x0A,
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
+ //PrintableString: "("
+ 0x13, 0x01, 0x28 });
+
+ //
+ //
+ // AttributeValue second alternative : "#" hexstring
+ //
+ //
+ list.add("CN=#130141", "CN=A", "CN=A", "cn=a"); // ASN1 Printable hex string = 'A'
+ list.add("CN=#140141", "CN=A", "CN=A", "cn=a", new byte[] { 0x30,
+ 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
+ 0x14, 0x01, 0x41 }); // ASN1 Teletex hex string = 'A'
+
+ list.add("CN=#010100", "CN=#010100", "CN=#010100", "cn=#010100"); // ASN1 Boolean = FALSE
+ list.add("CN=#0101fF", "CN=#0101ff", "CN=#0101FF", "cn=#0101ff"); // ASN1 Boolean = TRUE
+ //FIXME list.add("CN=#3000", "CN=#3000", "CN=#3000"); // ASN1 Sequence
+ //FIXME list.add("CN=#0500", "CN=A", "CN=A"); // ASN1 Null
+ list.add("CN= #0101fF", "CN=#0101ff", "CN=#0101FF", // space at beginning
+ new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x01, 0x01, (byte) 0xFF } // ASN.1 Boolean = TRUE
+ );
+ list.add("CN= #0101fF+ST=A", "CN=#0101ff+ST=A", "CN=#0101FF + ST=A",
+ "cn=#0101ff+st=a"); //space
+ list.add("CN= #0101fF ", "CN=#0101ff", "CN=#0101FF", // space at the end
+ new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x01, 0x01, (byte) 0xFF } // ASN.1 Boolean = TRUE
+ , (byte) 0x00);
+
+ //FIXME unspecified output for RFC1779
+ //FIXME list.add("CN=#1C0141", "CN=A", "CN=A"); // ASN1 Universal hex string = 'A'
+ //FIXME list.add("CN=#1E0141", "CN=A", "CN=A"); // ASN1 Bmp hex string = 'A'
+
+ //
+ // AttributeValue third alternative : " *( quotechar / pair ) "
+ // quotechar = <any character except '\' or '"' >
+ //
+ // Note:
+ // RFC2253: passed quoted AV string is unquoted, special chars are escaped
+ // RFC1779: escaped quoted chars are unescaped
+ //
+ list.add("CN=\"\"", "CN=", "CN="); // empty quoted string
+ list.add("CN=\"A\"", "CN=A", "CN=A"); // "A"
+ for (String element : RFC2253_SPECIAL) {
+ // "special" => \special
+ list.add("CN=\"" + element + "\"", "CN=\\"
+ + element, "CN=\"" + element + "\"");
+
+ // "A + special + B" => A + \special + B
+ list.add("CN=\"A" + element + "B\"", "CN=A\\"
+ + element + "B", "CN=\"A" + element
+ + "B\"");
+ }
+ for (String element : RFC2253_SPECIAL) {
+ // "\special" => \special
+ list.add("CN=\"\\" + element + "\"", "CN=\\"
+ + element, "CN=\"" + element + "\"");
+
+ // "A + \special + B" => A + \special + B
+ list.add("CN=\"A\\" + element + "B\"", "CN=A\\"
+ + element + "B", "CN=\"A" + element
+ + "B\"");
+ }
+ list.add("CN=\"\\\"\"", "CN=\\\"", "CN=\"\\\"\"", null, (byte) 0x02); // "\""
+ list.add("CN=\"A\\\"B\"", "CN=A\\\"B", "CN=\"A\\\"B\"", null,
+ (byte) 0x02); // "A\"B"
+
+ // pair = \hexpair (test cases are the same as for the first alternative)
+ list.add("CN=\"\\41\"", "CN=A", "CN=A"); // 0x41=='A'
+ list.add("CN=\"\\41\\2C\"", "CN=A\\,", "CN=\"A,\""); // 0x41=='A', 0x2C=','
+ list.add("CN=\"\\41\\2c\"", "CN=A\\,", "CN=\"A,\""); // 0x41=='A', 0x2c=','
+ list.add("CN=\"\\D0\\AF\"", "CN=" + ((char) 1071), "CN="
+ + ((char) 1071), new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF }); // 0xD0AF == the last letter(capital) of Russian alphabet
+ list.add("CN=\"\\D0\\AFA\\41\"", "CN=" + ((char) 1071) + "AA", "CN="
+ + ((char) 1071) + "AA", new byte[] { 0x30, 0x0F, 0x31, 0x0D,
+ 0x30, 0x0B, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x04, (byte) 0xD0, (byte) 0xAF, 0x41, 0x41 }); // 0xD0AF == the last letter(capital) of Russian alphabet
+ list.add("CN=\"\\E0\\90\\AF\"", "CN=" + ((char) 1071), "CN="
+ + ((char) 1071), new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF }); // UTF8(0xE090AF that is not quite correct)== UTF8(0xD0AF) == the last letter(capital) of Russian alphabet
+ list.add("CN=\"\\F0\\80\\90\\AF\"", "CN=" + ((char) 1071), "CN="
+ + ((char) 1071), new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8 String
+ 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF }); // UTF8(0xF08090AF that is not quite correct)== UTF8(0xD0AF) == the last letter(capital) of Russian alphabet
+
+ list.add("CN=\"\\41\"+ST=A", "CN=A+ST=A", "CN=A + ST=A"); // 0x41=='A'
+ list.add("CN=\"\\41\\2C\"+ST=A", "CN=A\\,+ST=A", "CN=\"A,\" + ST=A"); // 0x41=='A', 0x2C=','
+ list.add("CN=\"\\41\\2c\"+ST=A", "CN=A\\,+ST=A", "CN=\"A,\" + ST=A"); // 0x41=='A', 0x2c=','
+
+ // AttributeValue third alternative : RFC 1779 compatibility
+ //FIXME list.add("CN=\"\r\"", "CN=\"\r\""); // "<CR>"
+ //FIXME list.add("CN=\"\\\r\"", "CN=\"\\\r\""); // "\<CR>"
+
+ // AttributeValue : RFC 1779 compatibility
+ list.add("CN= A ", "CN=A", "CN=A", "cn=a"); // leading & trailing spaces
+ list.add("CN=\\ A ", "CN=\\ \\ A", "CN=\" A\"", "cn=a", null,
+ (byte) 0x01); // escaped leading space
+ list.add("CN= A \\ ", "CN=A\\ \\ ", "CN=\"A \"", "cn=a", null,
+ (byte) 0x01); // escaped trailing space
+
+ list.add("CN= \"A\" ", "CN=A", "CN=A", "cn=a"); // leading & trailing spaces
+
+ StringBuffer errorMsg = new StringBuffer();
+ for (int i = 0; i < list.size(); i++) {
+
+ Object[] obj = list.get(i);
+
+ String dn = (String) obj[0];
+ String rfc2253 = (String) obj[1];
+ String rfc1779 = (String) obj[2];
+ String canonical = (String) obj[3];
+ byte[] encoded = (byte[]) obj[4];
+ byte mask = ((byte[]) obj[5])[0];
+
+ try {
+ X500Principal p = new X500Principal(dn);
+ if (!rfc2253.equals(p.getName(X500Principal.RFC2253))) {
+ if (!testing || ((mask & 0x01) == 0)) {
+
+ errorMsg.append("\nRFC2253: " + i);
+ errorMsg.append(" \tparm: '" + dn + "'");
+ errorMsg.append("\t\texpected: '" + rfc2253 + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.RFC2253) + "'");
+ }
+ }
+
+ if (!rfc1779.equals(p.getName(X500Principal.RFC1779))) {
+ if (!testing || ((mask & 0x02) == 0)) {
+
+ errorMsg.append("\nRFC1779: " + i);
+ errorMsg.append(" \tparm: '" + dn + "'");
+ errorMsg.append("\t\texpected: '" + rfc1779 + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.RFC1779) + "'");
+ }
+ }
+
+ if (canonical != null) {
+ if (!canonical.equals(p.getName(X500Principal.CANONICAL))) {
+ if (!testing || ((mask & 0x04) == 0)) {
+
+ errorMsg.append("\nCANONICAL: " + i);
+ errorMsg.append("\tparm: '" + dn + "'");
+ errorMsg.append("\t\texpected: '" + canonical + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.CANONICAL) + "'");
+ }
+ }
+ }
+
+ if (encoded != null) {
+ if (!Arrays.equals(encoded, p.getEncoded())) {
+ if (!testing || ((mask & 0x08) == 0)) {
+
+ errorMsg.append("\nUnexpected encoding for: " + i
+ + ", dn= '" + dn + "'");
+
+ System.out.println("\nI " + i);
+ byte[] enc = p.getEncoded();
+ for (byte element : enc) {
+ System.out.print(", 0x"
+ + Integer.toHexString(element));
+ }
+ }
+ }
+ }
+ } catch (IllegalArgumentException e) {
+ errorMsg.append("\nIllegalArgumentException: " + i);
+ errorMsg.append("\tparm: '" + dn + "'");
+ } catch (Exception e) {
+ errorMsg.append("\nException: " + i);
+ errorMsg.append("\tparm: '" + dn + "'");
+ errorMsg.append("\texcep: " + e.getClass().getName());
+ }
+ }
+
+ if (errorMsg.length() != 0) {
+ fail(errorMsg.toString());
+ }
+
+ }
+
+ public void testInvalidDN() {
+ String[] illegalDN = new String[] {
+ // RDN
+ //FIXME " ", // space only
+ "CN", // attribute type only
+ "CN=A;", // RFC 1779: BNF allows this, but ...
+ "CN=A,", // RFC 1779: BNF allows this, but ...
+ ",CN=A", // no AttributeType for first RDN
+ "CN=,A", // no AttributeType for second RDN
+ "CN=A+", // no AttributeTypeAndValue for second RDN
+ "CN=#130141 ST=B", // no RDN separator
+
+ // AttributeType = <name string> | <OID>
+ "AAA=A", // no such <name string>
+ "1..1=A", // wrong OID
+ ".1.1=A", // wrong OID
+ "11=A", // wrong OID
+ "1=A", // wrong OID
+ "AID.1.1=A", // wrong OID
+ "1.50=A", // wrong OID
+ "5.1.0=A", // wrong OID
+ "2.-5.4.3=A", // wrong OID
+ "2.5.-4.3=A", // wrong OID
+ "2.5.4-.3=A", // wrong OID
+ //FIXME "2.5.4.-3=A", // wrong OID
+
+ // AttributeValue first alternative : *( stringchar / pair )
+ "CN=,", // stringchar = ','
+ //FIXME "CN==",
+ "CN=+", // stringchar = '+'
+ //FIXME "CN=<", // stringchar = '<'
+ //FIXME "CN=>", // stringchar = '>'
+ "CN=#", // stringchar = '#'
+ //FIXME "CN=Z#", // stringchar = '#'
+ "CN=;", // stringchar = ';'
+ "CN=\"", // stringchar = "
+ //FIXME "CN=A\"B", // stringchar = "
+ "CN=\\", // stringchar = \
+ "CN=A\\", // stringchar = \
+ "CN=A\\B", // stringchar = \
+ "CN=\\z", // invalid pair = \z
+ "CN=\\4", // invalid pair = \4
+ "CN=\\4Z", // invalid pair = \4Z
+ "CN=\\4\\2c", // invalid pair = \4\2c
+
+ // AttributeValue second alternative : "#" hexstring
+ "CN=#", // no hex string
+ "CN=#2", // no hex pair
+ "CN=#22", // hexpair is not BER encoding
+ "CN=#0001", // invalid BER encoding (missed content)
+ "CN=#000201", // invalid BER encoding (wrong length)
+ "CN=#0002010101", // invalid BER encoding (wrong length)
+ "CN=#00FF", // invalid BER encoding (wrong length)
+ "CN=#ZZ", // not hex pair
+
+ // FIXME boolean with indefinite length
+ //"CN=#0100010000", // invalid BER encoding (wrong length)
+
+ // AttributeValue third alternative : " *( quotechar / pair ) "
+ "CN=\"A\" B", // TODO comment me
+ "CN=\"A\\", // TODO comment me
+ "CN=\"\\4\"", // invalid pair = \4
+ "CN=\"\\4Z\"", // invalid pair = \4Z
+ "CN=\"\\4\\2c\"", // invalid pair = \4\2c
+ };
+
+ StringBuffer errorMsg = new StringBuffer();
+ for (String element : illegalDN) {
+
+ try {
+ new X500Principal(element);
+ errorMsg.append("No IllegalArgumentException: '" + element
+ + "'\n");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ if (errorMsg.length() != 0) {
+ fail(errorMsg.toString());
+ }
+ }
+
+ public void testValidEncoding() {
+ TestList list = new TestList();
+
+ //
+ // Empty
+ //
+ list.add(new byte[] { 0x30, 0x00 }, "", "", "");
+ list.add(new byte[] { 0x30, 0x02, 0x31, 0x00 }, "", "", ""); //??? invalid size constraints
+
+ //
+ // Known OID + string with different tags(all string)
+ //
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // PrintableString
+ 0x13, 0x01, 0x5A }, "CN=Z", "CN=Z", "cn=z");
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // TeletexString
+ 0x14, 0x01, 0x5A }, "CN=Z", "CN=Z", "cn=z");
+ //FIXME:compatibility list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // UniversalString
+ // 0x1C, 0x01, 0x5A }, "CN=Z", "CN=Z", "cn=z");
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String
+ 0x0C, 0x01, 0x5A }, "CN=Z", "CN=Z", "cn=z");
+ //FIXME:compatibility list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // BMPString
+ // 0x1E, 0x01, 0x5A }, "CN=Z", "CN=Z", "cn=z");
+
+ //
+ // Unknown OID + string with different tags(all string)
+ //
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // PrintableString
+ 0x13, 0x01, 0x5A }, "0.0=#13015a", "OID.0.0=Z", "0.0=#13015a");
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // TeletexString
+ 0x14, 0x01, 0x5A }, "0.0=#14015a", "OID.0.0=Z", "0.0=#14015a");
+ //FIXME:compatibility list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ // 0x00,
+ // // UniversalString
+ // 0x1C, 0x01, 0x5A }, "0.0=#1c015a", "OID.0.0=Z", "cn=z");
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // UTF8String
+ 0x0C, 0x01, 0x5A }, "0.0=#0c015a", "OID.0.0=Z", "0.0=#0c015a");
+ //FIXME:compatibility list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ // 0x00,
+ // // BMPString
+ // 0x1E, 0x01, 0x5A }, "0.0=#1e015a", "OID.0.0=Z", "cn=z");
+
+ //
+ // Known OID + not a string value
+ //
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // Boolean
+ 0x01, 0x01, (byte) 0xFF }, "CN=#0101ff", "CN=#0101FF",
+ "cn=#0101ff");
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // Integer
+ 0x02, 0x01, 0x0F }, "CN=#02010f", "CN=#02010F", "cn=#02010f");
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // BitString
+ 0x03, 0x01, 0x00 }, "CN=#030100", "CN=#030100", "cn=#030100");
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // SEQUENCE
+ 0x30, 0x01, 0x0A }, "CN=#30010a", "CN=#30010A", "cn=#30010a");
+
+ //
+ // unknown OID + not a string value
+ //
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // Boolean
+ 0x01, 0x01, (byte) 0xFF }, "0.0=#0101ff", "OID.0.0=#0101FF",
+ "0.0=#0101ff");
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // Integer
+ 0x02, 0x01, 0x0F }, "0.0=#02010f", "OID.0.0=#02010F",
+ "0.0=#02010f");
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // BitString
+ 0x03, 0x01, 0x00 }, "0.0=#030100", "OID.0.0=#030100",
+ "0.0=#030100");
+ list.add(new byte[] { 0x30, 0x0A, 0x31, 0x08, 0x30, 0x06, 0x06, 0x01,
+ 0x00,
+ // SEQUENCE
+ 0x30, 0x01, 0x0A }, "0.0=#30010a", "OID.0.0=#30010A",
+ "0.0=#30010a");
+
+ //
+ // Known OID + UTF-8 string with chars to be escaped
+ //
+
+ // spaces
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: a single space char
+ 0x0C, 0x01, 0x20 }, "CN=\\ ", "CN=\" \"", "cn=");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: a space char at the beginning
+ 0x0C, 0x02, 0x20, 0x5A }, "CN=\\ Z", "CN=\" Z\"", "cn=z");
+ list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: two space chars at the beginning
+ 0x0C, 0x03, 0x20, 0x20, 0x5A }, "CN=\\ \\ Z", "CN=\" Z\"",
+ "cn=z", (byte) 0x01);
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: a space char at the end
+ 0x0C, 0x02, 0x5A, 0x20 }, "CN=Z\\ ", "CN=\"Z \"", "cn=z");
+ list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: two space chars at the end
+ 0x0C, 0x03, 0x5A, 0x20, 0x20 }, "CN=Z\\ \\ ", "CN=\"Z \"",
+ "cn=z", (byte) 0x01);
+
+ // special chars
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: a '#' char at the beginning
+ 0x0C, 0x02, 0x23, 0x5A }, "CN=\\#Z", "CN=\"#Z\"", "cn=\\#z");
+ list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: two '#' chars
+ 0x0C, 0x03, 0x23, 0x5A, 0x23 }, "CN=\\#Z\\#", "CN=\"#Z#\"",
+ "cn=\\#z#");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: ','
+ 0x0C, 0x02, 0x5A, 0x2C }, "CN=Z\\,", "CN=\"Z,\"", "cn=z\\,");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '+'
+ 0x0C, 0x02, 0x5A, 0x2B }, "CN=Z\\+", "CN=\"Z+\"", "cn=z\\+");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '"'
+ 0x0C, 0x02, 0x5A, 0x22 }, "CN=Z\\\"", "CN=\"Z\\\"\"",
+ "cn=z\\\"", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '\'
+ 0x0C, 0x02, 0x5A, 0x5C }, "CN=Z\\\\", "CN=\"Z\\\\\"",
+ "cn=z\\\\", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '<'
+ 0x0C, 0x02, 0x5A, 0x3C }, "CN=Z\\<", "CN=\"Z<\"", "cn=z\\<");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '>'
+ 0x0C, 0x02, 0x5A, 0x3E }, "CN=Z\\>", "CN=\"Z>\"", "cn=z\\>");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: ';'
+ 0x0C, 0x02, 0x5A, 0x3B }, "CN=Z\\;", "CN=\"Z;\"", "cn=z\\;");
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '='
+ 0x0C, 0x02, 0x5A, 0x3D }, "CN=Z\\=", "CN=\"Z=\"", "cn=z=");
+ //FIXME list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // UTF8String: ';'
+ // 0x0C, 0x02, 0x5A, 0x0D }, "CN=Z\\\r", "CN=\"Z\r\"", "cn=z");
+
+ // combinations
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: '\ '
+ 0x0C, 0x02, 0x5C, 0x20 }, "CN=\\\\\\ ", "CN=\"\\\\ \"",
+ "cn=\\\\", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: ' \'
+ 0x0C, 0x02, 0x20, 0x5C }, "CN=\\ \\\\", "CN=\" \\\\\"",
+ "cn=\\\\", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: ' \ '
+ 0x0C, 0x03, 0x20, 0x5C, 0x20 }, "CN=\\ \\\\\\ ",
+ "CN=\" \\\\ \"", "cn=\\\\", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: 'Z Z' no escaping
+ 0x0C, 0x03, 0x5A, 0x20, 0x5A }, "CN=Z Z", "CN=Z Z", "cn=z z");
+ list.add(new byte[] { 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: 'Z Z' no escaping
+ 0x0C, 0x04, 0x5A, 0x20, 0x20, 0x5A }, "CN=Z Z", "CN=\"Z Z\"",
+ "cn=z z", (byte) 0x02);
+ list.add(new byte[] { 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: ' #Z ' no escaping
+ 0x0C, 0x04, 0x20, 0x23, 0x5A, 0x20 }, "CN=\\ \\#Z\\ ",
+ "CN=\" #Z \"", "cn=#z");
+
+ //
+ // Special cases
+ //
+ // list.add(new byte[] {
+ // // Name
+ // 0x30, 0x13, 0x31, 0x11, 0x30, 0x0F,
+ // // OID
+ // 0x06, 0x0A, 0x09, (byte) 0x92, 0x26, (byte) 0x89, (byte) 0x93,
+ // (byte) 0xF2, 0x2C, 0x64, 0x01, 0x01,
+ // // ANY
+ // 0x13, 0x01, 0x41 }, "UID=A", "OID.0.9.2342.19200300.100.1.1=A",
+ // "uid=a");
+ //
+ // list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ // 0x55, 0x04, 0x03, 0x1E, 0x01, 0x5A }, "CN=Z", "CN=Z",
+ // "cn=#1e015a");
+
+ //
+ // Multi-valued DN
+ //
+ list.add(new byte[] { 0x30, 0x14, 0x31, 0x12,
+ // 1
+ 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
+ // UTF8String: 'Z'
+ 0x0C, 0x01, 0x5A,
+ //2
+ 0x30, 0x06, 0x06, 0x01, 0x01,
+ // UTF8String: 'A'
+ 0x0C, 0x01, 0x41 }, "CN=Z+0.1=#0c0141", "CN=Z + OID.0.1=A",
+ "cn=z+0.1=#0c0141");
+
+ //
+ //
+ //
+ list.add(new byte[] { 0x30, 0x0D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // UTF8String: the last letter(capital) of Russian alphabet
+ 0x0C, 0x02, (byte) 0xD0, (byte) 0xAF }, "CN=" + ((char) 1071),
+ "CN=" + ((char) 1071), "cn=" + ((char) 1103));
+ // FIXME list.add(new byte[] { 0x30, 0x0E, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // UTF8String: the last letter(capital) of Russian alphabet
+ // 0x0C, 0x03, (byte) 0xE0, (byte) 0x90, (byte) 0xAF }, "CN="
+ // + ((char) 1071), "CN=" + ((char) 1071), "cn=" + ((char) 1103));
+ // FIXME list.add(
+ // new byte[] { 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, 0x06, 0x03,
+ // 0x55, 0x04, 0x03,
+ // // UTF8String: the last letter(capital) of Russian alphabet
+ // 0x0C, 0x04, (byte) 0xF0, (byte) 0x80, (byte) 0x90,
+ // (byte) 0xAF }, "CN=" + ((char) 1071), "CN="
+ // + ((char) 1071), "cn=" + ((char) 1103));
+ list.add(new byte[] { 0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
+ 0x55, 0x04, 0x03,
+ // PrintableString: char '$' is not in table 8 (X.680)
+ 0x13, 0x01, 0x24 }, "CN=$", "CN=$", "cn=$");
+
+ StringBuffer errorMsg = new StringBuffer();
+ for (int i = 0; i < list.size(); i++) {
+
+ Object[] values = list.get(i);
+ byte[] encoded = (byte[]) values[0];
+ String rfc2253 = (String) values[1];
+ String rfc1179 = (String) values[2];
+ String canonical = (String) values[3];
+ byte mask = ((byte[]) values[4])[0];
+
+ X500Principal p;
+ try {
+ p = new X500Principal(encoded);
+
+ if (!rfc2253.equals(p.getName(X500Principal.RFC2253))) {
+ if (!testing || ((mask & 0x01) == 0)) {
+ errorMsg.append("RFC2253: " + i);
+ errorMsg.append("\t\texpected: '" + rfc2253 + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.RFC2253) + "'\n");
+ }
+ }
+
+ if (!rfc1179.equals(p.getName(X500Principal.RFC1779))) {
+ if (!testing || ((mask & 0x02) == 0)) {
+ errorMsg.append("RFC1779: " + i);
+ errorMsg.append("\t\texpected: '" + rfc1179 + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.RFC1779) + "'\n");
+ }
+ }
+
+ if (!canonical.equals(p.getName(X500Principal.CANONICAL))) {
+ if (!testing || ((mask & 0x04) == 0)) {
+ errorMsg.append("CANONICAL: " + i);
+ errorMsg.append("\t\texpected: " + canonical + "'");
+ errorMsg.append("\treturned: '"
+ + p.getName(X500Principal.CANONICAL) + "'\n");
+ }
+ }
+
+ } catch (IllegalArgumentException e) {
+ errorMsg.append("\nIllegalArgumentException: " + i + ", for "
+ + rfc2253);
+ continue;
+ } catch (Exception e) {
+ errorMsg.append("Exception: " + i + ", for " + rfc2253);
+ errorMsg.append("\texcep: " + e.getClass().getName() + "\n");
+ continue;
+ }
+
+ }
+
+ if (errorMsg.length() != 0) {
+ fail(errorMsg.toString());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static class TestList extends ArrayList<Object[]> {
+ //
+ // TODO comment me
+ //
+ public void add(String param, String rfc2253, String rfc1779) {
+ add(param, rfc2253, rfc1779, (byte[]) null);
+ }
+
+ public void add(String param, String rfc2253, String rfc1779,
+ String canonical) {
+ add(param, rfc2253, rfc1779, canonical, null);
+ }
+
+ public void add(String param, String rfc2253, String rfc1779,
+ byte[] encoded) {
+ add(new Object[] { param, rfc2253, rfc1779, null, encoded,
+ emptyMask });
+ }
+
+ public void add(String param, String rfc2253, String rfc1779,
+ byte[] encoded, byte mask) {
+ add(new Object[] { param, rfc2253, rfc1779, null, encoded,
+ new byte[] { mask } });
+ }
+
+ public void add(String param, String rfc2253, String rfc1779,
+ String canonical, byte[] encoded) {
+ add(new Object[] { param, rfc2253, rfc1779, canonical, encoded,
+ emptyMask });
+ }
+
+ public void add(String param, String rfc2253, String rfc1779,
+ String canonical, byte[] encoded, byte mask) {
+ add(new Object[] { param, rfc2253, rfc1779, canonical, encoded,
+ new byte[] { mask } });
+ }
+
+ //
+ // TODO comment me
+ //
+
+ private static final byte[] emptyMask = new byte[] { 0x00 };
+
+ public void add(byte[] encoding, String rfc2253, String rfc1779,
+ String canonical) {
+ add(new Object[] { encoding, rfc2253, rfc1779, canonical, emptyMask });
+ }
+
+ public void add(byte[] encoding, String rfc2253, String rfc1779,
+ String canonical, byte mask) {
+ add(new Object[] { encoding, rfc2253, rfc1779, canonical,
+ new byte[] { mask } });
+ }
+ }
+
+
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(getSerializationData());
+ }
+
+ public void testSerializationGolden() throws Exception {
+ SerializationTest.verifyGolden(this, getSerializationData());
+ }
+
+ private Object[] getSerializationData() {
+ return new Object[] { new X500Principal("CN=A"),
+ new X500Principal("CN=A, C=B"),
+ new X500Principal("CN=A, CN=B + C=C") };
+ }
+}
+
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateEncodingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateEncodingExceptionTest.java
new file mode 100644
index 0000000..53fbd9f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateEncodingExceptionTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Vera Y. Petrashkova
+* @version $Revision$
+*/
+
+package tests.api.javax.security.cert;
+
+import junit.framework.TestCase;
+
+import javax.security.cert.CertificateEncodingException;
+
+/**
+ * Tests for <code>DigestException</code> class constructors and methods.
+ *
+ */
+public class CertificateEncodingExceptionTest extends TestCase {
+
+ static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>CertificateEncodingException()</code> constructor
+ * Assertion: constructs CertificateEncodingException with no detail message
+ */
+ public void testCertificateEncodingException01() {
+ CertificateEncodingException tE = new CertificateEncodingException();
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+
+ /**
+ * Test for <code>CertificateEncodingException(String)</code> constructor
+ * Assertion: constructs CertificateEncodingException with detail message
+ * msg. Parameter <code>msg</code> is not null.
+ */
+ public void testCertificateEncodingException02() {
+ CertificateEncodingException tE;
+ for (int i = 0; i < msgs.length; i++) {
+ tE = new CertificateEncodingException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), tE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", tE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>CertificateEncodingException(String)</code> constructor
+ * Assertion: constructs CertificateEncodingException when <code>msg</code>
+ * is null
+ */
+ public void testCertificateEncodingException03() {
+ String msg = null;
+ CertificateEncodingException tE = new CertificateEncodingException(msg);
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExceptionTest.java
new file mode 100644
index 0000000..ccc3a2c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExceptionTest.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Vera Y. Petrashkova
+* @version $Revision$
+*/
+
+package tests.api.javax.security.cert;
+
+import junit.framework.TestCase;
+
+import javax.security.cert.CertificateException;
+
+
+/**
+ * Tests for <code>DigestException</code> class constructors and methods.
+ *
+ */
+public class CertificateExceptionTest extends TestCase {
+
+ static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>CertificateException()</code> constructor Assertion:
+ * constructs CertificateException with no detail message
+ */
+ public void testCertificateException01() {
+ CertificateException tE = new CertificateException();
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+
+ /**
+ * Test for <code>CertificateException(String)</code> constructor
+ * Assertion: constructs CertificateException with detail message msg.
+ * Parameter <code>msg</code> is not null.
+ */
+ public void testCertificateException02() {
+ CertificateException tE;
+ for (int i = 0; i < msgs.length; i++) {
+ tE = new CertificateException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), tE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", tE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>CertificateException(String)</code> constructor
+ * Assertion: constructs CertificateException when <code>msg</code> is
+ * null
+ */
+ public void testCertificateException03() {
+ String msg = null;
+ CertificateException tE = new CertificateException(msg);
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExpiredExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExpiredExceptionTest.java
new file mode 100644
index 0000000..d0e94e3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateExpiredExceptionTest.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Vera Y. Petrashkova
+* @version $Revision$
+*/
+
+package tests.api.javax.security.cert;
+
+import junit.framework.TestCase;
+
+import javax.security.cert.CertificateExpiredException;
+
+
+/**
+ * Tests for <code>DigestException</code> class constructors and methods.
+ *
+ */
+public class CertificateExpiredExceptionTest extends TestCase {
+
+ static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>CertificateExpiredException()</code> constructor
+ * Assertion: constructs CertificateExpiredException with no detail message
+ */
+ public void testCertificateExpiredException01() {
+ CertificateExpiredException tE = new CertificateExpiredException();
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+
+ /**
+ * Test for <code>CertificateExpiredException(String)</code> constructor
+ * Assertion: constructs CertificateExpiredException with detail message
+ * msg. Parameter <code>msg</code> is not null.
+ */
+ public void testCertificateExpiredException02() {
+ CertificateExpiredException tE;
+ for (int i = 0; i < msgs.length; i++) {
+ tE = new CertificateExpiredException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), tE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", tE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>CertificateExpiredException(String)</code> constructor
+ * Assertion: constructs CertificateExpiredException when <code>msg</code>
+ * is null
+ */
+ public void testCertificateExpiredException03() {
+ String msg = null;
+ CertificateExpiredException tE = new CertificateExpiredException(msg);
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateNotYetValidExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateNotYetValidExceptionTest.java
new file mode 100644
index 0000000..c746648
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateNotYetValidExceptionTest.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Vera Y. Petrashkova
+* @version $Revision$
+*/
+
+package tests.api.javax.security.cert;
+
+import junit.framework.TestCase;
+
+import javax.security.cert.CertificateNotYetValidException;
+
+
+/**
+ * Tests for <code>DigestException</code> class constructors and methods.
+ *
+ */
+public class CertificateNotYetValidExceptionTest extends TestCase {
+
+ static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>CertificateNotYetValidException()</code> constructor
+ * Assertion: constructs CertificateNotYetValidException with no detail
+ * message
+ */
+ public void testCertificateNotYetValidException01() {
+ CertificateNotYetValidException tE = new CertificateNotYetValidException();
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+
+ /**
+ * Test for <code>CertificateNotYetValidException(String)</code>
+ * constructor Assertion: constructs CertificateNotYetValidException with
+ * detail message msg. Parameter <code>msg</code> is not null.
+ */
+ public void testCertificateNotYetValidException02() {
+ CertificateNotYetValidException tE;
+ for (int i = 0; i < msgs.length; i++) {
+ tE = new CertificateNotYetValidException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), tE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", tE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>CertificateNotYetValidException(String)</code>
+ * constructor Assertion: constructs CertificateNotYetValidException when
+ * <code>msg</code> is null
+ */
+ public void testCertificateNotYetValidException03() {
+ String msg = null;
+ CertificateNotYetValidException tE = new CertificateNotYetValidException(
+ msg);
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateParsingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateParsingExceptionTest.java
new file mode 100644
index 0000000..bc07ff6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateParsingExceptionTest.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* @author Vera Y. Petrashkova
+* @version $Revision$
+*/
+
+package tests.api.javax.security.cert;
+
+import junit.framework.TestCase;
+
+import javax.security.cert.CertificateParsingException;
+
+
+/**
+ * Tests for <code>DigestException</code> class constructors and methods.
+ *
+ */
+public class CertificateParsingExceptionTest extends TestCase {
+
+
+ static String[] msgs = {
+ "",
+ "Check new message",
+ "Check new message Check new message Check new message Check new message Check new message" };
+
+ static Throwable tCause = new Throwable("Throwable for exception");
+
+ /**
+ * Test for <code>CertificateParsingException()</code> constructor
+ * Assertion: constructs CertificateParsingException with no detail message
+ */
+ public void testCertificateParsingException01() {
+ CertificateParsingException tE = new CertificateParsingException();
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+
+ /**
+ * Test for <code>CertificateParsingException(String)</code> constructor
+ * Assertion: constructs CertificateParsingException with detail message
+ * msg. Parameter <code>msg</code> is not null.
+ */
+ public void testCertificateParsingException02() {
+ CertificateParsingException tE;
+ for (int i = 0; i < msgs.length; i++) {
+ tE = new CertificateParsingException(msgs[i]);
+ assertEquals("getMessage() must return: ".concat(msgs[i]), tE
+ .getMessage(), msgs[i]);
+ assertNull("getCause() must return null", tE.getCause());
+ }
+ }
+
+ /**
+ * Test for <code>CertificateParsingException(String)</code> constructor
+ * Assertion: constructs CertificateParsingException when <code>msg</code>
+ * is null
+ */
+ public void testCertificateParsingException03() {
+ String msg = null;
+ CertificateParsingException tE = new CertificateParsingException(msg);
+ assertNull("getMessage() must return null.", tE.getMessage());
+ assertNull("getCause() must return null", tE.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateTest.java
new file mode 100644
index 0000000..da1c7a0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/CertificateTest.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package tests.api.javax.security.cert;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PublicKey;
+import java.security.SignatureException;
+
+import javax.security.cert.Certificate;
+import javax.security.cert.CertificateEncodingException;
+import javax.security.cert.CertificateException;
+
+public class CertificateTest extends TestCase {
+
+ /**
+ * The stub class used for testing of non abstract methods.
+ */
+ private class TBTCert extends Certificate {
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return null;
+ }
+
+ public void verify(PublicKey key) throws CertificateException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException {
+ }
+
+ public void verify(PublicKey key, String sigProvider)
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException,
+ SignatureException {
+ }
+
+ public String toString() {
+ return "TBTCert";
+ }
+
+ public PublicKey getPublicKey() {
+ return null;
+ }
+ }
+
+ /**
+ * Test for <code>Certificate()</code> constructor<br>
+ */
+ public final void testCertificate() {
+ TBTCert tbt_cert = new TBTCert();
+
+ assertNull("Public key should be null", tbt_cert.getPublicKey());
+ assertEquals("Wrong string representation for Certificate", "TBTCert", tbt_cert.toString());
+ }
+
+ /**
+ * equals(Object obj) method testing. Tests the correctness of equal
+ * operation: it should be reflexive, symmetric, transitive, consistent and
+ * should be false on null object.
+ */
+ public void testEquals() {
+ TBTCert tbt_cert = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 1, 2, 3 };
+ }
+ };
+
+ TBTCert tbt_cert_1 = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 1, 2, 3 };
+ }
+ };
+
+ TBTCert tbt_cert_2 = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 1, 2, 3 };
+ }
+ };
+
+ TBTCert tbt_cert_3 = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 3, 2, 1 };
+ }
+ };
+
+ // checking for reflexive law:
+ assertTrue("The equivalence relation should be reflexive.", tbt_cert
+ .equals(tbt_cert));
+
+ assertEquals(
+ "The Certificates with equal encoded form should be equal",
+ tbt_cert, tbt_cert_1);
+ // checking for symmetric law:
+ assertTrue("The equivalence relation should be symmetric.", tbt_cert_1
+ .equals(tbt_cert));
+
+ assertEquals(
+ "The Certificates with equal encoded form should be equal",
+ tbt_cert_1, tbt_cert_2);
+ // checking for transitive law:
+ assertTrue("The equivalence relation should be transitive.", tbt_cert
+ .equals(tbt_cert_2));
+
+ assertFalse("Should not be equal to null object.", tbt_cert
+ .equals(null));
+
+ assertFalse("The Certificates with differing encoded form "
+ + "should not be equal", tbt_cert.equals(tbt_cert_3));
+ assertFalse("The Certificates should not be equals to the object "
+ + "which is not an instance of Certificate", tbt_cert
+ .equals(new Object()));
+ }
+
+ /**
+ * hashCode() method testing.
+ */
+ public void testHashCode() {
+ TBTCert tbt_cert = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 1, 2, 3 };
+ }
+ };
+ TBTCert tbt_cert_1 = new TBTCert() {
+ public byte[] getEncoded() {
+ return new byte[] { 1, 2, 3 };
+ }
+ };
+
+ assertTrue("Equal objects should have the same hash codes.", tbt_cert
+ .hashCode() == tbt_cert_1.hashCode());
+ }
+
+ public static Test suite() {
+ return new TestSuite(CertificateTest.class);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/X509CertificateTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/X509CertificateTest.java
new file mode 100644
index 0000000..64bfbb3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/security/cert/X509CertificateTest.java
@@ -0,0 +1,785 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package tests.api.javax.security.cert;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import tests.targets.security.cert.CertificateFactoryTestX509;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Principal;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.SignatureException;
+import java.security.Provider.Service;
+import java.security.cert.CertificateFactory;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.security.cert.Certificate;
+import javax.security.cert.CertificateEncodingException;
+import javax.security.cert.CertificateException;
+import javax.security.cert.CertificateExpiredException;
+import javax.security.cert.CertificateNotYetValidException;
+import javax.security.cert.X509Certificate;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import tests.targets.security.cert.CertificateFactoryTestX509;
+
+/**
+ */
+public class X509CertificateTest extends TestCase {
+
+ // Testing data was generated by using of classes
+ // from org.apache.harmony.security.asn1 package encoded
+ // by org.apache.harmony.misc.Base64 class.
+
+ private static String base64cert = "-----BEGIN CERTIFICATE-----\n"
+ + "MIIC+jCCAragAwIBAgICAiswDAYHKoZIzjgEAwEBADAdMRswGQYDVQQKExJDZXJ0a"
+ + "WZpY2F0ZSBJc3N1ZXIwIhgPMTk3MDAxMTIxMzQ2NDBaGA8xOTcwMDEyNDAzMzMyMF"
+ + "owHzEdMBsGA1UEChMUU3ViamVjdCBPcmdhbml6YXRpb24wGTAMBgcqhkjOOAQDAQE"
+ + "AAwkAAQIDBAUGBwiBAgCqggIAVaOCAhQwggIQMA8GA1UdDwEB/wQFAwMBqoAwEgYD"
+ + "VR0TAQH/BAgwBgEB/wIBBTAUBgNVHSABAf8ECjAIMAYGBFUdIAAwZwYDVR0RAQH/B"
+ + "F0wW4EMcmZjQDgyMi5OYW1lggdkTlNOYW1lpBcxFTATBgNVBAoTDE9yZ2FuaXphdG"
+ + "lvboYaaHR0cDovL3VuaWZvcm0uUmVzb3VyY2UuSWSHBP///wCIByoDolyDsgMwDAY"
+ + "DVR0eAQH/BAIwADAMBgNVHSQBAf8EAjAAMIGZBgNVHSUBAf8EgY4wgYsGBFUdJQAG"
+ + "CCsGAQUFBwMBBggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDBggrBgEFBQcDB"
+ + "AYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEFBQcDBwYIKwYBBQUHAwgGCCsGAQUFBw"
+ + "MJBggrBgEFBQgCAgYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GA1UdNgEB/wQDAgE"
+ + "BMA4GBCpNhgkBAf8EAwEBATBkBgNVHRIEXTBbgQxyZmNAODIyLk5hbWWCB2ROU05h"
+ + "bWWkFzEVMBMGA1UEChMMT3JnYW5pemF0aW9uhhpodHRwOi8vdW5pZm9ybS5SZXNvd"
+ + "XJjZS5JZIcE////AIgHKgOiXIOyAzAJBgNVHR8EAjAAMAoGA1UdIwQDAQEBMAoGA1"
+ + "UdDgQDAQEBMAoGA1UdIQQDAQEBMAwGByqGSM44BAMBAQADMAAwLQIUAL4QvoazNWP"
+ + "7jrj84/GZlhm09DsCFQCBKGKCGbrP64VtUt4JPmLjW1VxQA==\n"
+ + "-----END CERTIFICATE-----";
+
+ /*
+ * a self-signed certificate
+ */
+ private static final String selfSignedCert = "-----BEGIN CERTIFICATE-----\n" +
+ "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ" +
+ "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k" +
+ "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh" +
+ "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ" +
+ "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw" +
+ "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB" +
+ "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" +
+ "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3" +
+ "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU" +
+ "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G" +
+ "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q" +
+ "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu" +
+ "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV" +
+ "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C" +
+ "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF" +
+ "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL" +
+ "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T" +
+ "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n" +
+ "-----END CERTIFICATE-----";
+
+ private java.security.cert.X509Certificate cert;
+
+ private javax.security.cert.X509Certificate tbt_cert;
+
+ private java.security.cert.X509Certificate javaCert;
+
+ private Provider myProvider;
+
+ private javax.security.cert.X509Certificate javaxCert;
+
+ private java.security.cert.Certificate javaSSCert;
+
+ private Provider mySSProvider;
+
+ private Certificate javaxSSCert;
+
+ @Override
+ protected void setUp() throws Exception {
+ try {
+ ByteArrayInputStream bais = new ByteArrayInputStream(base64cert
+ .getBytes());
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ this.cert = (java.security.cert.X509Certificate) cf
+ .generateCertificate(bais);
+ this.tbt_cert = X509Certificate.getInstance(cert.getEncoded());
+
+ // non self signed cert
+ this.javaCert = (java.security.cert.X509Certificate)cf
+ .generateCertificate(new ByteArrayInputStream(selfSignedCert.getBytes()));
+ this.javaxCert = X509Certificate.getInstance(javaCert.getEncoded());
+ myProvider = cf.getProvider();
+ Security.addProvider(myProvider);
+
+ // self signed cert
+ this.javaSSCert = cf.generateCertificate(new ByteArrayInputStream(
+ selfSignedCert.getBytes()));
+ this.javaxSSCert = X509Certificate.getInstance(javaCert
+ .getEncoded());
+ mySSProvider = cf.getProvider();
+ Security.addProvider(mySSProvider);
+
+ } catch (java.security.cert.CertificateException e) {
+ // The requested certificate type is not available.
+ // Test pass..
+ this.cert = null;
+ Logger.global.warning("Error in test setup: Certificate type not supported");
+ } catch (javax.security.cert.CertificateException e) {
+ // The requested certificate type is not available.
+ // Test pass..
+ this.cert = null;
+ Logger.global.warning("Error in test setup: Certificate type not supported");
+ }
+ }
+
+ /**
+ * X509Certificate() constructor testing.
+ * {@link X509Certificate#X509Certificate() }
+ */
+ public void testConstructor() {
+ //Direct constructor, check if it throws an exception
+ X509Certificate cert = new MyCertificate();
+ }
+
+ /**
+ * getInstance(InputStream inStream) method testing.
+ */
+ public void testGetInstance1() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ try {
+ ByteArrayInputStream bais = new ByteArrayInputStream(cert
+ .getEncoded());
+
+ X509Certificate.getInstance(bais);
+ } catch (java.security.cert.CertificateEncodingException e) {
+ fail("Unexpected CertificateEncodingException was thrown.");
+ } catch (CertificateEncodingException e) {
+ fail("Unexpected CertificateEncodingException was thrown.");
+ } catch (CertificateException e) {
+ // The requested certificate type is not available.
+ // Test pass..
+ }
+
+ // Regression for HARMONY-756
+ try {
+ X509Certificate.getInstance((InputStream) null);
+ fail("No expected CertificateException");
+ } catch (CertificateException e) {
+ // expected;
+ }
+ }
+
+ /**
+ * getInstance(byte[] certData) method testing.
+ * @throws CertificateEncodingException
+ * @throws java.security.cert.CertificateEncodingException
+ */
+ public void testGetInstance2() throws java.security.cert.CertificateEncodingException, CertificateEncodingException {
+ boolean certificateException = false;
+ X509Certificate c = null;
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ try {
+ c = X509Certificate.getInstance(cert.getEncoded());
+ } catch (java.security.cert.CertificateEncodingException e) {
+ fail("Unexpected CertificateEncodingException was thrown.");
+ } catch (CertificateException e) {
+ // The requested certificate type is not available.
+ // Test pass..
+ certificateException = true;
+
+ }
+
+ if (! certificateException) {
+ assertNotNull(c);
+ assertTrue(Arrays.equals(c.getEncoded(),cert.getEncoded() ));
+ }
+
+ try {
+ X509Certificate.getInstance(new byte[]{(byte) 1 });
+ } catch (CertificateException e) {
+ //ok
+ }
+
+ // Regression for HARMONY-756
+ try {
+ X509Certificate.getInstance((byte[]) null);
+ fail("No expected CertificateException");
+ } catch (CertificateException e) {
+ // expected;
+ }
+
+ }
+
+ /**
+ * checkValidity() method testing.
+ * @throws CertificateNotYetValidException
+ * @throws CertificateExpiredException
+ * @throws java.security.cert.CertificateExpiredException
+ * @throws java.security.cert.CertificateNotYetValidException
+ */
+ public void testCheckValidity1() throws CertificateExpiredException, CertificateNotYetValidException, java.security.cert.CertificateExpiredException, java.security.cert.CertificateNotYetValidException {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ Date date = new Date();
+ Date nb_date = tbt_cert.getNotBefore();
+ Date na_date = tbt_cert.getNotAfter();
+ try {
+ tbt_cert.checkValidity();
+ assertFalse("CertificateExpiredException expected", date
+ .compareTo(na_date) > 0);
+ assertFalse("CertificateNotYetValidException expected", date
+ .compareTo(nb_date) < 0);
+ } catch (CertificateExpiredException e) {
+ assertTrue("Unexpected CertificateExpiredException was thrown",
+ date.compareTo(na_date) > 0);
+ } catch (CertificateNotYetValidException e) {
+ assertTrue("Unexpected CertificateNotYetValidException was thrown",
+ date.compareTo(nb_date) < 0);
+ }
+
+ try {
+ tbt_cert.checkValidity();
+ } catch (CertificateExpiredException e) {
+ // ok
+ }
+
+ try {
+ cert.checkValidity();
+ } catch (java.security.cert.CertificateExpiredException e) {
+ // ok
+ }
+
+ }
+
+ /**
+ * checkValidity(Date date) method testing.
+ * @throws CertificateNotYetValidException
+ * @throws CertificateExpiredException
+ */
+ public void testCheckValidity2() throws CertificateNotYetValidException, CertificateExpiredException {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ Date[] date = new Date[8];
+ Calendar calendar = Calendar.getInstance();
+ for (int i = 0; i < date.length; i++) {
+ calendar.set(i * 500, Calendar.JANUARY, 1);
+ date[i] = calendar.getTime();
+ }
+ Date nb_date = tbt_cert.getNotBefore();
+ Date na_date = tbt_cert.getNotAfter();
+ for (int i = 0; i < date.length; i++) {
+ try {
+ tbt_cert.checkValidity(date[i]);
+ assertFalse("CertificateExpiredException expected", date[i]
+ .compareTo(na_date) > 0);
+ assertFalse("CertificateNotYetValidException expected", date[i]
+ .compareTo(nb_date) < 0);
+ } catch (CertificateExpiredException e) {
+ assertTrue("Unexpected CertificateExpiredException was thrown",
+ date[i].compareTo(na_date) > 0);
+ } catch (CertificateNotYetValidException e) {
+ assertTrue("Unexpected CertificateNotYetValidException "
+ + "was thrown", date[i].compareTo(nb_date) < 0);
+ }
+ }
+
+ Calendar calendarNow = Calendar.getInstance();
+
+ try {
+ tbt_cert.checkValidity(calendarNow.getTime());
+ } catch (CertificateExpiredException e) {
+ //ok
+ }
+
+ Calendar calendarPast = GregorianCalendar.getInstance();
+ calendarPast.clear();
+
+ try {
+ tbt_cert.checkValidity(calendarPast.getTime());
+ } catch (CertificateNotYetValidException e) {
+ //ok
+ }
+
+ }
+
+ /**
+ * getVersion() method testing.
+ */
+ public void testGetVersion() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The version is not correct.", tbt_cert.getVersion(), 2);
+ }
+
+ /**
+ * getSerialNumber() method testing.
+ */
+ public void testGetSerialNumber() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The serial number is not correct.", tbt_cert
+ .getSerialNumber(), cert.getSerialNumber());
+ }
+
+ /**
+ * getIssuerDN() method testing.
+ */
+ public void testGetIssuerDN() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ Logger.global.warning("testGetIssuerDN: error in test setup.");
+ }
+ assertEquals("The issuer DN is not correct.", tbt_cert.getIssuerDN(),
+ cert.getIssuerDN());
+ }
+
+ /**
+ * getSubjectDN() method testing.
+ */
+ public void testGetSubjectDN() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The subject DN is not correct.", tbt_cert.getSubjectDN(),
+ cert.getSubjectDN());
+ }
+
+ /**
+ * getNotBefore() method testing.
+ */
+ public void testGetNotBefore() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The NotBefore date is not correct.", tbt_cert
+ .getNotBefore(), cert.getNotBefore());
+ }
+
+ /**
+ * getNotAfter() method testing.
+ */
+ public void testGetNotAfter() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The NotAfter date is not correct.", tbt_cert
+ .getNotAfter(), cert.getNotAfter());
+ }
+
+ /**
+ * getSigAlgName() method testing.
+ */
+ public void testGetSigAlgName() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The name of signature algorithm is not correct.",
+ tbt_cert.getSigAlgName(), cert.getSigAlgName());
+ }
+
+ /**
+ * getSigAlgOID() method testing.
+ */
+ public void testGetSigAlgOID() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertEquals("The name of OID of signature algorithm is not correct.",
+ tbt_cert.getSigAlgOID(), cert.getSigAlgOID());
+ }
+
+ /**
+ * getSigAlgParams() method testing.
+ */
+ public void testGetSigAlgParams() {
+ if (this.cert == null) {
+ // The requested certificate type is not available.
+ // Test can not be applied.
+ return;
+ }
+ assertTrue("The byte array with encoded algorithm parameters "
+ + "is not correct.", Arrays.equals(tbt_cert.getSigAlgParams(),
+ cert.getSigAlgParams()));
+ }
+
+ /**
+ * The stub class used for testing of non abstract methods.
+ */
+ private class MyCertificate extends X509Certificate {
+
+ public MyCertificate() {
+ super();
+ }
+
+ @Override
+ public void checkValidity() throws CertificateExpiredException,
+ CertificateNotYetValidException {
+ }
+
+ @Override
+ public void checkValidity(Date arg0)
+ throws CertificateExpiredException,
+ CertificateNotYetValidException {
+ }
+
+ @Override
+ public Principal getIssuerDN() {
+ return null;
+ }
+
+ @Override
+ public Date getNotAfter() {
+ return null;
+ }
+
+ @Override
+ public Date getNotBefore() {
+ return null;
+ }
+
+ @Override
+ public BigInteger getSerialNumber() {
+ return null;
+ }
+
+ @Override
+ public String getSigAlgName() {
+ return null;
+ }
+
+ @Override
+ public String getSigAlgOID() {
+ return null;
+ }
+
+ @Override
+ public byte[] getSigAlgParams() {
+ return null;
+ }
+
+ @Override
+ public Principal getSubjectDN() {
+ return null;
+ }
+
+ @Override
+ public int getVersion() {
+ return 0;
+ }
+
+ @Override
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return null;
+ }
+
+ @Override
+ public PublicKey getPublicKey() {
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return null;
+ }
+
+ @Override
+ public void verify(PublicKey key) throws CertificateException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException {
+ }
+
+ @Override
+ public void verify(PublicKey key, String sigProvider)
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException,
+ SignatureException {
+ }
+ }
+
+ public class MyModifiablePublicKey implements PublicKey {
+
+ private PublicKey key;
+ private boolean modifiedAlgo;
+ private String algo;
+ private String format;
+ private boolean modifiedFormat;
+ private boolean modifiedEncoding;
+ private byte[] encoding;
+
+ public MyModifiablePublicKey(PublicKey k) {
+ super();
+ this.key = k;
+ }
+
+ public String getAlgorithm() {
+ if (modifiedAlgo) {
+ return algo;
+ } else {
+ return key.getAlgorithm();
+ }
+ }
+
+ public String getFormat() {
+ if (modifiedFormat) {
+ return this.format;
+ } else {
+ return key.getFormat();
+ }
+
+ }
+
+ public byte[] getEncoded() {
+ if (modifiedEncoding) {
+ return this.encoding;
+ } else {
+ return key.getEncoded();
+ }
+
+ }
+
+ public long getSerVerUID() {
+ return key.serialVersionUID;
+ }
+
+ public void setAlgorithm(String myAlgo) {
+ modifiedAlgo = true;
+ this.algo = myAlgo;
+ }
+
+ public void setFormat(String myFormat) {
+ modifiedFormat = true;
+ format = myFormat;
+ }
+
+ public void setEncoding(byte[] myEncoded) {
+ modifiedEncoding = true;
+ encoding = myEncoded;
+ }
+ }
+
+ /**
+ * @throws CertificateEncodingException
+ * {@link Certificate#getEncoded()}
+ */
+ public void testGetEncoded()
+ throws CertificateEncodingException, java.security.cert.CertificateException {
+ // cert = DER encoding of the ASN1.0 structure
+ assertTrue(Arrays.equals(cert.getEncoded(), tbt_cert.getEncoded()));
+ assertFalse(Arrays.equals(javaxCert.getEncoded(), tbt_cert.getEncoded()));
+ }
+
+ /**
+ * {@link Certificate#getPublicKey()}
+ */
+ public void testGetPublicKey() {
+ PublicKey key = javaxCert.getPublicKey();
+ assertNotNull(key);
+ assertEquals(javaxCert.getPublicKey(), javaCert.getPublicKey());
+ assertEquals(key.getAlgorithm(),"RSA");
+
+ key = javaxSSCert.getPublicKey();
+ assertNotNull(key);
+ assertEquals(key.getAlgorithm(),"RSA");
+
+ //assertTrue(mySSProvider.containsKey(key));
+
+ }
+
+ /**
+ * @throws SignatureException
+ * @throws NoSuchProviderException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ * @throws CertificateException
+ * {@link Certificate#verify(PublicKey)}
+ */
+ // Side Effect: Destroys MD5 provider, hurts succeeding tests
+ public void testVerifyPublicKey() throws InvalidKeyException,
+ NoSuchAlgorithmException, NoSuchProviderException,
+ SignatureException, CertificateException {
+
+ // Preconditions
+ assertNotNull(javaxCert.getPublicKey());
+ assertNotNull(javaxSSCert.getPublicKey());
+ //precondition for self signed certificates
+ /*assertEquals(((X509Certificate) javaxSSCert).getIssuerDN().getName(),
+ ((X509Certificate) javaxSSCert).getSubjectDN());*/
+
+ // must always evaluate true for self signed
+ // here not self signed:
+ try {
+ javaxCert.verify(javaxCert.getPublicKey());
+ } catch (SignatureException e) {
+ // ok
+ }
+
+ PublicKey k = javaxCert.getPublicKey();
+
+ MyModifiablePublicKey changedEncoding = new MyModifiablePublicKey(k);
+ changedEncoding
+ .setEncoding(new byte[javaxCert.getEncoded().length - 1]);
+
+ try {
+ javaxCert.verify(tbt_cert.getPublicKey());
+ } catch (InvalidKeyException e) {
+ // ok
+ }
+
+
+ try {
+ javaxCert.verify(null);
+ } catch (Exception e) {
+ // ok
+ }
+
+ try {
+ javaxCert.verify(changedEncoding);
+ fail("Exception expected");
+ } catch (Exception e) {
+ // ok
+ }
+
+ // following test doesn't work because the algorithm is derived from
+ // somewhere else.
+
+ // MyModifiablePublicKey changedAlgo = new MyModifiablePublicKey(k);
+ // changedAlgo.setAlgorithm("MD5withBla");
+
+ // try {
+ // javaxCert.verify(changedAlgo);
+ // fail("Exception expected");
+ // } catch (SignatureException e) {
+ // // ok
+ // }
+
+ // Security.removeProvider(mySSProvider.getName());
+
+ // try {
+ // javaxSSCert.verify(javaxSSCert.getPublicKey());
+ // } catch (NoSuchProviderException e) {
+ // // ok
+ // }
+
+ // Security.addProvider(mySSProvider);
+
+ // must always evaluate true for self signed
+ // javaxSSCert.verify(javaxSSCert.getPublicKey());
+ }
+
+ /**
+ * @throws SignatureException
+ * @throws NoSuchProviderException
+ * @throws NoSuchAlgorithmException
+ * @throws java.security.cert.CertificateException
+ * @throws InvalidKeyException
+ * @throws IOException
+ * @throws CertificateException
+ * {@link Certificate#verify(PublicKey, String)}
+ */
+ // SideEffect: Destroys MD5 provider, hurts succeeding tests
+ public void testVerifyPublicKeyString() throws InvalidKeyException,
+ java.security.cert.CertificateException, NoSuchAlgorithmException,
+ NoSuchProviderException, SignatureException, IOException,
+ CertificateException {
+
+ try {
+ javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName());
+ } catch (NoSuchAlgorithmException e) {
+ // ok
+ }
+
+ // myProvider.getService(type, algorithm)
+
+ Security.removeProvider(myProvider.getName());
+ try {
+ javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName());
+ } catch (NoSuchProviderException e) {
+ // ok
+ }
+ Security.addProvider(myProvider);
+
+ Provider[] providers = Security.getProviders("Signature.MD5withRSA");
+ if (providers == null || providers.length == 0) {
+ fail("no Provider for Signature.MD5withRSA");
+ return;
+ }
+
+ // self signed cert: should verify with provider
+ try {
+ javaxSSCert.verify(javaxSSCert.getPublicKey(),
+ providers[0].getName());
+ } catch (SignatureException e) {
+ fail("blu");
+ }
+
+ }
+
+ public static Test suite() {
+ return new TestSuite(X509CertificateTest.class);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderFactoryTest.java
new file mode 100644
index 0000000..7d79560
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderFactoryTest.java
@@ -0,0 +1,975 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.xml.parsers;
+
+import junit.framework.TestCase;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+public class DocumentBuilderFactoryTest extends TestCase {
+
+ DocumentBuilderFactory dbf;
+
+ List<String> cdataElements;
+
+ List<String> textElements;
+
+ List<String> commentElements;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ dbf = DocumentBuilderFactory.newInstance();
+
+ cdataElements = new ArrayList<String>();
+ textElements = new ArrayList<String>();
+ commentElements = new ArrayList<String>();
+ }
+
+ protected void tearDown() throws Exception {
+ dbf = null;
+ cdataElements = null;
+ textElements = null;
+ commentElements = null;
+ super.tearDown();
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#DocumentBuilderFactory().
+ */
+ public void test_Constructor() {
+ try {
+ new DocumentBuilderFactoryChild();
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#getAttribute(String).
+ */
+// public void test_getAttributeLjava_lang_String() {
+// String[] attributes = {
+// "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
+// "http://java.sun.com/xml/jaxp/properties/schemaSource" };
+// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
+//
+// try {
+// for (int i = 0; i < attributes.length; i++) {
+// dbf.setAttribute(attributes[i], values[i]);
+// assertEquals(values[i], dbf.getAttribute(attributes[i]));
+// }
+// } catch (IllegalArgumentException e) {
+// fail("Unexpected IllegalArgumentException" + e.getMessage());
+// } catch (Exception e) {
+// fail("Unexpected exception" + e.getMessage());
+// }
+//
+// try {
+// for (int i = 0; i < attributes.length; i++) {
+// dbf.setAttribute(null, null);
+// fail("NullPointerException expected");
+// }
+// } catch (NullPointerException e) {
+// // expected
+// }
+//
+// String[] badAttributes = {"bad1", "bad2", ""};
+// try {
+// for (int i = 0; i < badAttributes.length; i++) {
+// dbf.getAttribute(badAttributes[i]);
+// fail("IllegalArgumentException expected");
+// }
+// } catch (IllegalArgumentException e) {
+// // expected
+// }
+// }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#getFeature(String).
+ */
+// TODO Fails on JDK. Why?
+// public void test_getFeatureLjava_lang_String() {
+// String[] features = { "http://xml.org/sax/features/namespaces",
+// "http://xml.org/sax/features/validation",
+// "http://xml.org/sax/features/external-general-entities" };
+// try {
+// for (int i = 0; i < features.length; i++) {
+// dbf.setFeature(features[i], true);
+// assertTrue(dbf.getFeature(features[i]));
+// }
+// } catch (ParserConfigurationException e) {
+// fail("Unexpected ParserConfigurationException " + e.getMessage());
+// }
+//
+// try {
+// for (int i = 0; i < features.length; i++) {
+// dbf.setFeature(features[i], false);
+// assertFalse(dbf.getFeature(features[i]));
+// }
+// } catch (ParserConfigurationException e) {
+// fail("Unexpected ParserConfigurationException " + e.getMessage());
+// }
+//
+// try {
+// for (int i = 0; i < features.length; i++) {
+// dbf.setFeature(null, false);
+// fail("NullPointerException expected");
+// }
+// } catch (NullPointerException e) {
+// // expected
+// } catch (ParserConfigurationException e) {
+// fail("Unexpected ParserConfigurationException" + e.getMessage());
+// }
+//
+// String[] badFeatures = {"bad1", "bad2", ""};
+// try {
+// for (int i = 0; i < badFeatures.length; i++) {
+// dbf.getFeature(badFeatures[i]);
+// fail("ParserConfigurationException expected");
+// }
+// } catch (ParserConfigurationException e) {
+// // expected
+// }
+//
+// }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#getSchema().
+ * TBD getSchemas() IS NOT SUPPORTED
+ */
+/* public void test_getSchema() {
+ assertNull(dbf.getSchema());
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ dbf.setSchema(schema);
+ assertNotNull(dbf.getSchema());
+ } catch (SAXException sax) {
+ fail("Unexpected exception " + sax.toString());
+ }
+ }
+ */
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#isCoalescing().
+ */
+ public void test_isCoalescing() {
+ dbf.setCoalescing(true);
+ assertTrue(dbf.isCoalescing());
+
+ dbf.setCoalescing(false);
+ assertFalse(dbf.isCoalescing());
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#isExpandEntityReferences().
+ */
+ public void test_isExpandEntityReferences() {
+ dbf.setExpandEntityReferences(true);
+ assertTrue(dbf.isExpandEntityReferences());
+
+ dbf.setExpandEntityReferences(false);
+ assertFalse(dbf.isExpandEntityReferences());
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#isIgnoringComments().
+ */
+ public void test_isIgnoringComments() {
+ dbf.setIgnoringComments(true);
+ assertTrue(dbf.isIgnoringComments());
+
+ dbf.setIgnoringComments(false);
+ assertFalse(dbf.isIgnoringComments());
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#isIgnoringElementContentWhitespace().
+ */
+ public void test_isIgnoringElementContentWhitespace() {
+ dbf.setIgnoringElementContentWhitespace(true);
+ assertTrue(dbf.isIgnoringElementContentWhitespace());
+
+ dbf.setIgnoringElementContentWhitespace(false);
+ assertFalse(dbf.isIgnoringElementContentWhitespace());
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#isNamespaceAware().
+ */
+ public void test_isNamespaceAware() {
+ dbf.setNamespaceAware(true);
+ assertTrue(dbf.isNamespaceAware());
+
+ dbf.setNamespaceAware(false);
+ assertFalse(dbf.isNamespaceAware());
+ }
+
+ public void test_setIsValidating() {
+ dbf.setValidating(true);
+ assertTrue(dbf.isValidating());
+
+ dbf.setValidating(false);
+ assertFalse(dbf.isValidating());
+ }
+
+ public void test_isSetXIncludeAware() {
+ dbf.setXIncludeAware(true);
+ assertTrue(dbf.isXIncludeAware());
+
+ dbf.setXIncludeAware(false);
+ assertFalse(dbf.isXIncludeAware());
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#newInstance().
+ */
+ public void test_newInstance() {
+ String className = null;
+ try {
+ // case 1: Try to obtain a new instance of factory by default.
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ assertNotNull(dbf);
+
+ // case 2: Try to create a new instance of factory using
+ // property DATATYPEFACTORY_PROPERTY
+ className = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
+ System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
+ "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl");
+
+ dbf = DocumentBuilderFactory.newInstance();
+ assertNotNull(dbf);
+ assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
+
+ // case 3: Try to create a new instance of factory using Property
+ String keyValuePair = "javax.xml.parsers.DocumentBuilderFactory"
+ + "=" + "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl";
+ ByteArrayInputStream bis = new ByteArrayInputStream(keyValuePair
+ .getBytes());
+ Properties prop = System.getProperties();
+ prop.load(bis);
+ dbf = DocumentBuilderFactory.newInstance();
+ assertNotNull(dbf);
+ assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
+
+ // case 4: Check FactoryConfiguration error
+ System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "");
+ try {
+ DocumentBuilderFactory.newInstance();
+ } catch (FactoryConfigurationError fce) {
+ // expected
+ }
+
+ } catch (Exception e) {
+ fail("Unexpected exception " + e.toString());
+ } finally {
+ // Set default value of Datatype factory,
+ // because of this test modifies it.
+ if (className == null) {
+ System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
+ } else {
+ System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
+ className);
+ }
+ }
+ }
+
+ public void test_newDocumentBuilder() {
+ // Ordinary case
+ try {
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ assertTrue(db instanceof DocumentBuilder);
+ db.parse(getClass().getResourceAsStream("/simple.xml"));
+ } catch(Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // Exception case
+ dbf.setValidating(true);
+ try {
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ } catch(ParserConfigurationException e) {
+ // Expected, since Android doesn't have a validating parser.
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setAttribute(java.lang.String,
+ * java.lang.Object).
+ */
+// public void test_setAttributeLjava_lang_StringLjava_lang_Object() {
+// String[] attributes = {
+// "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
+// "http://java.sun.com/xml/jaxp/properties/schemaSource" };
+// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
+//
+// try {
+// for (int i = 0; i < attributes.length; i++) {
+// dbf.setAttribute(attributes[i], values[i]);
+// assertEquals(values[i], dbf.getAttribute(attributes[i]));
+// }
+// } catch (IllegalArgumentException e) {
+// fail("Unexpected IllegalArgumentException" + e.getMessage());
+// } catch (Exception e) {
+// fail("Unexpected exception" + e.getMessage());
+// }
+//
+// String[] badAttributes = {"bad1", "bad2", ""};
+// try {
+// for (int i = 0; i < badAttributes.length; i++) {
+// dbf.setAttribute(badAttributes[i], "");
+// fail("IllegalArgumentException expected");
+// }
+// } catch (IllegalArgumentException iae) {
+// // expected
+// }
+//
+// try {
+// for (int i = 0; i < attributes.length; i++) {
+// dbf.setAttribute(null, null);
+// fail("NullPointerException expected");
+// }
+// } catch (NullPointerException e) {
+// // expected
+// }
+// }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setCoalescing(boolean).
+ */
+ public void test_setCoalescingZ() {
+ dbf.setCoalescing(true);
+ assertTrue(dbf.isCoalescing());
+
+ textElements.clear();
+ cdataElements.clear();
+ Exception parseException = null;
+ DocumentBuilder parser = null;
+
+ try {
+ parser = dbf.newDocumentBuilder();
+ ValidationErrorHandler errorHandler = new ValidationErrorHandler();
+ parser.setErrorHandler(errorHandler);
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ parseException = errorHandler.getFirstException();
+
+ goThroughDocument((Node) document, "");
+ assertTrue(textElements
+ .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
+ } catch (Exception ex) {
+ parseException = ex;
+ }
+ parser.setErrorHandler(null);
+
+ if (parseException != null) {
+ fail("Unexpected exception " + parseException.getMessage());
+ }
+
+ dbf.setCoalescing(false);
+ assertFalse(dbf.isCoalescing());
+
+ textElements.clear();
+ cdataElements.clear();
+
+ try {
+ parser = dbf.newDocumentBuilder();
+ ValidationErrorHandler errorHandler = new ValidationErrorHandler();
+ parser.setErrorHandler(errorHandler);
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ parseException = errorHandler.getFirstException();
+
+ goThroughDocument((Node) document, "");
+
+ assertFalse(textElements
+ .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
+
+ } catch (Exception ex) {
+ parseException = ex;
+ }
+ parser.setErrorHandler(null);
+
+ if (parseException != null) {
+ fail("Unexpected exception " + parseException.getMessage());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean).
+ */
+ public void test_setExpandEntityReferencesZ() {
+ dbf.setExpandEntityReferences(true);
+ assertTrue(dbf.isExpandEntityReferences());
+
+ Exception parseException = null;
+ DocumentBuilder parser = null;
+
+ try {
+ parser = dbf.newDocumentBuilder();
+ ValidationErrorHandler errorHandler = new ValidationErrorHandler();
+ parser.setErrorHandler(errorHandler);
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ parseException = errorHandler.getFirstException();
+
+ assertNotNull(document);
+
+ } catch (Exception ex) {
+ parseException = ex;
+ }
+ parser.setErrorHandler(null);
+
+ if (parseException != null) {
+ fail("Unexpected exception " + parseException.getMessage());
+ }
+
+ dbf.setExpandEntityReferences(false);
+ assertFalse(dbf.isExpandEntityReferences());
+ try {
+ parser = dbf.newDocumentBuilder();
+ ValidationErrorHandler errorHandler = new ValidationErrorHandler();
+ parser.setErrorHandler(errorHandler);
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ parseException = errorHandler.getFirstException();
+
+ assertNotNull(document);
+
+ } catch (Exception ex) {
+ parseException = ex;
+ }
+ parser.setErrorHandler(null);
+
+ if (parseException != null) {
+ fail("Unexpected exception " + parseException.getMessage());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setFeature(java.lang.String).
+ */
+ public void test_getSetFeatureLjava_lang_String() {
+ String[] features = { "http://xml.org/sax/features/namespaces",
+ "http://xml.org/sax/features/validation" };
+ try {
+ for (int i = 0; i < features.length; i++) {
+ dbf.setFeature(features[i], true);
+ assertTrue(dbf.getFeature(features[i]));
+ }
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException" + e.getMessage());
+ }
+
+ try {
+ for (int i = 0; i < features.length; i++) {
+ dbf.setFeature(features[i], false);
+ assertFalse(dbf.getFeature(features[i]));
+ }
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException" + e.getMessage());
+ }
+
+ try {
+ for (int i = 0; i < features.length; i++) {
+ dbf.setFeature(null, false);
+ fail("NullPointerException expected");
+ }
+ } catch (NullPointerException e) {
+ // expected
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException" + e.getMessage());
+ }
+
+ String[] badFeatures = { "bad1", "bad2", "" };
+ try {
+ for (int i = 0; i < badFeatures.length; i++) {
+ dbf.setFeature(badFeatures[i], false);
+ fail("ParserConfigurationException expected");
+ }
+ } catch (ParserConfigurationException e) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean).
+ */
+ public void test_setIgnoringCommentsZ() {
+ commentElements.clear();
+
+ dbf.setIgnoringComments(true);
+ assertTrue(dbf.isIgnoringComments());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ goThroughDocument((Node) document, "");
+ assertFalse(commentElements.contains("comment1"));
+ assertFalse(commentElements.contains("comment2"));
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+
+ commentElements.clear();
+
+ dbf.setIgnoringComments(false);
+ assertFalse(dbf.isIgnoringComments());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ goThroughDocument((Node) document, "");
+ assertTrue(commentElements.contains("comment1"));
+ assertTrue(commentElements.contains("comment2"));
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace(boolean).
+ */
+ public void test_setIgnoringElementContentWhitespaceZ() {
+ dbf.setIgnoringElementContentWhitespace(true);
+ assertTrue(dbf.isIgnoringElementContentWhitespace());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ assertNotNull(document);
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+
+ dbf.setIgnoringElementContentWhitespace(false);
+ assertFalse(dbf.isIgnoringElementContentWhitespace());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ assertNotNull(document);
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware(boolean).
+ */
+ public void test_setNamespaceAwareZ() {
+ dbf.setNamespaceAware(true);
+ assertTrue(dbf.isNamespaceAware());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ assertNotNull(document);
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+
+ dbf.setNamespaceAware(false);
+ assertFalse(dbf.isNamespaceAware());
+
+ try {
+ DocumentBuilder parser = dbf.newDocumentBuilder();
+
+ Document document = parser.parse(getClass().getResourceAsStream(
+ "/recipt.xml"));
+
+ assertNotNull(document);
+
+ } catch (IOException e) {
+ fail("Unexpected IOException " + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ fail("Unexpected ParserConfigurationException " + e.getMessage());
+ } catch (SAXException e) {
+ fail("Unexpected SAXException " + e.getMessage());
+ }
+ }
+
+ public void test_getSetAttribute() {
+ // Android SAX implementation doesn't support attributes, so
+ // we can only make sure the expected exception is thrown.
+ try {
+ dbf.setAttribute("foo", new Object());
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+
+ try {
+ dbf.getAttribute("foo");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setSchema(javax.xml.validation.Schema).
+ */
+ /* public void test_setSchemaLjavax_xml_validation_Schema() {
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ dbf.setSchema(schema);
+ assertNotNull(dbf.getSchema());
+ } catch (SAXException sax) {
+ fail("Unexpected exception " + sax.toString());
+ }
+ }
+*/
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setValidating(boolean).
+ */
+// public void test_setValidatingZ() {
+// Exception parseException = null;
+// DocumentBuilder parser = null;
+// Document document = null;
+//
+// ValidationErrorHandler errorHandler = new ValidationErrorHandler();
+//
+// dbf.setValidating(false);
+// assertFalse(dbf.isValidating());
+//
+// // case 1: Validation is not set. Correct xml-file
+// try {
+//
+// parser = dbf.newDocumentBuilder();
+// parser.setErrorHandler(errorHandler);
+//
+// document = parser.parse(getClass().getResourceAsStream(
+// "/recipt.xml"));
+//
+// parseException = errorHandler.getFirstException();
+//
+// assertNotNull(document);
+//
+// document = parser.parse(getClass().getResourceAsStream(
+// "/reciptWrong.xml"));
+//
+// parseException = errorHandler.getFirstException();
+//
+// assertNotNull(document);
+//
+// } catch (Exception ex) {
+// parseException = ex;
+// }
+// parser.setErrorHandler(null);
+//
+// if (parseException != null) {
+// fail("Unexpected exception " + parseException.getMessage());
+// }
+//
+// // case 2: Validation is not set. Wrong xml-file
+// try {
+//
+// parser = dbf.newDocumentBuilder();
+// parser.setErrorHandler(errorHandler);
+//
+// document = parser.parse(getClass().getResourceAsStream(
+// "/reciptWrong.xml"));
+// parseException = errorHandler.getFirstException();
+//
+// assertNotNull(document);
+//
+// } catch (Exception ex) {
+// parseException = ex;
+// }
+// parser.setErrorHandler(null);
+//
+// if (parseException != null) {
+// fail("Unexpected exception " + parseException.getMessage());
+// }
+//
+// // case 3: Validation is set. Correct xml-file
+// dbf.setValidating(true);
+// assertTrue(dbf.isValidating());
+//
+// try {
+//
+// parser = dbf.newDocumentBuilder();
+// parser.setErrorHandler(errorHandler);
+//
+// document = parser.parse(getClass().getResourceAsStream(
+// "/recipt.xml"));
+// parseException = errorHandler.getFirstException();
+//
+// assertNotNull(document);
+//
+// } catch (Exception ex) {
+// parseException = ex;
+// }
+// parser.setErrorHandler(null);
+//
+// if (parseException != null) {
+// fail("Unexpected exception " + parseException.getMessage());
+// }
+//
+// // case 4: Validation is set. Wrong xml-file
+// try {
+//
+// parser = dbf.newDocumentBuilder();
+// parser.setErrorHandler(errorHandler);
+//
+// document = parser.parse(getClass().getResourceAsStream(
+// "/reciptWrong.xml"));
+// parseException = errorHandler.getFirstException();
+//
+// assertNotNull(document);
+//
+// } catch (Exception ex) {
+// parseException = ex;
+// }
+// parser.setErrorHandler(null);
+//
+// if (parseException == null) {
+// fail("Unexpected exception " + parseException.getMessage());
+// } else {
+// assertTrue(parseException
+// .getMessage()
+// .contains(
+// "The content of element type \"collection\" must match \"(description,recipe+)\""));
+// }
+//
+// }
+
+ /**
+ * javax.xml.parsers.DocumentBuilderFactory#setXIncludeAware().
+ */
+// public void test_setXIncludeAware() {
+// dbf.setXIncludeAware(true);
+// assertTrue(dbf.isXIncludeAware());
+//
+// try {
+// DocumentBuilder parser = dbf.newDocumentBuilder();
+//
+// Document document = parser.parse(getClass().getResourceAsStream(
+// "/recipt.xml"));
+//
+// assertNotNull(document);
+//
+// } catch (IOException e) {
+// fail("Unexpected IOException " + e.getMessage());
+// } catch (ParserConfigurationException e) {
+// fail("Unexpected ParserConfigurationException " + e.getMessage());
+// } catch (SAXException e) {
+// fail("Unexpected SAXException " + e.getMessage());
+// }
+//
+// dbf.setXIncludeAware(false);
+// assertFalse(dbf.isXIncludeAware());
+//
+// try {
+// DocumentBuilder parser = dbf.newDocumentBuilder();
+//
+// Document document = parser.parse(getClass().getResourceAsStream(
+// "/recipt.xml"));
+//
+// assertNotNull(document);
+//
+// } catch (IOException e) {
+// fail("Unexpected IOException " + e.getMessage());
+// } catch (ParserConfigurationException e) {
+// fail("Unexpected ParserConfigurationException " + e.getMessage());
+// } catch (SAXException e) {
+// fail("Unexpected SAXException " + e.getMessage());
+// }
+// }
+
+ private void goThroughDocument(Node node, String indent) {
+ String value = node.getNodeValue();
+
+ if (value != null) {
+ value = value.replaceAll(" ", "");
+ value = value.replaceAll("\n", "");
+ }
+
+ switch (node.getNodeType()) {
+ case Node.CDATA_SECTION_NODE:
+ cdataElements.add(value);
+ // System.out.println(indent + "CDATA_SECTION_NODE " + value);
+ break;
+ case Node.COMMENT_NODE:
+ commentElements.add(value);
+ // System.out.println(indent + "COMMENT_NODE " + value);
+ break;
+ case Node.DOCUMENT_FRAGMENT_NODE:
+ // System.out.println(indent + "DOCUMENT_FRAGMENT_NODE " + value);
+ break;
+ case Node.DOCUMENT_NODE:
+ // System.out.println(indent + "DOCUMENT_NODE " + value);
+ break;
+ case Node.DOCUMENT_TYPE_NODE:
+ // System.out.println(indent + "DOCUMENT_TYPE_NODE " + value);
+ break;
+ case Node.ELEMENT_NODE:
+ // System.out.println(indent + "ELEMENT_NODE " + value);
+ break;
+ case Node.ENTITY_NODE:
+ // System.out.println(indent + "ENTITY_NODE " + value);
+ break;
+ case Node.ENTITY_REFERENCE_NODE:
+ // System.out.println(indent + "ENTITY_REFERENCE_NODE " + value);
+ break;
+ case Node.NOTATION_NODE:
+ // System.out.println(indent + "NOTATION_NODE " + value);
+ break;
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ // System.out.println(indent + "PROCESSING_INSTRUCTION_NODE " +
+ // value);
+ break;
+ case Node.TEXT_NODE:
+ textElements.add(value);
+ // System.out.println(indent + "TEXT_NODE " + value);
+ break;
+ default:
+ // System.out.println(indent + "Unknown node " + value);
+ break;
+ }
+ NodeList list = node.getChildNodes();
+ for (int i = 0; i < list.getLength(); i++)
+ goThroughDocument(list.item(i), indent + " ");
+ }
+
+ private class ValidationErrorHandler implements ErrorHandler {
+ private SAXException parseException;
+
+ private int errorCount;
+
+ private int warningCount;
+
+ public ValidationErrorHandler() {
+ parseException = null;
+ errorCount = 0;
+ warningCount = 0;
+ }
+
+ public void error(SAXParseException ex) {
+ errorCount++;
+ if (parseException == null) {
+ parseException = ex;
+ }
+ }
+
+ public void warning(SAXParseException ex) {
+ warningCount++;
+ }
+
+ public void fatalError(SAXParseException ex) {
+ if (parseException == null) {
+ parseException = ex;
+ }
+ }
+
+ public SAXException getFirstException() {
+ return parseException;
+ }
+ }
+
+ private class DocumentBuilderFactoryChild extends DocumentBuilderFactory {
+ public DocumentBuilderFactoryChild() {
+ super();
+ }
+
+ public Object getAttribute(String name) {
+ return null;
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public DocumentBuilder newDocumentBuilder() {
+ return null;
+ }
+
+ public void setAttribute(String name, Object value) {
+ }
+
+ public void setFeature(String name, boolean value) {
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderTest.java
new file mode 100644
index 0000000..66ce621
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/DocumentBuilderTest.java
@@ -0,0 +1,637 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.xml.parsers;
+
+import junit.framework.TestCase;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.EntityReference;
+import org.w3c.dom.Text;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import tests.api.org.xml.sax.support.MethodLogger;
+import tests.api.org.xml.sax.support.MockHandler;
+import tests.api.org.xml.sax.support.MockResolver;
+import tests.support.resource.Support_Resources;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+public class DocumentBuilderTest extends TestCase {
+
+ private class MockDocumentBuilder extends DocumentBuilder {
+
+ public MockDocumentBuilder() {
+ super();
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#getDOMImplementation()
+ */
+ @Override
+ public DOMImplementation getDOMImplementation() {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#isNamespaceAware()
+ */
+ @Override
+ public boolean isNamespaceAware() {
+ // it is a fake
+ return false;
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#isValidating()
+ */
+ @Override
+ public boolean isValidating() {
+ // it is a fake
+ return false;
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#newDocument()
+ */
+ @Override
+ public Document newDocument() {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#parse(org.xml.sax.InputSource)
+ */
+ @Override
+ public Document parse(InputSource is) throws SAXException, IOException {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#setEntityResolver(
+ * org.xml.sax.EntityResolver)
+ */
+ @Override
+ public void setEntityResolver(EntityResolver er) {
+ // it is a fake
+ }
+
+ /*
+ * @see javax.xml.parsers.DocumentBuilder#setErrorHandler(
+ * org.xml.sax.ErrorHandler)
+ */
+ @Override
+ public void setErrorHandler(ErrorHandler eh) {
+ // it is a fake
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+ }
+
+ DocumentBuilderFactory dbf;
+
+ DocumentBuilder db;
+
+ protected void setUp() throws Exception {
+
+ dbf = DocumentBuilderFactory.newInstance();
+
+ dbf.setIgnoringElementContentWhitespace(true);
+
+ db = dbf.newDocumentBuilder();
+ super.setUp();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testDocumentBuilder() {
+ try {
+ new MockDocumentBuilder();
+ } catch (Exception e) {
+ fail("unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#getSchema()
+ * TBD getSchema() is not supported
+ */
+ /* public void test_getSchema() {
+ assertNull(db.getSchema());
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ dbf.setSchema(schema);
+ assertNotNull(dbf.newDocumentBuilder().getSchema());
+ } catch (ParserConfigurationException pce) {
+ fail("Unexpected ParserConfigurationException " + pce.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+*/
+ public void testNewDocument() {
+ Document d;
+
+ try {
+ d = dbf.newDocumentBuilder().newDocument();
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertNotNull(d);
+ assertNull(d.getDoctype());
+ assertNull(d.getDocumentElement());
+ assertNull(d.getNamespaceURI());
+ }
+
+ public void testGetImplementation() {
+ DOMImplementation d;
+
+ try {
+ d = dbf.newDocumentBuilder().getDOMImplementation();
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertNotNull(d);
+ }
+
+ public void testIsNamespaceAware() {
+ try {
+ dbf.setNamespaceAware(true);
+ assertTrue(dbf.newDocumentBuilder().isNamespaceAware());
+ dbf.setNamespaceAware(false);
+ assertFalse(dbf.newDocumentBuilder().isNamespaceAware());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testIsValidating() {
+ try {
+ dbf.setValidating(false);
+ assertFalse(dbf.newDocumentBuilder().isValidating());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testIsXIncludeAware() {
+ try {
+ dbf.setXIncludeAware(false);
+ assertFalse(dbf.newDocumentBuilder().isXIncludeAware());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ /**
+ * Tests that the Base URI for the document is populated with the file URI.
+ */
+ public void testGetBaseURI() throws IOException, SAXException {
+ File f = Support_Resources.resourceToTempFile("/simple.xml");
+ Document d = db.parse(f);
+ assertTrue(d.getDocumentElement().getBaseURI().startsWith("file://"));
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#parse(java.io.File)
+ * Case 1: Try to parse correct xml document.
+ * Case 2: Try to call parse() with null argument.
+ * Case 3: Try to parse a non-existent file.
+ * Case 4: Try to parse incorrect xml file.
+ */
+ public void test_parseLjava_io_File() throws IOException {
+ File f = Support_Resources.resourceToTempFile("/simple.xml");
+
+ // case 1: Trivial use.
+ try {
+ Document d = db.parse(f);
+ assertNotNull(d);
+ // TBD getXmlEncoding() IS NOT SUPPORTED
+ // assertEquals("ISO-8859-1", d.getXmlEncoding());
+ assertEquals(2, d.getChildNodes().getLength());
+ assertEquals("#comment",
+ d.getChildNodes().item(0).getNodeName());
+ assertEquals("breakfast_menu",
+ d.getChildNodes().item(1).getNodeName());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 2: Try to call parse with null argument
+ try {
+ db.parse((File)null);
+ fail("Expected IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException iae) {
+ // expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 3: Try to parse a non-existent file
+ try {
+ db.parse(new File("_"));
+ fail("Expected IOException was not thrown");
+ } catch (IOException ioe) {
+ // expected
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 4: Try to parse incorrect xml file
+ f = Support_Resources.resourceToTempFile("/wrong.xml");
+ try {
+ db.parse(f);
+ fail("Expected SAXException was not thrown");
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream)
+ * Case 1: Try to parse correct xml document.
+ * Case 2: Try to call parse() with null argument.
+ * Case 3: Try to parse a non-existent file.
+ * Case 4: Try to parse incorrect xml file.
+ */
+ public void test_parseLjava_io_InputStream() {
+ InputStream is = getClass().getResourceAsStream("/simple.xml");
+ // case 1: Trivial use.
+ try {
+ Document d = db.parse(is);
+ assertNotNull(d);
+ // TBD getXmlEncoding() IS NOT SUPPORTED
+ // assertEquals("ISO-8859-1", d.getXmlEncoding());
+ assertEquals(2, d.getChildNodes().getLength());
+ assertEquals("#comment",
+ d.getChildNodes().item(0).getNodeName());
+ assertEquals("breakfast_menu",
+ d.getChildNodes().item(1).getNodeName());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 2: Try to call parse with null argument
+ try {
+ db.parse((InputStream)null);
+ fail("Expected IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException iae) {
+ // expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 3: Try to parse a non-existent file
+ try {
+ db.parse(new FileInputStream("_"));
+ fail("Expected IOException was not thrown");
+ } catch (IOException ioe) {
+ // expected
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 4: Try to parse incorrect xml file
+ try {
+ is = getClass().getResourceAsStream("/wrong.xml");
+ db.parse(is);
+ fail("Expected SAXException was not thrown");
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream)
+ * Case 1: Try to parse correct xml document.
+ * Case 2: Try to call parse() with null argument.
+ * Case 3: Try to parse a non-existent file.
+ * Case 4: Try to parse incorrect xml file.
+ */
+ public void testParseInputSource() {
+ InputStream stream = getClass().getResourceAsStream("/simple.xml");
+ InputSource is = new InputSource(stream);
+
+ // case 1: Trivial use.
+ try {
+ Document d = db.parse(is);
+ assertNotNull(d);
+ // TBD getXmlEncoding() IS NOT SUPPORTED
+ // assertEquals("ISO-8859-1", d.getXmlEncoding());
+ assertEquals(2, d.getChildNodes().getLength());
+ assertEquals("#comment",
+ d.getChildNodes().item(0).getNodeName());
+ assertEquals("breakfast_menu",
+ d.getChildNodes().item(1).getNodeName());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 2: Try to call parse with null argument
+ try {
+ db.parse((InputSource)null);
+ fail("Expected IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException iae) {
+ // expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 3: Try to parse a non-existent file
+ try {
+ db.parse(new InputSource(new FileInputStream("_")));
+ fail("Expected IOException was not thrown");
+ } catch (IOException ioe) {
+ // expected
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 4: Try to parse incorrect xml file
+ try {
+ is = new InputSource(getClass().getResourceAsStream("/wrong.xml"));
+ db.parse(is);
+ fail("Expected SAXException was not thrown");
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream,
+ * java.lang.String)
+ * Case 1: Try to parse correct xml document.
+ * Case 2: Try to call parse() with null argument.
+ * Case 3: Try to parse a non-existent file.
+ * Case 4: Try to parse incorrect xml file.
+ */
+ public void test_parseLjava_io_InputStreamLjava_lang_String() {
+ InputStream is = getClass().getResourceAsStream("/systemid.xml");
+ // case 1: Trivial use.
+ try {
+ Document d = db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID);
+ assertNotNull(d);
+// TBD getXmlEncoding() is not supported
+// assertEquals("UTF-8", d.getXmlEncoding());
+ assertEquals(4, d.getChildNodes().getLength());
+ assertEquals("collection",
+ d.getChildNodes().item(0).getNodeName());
+ assertEquals("#comment",
+ d.getChildNodes().item(1).getNodeName());
+ assertEquals("collection",
+ d.getChildNodes().item(2).getNodeName());
+ assertEquals("#comment",
+ d.getChildNodes().item(3).getNodeName());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 2: Try to call parse with null argument
+ try {
+ db.parse((InputStream)null, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("Expected IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException iae) {
+ // expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ // case 3: Try to parse a non-existent file
+// Doesn't make sense this way...
+// try {
+// db.parse(is, "/");
+// fail("Expected IOException was not thrown");
+// } catch (IOException ioe) {
+// // expected
+// } catch (SAXException sax) {
+// fail("Unexpected SAXException " + sax.toString());
+// }
+
+ // case 4: Try to parse incorrect xml file
+ try {
+ is = getClass().getResourceAsStream("/wrong.xml");
+ db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("Expected SAXException was not thrown");
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ // expected
+ }
+ }
+
+ /**
+ * javax.xml.parsers.DocumentBuilder#parse(java.lang.String)
+ * Case 1: Try to parse correct xml document.
+ * Case 2: Try to call parse() with null argument.
+ * Case 3: Try to parse a non-existent uri.
+ * Case 4: Try to parse incorrect xml file.
+ */
+ public void test_parseLjava_lang_String() throws Exception {
+ // case 1: Trivial use.
+ URL resource = getClass().getResource("/simple.xml");
+ Document d = db.parse(resource.toString());
+ assertNotNull(d);
+// TBD getXmlEncoding() is not supported
+// assertEquals("ISO-8859-1", d.getXmlEncoding());
+ assertEquals(2, d.getChildNodes().getLength());
+ assertEquals("#comment",
+ d.getChildNodes().item(0).getNodeName());
+ assertEquals("breakfast_menu",
+ d.getChildNodes().item(1).getNodeName());
+
+ // case 2: Try to call parse with null argument
+ try {
+ db.parse((String)null);
+ fail("Expected IllegalArgumentException was not thrown");
+ } catch (IllegalArgumentException iae) {
+ // expected
+ }
+
+ // case 3: Try to parse a non-existent uri
+ try {
+ db.parse("_");
+ fail("Expected IOException was not thrown");
+ } catch (IOException ioe) {
+ // expected
+ }
+
+ // case 4: Try to parse incorrect xml file
+ try {
+ resource = getClass().getResource("/wrong.xml");
+ db.parse(resource.toString());
+ fail("Expected SAXException was not thrown");
+ } catch (SAXException sax) {
+ // expected
+ }
+ }
+
+ public void testReset() {
+ // Make sure EntityResolver gets reset
+ InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
+ InputStream entity = new ByteArrayInputStream("bar".getBytes());
+
+ MockResolver resolver = new MockResolver();
+ resolver.addEntity("foo", "foo", new InputSource(entity));
+
+ Document d;
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setEntityResolver(resolver);
+ db.reset();
+ d = db.parse(source);
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ Element root = (Element)d.getElementsByTagName("a").item(0);
+ assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName());
+
+ // Make sure ErrorHandler gets reset
+ source = new ByteArrayInputStream("</a>".getBytes());
+
+ MethodLogger logger = new MethodLogger();
+ ErrorHandler handler = new MockHandler(logger);
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setErrorHandler(handler);
+ db.reset();
+ d = db.parse(source);
+ } catch (SAXParseException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(0, logger.size());
+ }
+
+ public void testSetErrorHandler() {
+ // Ordinary case
+ InputStream source = new ByteArrayInputStream("</a>".getBytes());
+
+ MethodLogger logger = new MethodLogger();
+ ErrorHandler handler = new MockHandler(logger);
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setErrorHandler(handler);
+ db.parse(source);
+ } catch (SAXParseException e) {
+ // Expected, ErrorHandler does not mask exception
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("error", logger.getMethod());
+ assertTrue(logger.getArgs()[0] instanceof SAXParseException);
+
+ // null case
+ source = new ByteArrayInputStream("</a>".getBytes());
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setErrorHandler(null);
+ db.parse(source);
+ } catch (SAXParseException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testSetEntityResolver() {
+ // Ordinary case
+ InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
+ InputStream entity = new ByteArrayInputStream("bar".getBytes());
+
+ MockResolver resolver = new MockResolver();
+ resolver.addEntity("foo", "foo", new InputSource(entity));
+
+ Document d;
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setEntityResolver(resolver);
+ d = db.parse(source);
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ Element root = (Element)d.getElementsByTagName("a").item(0);
+ assertEquals("bar", ((Text)root.getFirstChild()).getData());
+
+ // null case
+ source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
+
+ try {
+ db = dbf.newDocumentBuilder();
+ db.setEntityResolver(null);
+ d = db.parse(source);
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ root = (Element)d.getElementsByTagName("a").item(0);
+ assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/FactoryConfigurationErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/FactoryConfigurationErrorTest.java
new file mode 100644
index 0000000..cdef4e2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/FactoryConfigurationErrorTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.xml.parsers;
+
+import javax.xml.parsers.FactoryConfigurationError;
+
+import junit.framework.TestCase;
+
+public class FactoryConfigurationErrorTest extends TestCase {
+
+ public void test_Constructor() {
+ FactoryConfigurationError fce = new FactoryConfigurationError();
+ assertNull(fce.getMessage());
+ assertNull(fce.getLocalizedMessage());
+ assertNull(fce.getCause());
+ }
+
+ public void test_ConstructorLjava_lang_Exception() {
+ Exception e = new Exception();
+ // case 1: Try to create FactoryConfigurationError
+ // which is based on Exception without parameters.
+ FactoryConfigurationError fce = new FactoryConfigurationError(e);
+ assertNotNull(fce.getMessage());
+ assertNotNull(fce.getLocalizedMessage());
+ assertEquals(e.getCause(), fce.getCause());
+
+ // case 2: Try to create FactoryConfigurationError
+ // which is based on Exception with String parameter.
+ e = new Exception("test message");
+ fce = new FactoryConfigurationError(e);
+ assertEquals(e.toString(), fce.getMessage());
+ assertEquals(e.toString(), fce.getLocalizedMessage());
+ assertEquals(e.getCause(), fce.getCause());
+ }
+
+ public void test_ConstructorLjava_lang_ExceptionLjava_lang_String() {
+ Exception e = new Exception();
+ // case 1: Try to create FactoryConfigurationError
+ // which is based on Exception without parameters.
+ FactoryConfigurationError fce = new FactoryConfigurationError(e, "msg");
+ assertNotNull(fce.getMessage());
+ assertNotNull(fce.getLocalizedMessage());
+ assertEquals(e.getCause(), fce.getCause());
+
+ // case 2: Try to create FactoryConfigurationError
+ // which is based on Exception with String parameter.
+ e = new Exception("test message");
+ fce = new FactoryConfigurationError(e, "msg");
+ assertEquals("msg", fce.getMessage());
+ assertEquals("msg", fce.getLocalizedMessage());
+ assertEquals(e.getCause(), fce.getCause());
+ }
+
+ public void test_ConstructorLjava_lang_String() {
+ FactoryConfigurationError fce = new FactoryConfigurationError("Oops!");
+ assertEquals("Oops!", fce.getMessage());
+ assertEquals("Oops!", fce.getLocalizedMessage());
+ assertNull(fce.getCause());
+ }
+
+ public void test_getException() {
+ FactoryConfigurationError fce = new FactoryConfigurationError();
+ assertNull(fce.getException());
+ fce = new FactoryConfigurationError("test");
+ assertNull(fce.getException());
+ Exception e = new Exception("msg");
+ fce = new FactoryConfigurationError(e);
+ assertEquals(e, fce.getException());
+ NullPointerException npe = new NullPointerException();
+ fce = new FactoryConfigurationError(npe);
+ assertEquals(npe, fce.getException());
+ }
+
+ public void test_getMessage() {
+ assertNull(new FactoryConfigurationError().getMessage());
+ assertEquals("msg1",
+ new FactoryConfigurationError("msg1").getMessage());
+ assertEquals(new Exception("msg2").toString(),
+ new FactoryConfigurationError(
+ new Exception("msg2")).getMessage());
+ assertEquals(new NullPointerException().toString(),
+ new FactoryConfigurationError(
+ new NullPointerException()).getMessage());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/ParserConfigurationExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/ParserConfigurationExceptionTest.java
new file mode 100644
index 0000000..d1feb9f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/ParserConfigurationExceptionTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.xml.parsers;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import junit.framework.TestCase;
+
+public class ParserConfigurationExceptionTest extends TestCase{
+
+ public void test_Constructor() {
+ ParserConfigurationException pce = new ParserConfigurationException();
+ assertNull(pce.getMessage());
+ assertNull(pce.getLocalizedMessage());
+ assertNull(pce.getCause());
+ }
+
+ public void test_ConstructorLjava_lang_String() {
+ ParserConfigurationException pce =
+ new ParserConfigurationException("Oops!");
+ assertEquals("Oops!", pce.getMessage());
+ assertEquals("Oops!", pce.getLocalizedMessage());
+ assertNull(pce.getCause());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserFactoryTest.java
new file mode 100644
index 0000000..614b9d8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserFactoryTest.java
@@ -0,0 +1,415 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.xml.parsers;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Properties;
+import java.util.Vector;
+
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import dalvik.annotation.AndroidOnly;
+import dalvik.annotation.KnownFailure;
+
+public class SAXParserFactoryTest extends TestCase {
+
+ SAXParserFactory spf;
+
+ InputStream is1;
+
+ static HashMap<String, String> ns;
+
+ static Vector<String> el;
+
+ static HashMap<String, String> attr;
+
+ public void setUp() throws Exception {
+ spf = SAXParserFactory.newInstance();
+
+ is1 = getClass().getResourceAsStream("/simple.xml");
+
+ ns = new HashMap<String, String>();
+ attr = new HashMap<String, String>();
+ el = new Vector<String>();
+ }
+
+ public void tearDown() throws Exception {
+ is1.close();
+ super.tearDown();
+ }
+
+ @AndroidOnly("Android SAX implementation is non-validating")
+ public void test_Constructor() {
+ MySAXParserFactory mpf = new MySAXParserFactory();
+ assertTrue(mpf instanceof SAXParserFactory);
+ assertFalse(mpf.isValidating());
+ }
+
+ /**
+ * javax.xml.parsers.SAXParserFactory#getSchema().
+ * TBD getSchema() IS NOT SUPPORTED
+ */
+ /* public void test_getSchema() {
+ assertNull(spf.getSchema());
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ spf.setSchema(schema);
+ assertNotNull(spf.getSchema());
+ } catch (SAXException sax) {
+ fail("Unexpected exception " + sax.toString());
+ }
+ }
+ */
+
+ public void test_setIsNamespaceAware() {
+ spf.setNamespaceAware(true);
+ assertTrue(spf.isNamespaceAware());
+ spf.setNamespaceAware(false);
+ assertFalse(spf.isNamespaceAware());
+ spf.setNamespaceAware(true);
+ assertTrue(spf.isNamespaceAware());
+ }
+
+ public void test_setIsValidating() {
+ spf.setValidating(true);
+ assertTrue(spf.isValidating());
+ spf.setValidating(false);
+ assertFalse(spf.isValidating());
+ spf.setValidating(true);
+ assertTrue(spf.isValidating());
+ }
+
+ public void test_setIsXIncludeAware() {
+ spf.setXIncludeAware(true);
+ assertTrue(spf.isXIncludeAware());
+ spf.setXIncludeAware(false);
+ assertFalse(spf.isXIncludeAware());
+ }
+
+ @KnownFailure("Dalvik doesn't honor system properties when choosing a SAX implementation")
+ public void test_newInstance() {
+ try {
+ SAXParserFactory dtf = SAXParserFactory.newInstance();
+ assertNotNull("New Instance of DatatypeFactory is null", dtf);
+
+ System.setProperty("javax.xml.parsers.SAXParserFactory",
+ "org.apache.harmony.xml.parsers.SAXParserFactoryImpl");
+
+ SAXParserFactory spf1 = SAXParserFactory.newInstance();
+ assertTrue(spf1 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl);
+
+ String key = "javax.xml.parsers.SAXParserFactory = org.apache.harmony.xml.parsers.SAXParserFactoryImpl";
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(key.getBytes());
+ Properties prop = System.getProperties();
+ prop.load(bis);
+ SAXParserFactory spf2 = SAXParserFactory.newInstance();
+ assertTrue(spf2 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl);
+
+ System.setProperty("javax.xml.parsers.SAXParserFactory", "");
+ try {
+ SAXParserFactory.newInstance();
+ fail("Expected FactoryConfigurationError was not thrown");
+ } catch (FactoryConfigurationError e) {
+ // expected
+ }
+ } catch (IOException ioe) {
+ fail("Unexpected exception " + ioe.toString());
+ }
+ }
+
+ public void test_newSAXParser() {
+ // Ordinary case
+ try {
+ SAXParser sp = spf.newSAXParser();
+ assertTrue(sp instanceof SAXParser);
+ sp.parse(is1, new MyHandler());
+ } catch(Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // Exception case
+ spf.setValidating(true);
+ try {
+ SAXParser sp = spf.newSAXParser();
+ } catch(ParserConfigurationException e) {
+ // Expected, since Android doesn't have a validating parser.
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void test_setFeatureLjava_lang_StringZ() {
+ // We can't verify ParserConfigurationException and
+ // SAXNotSupportedException since these are never
+ // thrown by Android.
+
+ String[] features = {
+ "http://xml.org/sax/features/namespaces",
+ "http://xml.org/sax/features/validation" };
+ for (int i = 0; i < features.length; i++) {
+ try {
+ spf.setFeature(features[i], true);
+ assertTrue(spf.getFeature(features[i]));
+ spf.setFeature(features[i], false);
+ assertFalse(spf.getFeature(features[i]));
+ } catch (ParserConfigurationException pce) {
+ fail("ParserConfigurationException is thrown");
+ } catch (SAXNotRecognizedException snre) {
+ fail("SAXNotRecognizedException is thrown");
+ } catch (SAXNotSupportedException snse) {
+ fail("SAXNotSupportedException is thrown");
+ }
+ }
+
+ try {
+ spf.setFeature("", true);
+ fail("SAXNotRecognizedException is not thrown");
+ } catch (ParserConfigurationException pce) {
+ fail("ParserConfigurationException is thrown");
+ } catch (SAXNotRecognizedException snre) {
+ //expected
+ } catch (SAXNotSupportedException snse) {
+ fail("SAXNotSupportedException is thrown");
+ } catch (NullPointerException npe) {
+ fail("NullPointerException is thrown");
+ }
+
+ try {
+ spf.setFeature("http://xml.org/sax/features/unknown-feature", true);
+ } catch (ParserConfigurationException pce) {
+ fail("ParserConfigurationException is thrown");
+ } catch (SAXNotRecognizedException snre) {
+ fail("SAXNotRecognizedException is thrown");
+ } catch (SAXNotSupportedException snse) {
+ // Acceptable, although this doesn't happen an Android.
+ } catch (NullPointerException npe) {
+ fail("NullPointerException is thrown");
+ }
+
+ try {
+ spf.setFeature(null, true);
+ fail("NullPointerException is not thrown");
+ } catch (ParserConfigurationException pce) {
+ fail("ParserConfigurationException is thrown");
+ } catch (SAXNotRecognizedException snre) {
+ fail("SAXNotRecognizedException is thrown");
+ } catch (SAXNotSupportedException snse) {
+ fail("SAXNotSupportedException is thrown");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+ }
+
+ public void test_setNamespaceAwareZ() throws Exception {
+ MyHandler mh = new MyHandler();
+
+ spf.setNamespaceAware(true);
+ InputStream is = getClass().getResourceAsStream("/simple_ns.xml");
+ spf.newSAXParser().parse(is, mh);
+ is.close();
+
+ spf.setNamespaceAware(false);
+ is = getClass().getResourceAsStream("/simple_ns.xml");
+ spf.newSAXParser().parse(is, mh);
+ is.close();
+ }
+
+ /* public void test_setSchemaLjavax_xml_validation_Schema() {
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ spf.setSchema(schema);
+ assertNotNull(spf.getSchema());
+ } catch (SAXException sax) {
+ fail("Unexpected exception " + sax.toString());
+ }
+ }
+ */
+
+// public void test_setValidatingZ() {
+// MyHandler mh = new MyHandler();
+// InputStream is2 = getClass().getResourceAsStream("/recipe.xml");
+// try {
+// spf.setValidating(true);
+// assertTrue(spf.isValidating());
+// spf.newSAXParser().parse(is2, mh);
+// } catch (org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch (javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch (IOException ioe) {
+// fail("IOException was thrown during parsing");
+// } finally {
+// try {
+// is2.close();
+// } catch(Exception ioee) {}
+// }
+// InputStream is3 = getClass().getResourceAsStream("/recipe1.xml");
+// try {
+// assertTrue(spf.isValidating());
+// spf.newSAXParser().parse(is3, mh);
+// } catch (org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch (javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch (IOException ioe) {
+// fail("IOEXception was thrown during parsing: " + ioe.getMessage());
+// } finally {
+// try {
+// is3.close();
+// } catch(Exception ioee) {}
+// }
+// is2 = getClass().getResourceAsStream("/recipe.xml");
+// try {
+// spf.setValidating(false);
+// assertFalse(spf.isValidating());
+// spf.newSAXParser().parse(is2, mh);
+// } catch (org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch (javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch (IOException ioe) {
+// fail("IOException was thrown during parsing");
+// } finally {
+// try {
+// is2.close();
+// } catch(Exception ioee) {}
+// }
+// is3 = getClass().getResourceAsStream("/recipe1.xml");
+// try {
+// assertFalse(spf.isValidating());
+// spf.newSAXParser().parse(is3, mh);
+// } catch (org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch (javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch (IOException ioe) {
+// fail("IOEXception was thrown during parsing: " + ioe.getMessage());
+// } finally {
+// try {
+// is3.close();
+// } catch(Exception ioee) {}
+// }
+// }
+
+// public void test_setXIncludeAwareZ() {
+// spf.setXIncludeAware(true);
+// MyHandler mh = new MyHandler();
+// InputStream is = getClass().getResourceAsStream("/simple_ns.xml");
+// try {
+// spf.newSAXParser().parse(is, mh);
+// } catch(javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch(org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch(IOException ioe) {
+// fail("IOException was thrown during parsing");
+// } finally {
+// try {
+// is.close();
+// } catch(Exception ioee) {}
+// }
+// spf.setXIncludeAware(false);
+// is = getClass().getResourceAsStream("/simple_ns.xml");
+// try {
+// is = getClass().getResourceAsStream("/simple_ns.xml");
+// spf.newSAXParser().parse(is, mh);
+// } catch(javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch(org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch(IOException ioe) {
+// fail("IOException was thrown during parsing");
+// } finally {
+// try {
+// is.close();
+// } catch(Exception ioee) {}
+// }
+// is = getClass().getResourceAsStream("/simple_ns.xml");
+// try {
+// spf.setXIncludeAware(true);
+// spf.newSAXParser().parse(is, mh);
+// } catch(javax.xml.parsers.ParserConfigurationException pce) {
+// fail("ParserConfigurationException was thrown during parsing");
+// } catch(org.xml.sax.SAXException se) {
+// fail("SAXException was thrown during parsing");
+// } catch(IOException ioe) {
+// fail("IOException was thrown during parsing");
+// } finally {
+// try {
+// is.close();
+// } catch(Exception ioee) {}
+// }
+// }
+
+ static class MyHandler extends DefaultHandler {
+
+ public void startElement(String uri, String localName, String qName,
+ Attributes atts) {
+
+ el.add(qName);
+ if (!uri.equals(""))
+ ns.put(qName, uri);
+ for (int i = 0; i < atts.getLength(); i++) {
+ attr.put(atts.getQName(i), atts.getValue(i));
+ }
+
+ }
+ }
+
+ class MySAXParserFactory extends SAXParserFactory {
+
+ public MySAXParserFactory() {
+ super();
+ }
+
+ public SAXParser newSAXParser() {
+ return null;
+ }
+
+ public void setFeature(String name, boolean value) throws
+ ParserConfigurationException, SAXNotRecognizedException,
+ SAXNotSupportedException {
+
+ }
+
+ public boolean getFeature(String name) throws
+ ParserConfigurationException, SAXNotRecognizedException,
+ SAXNotSupportedException {
+ return true;
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTest.java
new file mode 100644
index 0000000..a51998c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTest.java
@@ -0,0 +1,899 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package tests.api.javax.xml.parsers;
+
+import dalvik.annotation.KnownFailure;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.Vector;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+import junit.framework.TestCase;
+import org.xml.sax.HandlerBase;
+import org.xml.sax.InputSource;
+import org.xml.sax.Parser;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.ext.LexicalHandler;
+import org.xml.sax.helpers.DefaultHandler;
+import tests.api.javax.xml.parsers.SAXParserTestSupport.MyDefaultHandler;
+import tests.api.javax.xml.parsers.SAXParserTestSupport.MyHandler;
+import tests.api.org.xml.sax.support.BrokenInputStream;
+import tests.api.org.xml.sax.support.MethodLogger;
+import tests.api.org.xml.sax.support.MockHandler;
+import tests.support.resource.Support_Resources;
+
+@SuppressWarnings("deprecation")
+public class SAXParserTest extends TestCase {
+
+ private class MockSAXParser extends SAXParser {
+ public MockSAXParser() {
+ super();
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#getParser()
+ */
+ @Override
+ public Parser getParser() throws SAXException {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#getProperty(java.lang.String)
+ */
+ @Override
+ public Object getProperty(String name) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#getXMLReader()
+ */
+ @Override
+ public XMLReader getXMLReader() throws SAXException {
+ // it is a fake
+ return null;
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#isNamespaceAware()
+ */
+ @Override
+ public boolean isNamespaceAware() {
+ // it is a fake
+ return false;
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#isValidating()
+ */
+ @Override
+ public boolean isValidating() {
+ // it is a fake
+ return false;
+ }
+
+ /*
+ * @see javax.xml.parsers.SAXParser#setProperty(java.lang.String,
+ * java.lang.Object)
+ */
+ @Override
+ public void setProperty(String name, Object value) throws
+ SAXNotRecognizedException, SAXNotSupportedException {
+ // it is a fake
+ }
+ }
+
+ private static final String LEXICAL_HANDLER_PROPERTY
+ = "http://xml.org/sax/properties/lexical-handler";
+
+ SAXParserFactory spf;
+
+ SAXParser parser;
+
+ static HashMap<String, String> ns;
+
+ static Vector<String> el;
+
+ static HashMap<String, String> attr;
+
+ SAXParserTestSupport sp = new SAXParserTestSupport();
+
+ File [] list_wf;
+ File [] list_nwf;
+ File [] list_out_dh;
+ File [] list_out_hb;
+
+ boolean validating = false;
+
+ private InputStream getResource(String name) {
+ return this.getClass().getResourceAsStream(name);
+ }
+
+ public void initFiles() throws Exception {
+ // we differntiate between a validating and a non validating parser
+ try {
+ SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
+ validating = parser.isValidating();
+ } catch (Exception e) {
+ fail("could not obtain a SAXParser");
+ }
+
+ String tmpPath = System.getProperty("java.io.tmpdir");
+
+ // nwf = not well formed, wf = well formed
+ list_wf = new File[] {new File(tmpPath + "/" +
+ SAXParserTestSupport.XML_WF + "staff.xml")};
+ list_nwf = new File[] {new File(tmpPath + "/" +
+ SAXParserTestSupport.XML_NWF + "staff.xml")};
+ list_out_dh = new File[] {new File(tmpPath + "/" +
+ SAXParserTestSupport.XML_WF_OUT_DH + "staff.out")};
+ list_out_hb = new File[] {new File(tmpPath + "/" +
+ SAXParserTestSupport.XML_WF_OUT_HB + "staff.out")};
+
+ list_wf[0].deleteOnExit();
+ list_nwf[0].deleteOnExit();
+ list_out_hb[0].deleteOnExit();
+ list_out_dh[0].deleteOnExit();
+
+
+ Support_Resources.copyLocalFileto(list_wf[0],
+ getResource(SAXParserTestSupport.XML_WF + "staff.xml"));
+ Support_Resources.copyLocalFileto(new File(
+ tmpPath + "/" + SAXParserTestSupport.XML_WF + "staff.dtd"),
+ getResource(SAXParserTestSupport.XML_WF + "staff.dtd"));
+
+ Support_Resources.copyLocalFileto(list_nwf[0],
+ getResource(SAXParserTestSupport.XML_NWF + "staff.xml"));
+ Support_Resources.copyLocalFileto(new File(
+ tmpPath + "/" + SAXParserTestSupport.XML_NWF + "staff.dtd"),
+ getResource(SAXParserTestSupport.XML_NWF + "staff.dtd"));
+
+ Support_Resources.copyLocalFileto(list_out_dh[0],
+ getResource(SAXParserTestSupport.XML_WF_OUT_DH + "staff.out"));
+ Support_Resources.copyLocalFileto(list_out_hb[0],
+ getResource(SAXParserTestSupport.XML_WF_OUT_HB + "staff.out"));
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ spf = SAXParserFactory.newInstance();
+ parser = spf.newSAXParser();
+ assertNotNull(parser);
+
+ ns = new HashMap<String, String>();
+ attr = new HashMap<String, String>();
+ el = new Vector<String>();
+ initFiles();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ }
+
+// public static void main(String[] args) throws Exception {
+// SAXParserTest st = new SAXParserTest();
+// st.setUp();
+// st.generateDataFromReferenceImpl();
+//
+// }
+//
+// private void generateDataFromReferenceImpl() {
+// try {
+// for(int i = 0; i < list_wf.length; i++) {
+// MyDefaultHandler dh = new MyDefaultHandler();
+// InputStream is = new FileInputStream(list_wf[i]);
+// parser.parse(is, dh, ParsingSupport.XML_SYSTEM_ID);
+// HashMap refHm = dh.createData();
+//
+// StringBuilder sb = new StringBuilder();
+// for (int j = 0; j < ParsingSupport.KEYS.length; j++) {
+// String key = ParsingSupport.KEYS[j];
+// sb.append(refHm.get(key)).append(
+// ParsingSupport.SEPARATOR_DATA);
+// }
+// FileWriter fw = new FileWriter("/tmp/build_dh"+i+".out");
+// fw.append(sb.toString());
+// fw.close();
+// }
+//
+// for(int i = 0; i < list_nwf.length; i++) {
+// MyHandler hb = new MyHandler();
+// InputStream is = new FileInputStream(list_wf[i]);
+// parser.parse(is, hb, ParsingSupport.XML_SYSTEM_ID);
+// HashMap refHm = hb.createData();
+//
+// StringBuilder sb = new StringBuilder();
+// for (int j = 0; j < ParsingSupport.KEYS.length; j++) {
+// String key = ParsingSupport.KEYS[j];
+// sb.append(refHm.get(key)).append(
+// ParsingSupport.SEPARATOR_DATA);
+// }
+// FileWriter fw = new FileWriter("/tmp/build_hb"+i+".out");
+// fw.append(sb.toString());
+// fw.close();
+// }
+//
+//
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+
+ public void testSAXParser() {
+ try {
+ new MockSAXParser();
+ } catch (Exception e) {
+ fail("unexpected exception " + e.toString());
+ }
+ }
+
+ /**
+ * javax.xml.parser.SAXParser#getSchema().
+ * TODO getSchema() IS NOT SUPPORTED
+ */
+ /* public void test_getSchema() {
+ assertNull(parser.getSchema());
+ SchemaFactory sf =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ try {
+ Schema schema = sf.newSchema();
+ spf.setSchema(schema);
+ assertNotNull(spf.newSAXParser().getSchema());
+ } catch (ParserConfigurationException pce) {
+ fail("Unexpected ParserConfigurationException " + pce.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+ */
+
+ public void testIsNamespaceAware() {
+ try {
+ spf.setNamespaceAware(true);
+ assertTrue(spf.newSAXParser().isNamespaceAware());
+ spf.setNamespaceAware(false);
+ assertFalse(spf.newSAXParser().isNamespaceAware());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testIsValidating() {
+ try {
+ spf.setValidating(false);
+ assertFalse(spf.newSAXParser().isValidating());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testIsXIncludeAware() {
+ try {
+ spf.setXIncludeAware(false);
+ assertFalse(spf.newSAXParser().isXIncludeAware());
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void test_parseLjava_io_FileLorg_xml_sax_helpers_DefaultHandler() throws Exception {
+
+ for(int i = 0; i < list_wf.length; i++) {
+ HashMap<String, String> hm =
+ new SAXParserTestSupport().readFile(list_out_dh[i].getPath());
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse(list_wf[i], dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse(list_nwf[i], dh);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ }
+ }
+
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse((File) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ parser.parse(list_wf[0], (DefaultHandler) null);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ }
+ }
+
+ public void testParseFileHandlerBase() {
+ for(int i = 0; i < list_wf.length; i++) {
+ try {
+ HashMap<String, String> hm = sp.readFile(
+ list_out_hb[i].getPath());
+ MyHandler dh = new MyHandler();
+ parser.parse(list_wf[i], dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm,
+ dh.createData()));
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse(list_nwf[i], dh);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ }
+ }
+
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse((File) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ try {
+ parser.parse(list_wf[0], (HandlerBase) null);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch(IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+
+ public void test_parseLorg_xml_sax_InputSourceLorg_xml_sax_helpers_DefaultHandler()
+ throws Exception {
+ for(int i = 0; i < list_wf.length; i++) {
+ HashMap<String, String> hm = new SAXParserTestSupport().readFile(
+ list_out_dh[i].getPath());
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputSource is = new InputSource(new FileInputStream(list_wf[i]));
+ parser.parse(is, dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for (File file : list_nwf) {
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputSource is = new InputSource(new FileInputStream(file));
+ parser.parse(is, dh);
+ fail("SAXException is not thrown");
+ } catch (SAXException expected) {
+ }
+ }
+
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse((InputSource) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ InputSource is = new InputSource(new FileInputStream(list_wf[0]));
+ parser.parse(is, (DefaultHandler) null);
+
+ InputStream in = null;
+ try {
+ in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
+ is = new InputSource(in);
+ parser.parse(is, (DefaultHandler) null);
+ fail("IOException expected");
+ } catch(IOException expected) {
+ } finally {
+ in.close();
+ }
+ }
+
+ public void testParseInputSourceHandlerBase() throws Exception {
+ for(int i = 0; i < list_wf.length; i++) {
+ HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
+ MyHandler dh = new MyHandler();
+ InputSource is = new InputSource(new FileInputStream(list_wf[i]));
+ parser.parse(is, dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for (File file : list_nwf) {
+ try {
+ MyHandler dh = new MyHandler();
+ InputSource is = new InputSource(new FileInputStream(file));
+ parser.parse(is, dh);
+ fail("SAXException is not thrown");
+ } catch (SAXException expected) {
+ }
+ }
+
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse((InputSource) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(IllegalArgumentException expected) {
+ }
+
+ InputSource is = new InputSource(new FileInputStream(list_wf[0]));
+ parser.parse(is, (HandlerBase) null);
+
+ // Reader case
+ is = new InputSource(new InputStreamReader(new FileInputStream(list_wf[0])));
+ parser.parse(is, (HandlerBase) null);
+
+ // SystemID case
+ is = new InputSource(list_wf[0].toURI().toString());
+ parser.parse(is, (HandlerBase) null);
+
+ // Inject IOException
+ InputStream in = null;
+ try {
+ in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
+ parser.parse(in, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("IOException expected");
+ } catch(IOException expected) {
+ } finally {
+ in.close();
+ }
+ }
+
+ public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandler() throws Exception {
+
+ for(int i = 0; i < list_wf.length; i++) {
+
+ HashMap<String, String> hm = new SAXParserTestSupport().readFile(
+ list_out_dh[i].getPath());
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputStream is = new FileInputStream(list_wf[i]);
+ parser.parse(is, dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputStream is = new FileInputStream(list_nwf[i]);
+ parser.parse(is, dh);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ }
+ }
+
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse((InputStream) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ InputStream is = new FileInputStream(list_wf[0]);
+ parser.parse(is, (DefaultHandler) null);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ }
+ }
+
+ @KnownFailure("We supply optional qnames, but this test doesn't expect them")
+ public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandlerLjava_lang_String() {
+ for(int i = 0; i < list_wf.length; i++) {
+ try {
+ HashMap<String, String> hm = sp.readFile(
+ list_out_hb[i].getPath());
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputStream is = new FileInputStream(list_wf[i]);
+ parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+ assertEquals(hm, dh.createData());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ InputStream is = new FileInputStream(list_nwf[i]);
+ parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ }
+ }
+
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse((InputStream) null, dh,
+ SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ try {
+ InputStream is = new FileInputStream(list_wf[0]);
+ parser.parse(is, (DefaultHandler) null,
+ SAXParserTestSupport.XML_SYSTEM_ID);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch(IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+//
+// for(int i = 0; i < list_wf.length; i++) {
+//
+// HashMap<String, String> hm = new SAXParserTestSupport().readFile(
+// list_out_dh[i].getPath());
+// MyDefaultHandler dh = new MyDefaultHandler();
+// InputStream is = new FileInputStream(list_wf[i]);
+// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+// assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+// }
+//
+// for(int i = 0; i < list_nwf.length; i++) {
+// try {
+// MyDefaultHandler dh = new MyDefaultHandler();
+// InputStream is = new FileInputStream(list_nwf[i]);
+// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+// fail("SAXException is not thrown");
+// } catch(org.xml.sax.SAXException se) {
+// //expected
+// }
+// }
+//
+// try {
+// MyDefaultHandler dh = new MyDefaultHandler();
+// parser.parse((InputStream) null, dh,
+// SAXParserTestSupport.XML_SYSTEM_ID);
+// fail("java.lang.IllegalArgumentException is not thrown");
+// } catch(java.lang.IllegalArgumentException iae) {
+// //expected
+// }
+//
+// try {
+// InputStream is = new FileInputStream(list_wf[0]);
+// parser.parse(is, (DefaultHandler) null,
+// SAXParserTestSupport.XML_SYSTEM_ID);
+// } catch(java.lang.IllegalArgumentException iae) {
+// fail("java.lang.IllegalArgumentException is thrown");
+// }
+//
+// // TODO commented out since our parser is nonvalidating and thus never
+// // tries to load staff.dtd in "/" ... and therefore never can fail with
+// // an IOException
+// /*try {
+// MyDefaultHandler dh = new MyDefaultHandler();
+// InputStream is = new FileInputStream(list_wf[0]);
+// parser.parse(is, dh, "/");
+// fail("Expected IOException was not thrown");
+// } catch(IOException ioe) {
+// // expected
+// }*/
+ }
+
+ public void testParseInputStreamHandlerBase() throws Exception {
+ for(int i = 0; i < list_wf.length; i++) {
+ HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
+ MyHandler dh = new MyHandler();
+ InputStream is = new FileInputStream(list_wf[i]);
+ parser.parse(is, dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for (File file : list_nwf) {
+ try {
+ MyHandler dh = new MyHandler();
+ InputStream is = new FileInputStream(file);
+ parser.parse(is, dh);
+ fail("SAXException is not thrown");
+ } catch (SAXException expected) {
+ }
+ }
+
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse((InputStream) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch (IllegalArgumentException expected) {
+ }
+
+ InputStream is = new FileInputStream(list_wf[0]);
+ parser.parse(is, (HandlerBase) null);
+
+ // Inject IOException
+ try {
+ is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
+ parser.parse(is, (HandlerBase) null);
+ fail("IOException expected");
+ } catch(IOException e) {
+ // Expected
+ } finally {
+ is.close();
+ }
+ }
+
+ public void testParseInputStreamHandlerBaseString() throws Exception {
+ for(int i = 0; i < list_wf.length; i++) {
+ HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
+ MyHandler dh = new MyHandler();
+ InputStream is = new FileInputStream(list_wf[i]);
+ parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for (File file : list_nwf) {
+ try {
+ MyHandler dh = new MyHandler();
+ InputStream is = new FileInputStream(file);
+ parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("SAXException is not thrown");
+ } catch (SAXException expected) {
+ }
+ }
+
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse(null, dh, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(IllegalArgumentException expected) {
+ }
+
+ InputStream is = new FileInputStream(list_wf[0]);
+ parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
+
+ // Inject IOException
+ try {
+ is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
+ parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
+ fail("IOException expected");
+ } catch(IOException expected) {
+ } finally {
+ is.close();
+ }
+ }
+
+ public void test_parseLjava_lang_StringLorg_xml_sax_helpers_DefaultHandler() throws Exception {
+
+ for(int i = 0; i < list_wf.length; i++) {
+
+ HashMap<String, String> hm = new SAXParserTestSupport().readFile(
+ list_out_dh[i].getPath());
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse(list_wf[i].toURI().toString(), dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse(list_nwf[i].toURI().toString(), dh);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ }
+ }
+
+ try {
+ MyDefaultHandler dh = new MyDefaultHandler();
+ parser.parse((String) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ parser.parse(list_wf[0].toURI().toString(), (DefaultHandler) null);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ }
+ }
+
+ public void testParseStringHandlerBase() {
+ for(int i = 0; i < list_wf.length; i++) {
+ try {
+ HashMap<String, String> hm = sp.readFile(
+ list_out_hb[i].getPath());
+ MyHandler dh = new MyHandler();
+ parser.parse(list_wf[i].toURI().toString(), dh);
+ assertTrue(SAXParserTestSupport.equalsMaps(hm,
+ dh.createData()));
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch (SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+
+ for(int i = 0; i < list_nwf.length; i++) {
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse(list_nwf[i].toURI().toString(), dh);
+ fail("SAXException is not thrown");
+ } catch(org.xml.sax.SAXException se) {
+ //expected
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ }
+ }
+
+ try {
+ MyHandler dh = new MyHandler();
+ parser.parse((String) null, dh);
+ fail("java.lang.IllegalArgumentException is not thrown");
+ } catch(java.lang.IllegalArgumentException iae) {
+ //expected
+ } catch (IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+
+ try {
+ parser.parse(list_wf[0].toURI().toString(), (HandlerBase) null);
+ } catch(java.lang.IllegalArgumentException iae) {
+ fail("java.lang.IllegalArgumentException is thrown");
+ } catch (FileNotFoundException fne) {
+ fail("Unexpected FileNotFoundException " + fne.toString());
+ } catch(IOException ioe) {
+ fail("Unexpected IOException " + ioe.toString());
+ } catch(SAXException sax) {
+ fail("Unexpected SAXException " + sax.toString());
+ }
+ }
+
+ public void testReset() {
+ try {
+ spf = SAXParserFactory.newInstance();
+ parser = spf.newSAXParser();
+
+ parser.setProperty(LEXICAL_HANDLER_PROPERTY, new MockHandler(new MethodLogger()));
+ parser.reset();
+ assertEquals(null, parser.getProperty(LEXICAL_HANDLER_PROPERTY));
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetParser() {
+ spf = SAXParserFactory.newInstance();
+ try {
+ Parser parser = spf.newSAXParser().getParser();
+ assertNotNull(parser);
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetReader() {
+ spf = SAXParserFactory.newInstance();
+ try {
+ XMLReader reader = spf.newSAXParser().getXMLReader();
+ assertNotNull(reader);
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testSetGetProperty() {
+ // Ordinary case
+ String validName = "http://xml.org/sax/properties/lexical-handler";
+ LexicalHandler validValue = new MockHandler(new MethodLogger());
+
+ try {
+ SAXParser parser = spf.newSAXParser();
+ parser.setProperty(validName, validValue);
+ assertEquals(validValue, parser.getProperty(validName));
+
+ parser.setProperty(validName, null);
+ assertEquals(null, parser.getProperty(validName));
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // Unsupported property
+ try {
+ SAXParser parser = spf.newSAXParser();
+ parser.setProperty("foo", "bar");
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ try {
+ SAXParser parser = spf.newSAXParser();
+ parser.getProperty("foo");
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // No name case
+ try {
+ SAXParser parser = spf.newSAXParser();
+ parser.setProperty(null, "bar");
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ try {
+ SAXParser parser = spf.newSAXParser();
+ parser.getProperty(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ } catch (Exception e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTestSupport.java b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTestSupport.java
new file mode 100644
index 0000000..2b7e1da
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/javax/xml/parsers/SAXParserTestSupport.java
@@ -0,0 +1,492 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.javax.xml.parsers;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.HandlerBase;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * Support for SAXParserTest. Shares the element keys used in the golden files.
+ * Compares the result of the parser with golden data.
+ * Contains the handler classes used to track the output of the parser.
+ */
+class SAXParserTestSupport {
+
+ public static final char SEPARATOR_ELEMENT = '^';
+ public static final char SEPARATOR_STRING = '$';
+ public static final char SEPARATOR_DATA = '#';
+
+ public static final String XML_WF = "/wf/";
+ public static final String XML_NWF = "/nwf/";
+
+ public static final String XML_WF_OUT_DH = "/out_dh/";
+ public static final String XML_WF_OUT_HB = "/out_hb/";
+
+ public static final String XML_SYSTEM_ID = "." + "/systemid/";
+
+ public static final String KEY_IS_START_DOC = "isEndDocument";
+ public static final String KEY_IS_END_DOC = "isStartDocument";
+ public static final String KEY_TEXT = "text";
+ public static final String KEY_ERROR = "error";
+ public static final String KEY_FATAL_ERROR = "fatalError";
+ public static final String KEY_WARNING = "warning";
+ public static final String KEY_END_ELEMENT = "endElement";
+ public static final String KEY_END_PREFIX_MAPPING = "endPrefixMapping";
+ public static final String KEY_IGNORABLE_WHITE_SPACE =
+ "ignorableWhitespace";
+ public static final String KEY_NOTATION_DECL = "notationDecl";
+ public static final String KEY_PROCESSING_INSTRUCTION =
+ "processingInstruction";
+ public static final String KEY_RESOLVE_ENTITY = "resolveEntity";
+ public static final String KEY_DOCUMENT_LOCATORS = "documentLocators";
+ public static final String KEY_SKIPPED_ENTITY = "skippedEntity";
+ public static final String KEY_START_ELEMENT = "startElement";
+ public static final String KEY_START_PREFIX_MAPPING = "startPrefixMapping";
+ public static final String KEY_UNPARSED_ENTITY_DECL = "unparsedEntityDecl";
+
+ static String [] KEYS = {KEY_IS_START_DOC, KEY_IS_END_DOC, KEY_TEXT,
+ KEY_ERROR, KEY_FATAL_ERROR, KEY_WARNING, KEY_END_ELEMENT,
+ KEY_END_PREFIX_MAPPING, KEY_PROCESSING_INSTRUCTION,
+ KEY_SKIPPED_ENTITY, KEY_START_ELEMENT,
+ KEY_START_PREFIX_MAPPING};
+
+ static {
+ String tmp = System.getProperty("java.io.tmpdir", ".");
+
+ new File(tmp).mkdirs();
+ new File(tmp, XML_WF).mkdirs();
+ new File(tmp, XML_NWF).mkdirs();
+ new File(tmp, XML_WF_OUT_DH).mkdirs();
+ new File(tmp, XML_WF_OUT_HB).mkdirs();
+ }
+
+ /**
+ * Initialize the SAXParserTest reference by filling in the data from the
+ * file passed to the method. This will be the reference to compare
+ * against with the output of the parser.
+ */
+ public HashMap<String, String> readFile(String fileName) {
+ HashMap<String, String> storage = new HashMap<String, String>();
+ try {
+
+ InputStream is = new FileInputStream(fileName);
+
+ int c = is.read();
+
+ StringBuffer str = new StringBuffer();
+ int i = 0;
+ while(c != -1) {
+ if((char)c == SEPARATOR_DATA) {
+ // if(str.length() > 0) {
+ if(i < KEYS.length) {
+ storage.put(KEYS[i], str.toString());
+ // System.out.println(str.toString());
+ str.setLength(0);
+ i++;
+ }
+ // }
+ } else {
+ str.append((char)c);
+ }
+ try {
+ c = is.read();
+ } catch (Exception e) {
+ c = -1;
+ }
+ }
+ try {
+ is.close();
+ } catch (IOException e) {
+ }
+
+ } catch(IOException ioe) {
+ System.out.println("IOException during processing the file: "
+ + fileName);
+ }
+ return storage;
+ }
+
+ /**
+ * Compares the content of two HashMaps. One map should be the reference
+ * containing the correct string for each xml document element and the other
+ * should contain the elements filled with output from the parser.
+ *
+ * @param original the reference
+ * @param result the result of the parser
+ * @return true if they're equal.
+ */
+ public static boolean equalsMaps(HashMap<String, String> original,
+ HashMap<String, String> result) {
+
+ if(original == null && result == null) {
+ return true;
+ } else {
+ if(original.size() != result.size()) return false;
+
+ for(int i = 0; i < KEYS.length; i++) {
+ if(!original.get(KEYS[i]).equals(result.get(KEYS[i]))) {
+ System.out.println("for "+KEYS[i]+": original:" +
+ original.get(KEYS[i]));
+ System.out.println();
+ System.out.println(" result:" + result.get(KEYS[i]));
+ System.out.println();
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
+ static class MyDefaultHandler extends DefaultHandler {
+
+ public StringBuffer data_isEndDocument = new StringBuffer();
+ public StringBuffer data_isStartDocument = new StringBuffer();
+ public StringBuffer data_text = new StringBuffer();
+ public StringBuffer data_error = new StringBuffer();
+ public StringBuffer data_fatalError = new StringBuffer();
+ public StringBuffer data_warning = new StringBuffer();
+ public StringBuffer data_endElement = new StringBuffer();
+ public StringBuffer data_endPrefixMapping = new StringBuffer();
+ public StringBuffer data_processingInstruction = new StringBuffer();
+ public StringBuffer data_skippedEntity = new StringBuffer();
+ public StringBuffer data_startElement = new StringBuffer();
+ public StringBuffer data_startPrefixMapping = new StringBuffer();
+
+ public HashMap<String, String> createData() {
+ HashMap<String, String> hm = new HashMap<String, String>();
+ hm.put(KEY_IS_END_DOC, data_isEndDocument.toString());
+ hm.put(KEY_IS_START_DOC, data_isStartDocument.toString());
+ hm.put(KEY_TEXT, data_text.toString());
+ hm.put(KEY_ERROR, data_error.toString());
+ hm.put(KEY_FATAL_ERROR, data_fatalError.toString());
+ hm.put(KEY_WARNING, data_warning.toString());
+ hm.put(KEY_END_ELEMENT, data_endElement.toString());
+ hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString());
+
+ hm.put(KEY_PROCESSING_INSTRUCTION,
+ data_processingInstruction.toString());
+ hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString());
+ hm.put(KEY_START_ELEMENT, data_startElement.toString());
+ hm.put(KEY_START_PREFIX_MAPPING,
+ data_startPrefixMapping.toString());
+ return hm;
+ }
+
+ public void printMap() {
+ System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA +
+ data_isEndDocument.toString() + SEPARATOR_DATA +
+ data_text.toString() + SEPARATOR_DATA +
+ data_error.toString()+ SEPARATOR_DATA +
+ data_fatalError.toString()+ SEPARATOR_DATA +
+ data_warning.toString()+ SEPARATOR_DATA +
+ data_endElement.toString() + SEPARATOR_DATA+
+ data_endPrefixMapping.toString()+ SEPARATOR_DATA +
+ data_processingInstruction.toString() + SEPARATOR_DATA +
+ data_skippedEntity.toString() + SEPARATOR_DATA +
+ data_startElement.toString() + SEPARATOR_DATA +
+ data_startPrefixMapping.toString()+ SEPARATOR_DATA);
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length) {
+ String str = new String(ch, start, length);
+ data_text.append(str);
+ // different sax parsers are allowed to handle chunking differently,
+ // therefore we cannot rely on identical chunks being delivered.
+ //data_text.append(ParsingSupport.SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void endDocument() {
+ data_isEndDocument.append(true);
+ data_isEndDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName) {
+ StringBuffer sb = new StringBuffer();
+ sb.append(uri);
+ sb.append(SEPARATOR_STRING);
+ sb.append(localName);
+ sb.append(SEPARATOR_STRING);
+ sb.append(qName);
+ data_endElement.append(sb);
+ data_endElement.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void endPrefixMapping(String prefix) {
+ data_endPrefixMapping.append(prefix);
+ data_endPrefixMapping.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void error(SAXParseException e) {
+ data_error.append(e);
+ data_error.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void fatalError(SAXParseException e) {
+ data_fatalError.append(e);
+ data_fatalError.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void ignorableWhitespace(char[] ch, int start, int length) {
+ /* String s = new String(ch, start, length);
+ ignorableWhitespace.append(s);
+ ignorableWhitespace.append(ParsingSupport.SEPARATOR_ELEMENT);*/
+ }
+
+ @Override
+ public void notationDecl(String name, String publicId,
+ String systemId) {
+ /* data_notationDecl.append(name + ParsingSupport.SEPARATOR_STRING +
+ publicId + ParsingSupport.SEPARATOR_STRING +
+ systemId + ParsingSupport.SEPARATOR_STRING);
+ data_notationDecl.append(ParsingSupport.SEPARATOR_ELEMENT);*/
+ }
+
+ @Override
+ public void processingInstruction(String target, String data) {
+ data_processingInstruction.append(target + SEPARATOR_STRING + data);
+ data_processingInstruction.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public InputSource resolveEntity(String publicId, String systemId) {
+ // data_resolveEntity.append(publicId +
+ // ParsingSupport.SEPARATOR_STRING + systemId);
+ // data_resolveEntity.append(ParsingSupport.SEPARATOR_ELEMENT);
+ return null;
+ }
+
+ @Override
+ public void setDocumentLocator(Locator locator) {
+ // data_documentLocators.append(locator);
+ // data_documentLocators.append(ParsingSupport.SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void skippedEntity(String name) {
+ data_skippedEntity.append(name);
+ data_skippedEntity.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void startDocument() {
+ data_isStartDocument.append(true);
+ data_isStartDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) {
+ data_startElement.append(uri);
+ data_startElement.append(SEPARATOR_STRING);
+ data_startElement.append(localName);
+ data_startElement.append(SEPARATOR_STRING);
+ data_startElement.append(qName);
+
+ for(int i = 0; i < attributes.getLength(); i ++)
+ data_startElement.append(
+ SEPARATOR_STRING +attributes.getQName(i) +
+ SEPARATOR_STRING + attributes.getValue(i));
+
+ data_isStartDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void startPrefixMapping(String prefix, String uri) {
+ data_startPrefixMapping.append(prefix + SEPARATOR_STRING + uri);
+ }
+
+ @Override
+ public void unparsedEntityDecl(String name, String publicId,
+ String systemId, String notationName) {
+ // data_unparsedEntityDecl.append(name
+ // + ParsingSupport.SEPARATOR_STRING + publicId
+ // + ParsingSupport.SEPARATOR_STRING
+ // + systemId + ParsingSupport.SEPARATOR_STRING + notationName);
+ }
+
+ @Override
+ public void warning(SAXParseException e) {
+ data_warning.append(e);
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ static class MyHandler extends HandlerBase {
+
+ public StringBuffer data_isEndDocument = new StringBuffer();
+ public StringBuffer data_isStartDocument = new StringBuffer();
+ public StringBuffer data_text = new StringBuffer();
+ public StringBuffer data_error = new StringBuffer();
+ public StringBuffer data_fatalError = new StringBuffer();
+ public StringBuffer data_warning = new StringBuffer();
+ public StringBuffer data_endElement = new StringBuffer();
+ public StringBuffer data_endPrefixMapping = new StringBuffer();
+ public StringBuffer data_processingInstruction = new StringBuffer();
+ public StringBuffer data_skippedEntity = new StringBuffer();
+ public StringBuffer data_startElement = new StringBuffer();
+ public StringBuffer data_startPrefixMapping = new StringBuffer();
+
+ public void printMap() {
+ System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA +
+ data_isEndDocument.toString() + SEPARATOR_DATA +
+ data_text.toString() + SEPARATOR_DATA +
+ data_error.toString()+ SEPARATOR_DATA +
+ data_fatalError.toString()+ SEPARATOR_DATA +
+ data_warning.toString()+ SEPARATOR_DATA +
+ data_endElement.toString() + SEPARATOR_DATA+
+ data_endPrefixMapping.toString()+ SEPARATOR_DATA +
+ data_processingInstruction.toString() + SEPARATOR_DATA +
+ data_skippedEntity.toString() + SEPARATOR_DATA +
+ data_startElement.toString() + SEPARATOR_DATA +
+ data_startPrefixMapping.toString()+ SEPARATOR_DATA);
+ }
+
+ public HashMap<String, String> createData() {
+ HashMap<String, String> hm = new HashMap<String, String>();
+ hm.put(KEY_IS_END_DOC, data_isEndDocument.toString());
+ hm.put(KEY_IS_START_DOC, data_isStartDocument.toString());
+ hm.put(KEY_TEXT, data_text.toString());
+ hm.put(KEY_ERROR, data_error.toString());
+ hm.put(KEY_FATAL_ERROR, data_fatalError.toString());
+ hm.put(KEY_WARNING, data_warning.toString());
+ hm.put(KEY_END_ELEMENT, data_endElement.toString());
+ hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString());
+ hm.put(KEY_PROCESSING_INSTRUCTION,
+ data_processingInstruction.toString());
+ hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString());
+ hm.put(KEY_START_ELEMENT, data_startElement.toString());
+ hm.put(KEY_START_PREFIX_MAPPING,
+ data_startPrefixMapping.toString());
+ return hm;
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length) {
+ String str = new String(ch, start, length);
+ data_text.append(str);
+ // different sax parsers are allowed to handle chunking differently,
+ // therefore we cannot rely on identical chunks being delivered.
+ //data_text.append(ParsingSupport.SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void endDocument() {
+ data_isEndDocument.append(true);
+ data_isEndDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ public void endElement(String uri, String localName, String qName) {
+ StringBuffer sb = new StringBuffer();
+ sb.append(uri);
+ sb.append(SEPARATOR_STRING);
+ sb.append(localName);
+ sb.append(SEPARATOR_STRING);
+ sb.append(qName);
+ data_endElement.append(sb);
+ data_endElement.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void error(SAXParseException e) {
+ data_error.append(e);
+ data_error.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void fatalError(SAXParseException e) {
+ data_fatalError.append(e);
+ data_fatalError.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void ignorableWhitespace(char[] ch, int start, int length) {
+
+ }
+
+ @Override
+ public void notationDecl(String name, String publicId,
+ String systemId) {
+
+ }
+
+ @Override
+ public void processingInstruction(String target, String data) {
+ data_processingInstruction.append(target + SEPARATOR_STRING + data);
+ data_processingInstruction.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public InputSource resolveEntity(String publicId, String systemId) {
+ return null;
+ }
+
+ @Override
+ public void setDocumentLocator(Locator locator) {
+
+ }
+
+ @Override
+ public void startDocument() {
+ data_isStartDocument.append(true);
+ data_isStartDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) {
+ data_startElement.append(uri);
+ data_startElement.append(SEPARATOR_STRING);
+ data_startElement.append(localName);
+ data_startElement.append(SEPARATOR_STRING);
+ data_startElement.append(qName);
+
+ for(int i = 0; i < attributes.getLength(); i ++)
+ data_startElement.append(SEPARATOR_STRING
+ + attributes.getQName(i) +
+ SEPARATOR_STRING + attributes.getValue(i));
+
+ data_isStartDocument.append(SEPARATOR_ELEMENT);
+ }
+
+ @Override
+ public void unparsedEntityDecl(String name, String publicId,
+ String systemId, String notationName) {
+
+ }
+
+ @Override
+ public void warning(SAXParseException e) {
+ data_warning.append(e);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/apache/harmony/kernel/dalvik/ThreadsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/apache/harmony/kernel/dalvik/ThreadsTest.java
new file mode 100644
index 0000000..19c6229
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/apache/harmony/kernel/dalvik/ThreadsTest.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.apache.harmony.kernel.dalvik;
+
+import java.lang.reflect.Field;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.TimeUnit;
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import sun.misc.Unsafe;
+
+/**
+ * Tests for the <code>park()</code> functionality of {@link Unsafe}.
+ */
+public class ThreadsTest extends TestCase {
+ private static Unsafe UNSAFE = null;
+ static {
+ /*
+ * Set up {@link #UNSAFE}. This subverts the access check to
+ * get the unique Unsafe instance. We can do this because
+ * there's no security manager installed when running the
+ * test.
+ */
+ try {
+ Field field = Unsafe.class.getDeclaredField("THE_ONE");
+ field.setAccessible(true);
+
+ UNSAFE = (Unsafe) field.get(null);
+ } catch (NoSuchFieldException ex) {
+ throw new RuntimeException(ex);
+ } catch (IllegalAccessException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ /** Test the case where the park times out. */
+ public void test_parkFor_1() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(2);
+ Parker parker = new Parker(barrier, false, 500);
+ Thread parkerThread = new Thread(parker);
+ Thread waiterThread =
+ new Thread(new WaitAndUnpark(barrier, 1000, parkerThread));
+
+ parkerThread.start();
+ waiterThread.start();
+ parker.assertDurationIsInRange(500);
+ waiterThread.join();
+ parkerThread.join();
+ }
+
+ /** Test the case where the unpark happens before the timeout. */
+ public void test_parkFor_2() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(2);
+ Parker parker = new Parker(barrier, false, 1000);
+ Thread parkerThread = new Thread(parker);
+ Thread waiterThread =
+ new Thread(new WaitAndUnpark(barrier, 300, parkerThread));
+
+ parkerThread.start();
+ waiterThread.start();
+ parker.assertDurationIsInRange(300);
+ waiterThread.join();
+ parkerThread.join();
+ }
+
+ /** Test the case where the thread is preemptively unparked. */
+ public void test_parkFor_3() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(1);
+ Parker parker = new Parker(barrier, false, 1000);
+ Thread parkerThread = new Thread(parker);
+
+ UNSAFE.unpark(parkerThread);
+ parkerThread.start();
+ parker.assertDurationIsInRange(0);
+ parkerThread.join();
+ }
+
+ /** Test the case where the park times out. */
+ public void test_parkUntil_1() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(2);
+ Parker parker = new Parker(barrier, true, 500);
+ Thread parkerThread = new Thread(parker);
+ Thread waiterThread =
+ new Thread(new WaitAndUnpark(barrier, 1000, parkerThread));
+
+ parkerThread.start();
+ waiterThread.start();
+ parker.assertDurationIsInRange(500);
+ waiterThread.join();
+ parkerThread.join();
+ }
+
+ /** Test the case where the unpark happens before the timeout. */
+ public void test_parkUntil_2() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(2);
+ Parker parker = new Parker(barrier, true, 1000);
+ Thread parkerThread = new Thread(parker);
+ Thread waiterThread =
+ new Thread(new WaitAndUnpark(barrier, 300, parkerThread));
+
+ parkerThread.start();
+ waiterThread.start();
+ parker.assertDurationIsInRange(300);
+ waiterThread.join();
+ parkerThread.join();
+ }
+
+ /** Test the case where the thread is preemptively unparked. */
+ public void test_parkUntil_3() throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(1);
+ Parker parker = new Parker(barrier, true, 1000);
+ Thread parkerThread = new Thread(parker);
+
+ UNSAFE.unpark(parkerThread);
+ parkerThread.start();
+ parker.assertDurationIsInRange(0);
+ parkerThread.join();
+ }
+
+ // TODO: Add more tests.
+
+ /**
+ * Helper <code>Runnable</code> for tests, which parks for or until
+ * the indicated value, noting the duration of time actually parked.
+ */
+ private static class Parker implements Runnable {
+
+ private final CyclicBarrier barrier;
+
+ /** whether {@link #amount} is milliseconds to wait in an
+ * absolute fashion (<code>true</code>) or nanoseconds to wait
+ * in a relative fashion (<code>false</code>) */
+ private final boolean absolute;
+
+ /** amount to wait (see above) */
+ private final long amount;
+
+ /** whether the run has completed */
+ private boolean completed;
+
+ /** recorded start time */
+ private long startMillis;
+
+ /** recorded end time */
+ private long endMillis;
+
+ /**
+ * Construct an instance.
+ *
+ * @param absolute whether to use an absolute time or not; in
+ * either case, this constructor takes a duration to park for
+ * @param parkMillis the number of milliseconds to be parked
+ */
+ public Parker(CyclicBarrier barrier, boolean absolute, long parkMillis) {
+ this.barrier = barrier;
+ this.absolute = absolute;
+
+ // Multiply by 1000000 because parkFor() takes nanoseconds.
+ this.amount = absolute ? parkMillis : parkMillis * 1000000;
+ }
+
+ public void run() {
+ try {
+ barrier.await(60, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ boolean absolute = this.absolute;
+ long amount = this.amount;
+ long startNanos = System.nanoTime();
+ long start = System.currentTimeMillis();
+
+ if (absolute) {
+ UNSAFE.park(true, start + amount);
+ } else {
+ UNSAFE.park(false, amount);
+ }
+
+ long endNanos = System.nanoTime();
+
+ synchronized (this) {
+ startMillis = startNanos / 1000000;
+ endMillis = endNanos / 1000000;
+ completed = true;
+ notifyAll();
+ }
+ }
+
+ /**
+ * Wait for the test to complete and return the duration.
+ *
+ * @param maxWaitMillis the maximum amount of time to
+ * wait for the test to complete
+ * @return the duration in milliseconds
+ */
+ public long getDurationMillis(long maxWaitMillis) {
+ synchronized (this) {
+ if (! completed) {
+ try {
+ wait(maxWaitMillis);
+ } catch (InterruptedException ignored) {
+ }
+ if (! completed) {
+ Assert.fail("parker hung for more than " + maxWaitMillis + " ms");
+ }
+ }
+
+ return endMillis - startMillis;
+ }
+ }
+
+ /**
+ * Asserts that the actual duration is within 10% of the
+ * given expected time.
+ *
+ * @param expectedMillis the expected duration, in milliseconds
+ */
+ public void assertDurationIsInRange(long expectedMillis) {
+ /*
+ * Allow a bit more slop for the maximum on "expected
+ * instantaneous" results.
+ */
+ long minimum = (long) ((double) expectedMillis * 0.90);
+ long maximum =
+ Math.max((long) ((double) expectedMillis * 1.10), 10);
+ long waitMillis = Math.max(expectedMillis * 10, 10);
+ long duration = getDurationMillis(waitMillis);
+
+ if (duration < minimum) {
+ Assert.fail("expected duration: " + expectedMillis +
+ " minimum duration: " + minimum +
+ " actual duration too short: " + duration);
+ } else if (duration > maximum) {
+ Assert.fail("expected duration: " + expectedMillis +
+ " maximum duration: " + maximum +
+ " actual duration too long: " + duration);
+ }
+ }
+ }
+
+ /**
+ * Helper <code>Runnable</code> for tests, which waits for the
+ * specified amount of time and then unparks an indicated thread.
+ */
+ private static class WaitAndUnpark implements Runnable {
+ private final CyclicBarrier barrier;
+ private final long waitMillis;
+ private final Thread thread;
+
+ public WaitAndUnpark(CyclicBarrier barrier, long waitMillis, Thread thread) {
+ this.barrier = barrier;
+ this.waitMillis = waitMillis;
+ this.thread = thread;
+ }
+
+ public void run() {
+ try {
+ barrier.await(60, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ try {
+ Thread.sleep(waitMillis);
+ } catch (InterruptedException ex) {
+ throw new RuntimeException("shouldn't happen", ex);
+ }
+
+ UNSAFE.unpark(thread);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/HandlerBaseTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/HandlerBaseTest.java
new file mode 100644
index 0000000..8dfe38b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/HandlerBaseTest.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.AttributeList;
+import org.xml.sax.HandlerBase;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.AttributeListImpl;
+import org.xml.sax.helpers.LocatorImpl;
+
+@SuppressWarnings("deprecation")
+public class HandlerBaseTest extends TestCase {
+
+ /*
+ * Note: most of the tests have to check for an empty implementation of the
+ * respective methods and, as a result, are somewhat trivial.
+ */
+
+ private HandlerBase h = new HandlerBase();
+
+ public void testResolveEntity() {
+ try {
+ h.resolveEntity("publicID", "systemID");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testNotationDecl() {
+ h.notationDecl("name", "publicID", "systemID");
+ }
+
+ public void testUnparsedEntityDecl() {
+ h.unparsedEntityDecl("name", "publicID", "systemID", "notationName");
+ }
+
+ public void testSetDocumentLocator() {
+ h.setDocumentLocator(new LocatorImpl());
+ }
+
+ public void testStartDocument() {
+ try {
+ h.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testEndDocument() {
+ try {
+ h.endDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testStartElement() {
+ try {
+ h.startElement("name", new AttributeListImpl());
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testEndElement() {
+ try {
+ h.endElement("name");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testCharacters() {
+ try {
+ h.characters("The quick brown fox".toCharArray(), 4, 11);
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testIgnorableWhitespace() {
+ try {
+ h.ignorableWhitespace(" ".toCharArray(), 4, 11);
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testProcessingInstruction() {
+ try {
+ h.processingInstruction("target", "data");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testWarning() {
+ try {
+ h.warning(new SAXParseException("Foo", new LocatorImpl()));
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testError() {
+ try {
+ h.error(new SAXParseException("Foo", new LocatorImpl()));
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testFatalError() {
+ // Ordinary case
+ try {
+ h.fatalError(new SAXParseException("Foo", new LocatorImpl()));
+ fail("SAXException expected");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // No exception
+ try {
+ h.fatalError(null);
+ fail("NullPointerException expected");
+ } catch (SAXException e) {
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/InputSourceTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/InputSourceTest.java
new file mode 100644
index 0000000..f9040f0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/InputSourceTest.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.InputSource;
+
+public class InputSourceTest extends TestCase {
+
+ public void testInputSource() {
+ InputSource i = new InputSource();
+
+ assertNull(i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+ }
+
+ public void testInputSourceString() {
+ InputSource i = new InputSource("Foo");
+
+ assertNull(i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertEquals("Foo", i.getSystemId());
+ }
+
+ public void testInputSourceInputStream() {
+ ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
+
+ // Ordinary case
+ InputSource i = new InputSource(bais);
+
+ assertEquals(bais, i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+
+ // No input stream
+ i = new InputSource((InputStream)null);
+
+ assertNull(i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+ }
+
+ public void testInputSourceReader() {
+ StringReader sr = new StringReader("Hello, world.");
+
+ // Ordinary case
+ InputSource i = new InputSource(sr);
+
+ assertNull(i.getByteStream());
+ assertEquals(sr, i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+
+ // No reader
+ i = new InputSource((Reader)null);
+
+ assertNull(i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+ }
+
+ public void testSetPublicIdGetPublicId() {
+ InputSource i = new InputSource();
+
+ i.setPublicId("Foo");
+ assertEquals("Foo", i.getPublicId());
+
+ i.setPublicId(null);
+ assertNull(i.getPublicId());
+ }
+
+ public void testSetSystemIdGetSystemId() {
+ InputSource i = new InputSource();
+
+ i.setSystemId("Foo");
+ assertEquals("Foo", i.getSystemId());
+
+ i.setSystemId(null);
+ assertNull(i.getSystemId());
+ }
+
+ public void testSetByteStreamGetByteStream() {
+ ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
+
+ InputSource i = new InputSource();
+
+ // Ordinary case
+ i.setByteStream(bais);
+
+ assertEquals(bais, i.getByteStream());
+
+ // No input stream
+ i.setByteStream(null);
+
+ assertNull(i.getByteStream());
+ }
+
+ public void testSetEncodingGetEncoding() {
+ InputSource i = new InputSource();
+
+ // Ordinary case
+ i.setEncoding("Klingon");
+
+ assertEquals("Klingon", i.getEncoding());
+
+ // No encoding
+ i.setEncoding(null);
+
+ assertNull(i.getEncoding());
+ }
+
+ public void testSetCharacterStreamGetCharacterStream() {
+ StringReader sr = new StringReader("Hello, world.");
+
+ InputSource i = new InputSource();
+
+ // Ordinary case
+ i.setCharacterStream(sr);
+
+ assertNull(i.getByteStream());
+ assertEquals(sr, i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+
+ // No reader
+ i.setCharacterStream(null);
+
+ assertNull(i.getByteStream());
+ assertNull(i.getCharacterStream());
+ assertNull(i.getEncoding());
+ assertNull(i.getPublicId());
+ assertNull(i.getSystemId());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXExceptionTest.java
new file mode 100644
index 0000000..11d00e7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXExceptionTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+public class SAXExceptionTest extends TestCase {
+
+ public static final String ERR = "Houston, we have a problem";
+
+ public void testSAXParseException() {
+ SAXException e = new SAXException();
+
+ assertNull(e.getMessage());
+ assertNull(e.getException());
+ }
+
+ public void testSAXException_String_Exception() {
+ Exception c = new Exception();
+
+ // Ordinary case
+ SAXException e = new SAXException(ERR, c);
+
+ assertEquals(ERR, e.getMessage());
+ assertEquals(c, e.getException());
+
+ // No message
+ e = new SAXException(null, c);
+
+ assertNull(e.getMessage());
+ assertEquals(c, e.getException());
+
+ // No cause
+ e = new SAXParseException(ERR, null);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+ }
+
+ public void testSAXException_String() {
+ // Ordinary case
+ SAXException e = new SAXException(ERR);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ // No message
+ e = new SAXException((String)null);
+
+ assertNull(e.getMessage());
+ assertNull(e.getException());
+ }
+
+ public void testSAXException_Exception() {
+ Exception c = new Exception();
+
+ // Ordinary case
+ SAXException e = new SAXException(c);
+
+ assertNull(e.getMessage());
+ assertEquals(c, e.getException());
+
+ // No cause
+ e = new SAXException((Exception)null);
+
+ assertNull(e.getMessage());
+ assertNull(e.getException());
+ }
+
+ public void testToString() {
+ // Ordinary case
+ SAXException e = new SAXException(ERR);
+ String s = e.toString();
+
+ assertTrue(s.contains(ERR));
+
+ // No message
+ e = new SAXException();
+ s = e.toString();
+
+ assertFalse(s.contains(ERR));
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotRecognizedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotRecognizedExceptionTest.java
new file mode 100644
index 0000000..3c73b56
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotRecognizedExceptionTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.SAXNotRecognizedException;
+
+public class SAXNotRecognizedExceptionTest extends TestCase {
+
+ public static final String ERR = "Houston, we have a problem";
+
+ public void testSAXNotRecognizedException() {
+ SAXNotRecognizedException e = new SAXNotRecognizedException();
+ assertNull(e.getMessage());
+ }
+
+ public void testSAXNotRecognizedException_String() {
+ SAXNotRecognizedException e = new SAXNotRecognizedException(ERR);
+ assertEquals(ERR, e.getMessage());
+
+ e = new SAXNotRecognizedException(null);
+ assertNull(e.getMessage());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotSupportedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotSupportedExceptionTest.java
new file mode 100644
index 0000000..71ea455
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXNotSupportedExceptionTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.SAXNotSupportedException;
+
+public class SAXNotSupportedExceptionTest extends TestCase {
+
+ public static final String ERR = "Houston, we have a problem";
+
+ public void testSAXNotSupportedException() {
+ SAXNotSupportedException e = new SAXNotSupportedException();
+ assertNull(e.getMessage());
+ }
+
+ public void testSAXNotSupportedException_String() {
+ SAXNotSupportedException e = new SAXNotSupportedException(ERR);
+ assertEquals(ERR, e.getMessage());
+
+ e = new SAXNotSupportedException(null);
+ assertNull(e.getMessage());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXParseExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXParseExceptionTest.java
new file mode 100644
index 0000000..bfc48d4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/SAXParseExceptionTest.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Locator;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.LocatorImpl;
+
+public class SAXParseExceptionTest extends TestCase {
+
+ public static final String ERR = "Houston, we have a problem";
+
+ public static final String SYS = "mySystemID";
+
+ public static final String PUB = "myPublicID";
+
+ public static final int ROW = 1;
+
+ public static final int COL = 2;
+
+ public void testSAXParseException_String_Locator_Exception() {
+ LocatorImpl l = new LocatorImpl();
+ l.setPublicId(PUB);
+ l.setSystemId(SYS);
+ l.setLineNumber(ROW);
+ l.setColumnNumber(COL);
+
+ Exception c = new Exception();
+
+ // Ordinary case
+ SAXParseException e = new SAXParseException(ERR, l, c);
+
+ assertEquals(ERR, e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No message
+ e = new SAXParseException(null, l, c);
+
+ assertNull(e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No locator
+ e = new SAXParseException(ERR, null, c);
+
+ assertEquals(ERR, e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertNull(e.getPublicId());
+ assertNull(e.getSystemId());
+ assertEquals(-1, e.getLineNumber());
+ assertEquals(-1, e.getColumnNumber());
+
+ // No cause
+ e = new SAXParseException(ERR, l, null);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+ }
+
+ public void testSAXParseException_String_Locator() {
+ LocatorImpl l = new LocatorImpl();
+ l.setPublicId(PUB);
+ l.setSystemId(SYS);
+ l.setLineNumber(ROW);
+ l.setColumnNumber(COL);
+
+ // Ordinary case
+ SAXParseException e = new SAXParseException(ERR, l);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No message
+ e = new SAXParseException(null, l);
+
+ assertNull(e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No locator
+ e = new SAXParseException(ERR, null);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertNull(e.getPublicId());
+ assertNull(e.getSystemId());
+ assertEquals(-1, e.getLineNumber());
+ assertEquals(-1, e.getColumnNumber());
+
+ }
+
+ public void testSAXParseException_String_String_String_int_int_Exception() {
+ Exception c = new Exception();
+
+ // Ordinary case
+ SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL, c);
+
+ assertEquals(ERR, e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No message
+ e = new SAXParseException(null, PUB, SYS, ROW, COL, c);
+
+ assertNull(e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No locator
+ e = new SAXParseException(ERR, null, null, -1, -1, c);
+
+ assertEquals(ERR, e.getMessage());
+ assertEquals(c, e.getException());
+
+ assertNull(e.getPublicId());
+ assertNull(e.getSystemId());
+ assertEquals(-1, e.getLineNumber());
+ assertEquals(-1, e.getColumnNumber());
+
+ // No cause
+ e = new SAXParseException(ERR, PUB, SYS, ROW, COL, null);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+ }
+
+ public void testSAXParseException_String_String_String_int_int() {
+ // Ordinary case
+ SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No message
+ e = new SAXParseException(null, PUB, SYS, ROW, COL);
+
+ assertNull(e.getMessage());
+ assertNull(e.getException());
+
+ assertEquals(PUB, e.getPublicId());
+ assertEquals(SYS, e.getSystemId());
+ assertEquals(ROW, e.getLineNumber());
+ assertEquals(COL, e.getColumnNumber());
+
+ // No locator
+ e = new SAXParseException(ERR, null, null, -1, -1);
+
+ assertEquals(ERR, e.getMessage());
+ assertNull(e.getException());
+
+ assertNull(e.getPublicId());
+ assertNull(e.getSystemId());
+ assertEquals(-1, e.getLineNumber());
+ assertEquals(-1, e.getColumnNumber());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Attributes2ImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Attributes2ImplTest.java
new file mode 100644
index 0000000..348bef5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Attributes2ImplTest.java
@@ -0,0 +1,392 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.ext;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.ext.Attributes2Impl;
+import org.xml.sax.helpers.AttributesImpl;
+
+public class Attributes2ImplTest extends TestCase {
+
+ // Note: The original SAX2 implementation of Attributes2Impl is
+ // severely broken. Thus all of these tests will probably fail
+ // unless the Android implementation of the class gets fixed.
+
+ private Attributes2Impl empty = new Attributes2Impl();
+
+ private Attributes2Impl multi = new Attributes2Impl();
+
+ private Attributes2Impl cdata = new Attributes2Impl();
+
+ @Override
+ public void setUp() {
+ multi.addAttribute("http://some.uri", "foo", "ns1:foo",
+ "string", "abc");
+ multi.addAttribute("http://some.uri", "bar", "ns1:bar",
+ "string", "xyz");
+ multi.addAttribute("http://some.other.uri", "answer", "ns2:answer",
+ "int", "42");
+ multi.addAttribute("http://yet.another.uri", "gabba", "ns3:gabba",
+ "string", "gabba");
+
+ multi.setDeclared(0, false);
+ multi.setSpecified(0, false);
+
+ multi.setDeclared(1, true);
+ multi.setSpecified(1, false);
+
+ multi.setDeclared(2, false);
+ multi.setSpecified(2, true);
+
+ multi.setDeclared(3, true);
+ multi.setSpecified(3, true);
+
+ cdata.addAttribute("http://yet.another.uri", "hey", "ns3:hey",
+ "CDATA", "hey");
+ }
+
+ public void testSetAttributes() {
+ // Ordinary case with Attributes2Impl
+ Attributes2Impl attrs = new Attributes2Impl();
+ attrs.addAttribute("", "", "john", "string", "doe");
+
+ attrs.setAttributes(empty);
+ assertEquals(0, attrs.getLength());
+
+ attrs.setAttributes(multi);
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getURI(i), attrs.getURI(i));
+ assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
+ assertEquals(multi.getQName(i), attrs.getQName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ assertEquals(multi.isDeclared(i), attrs.isDeclared(i));
+ assertEquals(multi.isSpecified(i), attrs.isSpecified(i));
+ }
+
+ attrs.setAttributes(empty);
+ assertEquals(0, attrs.getLength());
+
+ // Ordinary case with AttributesImpl
+ attrs.setAttributes(new AttributesImpl(multi));
+ assertEquals(multi.getLength(), attrs.getLength());
+
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getURI(i), attrs.getURI(i));
+ assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
+ assertEquals(multi.getQName(i), attrs.getQName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ assertEquals(true, attrs.isDeclared(i));
+ assertEquals(true, attrs.isSpecified(i));
+ }
+
+ // Special case with CDATA
+ attrs.setAttributes(new AttributesImpl(cdata));
+ assertEquals(1, attrs.getLength());
+ assertEquals(false, attrs.isDeclared(0));
+ assertEquals(true, attrs.isSpecified(0));
+
+ // null case
+ try {
+ attrs.setAttributes(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testAddAttribute() {
+ Attributes2Impl attrs = new Attributes2Impl();
+
+ // Ordinary case
+ attrs.addAttribute("http://yet.another.uri", "doe", "john:doe",
+ "string", "abc");
+
+ assertEquals(1, attrs.getLength());
+
+ assertEquals("http://yet.another.uri", attrs.getURI(0));
+ assertEquals("doe", attrs.getLocalName(0));
+ assertEquals("john:doe", attrs.getQName(0));
+ assertEquals("string", attrs.getType(0));
+ assertEquals("abc", attrs.getValue(0));
+
+ assertEquals(true, attrs.isDeclared(0));
+ assertEquals(true, attrs.isSpecified(0));
+
+ // CDATA case
+ attrs.addAttribute("http://yet.another.uri", "doe", "jane:doe",
+ "CDATA", "abc");
+
+ assertEquals(2, attrs.getLength());
+
+ assertEquals("http://yet.another.uri", attrs.getURI(1));
+ assertEquals("doe", attrs.getLocalName(1));
+ assertEquals("jane:doe", attrs.getQName(1));
+ assertEquals("CDATA", attrs.getType(1));
+ assertEquals("abc", attrs.getValue(1));
+
+ assertEquals(false, attrs.isDeclared(1));
+ assertEquals(true, attrs.isSpecified(1));
+ }
+
+ public void testRemoveAttribute() {
+ Attributes2Impl attrs = new Attributes2Impl(multi);
+
+ // Ordinary case
+ attrs.removeAttribute(1);
+
+ assertEquals(3, attrs.getLength());
+
+ assertEquals(multi.getURI(0), attrs.getURI(0));
+ assertEquals(multi.getLocalName(0), attrs.getLocalName(0));
+ assertEquals(multi.getQName(0), attrs.getQName(0));
+ assertEquals(multi.getType(0), attrs.getType(0));
+ assertEquals(multi.getValue(0), attrs.getValue(0));
+ assertEquals(multi.isDeclared(0), attrs.isDeclared(0));
+ assertEquals(multi.isSpecified(0), attrs.isSpecified(0));
+
+ assertEquals(multi.getURI(2), attrs.getURI(1));
+ assertEquals(multi.getLocalName(2), attrs.getLocalName(1));
+ assertEquals(multi.getQName(2), attrs.getQName(1));
+ assertEquals(multi.getType(2), attrs.getType(1));
+ assertEquals(multi.getValue(2), attrs.getValue(1));
+ assertEquals(multi.isDeclared(2), attrs.isDeclared(1));
+ assertEquals(multi.isSpecified(2), attrs.isSpecified(1));
+
+ // Out of range
+ try {
+ attrs.removeAttribute(-1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ attrs.removeAttribute(3);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testAttributes2Impl() {
+ assertEquals(0, empty.getLength());
+ }
+
+ public void testAttributes2ImplAttributes() {
+ // Ordinary case with Attributes2Impl
+ Attributes2Impl attrs = new Attributes2Impl(multi);
+ assertEquals(multi.getLength(), attrs.getLength());
+
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getURI(i), attrs.getURI(i));
+ assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
+ assertEquals(multi.getQName(i), attrs.getQName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ assertEquals(multi.isDeclared(i), attrs.isDeclared(i));
+ assertEquals(multi.isSpecified(i), attrs.isSpecified(i));
+ }
+
+ attrs = new Attributes2Impl(empty);
+ assertEquals(0, attrs.getLength());
+
+ // Ordinary case with AttributesImpl
+ attrs = new Attributes2Impl(new AttributesImpl(multi));
+ assertEquals(multi.getLength(), attrs.getLength());
+
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getURI(i), attrs.getURI(i));
+ assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
+ assertEquals(multi.getQName(i), attrs.getQName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ assertEquals(true, attrs.isDeclared(i));
+ assertEquals(true, attrs.isSpecified(i));
+ }
+
+ // Special case with CDATA
+ attrs = new Attributes2Impl(new AttributesImpl(cdata));
+ assertEquals(1, attrs.getLength());
+ assertEquals(false, attrs.isDeclared(0));
+ assertEquals(true, attrs.isSpecified(0));
+
+ // null case
+ try {
+ attrs = new Attributes2Impl(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testIsDeclaredInt() {
+ // Ordinary cases
+ assertEquals(false, multi.isDeclared(0));
+ assertEquals(true, multi.isDeclared(1));
+
+ // Out of range
+ try {
+ multi.isDeclared(-1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.isDeclared(4);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testIsDeclaredStringString() {
+ // Ordinary cases
+ assertEquals(false, multi.isDeclared("http://some.uri", "foo"));
+ assertEquals(true, multi.isDeclared("http://some.uri", "bar"));
+
+ // Not found
+ try {
+ assertFalse(multi.isDeclared("not", "found"));
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testIsDeclaredString() {
+ // Ordinary cases
+ assertEquals(false, multi.isDeclared("ns1:foo"));
+ assertEquals(true, multi.isDeclared("ns1:bar"));
+
+ // Not found
+ try {
+ assertFalse(multi.isDeclared("notfound"));
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testIsSpecifiedInt() {
+ // Ordinary cases
+ assertEquals(false, multi.isSpecified(1));
+ assertEquals(true, multi.isSpecified(2));
+
+ // Out of range
+ try {
+ multi.isSpecified(-1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.isSpecified(4);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testIsSpecifiedStringString() {
+ // Ordinary cases
+ assertEquals(false, multi.isSpecified("http://some.uri", "bar"));
+ assertEquals(true, multi.isSpecified("http://some.other.uri", "answer"));
+
+ // Not found
+ try {
+ assertFalse(multi.isSpecified("not", "found"));
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testIsSpecifiedString() {
+ // Ordinary cases
+ assertEquals(false, multi.isSpecified("ns1:bar"));
+ assertEquals(true, multi.isSpecified("ns2:answer"));
+
+ // Not found
+ try {
+ assertFalse(multi.isSpecified("notfound"));
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testSetDeclared() {
+ // Ordinary cases
+ multi.setSpecified(0, false);
+ assertEquals(false, multi.isSpecified(0));
+
+ multi.setSpecified(0, true);
+ assertEquals(true, multi.isSpecified(0));
+
+ multi.setSpecified(0, false);
+ assertEquals(false, multi.isSpecified(0));
+
+ // Out of range
+ try {
+ multi.setSpecified(-1, true);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setSpecified(5, true);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetSpecified() {
+ // Ordinary cases
+ multi.setSpecified(0, false);
+ assertEquals(false, multi.isSpecified(0));
+
+ multi.setSpecified(0, true);
+ assertEquals(true, multi.isSpecified(0));
+
+ multi.setSpecified(0, false);
+ assertEquals(false, multi.isSpecified(0));
+
+ // Out of range
+ try {
+ multi.setSpecified(-1, true);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setSpecified(5, true);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/DefaultHandler2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/DefaultHandler2Test.java
new file mode 100644
index 0000000..0e6c245
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/DefaultHandler2Test.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.ext;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.ext.DefaultHandler2;
+
+import java.io.IOException;
+
+public class DefaultHandler2Test extends TestCase {
+
+ private DefaultHandler2 h = new DefaultHandler2();
+
+ public void testDefaultHandler2() {
+ new DefaultHandler2();
+ }
+
+ public void testStartCDATA() {
+ try {
+ h.startCDATA();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testEndCDATA() {
+ try {
+ h.endCDATA();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testStartDTD() {
+ try {
+ h.startDTD("name", "publicId", "systemId");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testEndDTD() {
+ try {
+ h.endDTD();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testStartEntity() {
+ try {
+ h.startEntity("name");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testEndEntity() {
+ try {
+ h.endEntity("name");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testComment() {
+ try {
+ h.comment("<!-- Comment -->".toCharArray(), 0, 15);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testAttributeDecl() {
+ try {
+ h.attributeDecl("eName", "aName", "type", "mode", "value");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testElementDecl() {
+ try {
+ h.elementDecl("name", "model");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testExternalEntityDecl() {
+ try {
+ h.externalEntityDecl("name", "publicId", "systemId");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testInternalEntityDecl() {
+ try {
+ h.internalEntityDecl("name", "value");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetExternalSubset() {
+ try {
+ assertNull(h.getExternalSubset("name", "http://some.uri"));
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testResolveEntityStringString() {
+ try {
+ assertNull(h.resolveEntity("publicId", "systemId"));
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testResolveEntityStringStringStringString() {
+ try {
+ assertNull(h.resolveEntity("name", "publicId", "http://some.uri",
+ "systemId"));
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Locator2ImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Locator2ImplTest.java
new file mode 100644
index 0000000..dbed1de
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/ext/Locator2ImplTest.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.ext;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Locator;
+import org.xml.sax.ext.Locator2Impl;
+import org.xml.sax.helpers.LocatorImpl;
+
+public class Locator2ImplTest extends TestCase {
+
+ public static final String SYS = "mySystemID";
+
+ public static final String PUB = "myPublicID";
+
+ public static final int ROW = 1;
+
+ public static final int COL = 2;
+
+ public static final String ENC = "Klingon";
+
+ public static final String XML = "1.0";
+
+ public void testLocatorImpl() {
+ Locator2Impl l = new Locator2Impl();
+
+ assertEquals(null, l.getPublicId());
+ assertEquals(null, l.getSystemId());
+ assertEquals(0, l.getLineNumber());
+ assertEquals(0, l.getColumnNumber());
+
+ assertEquals(null, l.getEncoding());
+ assertEquals(null, l.getXMLVersion());
+ }
+
+ public void testLocatorImplLocator() {
+ Locator2Impl inner = new Locator2Impl();
+
+ inner.setPublicId(PUB);
+ inner.setSystemId(SYS);
+ inner.setLineNumber(ROW);
+ inner.setColumnNumber(COL);
+
+ inner.setEncoding(ENC);
+ inner.setXMLVersion(XML);
+
+ // Ordinary case
+ Locator2Impl outer = new Locator2Impl(inner);
+
+ assertEquals(PUB, outer.getPublicId());
+ assertEquals(SYS, outer.getSystemId());
+ assertEquals(ROW, outer.getLineNumber());
+ assertEquals(COL, outer.getColumnNumber());
+
+ assertEquals(ENC, outer.getEncoding());
+ assertEquals(XML, outer.getXMLVersion());
+
+ // Instance of old locator
+ outer = new Locator2Impl(new LocatorImpl(inner));
+
+ assertEquals(PUB, outer.getPublicId());
+ assertEquals(SYS, outer.getSystemId());
+ assertEquals(ROW, outer.getLineNumber());
+ assertEquals(COL, outer.getColumnNumber());
+
+ assertEquals(null, outer.getEncoding());
+ assertEquals(null, outer.getXMLVersion());
+
+ // No locator
+ try {
+ outer = new Locator2Impl(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testSetXMLVersionGetXMLVersion() {
+ Locator2Impl l = new Locator2Impl();
+
+ l.setXMLVersion(XML);
+ assertEquals(XML, l.getXMLVersion());
+
+ l.setXMLVersion(null);
+ assertEquals(null, l.getXMLVersion());
+ }
+
+ public void testSetEncodingGetEncoding() {
+ Locator2Impl l = new Locator2Impl();
+
+ l.setEncoding(ENC);
+ assertEquals(ENC, l.getEncoding());
+
+ l.setEncoding(null);
+ assertEquals(null, l.getEncoding());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributeListImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributeListImplTest.java
new file mode 100644
index 0000000..27f36ae
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributeListImplTest.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.AttributeList;
+import org.xml.sax.helpers.AttributeListImpl;
+
+@SuppressWarnings("deprecation")
+public class AttributeListImplTest extends TestCase {
+
+ private AttributeListImpl empty = new AttributeListImpl();
+
+ private AttributeListImpl multi = new AttributeListImpl();
+
+ @Override
+ public void setUp() {
+ multi.addAttribute("foo", "string", "abc");
+ multi.addAttribute("bar", "string", "xyz");
+ multi.addAttribute("answer", "int", "42");
+ }
+
+ public void testAttributeListImpl() {
+ assertEquals(0, empty.getLength());
+ assertEquals(3, multi.getLength());
+ }
+
+ public void testAttributeListImplAttributeList() {
+ // Ordinary case
+ AttributeListImpl ai = new AttributeListImpl(empty);
+ assertEquals(0, ai.getLength());
+
+ // Another ordinary case
+ ai = new AttributeListImpl(multi);
+ assertEquals(3, ai.getLength());
+
+ // No Attributes
+ try {
+ ai = new AttributeListImpl(null);
+ assertEquals(0, ai.getLength());
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testSetAttributeList() {
+ // Ordinary cases
+ AttributeListImpl attrs = new AttributeListImpl();
+ attrs.addAttribute("doe", "boolean", "false");
+
+ attrs.setAttributeList(empty);
+ assertEquals(0, attrs.getLength());
+
+ attrs.setAttributeList(multi);
+ assertEquals(multi.getLength(), attrs.getLength());
+
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getName(i), attrs.getName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ }
+
+ // null case
+ try {
+ attrs.setAttributeList(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected, must still have old elements
+ assertEquals(3, attrs.getLength());
+ }
+ }
+
+ public void testAddAttribute() {
+ // Ordinary case
+ multi.addAttribute("doe", "boolean", "false");
+
+ assertEquals("doe", multi.getName(3));
+ assertEquals("boolean", multi.getType(3));
+ assertEquals("false", multi.getValue(3));
+
+ // Duplicate case
+ multi.addAttribute("doe", "boolean", "false");
+
+ assertEquals("doe", multi.getName(4));
+ assertEquals("boolean", multi.getType(4));
+ assertEquals("false", multi.getValue(4));
+
+ // null case
+ multi.addAttribute(null, null, null);
+ assertEquals(null, multi.getName(5));
+ assertEquals(null, multi.getType(5));
+ assertEquals(null, multi.getValue(5));
+ }
+
+ public void testRemoveAttribute() {
+ // Ordinary case
+ multi.removeAttribute("foo");
+ assertEquals("bar", multi.getName(0));
+ assertEquals("string", multi.getType(0));
+ assertEquals("xyz", multi.getValue(0));
+
+ // Unknown attribute
+ multi.removeAttribute("john");
+ assertEquals(2, multi.getLength());
+
+ // null case
+ multi.removeAttribute(null);
+ assertEquals(2, multi.getLength());
+ }
+
+ public void testClear() {
+ assertEquals(3, multi.getLength());
+ multi.clear();
+ assertEquals(0, multi.getLength());
+ }
+
+ public void testGetLength() {
+ AttributeListImpl ai = new AttributeListImpl(empty);
+ assertEquals(0, ai.getLength());
+
+ ai = new AttributeListImpl(multi);
+ assertEquals(3, ai.getLength());
+
+ for (int i = 2; i >= 0; i--) {
+ ai.removeAttribute(ai.getName(i));
+ assertEquals(i, ai.getLength());
+ }
+ }
+
+ public void testGetName() {
+ // Ordinary cases
+ assertEquals("foo", multi.getName(0));
+ assertEquals("bar", multi.getName(1));
+ assertEquals("answer", multi.getName(2));
+
+ // Out of range
+ assertEquals(null, multi.getName(-1));
+ assertEquals(null, multi.getName(3));
+ }
+
+ public void testGetTypeInt() {
+ // Ordinary cases
+ assertEquals("string", multi.getType(0));
+ assertEquals("string", multi.getType(1));
+ assertEquals("int", multi.getType(2));
+
+ // Out of range
+ assertEquals(null, multi.getType(-1));
+ assertEquals(null, multi.getType(3));
+ }
+
+ public void testGetValueInt() {
+ // Ordinary cases
+ assertEquals("abc", multi.getValue(0));
+ assertEquals("xyz", multi.getValue(1));
+ assertEquals("42", multi.getValue(2));
+
+ // Out of range
+ assertEquals(null, multi.getValue(-1));
+ assertEquals(null, multi.getValue(5));
+ }
+
+ public void testGetTypeString() {
+ // Ordinary cases
+ assertEquals("string", multi.getType("foo"));
+ assertEquals("string", multi.getType("bar"));
+ assertEquals("int", multi.getType("answer"));
+
+ // Not found
+ assertEquals(null, multi.getType("john"));
+
+ // null case
+ assertEquals(null, multi.getType(null));
+ }
+
+ public void testGetValueString() {
+ // Ordinary cases
+ assertEquals("abc", multi.getValue("foo"));
+ assertEquals("xyz", multi.getValue("bar"));
+ assertEquals("42", multi.getValue("answer"));
+
+ // Not found
+ assertEquals(null, multi.getValue("john"));
+
+ // null case
+ assertEquals(null, multi.getValue(null));
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributesImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributesImplTest.java
new file mode 100644
index 0000000..1cc77ee
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/AttributesImplTest.java
@@ -0,0 +1,481 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.helpers.AttributesImpl;
+
+public class AttributesImplTest extends TestCase {
+
+ private AttributesImpl empty = new AttributesImpl();
+
+ private AttributesImpl multi = new AttributesImpl();
+
+ @Override
+ public void setUp() {
+ multi.addAttribute("http://some.uri", "foo", "ns1:foo",
+ "string", "abc");
+ multi.addAttribute("http://some.uri", "bar", "ns1:bar",
+ "string", "xyz");
+ multi.addAttribute("http://some.other.uri", "answer", "ns2:answer",
+ "int", "42");
+
+ multi.addAttribute("", "gabbaHey", "", "string", "1-2-3-4");
+ multi.addAttribute("", "", "gabba:hey", "string", "1-2-3-4");
+ }
+
+ public void testAttributesImpl() {
+ assertEquals(0, empty.getLength());
+ assertEquals(5, multi.getLength());
+ }
+
+ public void testAttributesImplAttributes() {
+ // Ordinary case
+ AttributesImpl ai = new AttributesImpl(empty);
+ assertEquals(0, ai.getLength());
+
+ // Another ordinary case
+ ai = new AttributesImpl(multi);
+ assertEquals(5, ai.getLength());
+
+ // No Attributes
+ try {
+ ai = new AttributesImpl(null);
+ assertEquals(0, ai.getLength());
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testGetLength() {
+ AttributesImpl ai = new AttributesImpl(empty);
+ assertEquals(0, ai.getLength());
+
+ ai = new AttributesImpl(multi);
+ assertEquals(5, ai.getLength());
+
+ for (int i = 4; i >= 0; i--) {
+ ai.removeAttribute(i);
+ assertEquals(i, ai.getLength());
+ }
+ }
+
+ public void testGetURI() {
+ // Ordinary cases
+ assertEquals("http://some.uri", multi.getURI(0));
+ assertEquals("http://some.uri", multi.getURI(1));
+ assertEquals("http://some.other.uri", multi.getURI(2));
+ assertEquals("", multi.getURI(3));
+ assertEquals("", multi.getURI(4));
+
+ // Out of range
+ assertEquals(null, multi.getURI(-1));
+ assertEquals(null, multi.getURI(5));
+ }
+
+ public void testGetLocalName() {
+ // Ordinary cases
+ assertEquals("foo", multi.getLocalName(0));
+ assertEquals("bar", multi.getLocalName(1));
+ assertEquals("answer", multi.getLocalName(2));
+ assertEquals("gabbaHey", multi.getLocalName(3));
+ assertEquals("", multi.getLocalName(4));
+
+ // Out of range
+ assertEquals(null, multi.getLocalName(-1));
+ assertEquals(null, multi.getLocalName(5));
+ }
+
+ public void testGetQName() {
+ // Ordinary cases
+ assertEquals("ns1:foo", multi.getQName(0));
+ assertEquals("ns1:bar", multi.getQName(1));
+ assertEquals("ns2:answer", multi.getQName(2));
+ assertEquals("", multi.getQName(3));
+ assertEquals("gabba:hey", multi.getQName(4));
+
+ // Out of range
+ assertEquals(null, multi.getQName(-1));
+ assertEquals(null, multi.getQName(5));
+ }
+
+ public void testGetTypeInt() {
+ // Ordinary cases
+ assertEquals("string", multi.getType(0));
+ assertEquals("string", multi.getType(1));
+ assertEquals("int", multi.getType(2));
+ assertEquals("string", multi.getType(3));
+ assertEquals("string", multi.getType(4));
+
+ // Out of range
+ assertEquals(null, multi.getType(-1));
+ assertEquals(null, multi.getType(5));
+ }
+
+ public void testGetValueInt() {
+ // Ordinary cases
+ assertEquals("abc", multi.getValue(0));
+ assertEquals("xyz", multi.getValue(1));
+ assertEquals("42", multi.getValue(2));
+ assertEquals("1-2-3-4", multi.getValue(3));
+ assertEquals("1-2-3-4", multi.getValue(4));
+
+ // Out of range
+ assertEquals(null, multi.getValue(-1));
+ assertEquals(null, multi.getValue(5));
+ }
+
+ public void testGetIndexStringString() {
+ // Ordinary cases
+ assertEquals(0, multi.getIndex("http://some.uri", "foo"));
+ assertEquals(1, multi.getIndex("http://some.uri", "bar"));
+ assertEquals(2, multi.getIndex("http://some.other.uri", "answer"));
+
+ // Not found
+ assertEquals(-1, multi.getIndex("john", "doe"));
+
+ // null cases
+ assertEquals(-1, multi.getIndex("http://some.uri", null));
+ assertEquals(-1, multi.getIndex(null, "foo"));
+ }
+
+ public void testGetIndexString() {
+ // Ordinary cases
+ assertEquals(0, multi.getIndex("ns1:foo"));
+ assertEquals(1, multi.getIndex("ns1:bar"));
+ assertEquals(2, multi.getIndex("ns2:answer"));
+ assertEquals(4, multi.getIndex("gabba:hey"));
+
+ // Not found
+ assertEquals(-1, multi.getIndex("john:doe"));
+
+ // null case
+ assertEquals(-1, multi.getIndex(null));
+ }
+
+ public void testGetTypeStringString() {
+ // Ordinary cases
+ assertEquals("string", multi.getType("http://some.uri", "foo"));
+ assertEquals("string", multi.getType("http://some.uri", "bar"));
+ assertEquals("int", multi.getType("http://some.other.uri", "answer"));
+
+ // Not found
+ assertEquals(null, multi.getType("john", "doe"));
+
+ // null cases
+ assertEquals(null, multi.getType("http://some.uri", null));
+ assertEquals(null, multi.getType(null, "foo"));
+ }
+
+ public void testGetTypeString() {
+ // Ordinary cases
+ assertEquals("string", multi.getType("ns1:foo"));
+ assertEquals("string", multi.getType("ns1:bar"));
+ assertEquals("int", multi.getType("ns2:answer"));
+ assertEquals("string", multi.getType("gabba:hey"));
+
+ // Not found
+ assertEquals(null, multi.getType("john:doe"));
+
+ // null case
+ assertEquals(null, multi.getType(null));
+ }
+
+ public void testGetValueStringString() {
+ // Ordinary cases
+ assertEquals("abc", multi.getValue("http://some.uri", "foo"));
+ assertEquals("xyz", multi.getValue("http://some.uri", "bar"));
+ assertEquals("42", multi.getValue("http://some.other.uri", "answer"));
+
+ // Not found
+ assertEquals(null, multi.getValue("john", "doe"));
+
+ // null cases
+ assertEquals(null, multi.getValue("http://some.uri", null));
+ assertEquals(null, multi.getValue(null, "foo"));
+ }
+
+ public void testGetValueString() {
+ // Ordinary cases
+ assertEquals("abc", multi.getValue("ns1:foo"));
+ assertEquals("xyz", multi.getValue("ns1:bar"));
+ assertEquals("42", multi.getValue("ns2:answer"));
+ assertEquals("1-2-3-4", multi.getValue("gabba:hey"));
+
+ // Not found
+ assertEquals(null, multi.getValue("john:doe"));
+
+ // null case
+ assertEquals(null, multi.getValue(null));
+ }
+
+ public void testClear() {
+ assertEquals(5, multi.getLength());
+ multi.clear();
+ assertEquals(0, multi.getLength());
+ }
+
+ public void testSetAttributes() {
+ // Ordinary cases
+ AttributesImpl attrs = new AttributesImpl();
+ attrs.addAttribute("http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+
+ attrs.setAttributes(empty);
+ assertEquals(0, attrs.getLength());
+
+ attrs.setAttributes(multi);
+ assertEquals(multi.getLength(), attrs.getLength());
+
+ for (int i = 0; i < multi.getLength(); i++) {
+ assertEquals(multi.getURI(i), attrs.getURI(i));
+ assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
+ assertEquals(multi.getQName(i), attrs.getQName(i));
+ assertEquals(multi.getType(i), attrs.getType(i));
+ assertEquals(multi.getValue(i), attrs.getValue(i));
+ }
+
+ // null case
+ try {
+ attrs.setAttributes(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected, but must be empty now
+ assertEquals(0, attrs.getLength());
+ }
+ }
+
+ public void testAddAttribute() {
+ // Ordinary case
+ multi.addAttribute("http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+
+ assertEquals("http://yet.another.uri", multi.getURI(5));
+ assertEquals("doe", multi.getLocalName(5));
+ assertEquals("john:doe", multi.getQName(5));
+ assertEquals("boolean", multi.getType(5));
+ assertEquals("false", multi.getValue(5));
+
+ // Duplicate case
+ multi.addAttribute("http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+
+ assertEquals("http://yet.another.uri", multi.getURI(6));
+ assertEquals("doe", multi.getLocalName(6));
+ assertEquals("john:doe", multi.getQName(6));
+ assertEquals("boolean", multi.getType(6));
+ assertEquals("false", multi.getValue(6));
+
+ // null case
+ multi.addAttribute(null, null, null, null, null);
+ assertEquals(null, multi.getURI(7));
+ assertEquals(null, multi.getLocalName(7));
+ assertEquals(null, multi.getQName(7));
+ assertEquals(null, multi.getType(7));
+ assertEquals(null, multi.getValue(7));
+ }
+
+ public void testSetAttribute() {
+ // Ordinary case
+ multi.setAttribute(0, "http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+ assertEquals("http://yet.another.uri", multi.getURI(0));
+ assertEquals("doe", multi.getLocalName(0));
+ assertEquals("john:doe", multi.getQName(0));
+ assertEquals("boolean", multi.getType(0));
+ assertEquals("false", multi.getValue(0));
+
+ // null case
+ multi.setAttribute(1, null, null, null, null, null);
+ assertEquals(null, multi.getURI(1));
+ assertEquals(null, multi.getLocalName(1));
+ assertEquals(null, multi.getQName(1));
+ assertEquals(null, multi.getType(1));
+ assertEquals(null, multi.getValue(1));
+
+ // Out of range
+ try {
+ multi.setAttribute(-1, "http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setAttribute(5, "http://yet.another.uri", "doe", "john:doe",
+ "boolean", "false");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testRemoveAttribute() {
+ // Ordinary case
+ multi.removeAttribute(0);
+ assertEquals("http://some.uri", multi.getURI(0));
+ assertEquals("bar", multi.getLocalName(0));
+ assertEquals("ns1:bar", multi.getQName(0));
+ assertEquals("string", multi.getType(0));
+ assertEquals("xyz", multi.getValue(0));
+
+ // Out of range
+ try {
+ multi.removeAttribute(-1);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.removeAttribute(4);
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetURI() {
+ // Ordinary case
+ multi.setURI(0, "http://yet.another.uri");
+ assertEquals("http://yet.another.uri", multi.getURI(0));
+
+ // null case
+ multi.setURI(1, null);
+ assertEquals(null, multi.getURI(1));
+
+ // Out of range
+ try {
+ multi.setURI(-1, "http://yet.another.uri");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setURI(5, "http://yet.another.uri");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetLocalName() {
+ // Ordinary case
+ multi.setLocalName(0, "john");
+ assertEquals("john", multi.getLocalName(0));
+
+ // null case
+ multi.setLocalName(1, null);
+ assertEquals(null, multi.getLocalName(1));
+
+ // Out of range
+ try {
+ multi.setLocalName(-1, "john");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setLocalName(5, "john");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetQName() {
+ // Ordinary case
+ multi.setQName(0, "john:doe");
+ assertEquals("john:doe", multi.getQName(0));
+
+ // null case
+ multi.setQName(1, null);
+ assertEquals(null, multi.getQName(1));
+
+ // Out of range
+ try {
+ multi.setQName(-1, "john:doe");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setQName(5, "john:doe");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetType() {
+ // Ordinary case
+ multi.setType(0, "float");
+ assertEquals("float", multi.getType(0));
+
+ // null case
+ multi.setType(1, null);
+ assertEquals(null, multi.getType(1));
+
+ // Out of range
+ try {
+ multi.setType(-1, "float");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setType(5, "float");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+ public void testSetValue() {
+ // Ordinary case
+ multi.setValue(0, "too much");
+ assertEquals("too much", multi.getValue(0));
+
+ // null case
+ multi.setValue(1, null);
+ assertEquals(null, multi.getValue(1));
+
+ // Out of range
+ try {
+ multi.setValue(-1, "too much");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ multi.setValue(5, "too much");
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Expected
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/DefaultHandlerTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/DefaultHandlerTest.java
new file mode 100644
index 0000000..a9530f2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/DefaultHandlerTest.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.LocatorImpl;
+
+import java.io.IOException;
+
+public class DefaultHandlerTest extends TestCase {
+
+ /*
+ * Note: most of the tests have to check for an empty implementation of the
+ * respective methods and, as a result, are somewhat trivial.
+ */
+
+ private DefaultHandler h = new DefaultHandler();
+
+ public void testResolveEntity() {
+ try {
+ h.resolveEntity("publicID", "systemID");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testNotationDecl() {
+ try {
+ h.notationDecl("name", "publicID", "systemID");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testUnparsedEntityDecl() {
+ try {
+ h.unparsedEntityDecl("name", "publicID", "systemID",
+ "notationName");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testSetDocumentLocator() {
+ h.setDocumentLocator(new LocatorImpl());
+ }
+
+ public void testStartDocument() {
+ try {
+ h.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testEndDocument() {
+ try {
+ h.endDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testStartPrefixMapping() {
+ try {
+ h.startPrefixMapping("prefix", "uri");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testEndPrefixMapping() {
+ try {
+ h.endPrefixMapping("prefix");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testStartElement() {
+ try {
+ h.startElement("uri", "name", "qname", new AttributesImpl());
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testEndElement() {
+ try {
+ h.endElement("uri", "name", "qname");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testCharacters() {
+ try {
+ h.characters("The quick brown fox".toCharArray(), 4, 11);
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testIgnorableWhitespace() {
+ try {
+ h.ignorableWhitespace(" ".toCharArray(), 4, 11);
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testProcessingInstruction() {
+ try {
+ h.processingInstruction("target", "data");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testSkippedEntity() {
+ try {
+ h.skippedEntity("name");
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testWarning() {
+ try {
+ h.warning(new SAXParseException("Foo", new LocatorImpl()));
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testError() {
+ try {
+ h.error(new SAXParseException("Foo", new LocatorImpl()));
+ } catch (SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void testFatalError() {
+ // Ordinary case
+ try {
+ h.fatalError(new SAXParseException("Foo", new LocatorImpl()));
+ fail("SAXException expected");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // No exception
+ try {
+ h.fatalError(null);
+ fail("NullPointerException expected");
+ } catch (SAXException e) {
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/LocatorImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/LocatorImplTest.java
new file mode 100644
index 0000000..8aa9c11
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/LocatorImplTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Locator;
+import org.xml.sax.helpers.LocatorImpl;
+
+public class LocatorImplTest extends TestCase {
+
+ public static final String SYS = "mySystemID";
+
+ public static final String PUB = "myPublicID";
+
+ public static final int ROW = 1;
+
+ public static final int COL = 2;
+
+ public void testLocatorImpl() {
+ LocatorImpl l = new LocatorImpl();
+
+ assertEquals(null, l.getPublicId());
+ assertEquals(null, l.getSystemId());
+ assertEquals(0, l.getLineNumber());
+ assertEquals(0, l.getColumnNumber());
+ }
+
+ public void testLocatorImplLocator() {
+ LocatorImpl inner = new LocatorImpl();
+
+ inner.setPublicId(PUB);
+ inner.setSystemId(SYS);
+ inner.setLineNumber(ROW);
+ inner.setColumnNumber(COL);
+
+ // Ordinary case
+ LocatorImpl outer = new LocatorImpl(inner);
+
+ assertEquals(PUB, outer.getPublicId());
+ assertEquals(SYS, outer.getSystemId());
+ assertEquals(ROW, outer.getLineNumber());
+ assertEquals(COL, outer.getColumnNumber());
+
+ // No locator
+ try {
+ outer = new LocatorImpl(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testSetPublicIdGetPublicId() {
+ LocatorImpl l = new LocatorImpl();
+
+ l.setPublicId(PUB);
+ assertEquals(PUB, l.getPublicId());
+
+ l.setPublicId(null);
+ assertEquals(null, l.getPublicId());
+ }
+
+ public void testSetSystemIdGetSystemId() {
+ LocatorImpl l = new LocatorImpl();
+
+ l.setSystemId(SYS);
+ assertEquals(SYS, l.getSystemId());
+
+ l.setSystemId(null);
+ assertEquals(null, l.getSystemId());
+ }
+
+ public void testSetLineNumberGetLineNumber() {
+ LocatorImpl l = new LocatorImpl();
+
+ l.setLineNumber(ROW);
+ assertEquals(ROW, l.getLineNumber());
+
+ l.setLineNumber(0);
+ assertEquals(0, l.getLineNumber());
+ }
+
+ public void testSetColumnNumberGetColumnNumber() {
+ LocatorImpl l = new LocatorImpl();
+
+ l.setColumnNumber(COL);
+ assertEquals(COL, l.getColumnNumber());
+
+ l.setColumnNumber(0);
+ assertEquals(0, l.getColumnNumber());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/NamespaceSupportTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/NamespaceSupportTest.java
new file mode 100644
index 0000000..2f1ff8d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/NamespaceSupportTest.java
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EmptyStackException;
+import java.util.Enumeration;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.helpers.NamespaceSupport;
+
+public class NamespaceSupportTest extends TestCase {
+
+ final static String defaultUri = "http://www.android.com";
+ final static String marketUri = "http://www.android.com/market";
+
+ NamespaceSupport ns;
+ ArrayList<String> expected;
+
+ @Override
+ public void setUp() {
+ expected = new ArrayList<String>();
+ expected.add("ak");
+ expected.add("bk");
+
+ ns = new NamespaceSupport();
+ ns.pushContext();
+
+ ns.declarePrefix("ak", marketUri);
+ ns.declarePrefix("bk", marketUri);
+ ns.declarePrefix("", defaultUri);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testConstructor() {
+ String prefix;
+ boolean xmlPrefixExists = false;
+
+ ns = new NamespaceSupport();
+ Enumeration<String> prefixes = ns.getDeclaredPrefixes();
+
+ while (prefixes.hasMoreElements()) {
+ prefix = prefixes.nextElement();
+ if (prefix.equals("xml")) xmlPrefixExists = true;
+ }
+
+ assertTrue("Test 1: xml prefix does not exist.", xmlPrefixExists);
+
+ // Check that only one context has been created by the constructor.
+ try {
+ ns.popContext();
+ fail("Test 2: EmptyStackException expected.");
+ } catch (EmptyStackException e) {
+ // Expected.
+ }
+ }
+
+ public void testPush_PopContext() {
+ int count;
+
+ ns = new NamespaceSupport();
+ count = countPrefixes();
+
+ ns.pushContext();
+ ns.declarePrefix("dc", "http://www.purl.org/dc#");
+ assertEquals("Test 1: Incorrect prefix count;",
+ count + 1, countPrefixes());
+
+ ns.popContext();
+ assertEquals("Test 2: Incorrect prefix count;",
+ count, countPrefixes());
+
+ // Check that only one context has been created by pushContext().
+ try {
+ ns.popContext();
+ fail("Test 3: EmptyStackException expected.");
+ } catch (EmptyStackException e) {
+ // Expected.
+ }
+ }
+
+ public void testReset() {
+ int count;
+
+ ns = new NamespaceSupport();
+ count = countPrefixes();
+
+ ns.pushContext();
+ ns.declarePrefix("dc", "http://www.purl.org/dc#");
+
+ assertEquals("Test 1: Incorrect prefix count;",
+ count + 1, countPrefixes());
+
+ ns.reset();
+ assertEquals("Test 2: Incorrect prefix count;",
+ count, countPrefixes());
+
+ // Check that only one context has been created by reset().
+ try {
+ ns.popContext();
+ fail("Test 3: EmptyStackException expected.");
+ } catch (EmptyStackException e) {
+ // Expected.
+ }
+ }
+
+ public void testDeclare_GetPrefix() {
+ ns.pushContext();
+
+ // Part 1: Check that xml and xmlns are not accepted as prefixes.
+ assertFalse("Test 1: Invalid prefix accepted.",
+ ns.declarePrefix("xml", marketUri));
+
+ assertFalse("Test 2: Invalid prefix accepted.",
+ ns.declarePrefix("xmlns", marketUri));
+
+ // Part 2: Check that declarePrefix and getPrefix work for valid
+ // prefixes.
+ assertTrue("Test 3: Valid prefix not accepted.",
+ ns.declarePrefix("ak", marketUri));
+
+ assertTrue("Test 4: Incorrect prefix returned.",
+ ns.getPrefix(marketUri).equals("ak"));
+
+ assertTrue("Test 5: Valid prefix not accepted.",
+ ns.declarePrefix("bk", marketUri));
+
+ assertTrue("Test 6: Incorrect prefix returned.",
+ expected.contains(ns.getPrefix(marketUri)));
+
+ assertTrue("Test 7: Valid prefix not accepted.",
+ ns.declarePrefix("", defaultUri));
+
+ // Part 3: Negative Tests for getPrefix.
+ assertNull("Test 8: Non-null value returned for the URI that is " +
+ "assigned to the default namespace.",
+ ns.getPrefix(defaultUri));
+
+ assertNull("Test 9: Non-null value returned for an unassigned URI.",
+ ns.getPrefix(defaultUri + "/42"));
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testGetPrefixesLjava_lang_String() {
+ ArrayList<String> prefixes;
+
+ prefixes = Collections.list(ns.getPrefixes(marketUri));
+ assertTrue("Test 1: Incorrect set of prefixes returned.",
+ expected.containsAll(prefixes) && prefixes.containsAll(expected));
+
+ prefixes = Collections.list(ns.getPrefixes(defaultUri));
+ assertTrue("Test 2: Default namespace prefix should not be returned.",
+ prefixes.size() == 0);
+
+ prefixes = Collections.list(ns.getPrefixes(NamespaceSupport.XMLNS));
+ assertTrue("Test 3: xml prefix is missing.",
+ prefixes.contains("xml") && prefixes.size() == 1);
+
+ prefixes = Collections.list(ns.getPrefixes(defaultUri + "/42"));
+ assertTrue("Test 4: Non-empty enumeration returned for an unassigned URI.",
+ prefixes.size() == 0);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testGetPrefixes() {
+ ArrayList<String> prefixes;
+
+ expected.add("xml");
+
+ prefixes = Collections.list(ns.getPrefixes());
+ assertTrue("Test 1: Incorrect set of prefixes returned.",
+ expected.containsAll(prefixes) && prefixes.containsAll(expected));
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testGetDeclaredPrefixes() {
+ ArrayList<String> prefixes;
+
+ expected.add("");
+
+ prefixes = Collections.list(ns.getDeclaredPrefixes());
+ assertTrue("Test 1: Incorrect set of prefixes returned.",
+ expected.containsAll(prefixes) && prefixes.containsAll(expected));
+ }
+
+ public void testGetUri() {
+ assertEquals("Test 1: Incorrect URI returned;",
+ marketUri, ns.getURI("bk"));
+ assertEquals("Test 2: Incorrect URI returned;",
+ defaultUri, ns.getURI(""));
+ assertNull("Test 3: Null expected for not-existing prefix.",
+ ns.getURI("ck"));
+
+ ns.popContext();
+ assertNull("Test 4: Null expected for not-existing prefix.",
+ ns.getURI("bk"));
+ assertEquals("Test 5: Incorrect URI returned;",
+ NamespaceSupport.XMLNS, ns.getURI("xml"));
+ }
+
+ public void testNamespaceDeclUris() {
+
+ assertFalse("Test 1: Incorrect default value returned by isNamespaceDeclUris().",
+ ns.isNamespaceDeclUris());
+
+ try {
+ ns.setNamespaceDeclUris(true);
+ fail("Test 2: IllegalStateException expected since a context has already been pushed in setUp().");
+ } catch (IllegalStateException e) {
+ // Expected.
+ }
+
+ ns = new NamespaceSupport();
+ ns.setNamespaceDeclUris(true);
+ assertTrue("Test 3: Incorrect value returned by isNamespaceDeclUris().",
+ ns.isNamespaceDeclUris());
+
+ ns.setNamespaceDeclUris(false);
+ assertFalse("Test 4: Incorrect value returned by isNamespaceDeclUris().",
+ ns.isNamespaceDeclUris());
+ }
+
+ public void testProcessName_Element() {
+ String[] parts = new String[3];
+
+ assertNotNull("Test 1: Non-null value expected.",
+ ns.processName("ak:hello", parts, false));
+ assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]);
+ assertEquals("Test 3: Incorrect local name;", "hello", parts[1]);
+ assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]);
+
+ assertNotNull("Test 5: Non-null value expected.",
+ ns.processName("bk:", parts, false));
+ assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]);
+ assertEquals("Test 7: Incorrect local name;", "", parts[1]);
+ assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]);
+
+ assertNotNull("Test 9: Non-null value expected.",
+ ns.processName("world", parts, false));
+ assertEquals("Test 10: Incorrect namespace URI;", defaultUri, parts[0]);
+ assertEquals("Test 11: Incorrect local name;", "world", parts[1]);
+ assertEquals("Test 12: Incorrect raw name;", "world", parts[2]);
+
+ assertNull("Test 13: Null expected for undeclared prefix.",
+ ns.processName("ck:lorem", parts, false));
+
+ assertNull("Test 14: Null expected for xmlns prefix.",
+ ns.processName("xmlns:ipsum", parts, false));
+
+ ns = new NamespaceSupport();
+ ns.pushContext();
+ assertNotNull("Test 15: Non-null value expected.",
+ ns.processName("world", parts, false));
+ assertEquals("Test 16: Incorrect namespace URI;", "", parts[0]);
+ assertEquals("Test 17: Incorrect local name;", "world", parts[1]);
+ assertEquals("Test 18: Incorrect raw name;", "world", parts[2]);
+ }
+
+ public void testProcessName_Attribute() {
+ String[] parts = new String[3];
+
+ assertNotNull("Test 1: Non-null value expected.",
+ ns.processName("ak:hello", parts, true));
+ assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]);
+ assertEquals("Test 3: Incorrect local name;", "hello", parts[1]);
+ assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]);
+
+ assertNotNull("Test 5: Non-null value expected.",
+ ns.processName("bk:", parts, true));
+ assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]);
+ assertEquals("Test 7: Incorrect local name;", "", parts[1]);
+ assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]);
+
+ assertNotNull("Test 9: Non-null value expected.",
+ ns.processName("world", parts, true));
+ assertEquals("Test 10: Incorrect namespace URI;", "", parts[0]);
+ assertEquals("Test 11: Incorrect local name;", "world", parts[1]);
+ assertEquals("Test 12: Incorrect raw name;", "world", parts[2]);
+
+ assertNull("Test 13: Null expected for undeclared prefix.",
+ ns.processName("ck:lorem", parts, true));
+
+ assertNull("Test 14: Null expected for xmlns prefix.",
+ ns.processName("xmlns:ipsum", parts, true));
+
+ ns = new NamespaceSupport();
+ ns.setNamespaceDeclUris(true);
+ ns.pushContext();
+ assertNotNull("Test 15: Non-null value expected.",
+ ns.processName("xmlns", parts, true));
+ assertEquals("Test 16: Incorrect namespace URI;", NamespaceSupport.NSDECL, parts[0]);
+ assertEquals("Test 17: Incorrect local name;", "xmlns", parts[1]);
+ assertEquals("Test 18: Incorrect raw name;", "xmlns", parts[2]);
+ }
+
+ @SuppressWarnings("unchecked")
+ private int countPrefixes()
+ {
+ ArrayList<String> prefixes = Collections.list(ns.getPrefixes());
+ return prefixes.size();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserAdapterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserAdapterTest.java
new file mode 100644
index 0000000..2344736
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserAdapterTest.java
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.AttributeList;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.Parser;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.helpers.AttributeListImpl;
+import org.xml.sax.helpers.LocatorImpl;
+import org.xml.sax.helpers.ParserAdapter;
+
+import tests.api.org.xml.sax.support.MethodLogger;
+import tests.api.org.xml.sax.support.MockHandler;
+import tests.api.org.xml.sax.support.MockParser;
+import tests.api.org.xml.sax.support.MockResolver;
+
+@SuppressWarnings("deprecation")
+public class ParserAdapterTest extends TestCase {
+
+ // Note: In many cases we can only test that delegation works
+ // properly. The rest is outside the scope of the specification.
+
+ private final static String FEATURES = "http://xml.org/sax/features/";
+
+ private final static String NAMESPACES = FEATURES + "namespaces";
+
+ private final static String NAMESPACE_PREFIXES = FEATURES
+ + "namespace-prefixes";
+
+ private final static String XMLNS_URIs = FEATURES + "xmlns-uris";
+
+ private MethodLogger logger = new MethodLogger();
+
+ private MockHandler handler = new MockHandler(logger);
+
+ private Parser parser = new MockParser(logger);
+
+ private ParserAdapter adapter = new ParserAdapter(parser);
+
+ private void assertEquals(Object[] a, Object[] b) {
+ assertEquals(a.length, b.length);
+
+ for (int i = 0; i < a.length; i++) {
+ assertEquals("Element #" + i + " must be equal", a[i], b[i]);
+ }
+ }
+
+ @Override
+ public void setUp() {
+ adapter.setContentHandler(handler);
+ adapter.setDTDHandler(handler);
+ adapter.setErrorHandler(handler);
+ }
+
+ @Override protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testParserAdapter() {
+ System.setProperty("org.xml.sax.parser",
+ "tests.api.org.xml.sax.support.DoNothingParser");
+
+ try {
+ new ParserAdapter();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testParserAdapterParser() {
+ // Ordinary case
+ @SuppressWarnings("unused")
+ ParserAdapter adapter = new ParserAdapter(parser);
+
+ // Null case
+ try {
+ adapter = new ParserAdapter(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testGetSetFeature() {
+ String[] features = new String[] { NAMESPACES, NAMESPACE_PREFIXES,
+ XMLNS_URIs };
+
+ for (String s: features) {
+ try {
+ adapter.setFeature(s, true);
+ assertEquals(true, adapter.getFeature(s));
+
+ adapter.setFeature(s, false);
+ assertEquals(false, adapter.getFeature(s));
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ try {
+ adapter.setFeature("http://argle.bargle", true);
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetSetProperty() {
+ try {
+ adapter.setProperty("http://argle.bargle", ":)");
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ try {
+ adapter.getProperty("http://argle.bargle");
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetSetEntityResolver() {
+ EntityResolver resolver = new MockResolver();
+
+ adapter.setEntityResolver(resolver);
+ assertEquals(resolver, adapter.getEntityResolver());
+
+ adapter.setEntityResolver(null);
+ assertEquals(null, adapter.getEntityResolver());
+ }
+
+ public void testGetSetDTDHandler() {
+ adapter.setDTDHandler(null);
+ assertEquals(null, adapter.getDTDHandler());
+
+ adapter.setDTDHandler(handler);
+ assertEquals(handler, adapter.getDTDHandler());
+ }
+
+ public void testGetSetContentHandler() {
+ adapter.setContentHandler(null);
+ assertEquals(null, adapter.getContentHandler());
+
+ adapter.setContentHandler(handler);
+ assertEquals(handler, adapter.getContentHandler());
+ }
+
+ public void testGetSetErrorHandler() {
+ adapter.setErrorHandler(null);
+ assertEquals(null, adapter.getErrorHandler());
+
+ adapter.setErrorHandler(handler);
+ assertEquals(handler, adapter.getErrorHandler());
+ }
+
+ public void testParseString() {
+ try {
+ adapter.parse("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // The SAX RI creates an InputSource itself and then delegates to the
+ // "other" parse method.
+ assertEquals("parse", logger.getMethod());
+ assertEquals(InputSource.class, logger.getArgs()[0].getClass());
+ }
+
+ public void testParseInputSource() {
+ InputSource source = new InputSource("foo");
+
+ try {
+ adapter.parse(source);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("parse", logger.getMethod());
+ assertEquals(new Object[] { source }, logger.getArgs());
+ }
+
+ public void testSetDocumentLocator() {
+ Locator l = new LocatorImpl();
+
+ adapter.setDocumentLocator(l);
+
+ assertEquals(logger.size(), 1);
+ assertEquals("setDocumentLocator", logger.getMethod());
+ assertEquals(new Object[] { l }, logger.getArgs());
+
+ adapter.setDocumentLocator(null);
+
+ assertEquals(logger.size(), 2);
+ assertEquals("setDocumentLocator", logger.getMethod());
+ assertEquals(new Object[] { null }, logger.getArgs());
+ }
+
+ public void testStartDocument() {
+ try {
+ adapter.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testEndDocument() {
+ try {
+ adapter.endDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testStartElement() {
+ AttributeListImpl atts = new AttributeListImpl();
+ atts.addAttribute("john:doe", "int", "42");
+
+ try {
+ adapter.startDocument();
+ adapter.startElement("foo:bar", atts);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("startElement", logger.getMethod());
+ assertEquals("", logger.getArgs()[0]);
+ assertEquals("", logger.getArgs()[1]);
+ assertEquals("foo:bar", logger.getArgs()[2]);
+ assertEquals("john:doe", ((Attributes)logger.getArgs()[3]).getQName(0));
+ }
+
+ public void testEndElement() {
+ AttributeListImpl atts = new AttributeListImpl();
+ atts.addAttribute("john:doe", "int", "42");
+
+ try {
+ adapter.startDocument();
+ adapter.startElement("foo:bar", atts);
+ adapter.endElement("foo:bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("endElement", logger.getMethod());
+ assertEquals(new String[] { "", "", "foo:bar" }, logger.getArgs());
+ }
+
+ public void testCharacters() {
+ char[] ch = "Android".toCharArray();
+
+ try {
+ adapter.characters(ch, 2, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("characters", logger.getMethod());
+ assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
+ }
+
+ public void testIgnorableWhitespace() {
+ char[] ch = " ".toCharArray();
+
+ try {
+ adapter.ignorableWhitespace(ch, 0, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("ignorableWhitespace", logger.getMethod());
+ assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
+ }
+
+ public void testProcessingInstruction() {
+ try {
+ adapter.processingInstruction("foo", "bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("processingInstruction", logger.getMethod());
+ assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserFactoryTest.java
new file mode 100644
index 0000000..b59ce50
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/ParserFactoryTest.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.helpers.ParserFactory;
+
+@SuppressWarnings("deprecation")
+public class ParserFactoryTest extends TestCase {
+
+ @Override protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testMakeParser() throws ClassNotFoundException,
+ IllegalAccessException, InstantiationException {
+
+ System.clearProperty("org.xml.sax.parser");
+
+ // Property not set at all
+ try {
+ ParserFactory.makeParser();
+ fail("expected NullPointerException was not thrown");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // Unknown class
+ System.setProperty("org.xml.sax.parser", "foo.bar.SAXParser");
+
+ try {
+ ParserFactory.makeParser();
+ fail("expected ClassNotFoundException was not thrown");
+ } catch (ClassNotFoundException e) {
+ // Expected
+ }
+
+ // Non-accessible class
+ System.setProperty("org.xml.sax.parser",
+ "tests.api.org.xml.sax.support.NoAccessParser");
+
+ try {
+ ParserFactory.makeParser();
+ fail("expected IllegalAccessException was not thrown");
+ } catch (IllegalAccessException e) {
+ // Expected
+ }
+
+ // Non-instantiable class
+ System.setProperty("org.xml.sax.parser",
+ "tests.api.org.xml.sax.support.NoInstanceParser");
+
+ try {
+ ParserFactory.makeParser();
+ fail("expected InstantiationException was not thrown");
+ } catch (InstantiationException e) {
+ // Expected
+ }
+
+ // Non-Parser class
+ System.setProperty("org.xml.sax.parser",
+ "tests.api.org.xml.sax.support.NoSubclassParser");
+
+ try {
+ ParserFactory.makeParser();
+ fail("expected ClassCastException was not thrown");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ // Good one, finally
+ System.setProperty("org.xml.sax.parser",
+ "tests.api.org.xml.sax.support.DoNothingParser");
+
+ ParserFactory.makeParser();
+
+ }
+
+ public void testMakeParserString() throws ClassNotFoundException,
+ IllegalAccessException, InstantiationException {
+ // No class
+ try {
+ ParserFactory.makeParser(null);
+ fail("expected NullPointerException was not thrown");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // Unknown class
+ try {
+ ParserFactory.makeParser("foo.bar.SAXParser");
+ fail("expected ClassNotFoundException was not thrown");
+ } catch (ClassNotFoundException e) {
+ // Expected
+ }
+
+ // Non-accessible class
+ try {
+ ParserFactory.makeParser(
+ "tests.api.org.xml.sax.support.NoAccessParser");
+ fail("expected IllegalAccessException was not thrown");
+ } catch (IllegalAccessException e) {
+ // Expected
+ }
+
+ // Non-instantiable class
+ try {
+ ParserFactory.makeParser(
+ "tests.api.org.xml.sax.support.NoInstanceParser");
+ fail("expected InstantiationException was not thrown");
+ } catch (InstantiationException e) {
+ // Expected
+ }
+
+ // Non-Parser class
+ try {
+ ParserFactory.makeParser(
+ "tests.api.org.xml.sax.support.NoSubclassParser");
+ fail("expected ClassCastException was not thrown");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+
+ // Good one, finally
+ ParserFactory.makeParser(
+ "tests.api.org.xml.sax.support.DoNothingParser");
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLFilterImplTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLFilterImplTest.java
new file mode 100644
index 0000000..d00879b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLFilterImplTest.java
@@ -0,0 +1,484 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.LocatorImpl;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+import tests.api.org.xml.sax.support.MethodLogger;
+import tests.api.org.xml.sax.support.MockFilter;
+import tests.api.org.xml.sax.support.MockHandler;
+import tests.api.org.xml.sax.support.MockResolver;
+
+public class XMLFilterImplTest extends TestCase {
+
+ // Note: In many cases we can only test that delegation works
+ // properly. The rest is outside the scope of the specification.
+
+ private MethodLogger logger = new MethodLogger();
+
+ private MockHandler handler = new MockHandler(logger);
+
+ private XMLFilterImpl parent = new MockFilter(logger);
+
+ private XMLFilterImpl child = new XMLFilterImpl(parent);
+
+ private XMLFilterImpl orphan = new XMLFilterImpl();
+
+ private void assertEquals(Object[] a, Object[] b) {
+ assertEquals(a.length, b.length);
+
+ for (int i = 0; i < a.length; i++) {
+ assertEquals("Element #" + i + " must be equal", a[i], b[i]);
+ }
+ }
+
+ public void setUp() {
+ parent.setContentHandler(handler);
+ parent.setDTDHandler(handler);
+ parent.setErrorHandler(handler);
+
+ child.setContentHandler(handler);
+ child.setDTDHandler(handler);
+ child.setErrorHandler(handler);
+ }
+
+ public void testXMLFilterImpl() {
+ assertEquals(null, parent.getParent());
+ }
+
+ public void testXMLFilterImplXMLReader() {
+ // Ordinary case
+ assertEquals(null, parent.getParent());
+
+ // null case
+ XMLFilterImpl filter = new XMLFilterImpl(null);
+ assertEquals(null, filter.getParent());
+ }
+
+ public void testGetSetParent() {
+ child.setParent(null);
+ assertEquals(null, child.getParent());
+
+ child.setParent(parent);
+ assertEquals(parent, child.getParent());
+ }
+
+ public void testGetSetFeature() {
+ // Ordinary case
+ try {
+ child.setFeature("foo", true);
+ assertEquals(true, child.getFeature("foo"));
+
+ child.setFeature("foo", false);
+ assertEquals(false, child.getFeature("foo"));
+ } catch (SAXNotRecognizedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // No parent case
+ try {
+ orphan.setFeature("foo", false);
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetSetProperty() {
+ // Ordinary case
+ try {
+ child.setProperty("foo", "bar");
+ assertEquals("bar", child.getProperty("foo"));
+
+ child.setProperty("foo", null);
+ assertEquals(null, child.getProperty("foo"));
+ } catch (SAXNotRecognizedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // No parent case
+ try {
+ orphan.setProperty("foo", "bar");
+ fail("SAXNotRecognizedException expected");
+ } catch (SAXNotRecognizedException e) {
+ // Expected
+ } catch (SAXNotSupportedException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testGetSetEntityResolver() {
+ EntityResolver resolver = new MockResolver();
+
+ parent.setEntityResolver(resolver);
+ assertEquals(resolver, parent.getEntityResolver());
+
+ parent.setEntityResolver(null);
+ assertEquals(null, parent.getEntityResolver());
+ }
+
+ public void testGetSetDTDHandler() {
+ parent.setDTDHandler(null);
+ assertEquals(null, parent.getDTDHandler());
+
+ parent.setDTDHandler(handler);
+ assertEquals(handler, parent.getDTDHandler());
+ }
+
+ public void testGetSetContentHandler() {
+ parent.setContentHandler(null);
+ assertEquals(null, parent.getContentHandler());
+
+ parent.setContentHandler(handler);
+ assertEquals(handler, parent.getContentHandler());
+ }
+
+ public void testGetSetErrorHandler() {
+ parent.setErrorHandler(null);
+ assertEquals(null, parent.getErrorHandler());
+
+ parent.setErrorHandler(handler);
+ assertEquals(handler, parent.getErrorHandler());
+ }
+
+ public void testParseInputSource() {
+ InputSource is = new InputSource();
+
+ // Ordinary case
+ try {
+ child.parse(is);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(1, logger.size());
+ assertEquals("parse", logger.getMethod());
+
+ // No parent case
+ try {
+ orphan.parse(is);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testParseString() {
+ // Ordinary case
+ try {
+ child.parse("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(1, logger.size());
+ assertEquals("parse", logger.getMethod());
+
+ // No parent case
+ try {
+ orphan.parse("foo");
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testResolveEntity() {
+ InputSource expected = new InputSource();
+
+ MockResolver resolver = new MockResolver();
+ resolver.addEntity("foo", "bar", expected);
+
+ InputSource result = null;
+
+ parent.setEntityResolver(resolver);
+
+ // Ordinary case
+ try {
+ result = parent.resolveEntity("foo", "bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(expected, result);
+
+ // No entity resolver case
+ parent.setEntityResolver(null);
+
+ try {
+ result = parent.resolveEntity("foo", "bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(null, result);
+ }
+
+ public void testNotationDecl() {
+ try {
+ parent.notationDecl("foo", "bar", "foobar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("notationDecl", logger.getMethod());
+ assertEquals(new Object[] { "foo", "bar", "foobar" },
+ logger.getArgs());
+ }
+
+ public void testUnparsedEntityDecl() {
+ try {
+ parent.unparsedEntityDecl("foo", "bar", "gabba", "hey");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("unparsedEntityDecl", logger.getMethod());
+ assertEquals(new Object[] { "foo", "bar", "gabba", "hey" },
+ logger.getArgs());
+ }
+
+ public void testSetDocumentLocator() {
+ Locator l = new LocatorImpl();
+
+ child.setDocumentLocator(l);
+
+ assertEquals(logger.size(), 1);
+ assertEquals("setDocumentLocator", logger.getMethod());
+ assertEquals(new Object[] { l }, logger.getArgs());
+
+ child.setDocumentLocator(null);
+
+ assertEquals(logger.size(), 2);
+ assertEquals("setDocumentLocator", logger.getMethod());
+ assertEquals(new Object[] { null }, logger.getArgs());
+ }
+
+ public void testStartDocument() {
+ try {
+ parent.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testEndDocument() {
+ try {
+ parent.endDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testStartPrefixMapping() {
+ try {
+ parent.startPrefixMapping("foo", "http://some.uri");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startPrefixMapping", logger.getMethod());
+ assertEquals(new Object[] { "foo", "http://some.uri" },
+ logger.getArgs());
+ }
+
+ public void testEndPrefixMapping() {
+ try {
+ parent.endPrefixMapping("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endPrefixMapping", logger.getMethod());
+ assertEquals(new Object[] { "foo" }, logger.getArgs());
+ }
+
+ public void testStartElement() {
+ Attributes atts = new AttributesImpl();
+
+ try {
+ parent.startElement("http://some.uri", "bar", "foo:bar", atts);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startElement", logger.getMethod());
+ assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar", atts },
+ logger.getArgs());
+ }
+
+ public void testEndElement() {
+ try {
+ parent.endElement("http://some.uri", "bar", "foo:bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endElement", logger.getMethod());
+ assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar" },
+ logger.getArgs());
+ }
+
+ public void testCharacters() {
+ char[] ch = "Android".toCharArray();
+
+ try {
+ parent.characters(ch, 2, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("characters", logger.getMethod());
+ assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
+ }
+
+ public void testIgnorableWhitespace() {
+ char[] ch = " ".toCharArray();
+
+ try {
+ parent.ignorableWhitespace(ch, 0, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("ignorableWhitespace", logger.getMethod());
+ assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
+ }
+
+ public void testProcessingInstruction() {
+ try {
+ parent.processingInstruction("foo", "bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("processingInstruction", logger.getMethod());
+ assertEquals(new Object[] { "foo", "bar" }, logger.getArgs());
+ }
+
+ public void testSkippedEntity() {
+ try {
+ parent.skippedEntity("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("skippedEntity", logger.getMethod());
+ assertEquals(new Object[] { "foo" }, logger.getArgs());
+ }
+
+ public void testWarning() {
+ SAXParseException exception = new SAXParseException("Oops!", null);
+
+ try {
+ parent.warning(exception);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("warning", logger.getMethod());
+ assertEquals(new Object[] { exception }, logger.getArgs());
+ }
+
+ public void testError() {
+ SAXParseException exception = new SAXParseException("Oops!", null);
+
+ try {
+ parent.error(exception);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("error", logger.getMethod());
+ assertEquals(new Object[] { exception }, logger.getArgs());
+ }
+
+ public void testFatalError() {
+ SAXParseException exception = new SAXParseException("Oops!", null);
+
+ try {
+ parent.fatalError(exception);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("fatalError", logger.getMethod());
+ assertEquals(new Object[] { exception }, logger.getArgs());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderAdapterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderAdapterTest.java
new file mode 100644
index 0000000..16104b3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderAdapterTest.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import java.io.IOException;
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.AttributeList;
+import org.xml.sax.Attributes;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.LocatorImpl;
+import org.xml.sax.helpers.XMLReaderAdapter;
+
+import tests.api.org.xml.sax.support.MethodLogger;
+import tests.api.org.xml.sax.support.MockHandler;
+import tests.api.org.xml.sax.support.MockReader;
+import tests.api.org.xml.sax.support.MockResolver;
+
+@SuppressWarnings("deprecation")
+public class XMLReaderAdapterTest extends TestCase {
+
+ // Note: In many cases we can only test that delegation works
+ // properly. The rest is outside the scope of the specification.
+
+ private MethodLogger logger = new MethodLogger();
+
+ private MockHandler handler = new MockHandler(logger);
+
+ private XMLReader reader = new MockReader(logger);
+
+ private XMLReaderAdapter adapter = new XMLReaderAdapter(reader);
+
+ private void assertEquals(Object[] a, Object[] b) {
+ assertEquals(a.length, b.length);
+
+ for (int i = 0; i < a.length; i++) {
+ assertEquals("Element #" + i + " must be equal", a[i], b[i]);
+ }
+ }
+
+ @Override
+ public void setUp() {
+ adapter.setDocumentHandler(handler);
+ adapter.setDTDHandler(handler);
+ adapter.setErrorHandler(handler);
+ }
+
+ @Override protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testXMLReaderAdapter() {
+ System.setProperty("org.xml.sax.driver",
+ "tests.api.org.xml.sax.support.DoNothingXMLReader");
+
+ try {
+ new XMLReaderAdapter();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+ }
+
+ public void testXMLReaderAdapterXMLReader() {
+ // Ordinary case
+ @SuppressWarnings("unused")
+ XMLReaderAdapter adapter = new XMLReaderAdapter(reader);
+
+ // Null case
+ try {
+ adapter = new XMLReaderAdapter(null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ }
+
+ public void testSetLocale() {
+ // SAX RI does not support this, hence always expect exception
+ try {
+ adapter.setLocale(Locale.getDefault());
+ fail("SAXException expected");
+ } catch (SAXException e) {
+ // Expected
+ }
+ }
+
+ public void testSetEntityResolver() {
+ EntityResolver resolver = new MockResolver();
+
+ // Ordinary case
+ adapter.setEntityResolver(resolver);
+ assertEquals(resolver, reader.getEntityResolver());
+
+ // null case
+ adapter.setEntityResolver(null);
+ assertEquals(null, reader.getEntityResolver());
+ }
+
+ public void testSetDTDHandler() {
+ // Ordinary case
+ assertEquals(handler, reader.getDTDHandler());
+
+ // null case
+ adapter.setDTDHandler(null);
+ assertEquals(null, reader.getDTDHandler());
+ }
+
+ public void testSetDocumentHandler() {
+ // There is no getter for the DocumentHandler, so we can only test
+ // indirectly whether is has been set correctly.
+ try {
+ adapter.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("startDocument", logger.getMethod());
+ assertEquals(new Object[] { }, logger.getArgs());
+
+ // null case
+ adapter.setDocumentHandler(null);
+ }
+
+ public void testSetErrorHandler() {
+ // Ordinary case
+ assertEquals(handler, reader.getErrorHandler());
+
+ // null case
+ adapter.setErrorHandler(null);
+ assertEquals(null, reader.getErrorHandler());
+ }
+
+ public void testParseString() {
+ try {
+ adapter.parse("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // The SAX RI creates an InputSource itself and then delegates to the
+ // "other" parse method.
+ assertEquals("parse", logger.getMethod(0));
+ assertEquals(InputSource.class, logger.getArgs(0)[0].getClass());
+ }
+
+ public void testParseInputSource() {
+ InputSource source = new InputSource("foo");
+
+ try {
+ adapter.parse(source);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals("parse", logger.getMethod());
+ assertEquals(new Object[] { source }, logger.getArgs());
+ }
+
+ public void testSetDocumentLocator() {
+ // Ordinary case
+ LocatorImpl locator = new LocatorImpl();
+ adapter.setDocumentLocator(locator);
+
+ assertEquals("setDocumentLocator", logger.getMethod());
+ assertEquals(new Object[] { locator }, logger.getArgs());
+
+ // null case (for the DocumentHandler itself!)
+ adapter.setDocumentHandler(null);
+ adapter.setDocumentLocator(locator);
+ }
+
+ public void testStartDocument() {
+ try {
+ adapter.startDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testEndDocument() {
+ try {
+ adapter.endDocument();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endDocument", logger.getMethod());
+ assertEquals(new Object[] {}, logger.getArgs());
+ }
+
+ public void testStartPrefixMapping() {
+ adapter.startPrefixMapping("foo", "http://some.uri");
+ assertEquals(logger.size(), 0);
+ }
+
+ public void testEndPrefixMapping() {
+ adapter.endPrefixMapping("foo");
+ assertEquals(logger.size(), 0);
+ }
+
+ public void testStartElement() {
+ AttributesImpl atts = new AttributesImpl();
+ atts.addAttribute("http://some.other.uri", "gabba", "gabba:hey",
+ "int", "42");
+
+ try {
+ adapter.startElement("http://some.uri", "bar", "foo:bar", atts);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("startElement", logger.getMethod());
+ assertEquals("foo:bar", logger.getArgs()[0]);
+ assertEquals("gabba:hey",
+ ((AttributeList)logger.getArgs()[1]).getName(0));
+ }
+
+ public void testEndElement() {
+ try {
+ adapter.endElement("http://some.uri", "bar", "foo:bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("endElement", logger.getMethod());
+ assertEquals(new Object[] { "foo:bar" }, logger.getArgs());
+ }
+
+ public void testCharacters() {
+ char[] ch = "Android".toCharArray();
+
+ try {
+ adapter.characters(ch, 2, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("characters", logger.getMethod());
+ assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
+ }
+
+ public void testIgnorableWhitespace() {
+ char[] ch = " ".toCharArray();
+
+ try {
+ adapter.ignorableWhitespace(ch, 0, 5);
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("ignorableWhitespace", logger.getMethod());
+ assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
+ }
+
+ public void testProcessingInstruction() {
+ try {
+ adapter.processingInstruction("foo", "bar");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 1);
+ assertEquals("processingInstruction", logger.getMethod());
+ assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs());
+ }
+
+ public void testSkippedEntity() {
+ try {
+ adapter.skippedEntity("foo");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ assertEquals(logger.size(), 0);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderFactoryTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderFactoryTest.java
new file mode 100644
index 0000000..8205dfd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/helpers/XMLReaderFactoryTest.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.helpers;
+
+import junit.framework.TestCase;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+public class XMLReaderFactoryTest extends TestCase {
+
+ @Override protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ @Override protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testCreateXMLReader() {
+ // Property not set at all
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Unknown class
+ System.setProperty("org.xml.sax.driver", "foo.bar.XMLReader");
+
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-accessible class
+ System.setProperty("org.xml.sax.driver",
+ "tests.api.org.xml.sax.support.NoAccessXMLReader");
+
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-instantiable class
+ System.setProperty("org.xml.sax.driver",
+ "tests.api.org.xml.sax.support.NoInstanceXMLReader");
+
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-XMLReader class
+ System.setProperty("org.xml.sax.driver",
+ "tests.api.org.xml.sax.support.NoSubclassXMLReader");
+
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (ClassCastException e) {
+ // Expected
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // Good one, finally
+ System.setProperty("org.xml.sax.driver",
+ "tests.api.org.xml.sax.support.DoNothingXMLReader");
+
+ try {
+ XMLReaderFactory.createXMLReader();
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ }
+
+ public void testMakeParserString() {
+ // No class
+ try {
+ XMLReaderFactory.createXMLReader(null);
+ } catch (NullPointerException e) {
+ // Expected
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ // Unknown class
+ try {
+ XMLReaderFactory.createXMLReader("foo.bar.XMLReader");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-accessible class
+ try {
+ XMLReaderFactory.createXMLReader(
+ "tests.api.org.xml.sax.support.NoAccessXMLReader");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-instantiable class
+ try {
+ XMLReaderFactory.createXMLReader(
+ "tests.api.org.xml.sax.support.NoInstanceXMLReader");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Non-Parser class
+ try {
+ XMLReaderFactory.createXMLReader(
+ "tests.api.org.xml.sax.support.NoSubclassXMLReader");
+ } catch (SAXException e) {
+ // Expected
+ }
+
+ // Good one, finally
+ try {
+ XMLReaderFactory.createXMLReader(
+ "tests.api.org.xml.sax.support.DoNothingXMLReader");
+ } catch (SAXException e) {
+ throw new RuntimeException("Unexpected exception", e);
+ }
+
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/BrokenInputStream.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/BrokenInputStream.java
new file mode 100644
index 0000000..8136b86
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/BrokenInputStream.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Implements an InputStream what wraps another InputStream and throws an
+ * IOException after having read a specified number of bytes. Used for
+ * injecting IOExceptions on lower levels.
+ */
+public class BrokenInputStream extends InputStream {
+
+ private InputStream stream;
+
+ private int offset;
+
+ public BrokenInputStream(InputStream stream, int offset) {
+ super();
+
+ this.stream = stream;
+ this.offset = offset;
+ }
+
+ @Override
+ public int read() throws IOException {
+ if (offset == 0) {
+ throw new IOException("Injected exception");
+ }
+
+ offset--;
+ return stream.read();
+ }
+
+ @Override
+ public void close() throws IOException {
+ stream.close();
+ }
+} \ No newline at end of file
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingParser.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingParser.java
new file mode 100644
index 0000000..c18b6ee
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingParser.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Parser;
+
+import java.util.Locale;
+
+/**
+ * A SAX Parser that does nothing, but can be instantiated properly.
+ */
+@SuppressWarnings("deprecation")
+public class DoNothingParser implements Parser {
+
+ public void parse(InputSource source) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setDocumentHandler(DocumentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setLocale(Locale locale) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingXMLReader.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingXMLReader.java
new file mode 100644
index 0000000..8687bff
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/DoNothingXMLReader.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+
+/**
+ * An XMLReader that does nothing, but can be instantiated properly.
+ */
+public class DoNothingXMLReader implements XMLReader {
+
+ public ContentHandler getContentHandler() {
+ return null;
+ }
+
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
+
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void parse(InputSource input) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setFeature(String name, boolean value) {
+ }
+
+ public void setProperty(String name, Object value) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MethodLogger.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MethodLogger.java
new file mode 100644
index 0000000..ad8ef5f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MethodLogger.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A simple helper class that logs method calls by storing method names and
+ * parameter lists. Used as a foundation for various simple SAX handlers.
+ */
+public class MethodLogger {
+
+ /**
+ * The names of the invoked methods, in order.
+ */
+ private List<String> methods = new ArrayList<String>();
+
+ /**
+ * The parameter lists of the invoked methods, in order.
+ */
+ private List<Object[]> argLists = new ArrayList<Object[]>();
+
+ /**
+ * Adds a method call with a variable list of arguments.
+ */
+ public void add(String method, Object ... args) {
+ Object[] argsCopy = new Object[args.length];
+ System.arraycopy(args, 0, argsCopy, 0, args.length);
+
+ methods.add(method);
+ argLists.add(argsCopy);
+ }
+
+ /**
+ * Returns the number of method invoked so far.
+ */
+ public int size() {
+ return methods.size();
+ }
+
+ /**
+ * Returns the method name stored at the given index.
+ */
+ public String getMethod(int index) {
+ return methods.get(index);
+ }
+
+ /**
+ * Returns the name of the last method that was invoked. Returns null if no
+ * method calls have been logged so far.
+ */
+ public String getMethod() {
+ return (size() == 0 ? null : getMethod(size() - 1));
+ }
+
+ /**
+ * Returns the argument array stored at the given index. May be empty, but
+ * not null.
+ */
+ public Object[] getArgs(int index) {
+ return argLists.get(index);
+ }
+
+ /**
+ * Returns the argument array of the last method that was invoked. Returns
+ * null if no method has been invoked so far.
+ */
+ public Object[] getArgs() {
+ return (size() == 0 ? null : getArgs(size() - 1));
+ }
+
+ /**
+ * Clears the log.
+ */
+ public void clear() {
+ methods.clear();
+ argLists.clear();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockFilter.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockFilter.java
new file mode 100644
index 0000000..1189ebd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockFilter.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+/**
+ * A helper class that extends XMLFilterImpl, provides dummy feature/property
+ * management, and logs some method calls.
+ */
+public class MockFilter extends XMLFilterImpl {
+
+ private MethodLogger logger;
+
+ private Set<String> features = new HashSet<String>();
+
+ private Map<String, Object> properties = new HashMap<String, Object>();
+
+ public MockFilter(MethodLogger logger) {
+ super();
+ this.logger = logger;
+ }
+
+ @Override
+ public boolean getFeature(String name) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ return features.contains(name);
+ }
+
+ @Override
+ public Object getProperty(String name) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ return properties.get(name);
+ }
+
+ @Override
+ public void setFeature(String name, boolean value) {
+ if (value) {
+ features.add(name);
+ } else {
+ features.remove(name);
+ }
+ }
+
+ @Override
+ public void setProperty(String name, Object value) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ if (value == null) {
+ properties.remove(name);
+ } else {
+ properties.put(name, value);
+ }
+ }
+
+ @Override
+ public void parse(InputSource input) throws SAXException, IOException {
+ logger.add("parse", input);
+ }
+
+ @Override
+ public void parse(String systemId) throws SAXException, IOException {
+ logger.add("parse", systemId);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockHandler.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockHandler.java
new file mode 100644
index 0000000..55757c9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockHandler.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.AttributeList;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.ext.LexicalHandler;
+
+/**
+ * A helper class that implements the various SAX callback interfaces and logs
+ * method calls.
+ */
+@SuppressWarnings("deprecation")
+public class MockHandler implements ContentHandler, DTDHandler, DocumentHandler,
+ ErrorHandler, LexicalHandler {
+
+ private MethodLogger logger;
+
+ public MockHandler(MethodLogger logger) {
+ super();
+ this.logger = logger;
+ }
+
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ logger.add("characters", ch, start, length);
+ }
+
+ public void endDocument() throws SAXException {
+ logger.add("endDocument");
+ }
+
+ public void endElement(String name) throws SAXException {
+ logger.add("endElement", name);
+ }
+
+ public void endElement(String uri, String localName, String name) throws SAXException {
+ logger.add("endElement", uri, localName, name);
+ }
+
+ public void endPrefixMapping(String prefix) throws SAXException {
+ logger.add("endPrefixMapping", prefix);
+ }
+
+ public void error(SAXParseException exception) throws SAXException {
+ logger.add("error", exception);
+ }
+
+ public void fatalError(SAXParseException exception) throws SAXException {
+ logger.add("fatalError", exception);
+ }
+
+ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
+ logger.add("ignorableWhitespace", ch, start, length);
+ }
+
+ public void notationDecl(String name, String publicId, String systemId) throws SAXException {
+ logger.add("notationDecl", name, publicId, systemId);
+ }
+
+ public void processingInstruction(String target, String data) throws SAXException {
+ logger.add("processingInstruction", target, data);
+ }
+
+ public void setDocumentLocator(Locator locator) {
+ logger.add("setDocumentLocator", locator);
+ }
+
+ public void skippedEntity(String name) throws SAXException {
+ logger.add("skippedEntity", name);
+ }
+
+ public void startDocument() throws SAXException {
+ logger.add("startDocument");
+ }
+
+ public void startElement(String name, AttributeList atts) throws SAXException {
+ logger.add("startElement", name, atts);
+ }
+
+ public void startElement(String uri, String localName, String name, Attributes atts)
+ throws SAXException {
+ logger.add("startElement", uri, localName, name, atts);
+ }
+
+ public void startPrefixMapping(String prefix, String uri) throws SAXException {
+ logger.add("startPrefixMapping", prefix, uri);
+ }
+
+ public void unparsedEntityDecl(String name, String publicId, String systemId,
+ String notationName) throws SAXException {
+ logger.add("unparsedEntityDecl", name, publicId, systemId, notationName);
+ }
+
+ public void warning(SAXParseException exception) throws SAXException {
+ logger.add("warning", exception);
+ }
+
+ public void comment(char[] ch, int start, int length) throws SAXException {
+ logger.add("comment", ch, start, length);
+ }
+
+ public void endCDATA() throws SAXException {
+ logger.add("endCDATA");
+ }
+
+ public void endDTD() throws SAXException {
+ logger.add("endDTD");
+ }
+
+ public void endEntity(String name) throws SAXException {
+ logger.add("endEntity", name);
+ }
+
+ public void startCDATA() throws SAXException {
+ logger.add("startCDATA");
+ }
+
+ public void startDTD(String name, String publicId, String systemId) throws SAXException {
+ logger.add("startDTD", name, publicId, systemId);
+ }
+
+ public void startEntity(String name) throws SAXException {
+ logger.add("startEntity", name);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockParser.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockParser.java
new file mode 100644
index 0000000..e19e14e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockParser.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.io.IOException;
+import java.util.Locale;
+
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Parser;
+import org.xml.sax.SAXException;
+
+@SuppressWarnings("deprecation")
+public class MockParser implements Parser {
+
+ private MethodLogger logger;
+
+ public MockParser(MethodLogger logger) {
+ super();
+ this.logger = logger;
+ }
+
+ public void parse(InputSource source) throws SAXException, IOException {
+ logger.add("parse", source);
+ }
+
+ public void parse(String systemId) throws SAXException, IOException {
+ logger.add("parse", systemId);
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ logger.add("setDTDHandler", handler);
+ }
+
+ public void setDocumentHandler(DocumentHandler handler) {
+ logger.add("setDocumentHandler", handler);
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ logger.add("setEntityResolver", resolver);
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ logger.add("setErrorHandler", handler);
+ }
+
+ public void setLocale(Locale locale) throws SAXException {
+ logger.add("setLocale", locale);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockReader.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockReader.java
new file mode 100644
index 0000000..2f0081c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockReader.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.XMLReader;
+
+/**
+ * A helper class that implements the SAX XMLReader interface and logs method
+ * calls.
+ */
+public class MockReader implements XMLReader {
+
+ private MethodLogger logger;
+
+ private ContentHandler contentHandler;
+
+ private DTDHandler dtdHandler;
+
+ private EntityResolver resolver;
+
+ private ErrorHandler errorHandler;
+
+ private Set<String> features = new HashSet<String>();
+
+ private Map<String, Object> properties = new HashMap<String, Object>();
+
+ public MockReader(MethodLogger logger) {
+ super();
+ this.logger = logger;
+ }
+
+
+ public ContentHandler getContentHandler() {
+ return contentHandler;
+ }
+
+ public DTDHandler getDTDHandler() {
+ return dtdHandler;
+ }
+
+ public EntityResolver getEntityResolver() {
+ return resolver;
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return errorHandler;
+ }
+
+ public boolean getFeature(String name) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ return features.contains(name);
+ }
+
+ public Object getProperty(String name) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ return properties.get(name);
+ }
+
+ public void parse(InputSource input) throws IOException, SAXException {
+ logger.add("parse", input);
+ }
+
+ public void parse(String systemId) throws IOException, SAXException {
+ logger.add("parse", systemId);
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ this.contentHandler = handler;
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ this.dtdHandler = handler;
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ this.resolver = resolver;
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ this.errorHandler = handler;
+ }
+
+ public void setFeature(String name, boolean value) {
+ if (value) {
+ features.add(name);
+ } else {
+ features.remove(name);
+ }
+ }
+
+ public void setProperty(String name, Object value) throws SAXNotRecognizedException,
+ SAXNotSupportedException {
+ if (value == null) {
+ properties.remove(name);
+ } else {
+ properties.put(name, value);
+ }
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockResolver.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockResolver.java
new file mode 100644
index 0000000..df4ddbf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/MockResolver.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * A helper class for resolving entities.
+ */
+public class MockResolver implements EntityResolver {
+
+ private Map<String, InputSource> entities = new HashMap<String, InputSource>();
+
+ public void addEntity(String publicId, String systemId, InputSource source) {
+ entities.put("[" + publicId + ":" + systemId + "]", source);
+ }
+
+ public void removeEntity(String publicId, String systemId) {
+ entities.remove("[" + publicId + ":" + systemId + "]");
+ }
+
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws SAXException, IOException {
+ return entities.get("[" + publicId + ":" + systemId + "]");
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessParser.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessParser.java
new file mode 100644
index 0000000..9fca514
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessParser.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Parser;
+
+import java.util.Locale;
+
+/**
+ * A SAX Parser that can't be accessed.
+ */
+@SuppressWarnings("deprecation")
+class NoAccessParser implements Parser {
+
+ public void parse(InputSource source) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setDocumentHandler(DocumentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setLocale(Locale locale) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessXMLReader.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessXMLReader.java
new file mode 100644
index 0000000..b6a0a68
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoAccessXMLReader.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+
+/**
+ * An XMLReader that is not accessible.
+ */
+class NoAccessXMLReader implements XMLReader {
+
+ public ContentHandler getContentHandler() {
+ return null;
+ }
+
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
+
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void parse(InputSource input) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setFeature(String name, boolean value) {
+ }
+
+ public void setProperty(String name, Object value) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceParser.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceParser.java
new file mode 100644
index 0000000..48cfba7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceParser.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Parser;
+
+import java.util.Locale;
+
+/**
+ * A SAX Parser that can be accessed, but not instantiated.
+ */
+@SuppressWarnings("deprecation")
+public class NoInstanceParser implements Parser {
+
+ public NoInstanceParser(int i) {
+ }
+
+ public void parse(InputSource source) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setDocumentHandler(DocumentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setLocale(Locale locale) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceXMLReader.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceXMLReader.java
new file mode 100644
index 0000000..7b386bc
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoInstanceXMLReader.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+
+/**
+ * An XMLReader that is accessible, but can't be instantiated.
+ */
+public class NoInstanceXMLReader implements XMLReader {
+
+ public NoInstanceXMLReader(int i) {
+ }
+
+ public ContentHandler getContentHandler() {
+ return null;
+ }
+
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
+
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void parse(InputSource input) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setFeature(String name, boolean value) {
+ }
+
+ public void setProperty(String name, Object value) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassParser.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassParser.java
new file mode 100644
index 0000000..8016c10
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassParser.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.DTDHandler;
+import org.xml.sax.DocumentHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+
+import java.util.Locale;
+
+/**
+ * A SAX Parser that does not implement the Parser interface.
+ */
+@SuppressWarnings("deprecation")
+public class NoSubclassParser {
+
+ public void parse(InputSource source) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setDocumentHandler(DocumentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setLocale(Locale locale) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassXMLReader.java b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassXMLReader.java
new file mode 100644
index 0000000..acdbd88
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/org/xml/sax/support/NoSubclassXMLReader.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.org.xml.sax.support;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+
+/**
+ * An XMLReader that does not implement the XMLReader interface.
+ */
+public class NoSubclassXMLReader implements XMLReader {
+
+ public ContentHandler getContentHandler() {
+ return null;
+ }
+
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
+
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void parse(InputSource input) {
+ }
+
+ public void parse(String systemId) {
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public void setFeature(String name, boolean value) {
+ }
+
+ public void setProperty(String name, Object value) {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/pkg1/TestClass.java b/harmony-tests/src/test/java/org/apache/harmony/tests/pkg1/TestClass.java
new file mode 100644
index 0000000..37765b7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/pkg1/TestClass.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.pkg1;
+
+import java.io.Serializable;
+
+/**
+ * Used for a serialization test, must have different package and same base name
+ * as the TestClass in o.a.h.l.tests.pkg2
+ */
+public class TestClass implements Serializable {
+ private static final long serialVersionUID = 11111L;
+
+ public int i = 0;
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/pkg2/TestClass.java b/harmony-tests/src/test/java/org/apache/harmony/tests/pkg2/TestClass.java
new file mode 100644
index 0000000..1df7cdd
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/pkg2/TestClass.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.pkg2;
+
+import java.io.Serializable;
+
+/**
+ * Used for a serialization test, must have different package and same base name
+ * as the TestClass in o.a.h.l.tests.pkg1
+ */
+public class TestClass implements Serializable {
+ private static final long serialVersionUID = 11111L;
+ public int i = 0;
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/support/A.java b/harmony-tests/src/test/java/org/apache/harmony/tests/support/A.java
new file mode 100644
index 0000000..11522be
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/support/A.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.support;
+
+public class A implements I {
+ private static P pp = new P();
+
+ public A() {
+ pp.setClazz(getClass());
+ }
+
+ public String find(String key) {
+ return pp.findProp(key);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/support/B.java b/harmony-tests/src/test/java/org/apache/harmony/tests/support/B.java
new file mode 100644
index 0000000..f0f6473
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/support/B.java
@@ -0,0 +1,21 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.support;
+
+public class B extends A {
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/support/I.java b/harmony-tests/src/test/java/org/apache/harmony/tests/support/I.java
new file mode 100644
index 0000000..65cbd22
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/support/I.java
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.support;
+
+public interface I {
+ String find(String key);
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/support/P.java b/harmony-tests/src/test/java/org/apache/harmony/tests/support/P.java
new file mode 100644
index 0000000..95e879d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/support/P.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.support;
+
+import java.util.ResourceBundle;
+
+public class P {
+ private Class c;
+
+ public void setClazz(Class c) {
+ this.c = c;
+ }
+
+ public String findProp(String key) {
+ return findProp(this.c, key);
+ }
+
+ private String findProp(Class cls, String key) {
+ String ret = null;
+ try {
+ ResourceBundle b = ResourceBundle.getBundle(cls.getName());
+ ret = (String) b.getObject(key);
+ } catch (Exception e) {
+ }
+ if (ret == null && !cls.equals(Object.class) && !cls.isPrimitive()) {
+ ret = findProp(cls.getSuperclass(), key);
+ }
+ return ret;
+ }
+}